apache-couchdb-1.5.0/0000755000175000001440000000000012230722613011336 500000000000000apache-couchdb-1.5.0/m4/0000755000175000001440000000000012230722301011650 500000000000000apache-couchdb-1.5.0/m4/libtool.m40000644000175000001440000106002312230722215013504 00000000000000# libtool.m4 - Configure libtool for the host system. -*-Autoconf-*- # # Copyright (C) 1996, 1997, 1998, 1999, 2000, 2001, 2003, 2004, 2005, # 2006, 2007, 2008, 2009, 2010, 2011 Free Software # Foundation, Inc. # Written by Gordon Matzigkeit, 1996 # # This file is free software; the Free Software Foundation gives # unlimited permission to copy and/or distribute it, with or without # modifications, as long as this notice is preserved. m4_define([_LT_COPYING], [dnl # Copyright (C) 1996, 1997, 1998, 1999, 2000, 2001, 2003, 2004, 2005, # 2006, 2007, 2008, 2009, 2010, 2011 Free Software # Foundation, Inc. # Written by Gordon Matzigkeit, 1996 # # This file is part of GNU Libtool. # # GNU Libtool is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License as # published by the Free Software Foundation; either version 2 of # the License, or (at your option) any later version. # # As a special exception to the GNU General Public License, # if you distribute this file as part of a program or library that # is built using GNU Libtool, you may include this file under the # same distribution terms that you use for the rest of that program. # # GNU Libtool is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Libtool; see the file COPYING. If not, a copy # can be downloaded from http://www.gnu.org/licenses/gpl.html, or # obtained by writing to the Free Software Foundation, Inc., # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. ]) # serial 57 LT_INIT # LT_PREREQ(VERSION) # ------------------ # Complain and exit if this libtool version is less that VERSION. m4_defun([LT_PREREQ], [m4_if(m4_version_compare(m4_defn([LT_PACKAGE_VERSION]), [$1]), -1, [m4_default([$3], [m4_fatal([Libtool version $1 or higher is required], 63)])], [$2])]) # _LT_CHECK_BUILDDIR # ------------------ # Complain if the absolute build directory name contains unusual characters m4_defun([_LT_CHECK_BUILDDIR], [case `pwd` in *\ * | *\ *) AC_MSG_WARN([Libtool does not cope well with whitespace in `pwd`]) ;; esac ]) # LT_INIT([OPTIONS]) # ------------------ AC_DEFUN([LT_INIT], [AC_PREREQ([2.58])dnl We use AC_INCLUDES_DEFAULT AC_REQUIRE([AC_CONFIG_AUX_DIR_DEFAULT])dnl AC_BEFORE([$0], [LT_LANG])dnl AC_BEFORE([$0], [LT_OUTPUT])dnl AC_BEFORE([$0], [LTDL_INIT])dnl m4_require([_LT_CHECK_BUILDDIR])dnl dnl Autoconf doesn't catch unexpanded LT_ macros by default: m4_pattern_forbid([^_?LT_[A-Z_]+$])dnl m4_pattern_allow([^(_LT_EOF|LT_DLGLOBAL|LT_DLLAZY_OR_NOW|LT_MULTI_MODULE)$])dnl dnl aclocal doesn't pull ltoptions.m4, ltsugar.m4, or ltversion.m4 dnl unless we require an AC_DEFUNed macro: AC_REQUIRE([LTOPTIONS_VERSION])dnl AC_REQUIRE([LTSUGAR_VERSION])dnl AC_REQUIRE([LTVERSION_VERSION])dnl AC_REQUIRE([LTOBSOLETE_VERSION])dnl m4_require([_LT_PROG_LTMAIN])dnl _LT_SHELL_INIT([SHELL=${CONFIG_SHELL-/bin/sh}]) dnl Parse OPTIONS _LT_SET_OPTIONS([$0], [$1]) # This can be used to rebuild libtool when needed LIBTOOL_DEPS="$ltmain" # Always use our own libtool. LIBTOOL='$(SHELL) $(top_builddir)/libtool' AC_SUBST(LIBTOOL)dnl _LT_SETUP # Only expand once: m4_define([LT_INIT]) ])# LT_INIT # Old names: AU_ALIAS([AC_PROG_LIBTOOL], [LT_INIT]) AU_ALIAS([AM_PROG_LIBTOOL], [LT_INIT]) dnl aclocal-1.4 backwards compatibility: dnl AC_DEFUN([AC_PROG_LIBTOOL], []) dnl AC_DEFUN([AM_PROG_LIBTOOL], []) # _LT_CC_BASENAME(CC) # ------------------- # Calculate cc_basename. Skip known compiler wrappers and cross-prefix. m4_defun([_LT_CC_BASENAME], [for cc_temp in $1""; do case $cc_temp in compile | *[[\\/]]compile | ccache | *[[\\/]]ccache ) ;; distcc | *[[\\/]]distcc | purify | *[[\\/]]purify ) ;; \-*) ;; *) break;; esac done cc_basename=`$ECHO "$cc_temp" | $SED "s%.*/%%; s%^$host_alias-%%"` ]) # _LT_FILEUTILS_DEFAULTS # ---------------------- # It is okay to use these file commands and assume they have been set # sensibly after `m4_require([_LT_FILEUTILS_DEFAULTS])'. m4_defun([_LT_FILEUTILS_DEFAULTS], [: ${CP="cp -f"} : ${MV="mv -f"} : ${RM="rm -f"} ])# _LT_FILEUTILS_DEFAULTS # _LT_SETUP # --------- m4_defun([_LT_SETUP], [AC_REQUIRE([AC_CANONICAL_HOST])dnl AC_REQUIRE([AC_CANONICAL_BUILD])dnl AC_REQUIRE([_LT_PREPARE_SED_QUOTE_VARS])dnl AC_REQUIRE([_LT_PROG_ECHO_BACKSLASH])dnl _LT_DECL([], [PATH_SEPARATOR], [1], [The PATH separator for the build system])dnl dnl _LT_DECL([], [host_alias], [0], [The host system])dnl _LT_DECL([], [host], [0])dnl _LT_DECL([], [host_os], [0])dnl dnl _LT_DECL([], [build_alias], [0], [The build system])dnl _LT_DECL([], [build], [0])dnl _LT_DECL([], [build_os], [0])dnl dnl AC_REQUIRE([AC_PROG_CC])dnl AC_REQUIRE([LT_PATH_LD])dnl AC_REQUIRE([LT_PATH_NM])dnl dnl AC_REQUIRE([AC_PROG_LN_S])dnl test -z "$LN_S" && LN_S="ln -s" _LT_DECL([], [LN_S], [1], [Whether we need soft or hard links])dnl dnl AC_REQUIRE([LT_CMD_MAX_LEN])dnl _LT_DECL([objext], [ac_objext], [0], [Object file suffix (normally "o")])dnl _LT_DECL([], [exeext], [0], [Executable file suffix (normally "")])dnl dnl m4_require([_LT_FILEUTILS_DEFAULTS])dnl m4_require([_LT_CHECK_SHELL_FEATURES])dnl m4_require([_LT_PATH_CONVERSION_FUNCTIONS])dnl m4_require([_LT_CMD_RELOAD])dnl m4_require([_LT_CHECK_MAGIC_METHOD])dnl m4_require([_LT_CHECK_SHAREDLIB_FROM_LINKLIB])dnl m4_require([_LT_CMD_OLD_ARCHIVE])dnl m4_require([_LT_CMD_GLOBAL_SYMBOLS])dnl m4_require([_LT_WITH_SYSROOT])dnl _LT_CONFIG_LIBTOOL_INIT([ # See if we are running on zsh, and set the options which allow our # commands through without removal of \ escapes INIT. if test -n "\${ZSH_VERSION+set}" ; then setopt NO_GLOB_SUBST fi ]) if test -n "${ZSH_VERSION+set}" ; then setopt NO_GLOB_SUBST fi _LT_CHECK_OBJDIR m4_require([_LT_TAG_COMPILER])dnl case $host_os in aix3*) # AIX sometimes has problems with the GCC collect2 program. For some # reason, if we set the COLLECT_NAMES environment variable, the problems # vanish in a puff of smoke. if test "X${COLLECT_NAMES+set}" != Xset; then COLLECT_NAMES= export COLLECT_NAMES fi ;; esac # Global variables: ofile=libtool can_build_shared=yes # All known linkers require a `.a' archive for static linking (except MSVC, # which needs '.lib'). libext=a with_gnu_ld="$lt_cv_prog_gnu_ld" old_CC="$CC" old_CFLAGS="$CFLAGS" # Set sane defaults for various variables test -z "$CC" && CC=cc test -z "$LTCC" && LTCC=$CC test -z "$LTCFLAGS" && LTCFLAGS=$CFLAGS test -z "$LD" && LD=ld test -z "$ac_objext" && ac_objext=o _LT_CC_BASENAME([$compiler]) # Only perform the check for file, if the check method requires it test -z "$MAGIC_CMD" && MAGIC_CMD=file case $deplibs_check_method in file_magic*) if test "$file_magic_cmd" = '$MAGIC_CMD'; then _LT_PATH_MAGIC fi ;; esac # Use C for the default configuration in the libtool script LT_SUPPORTED_TAG([CC]) _LT_LANG_C_CONFIG _LT_LANG_DEFAULT_CONFIG _LT_CONFIG_COMMANDS ])# _LT_SETUP # _LT_PREPARE_SED_QUOTE_VARS # -------------------------- # Define a few sed substitution that help us do robust quoting. m4_defun([_LT_PREPARE_SED_QUOTE_VARS], [# Backslashify metacharacters that are still active within # double-quoted strings. sed_quote_subst='s/\([["`$\\]]\)/\\\1/g' # Same as above, but do not quote variable references. double_quote_subst='s/\([["`\\]]\)/\\\1/g' # Sed substitution to delay expansion of an escaped shell variable in a # double_quote_subst'ed string. delay_variable_subst='s/\\\\\\\\\\\$/\\\\\\$/g' # Sed substitution to delay expansion of an escaped single quote. delay_single_quote_subst='s/'\''/'\'\\\\\\\'\''/g' # Sed substitution to avoid accidental globbing in evaled expressions no_glob_subst='s/\*/\\\*/g' ]) # _LT_PROG_LTMAIN # --------------- # Note that this code is called both from `configure', and `config.status' # now that we use AC_CONFIG_COMMANDS to generate libtool. Notably, # `config.status' has no value for ac_aux_dir unless we are using Automake, # so we pass a copy along to make sure it has a sensible value anyway. m4_defun([_LT_PROG_LTMAIN], [m4_ifdef([AC_REQUIRE_AUX_FILE], [AC_REQUIRE_AUX_FILE([ltmain.sh])])dnl _LT_CONFIG_LIBTOOL_INIT([ac_aux_dir='$ac_aux_dir']) ltmain="$ac_aux_dir/ltmain.sh" ])# _LT_PROG_LTMAIN ## ------------------------------------- ## ## Accumulate code for creating libtool. ## ## ------------------------------------- ## # So that we can recreate a full libtool script including additional # tags, we accumulate the chunks of code to send to AC_CONFIG_COMMANDS # in macros and then make a single call at the end using the `libtool' # label. # _LT_CONFIG_LIBTOOL_INIT([INIT-COMMANDS]) # ---------------------------------------- # Register INIT-COMMANDS to be passed to AC_CONFIG_COMMANDS later. m4_define([_LT_CONFIG_LIBTOOL_INIT], [m4_ifval([$1], [m4_append([_LT_OUTPUT_LIBTOOL_INIT], [$1 ])])]) # Initialize. m4_define([_LT_OUTPUT_LIBTOOL_INIT]) # _LT_CONFIG_LIBTOOL([COMMANDS]) # ------------------------------ # Register COMMANDS to be passed to AC_CONFIG_COMMANDS later. m4_define([_LT_CONFIG_LIBTOOL], [m4_ifval([$1], [m4_append([_LT_OUTPUT_LIBTOOL_COMMANDS], [$1 ])])]) # Initialize. m4_define([_LT_OUTPUT_LIBTOOL_COMMANDS]) # _LT_CONFIG_SAVE_COMMANDS([COMMANDS], [INIT_COMMANDS]) # ----------------------------------------------------- m4_defun([_LT_CONFIG_SAVE_COMMANDS], [_LT_CONFIG_LIBTOOL([$1]) _LT_CONFIG_LIBTOOL_INIT([$2]) ]) # _LT_FORMAT_COMMENT([COMMENT]) # ----------------------------- # Add leading comment marks to the start of each line, and a trailing # full-stop to the whole comment if one is not present already. m4_define([_LT_FORMAT_COMMENT], [m4_ifval([$1], [ m4_bpatsubst([m4_bpatsubst([$1], [^ *], [# ])], [['`$\]], [\\\&])]m4_bmatch([$1], [[!?.]$], [], [.]) )]) ## ------------------------ ## ## FIXME: Eliminate VARNAME ## ## ------------------------ ## # _LT_DECL([CONFIGNAME], VARNAME, VALUE, [DESCRIPTION], [IS-TAGGED?]) # ------------------------------------------------------------------- # CONFIGNAME is the name given to the value in the libtool script. # VARNAME is the (base) name used in the configure script. # VALUE may be 0, 1 or 2 for a computed quote escaped value based on # VARNAME. Any other value will be used directly. m4_define([_LT_DECL], [lt_if_append_uniq([lt_decl_varnames], [$2], [, ], [lt_dict_add_subkey([lt_decl_dict], [$2], [libtool_name], [m4_ifval([$1], [$1], [$2])]) lt_dict_add_subkey([lt_decl_dict], [$2], [value], [$3]) m4_ifval([$4], [lt_dict_add_subkey([lt_decl_dict], [$2], [description], [$4])]) lt_dict_add_subkey([lt_decl_dict], [$2], [tagged?], [m4_ifval([$5], [yes], [no])])]) ]) # _LT_TAGDECL([CONFIGNAME], VARNAME, VALUE, [DESCRIPTION]) # -------------------------------------------------------- m4_define([_LT_TAGDECL], [_LT_DECL([$1], [$2], [$3], [$4], [yes])]) # lt_decl_tag_varnames([SEPARATOR], [VARNAME1...]) # ------------------------------------------------ m4_define([lt_decl_tag_varnames], [_lt_decl_filter([tagged?], [yes], $@)]) # _lt_decl_filter(SUBKEY, VALUE, [SEPARATOR], [VARNAME1..]) # --------------------------------------------------------- m4_define([_lt_decl_filter], [m4_case([$#], [0], [m4_fatal([$0: too few arguments: $#])], [1], [m4_fatal([$0: too few arguments: $#: $1])], [2], [lt_dict_filter([lt_decl_dict], [$1], [$2], [], lt_decl_varnames)], [3], [lt_dict_filter([lt_decl_dict], [$1], [$2], [$3], lt_decl_varnames)], [lt_dict_filter([lt_decl_dict], $@)])[]dnl ]) # lt_decl_quote_varnames([SEPARATOR], [VARNAME1...]) # -------------------------------------------------- m4_define([lt_decl_quote_varnames], [_lt_decl_filter([value], [1], $@)]) # lt_decl_dquote_varnames([SEPARATOR], [VARNAME1...]) # --------------------------------------------------- m4_define([lt_decl_dquote_varnames], [_lt_decl_filter([value], [2], $@)]) # lt_decl_varnames_tagged([SEPARATOR], [VARNAME1...]) # --------------------------------------------------- m4_define([lt_decl_varnames_tagged], [m4_assert([$# <= 2])dnl _$0(m4_quote(m4_default([$1], [[, ]])), m4_ifval([$2], [[$2]], [m4_dquote(lt_decl_tag_varnames)]), m4_split(m4_normalize(m4_quote(_LT_TAGS)), [ ]))]) m4_define([_lt_decl_varnames_tagged], [m4_ifval([$3], [lt_combine([$1], [$2], [_], $3)])]) # lt_decl_all_varnames([SEPARATOR], [VARNAME1...]) # ------------------------------------------------ m4_define([lt_decl_all_varnames], [_$0(m4_quote(m4_default([$1], [[, ]])), m4_if([$2], [], m4_quote(lt_decl_varnames), m4_quote(m4_shift($@))))[]dnl ]) m4_define([_lt_decl_all_varnames], [lt_join($@, lt_decl_varnames_tagged([$1], lt_decl_tag_varnames([[, ]], m4_shift($@))))dnl ]) # _LT_CONFIG_STATUS_DECLARE([VARNAME]) # ------------------------------------ # Quote a variable value, and forward it to `config.status' so that its # declaration there will have the same value as in `configure'. VARNAME # must have a single quote delimited value for this to work. m4_define([_LT_CONFIG_STATUS_DECLARE], [$1='`$ECHO "$][$1" | $SED "$delay_single_quote_subst"`']) # _LT_CONFIG_STATUS_DECLARATIONS # ------------------------------ # We delimit libtool config variables with single quotes, so when # we write them to config.status, we have to be sure to quote all # embedded single quotes properly. In configure, this macro expands # each variable declared with _LT_DECL (and _LT_TAGDECL) into: # # ='`$ECHO "$" | $SED "$delay_single_quote_subst"`' m4_defun([_LT_CONFIG_STATUS_DECLARATIONS], [m4_foreach([_lt_var], m4_quote(lt_decl_all_varnames), [m4_n([_LT_CONFIG_STATUS_DECLARE(_lt_var)])])]) # _LT_LIBTOOL_TAGS # ---------------- # Output comment and list of tags supported by the script m4_defun([_LT_LIBTOOL_TAGS], [_LT_FORMAT_COMMENT([The names of the tagged configurations supported by this script])dnl available_tags="_LT_TAGS"dnl ]) # _LT_LIBTOOL_DECLARE(VARNAME, [TAG]) # ----------------------------------- # Extract the dictionary values for VARNAME (optionally with TAG) and # expand to a commented shell variable setting: # # # Some comment about what VAR is for. # visible_name=$lt_internal_name m4_define([_LT_LIBTOOL_DECLARE], [_LT_FORMAT_COMMENT(m4_quote(lt_dict_fetch([lt_decl_dict], [$1], [description])))[]dnl m4_pushdef([_libtool_name], m4_quote(lt_dict_fetch([lt_decl_dict], [$1], [libtool_name])))[]dnl m4_case(m4_quote(lt_dict_fetch([lt_decl_dict], [$1], [value])), [0], [_libtool_name=[$]$1], [1], [_libtool_name=$lt_[]$1], [2], [_libtool_name=$lt_[]$1], [_libtool_name=lt_dict_fetch([lt_decl_dict], [$1], [value])])[]dnl m4_ifval([$2], [_$2])[]m4_popdef([_libtool_name])[]dnl ]) # _LT_LIBTOOL_CONFIG_VARS # ----------------------- # Produce commented declarations of non-tagged libtool config variables # suitable for insertion in the LIBTOOL CONFIG section of the `libtool' # script. Tagged libtool config variables (even for the LIBTOOL CONFIG # section) are produced by _LT_LIBTOOL_TAG_VARS. m4_defun([_LT_LIBTOOL_CONFIG_VARS], [m4_foreach([_lt_var], m4_quote(_lt_decl_filter([tagged?], [no], [], lt_decl_varnames)), [m4_n([_LT_LIBTOOL_DECLARE(_lt_var)])])]) # _LT_LIBTOOL_TAG_VARS(TAG) # ------------------------- m4_define([_LT_LIBTOOL_TAG_VARS], [m4_foreach([_lt_var], m4_quote(lt_decl_tag_varnames), [m4_n([_LT_LIBTOOL_DECLARE(_lt_var, [$1])])])]) # _LT_TAGVAR(VARNAME, [TAGNAME]) # ------------------------------ m4_define([_LT_TAGVAR], [m4_ifval([$2], [$1_$2], [$1])]) # _LT_CONFIG_COMMANDS # ------------------- # Send accumulated output to $CONFIG_STATUS. Thanks to the lists of # variables for single and double quote escaping we saved from calls # to _LT_DECL, we can put quote escaped variables declarations # into `config.status', and then the shell code to quote escape them in # for loops in `config.status'. Finally, any additional code accumulated # from calls to _LT_CONFIG_LIBTOOL_INIT is expanded. m4_defun([_LT_CONFIG_COMMANDS], [AC_PROVIDE_IFELSE([LT_OUTPUT], dnl If the libtool generation code has been placed in $CONFIG_LT, dnl instead of duplicating it all over again into config.status, dnl then we will have config.status run $CONFIG_LT later, so it dnl needs to know what name is stored there: [AC_CONFIG_COMMANDS([libtool], [$SHELL $CONFIG_LT || AS_EXIT(1)], [CONFIG_LT='$CONFIG_LT'])], dnl If the libtool generation code is destined for config.status, dnl expand the accumulated commands and init code now: [AC_CONFIG_COMMANDS([libtool], [_LT_OUTPUT_LIBTOOL_COMMANDS], [_LT_OUTPUT_LIBTOOL_COMMANDS_INIT])]) ])#_LT_CONFIG_COMMANDS # Initialize. m4_define([_LT_OUTPUT_LIBTOOL_COMMANDS_INIT], [ # The HP-UX ksh and POSIX shell print the target directory to stdout # if CDPATH is set. (unset CDPATH) >/dev/null 2>&1 && unset CDPATH sed_quote_subst='$sed_quote_subst' double_quote_subst='$double_quote_subst' delay_variable_subst='$delay_variable_subst' _LT_CONFIG_STATUS_DECLARATIONS LTCC='$LTCC' LTCFLAGS='$LTCFLAGS' compiler='$compiler_DEFAULT' # A function that is used when there is no print builtin or printf. func_fallback_echo () { eval 'cat <<_LTECHO_EOF \$[]1 _LTECHO_EOF' } # Quote evaled strings. for var in lt_decl_all_varnames([[ \ ]], lt_decl_quote_varnames); do case \`eval \\\\\$ECHO \\\\""\\\\\$\$var"\\\\"\` in *[[\\\\\\\`\\"\\\$]]*) eval "lt_\$var=\\\\\\"\\\`\\\$ECHO \\"\\\$\$var\\" | \\\$SED \\"\\\$sed_quote_subst\\"\\\`\\\\\\"" ;; *) eval "lt_\$var=\\\\\\"\\\$\$var\\\\\\"" ;; esac done # Double-quote double-evaled strings. for var in lt_decl_all_varnames([[ \ ]], lt_decl_dquote_varnames); do case \`eval \\\\\$ECHO \\\\""\\\\\$\$var"\\\\"\` in *[[\\\\\\\`\\"\\\$]]*) eval "lt_\$var=\\\\\\"\\\`\\\$ECHO \\"\\\$\$var\\" | \\\$SED -e \\"\\\$double_quote_subst\\" -e \\"\\\$sed_quote_subst\\" -e \\"\\\$delay_variable_subst\\"\\\`\\\\\\"" ;; *) eval "lt_\$var=\\\\\\"\\\$\$var\\\\\\"" ;; esac done _LT_OUTPUT_LIBTOOL_INIT ]) # _LT_GENERATED_FILE_INIT(FILE, [COMMENT]) # ------------------------------------ # Generate a child script FILE with all initialization necessary to # reuse the environment learned by the parent script, and make the # file executable. If COMMENT is supplied, it is inserted after the # `#!' sequence but before initialization text begins. After this # macro, additional text can be appended to FILE to form the body of # the child script. The macro ends with non-zero status if the # file could not be fully written (such as if the disk is full). m4_ifdef([AS_INIT_GENERATED], [m4_defun([_LT_GENERATED_FILE_INIT],[AS_INIT_GENERATED($@)])], [m4_defun([_LT_GENERATED_FILE_INIT], [m4_require([AS_PREPARE])]dnl [m4_pushdef([AS_MESSAGE_LOG_FD])]dnl [lt_write_fail=0 cat >$1 <<_ASEOF || lt_write_fail=1 #! $SHELL # Generated by $as_me. $2 SHELL=\${CONFIG_SHELL-$SHELL} export SHELL _ASEOF cat >>$1 <<\_ASEOF || lt_write_fail=1 AS_SHELL_SANITIZE _AS_PREPARE exec AS_MESSAGE_FD>&1 _ASEOF test $lt_write_fail = 0 && chmod +x $1[]dnl m4_popdef([AS_MESSAGE_LOG_FD])])])# _LT_GENERATED_FILE_INIT # LT_OUTPUT # --------- # This macro allows early generation of the libtool script (before # AC_OUTPUT is called), incase it is used in configure for compilation # tests. AC_DEFUN([LT_OUTPUT], [: ${CONFIG_LT=./config.lt} AC_MSG_NOTICE([creating $CONFIG_LT]) _LT_GENERATED_FILE_INIT(["$CONFIG_LT"], [# Run this file to recreate a libtool stub with the current configuration.]) cat >>"$CONFIG_LT" <<\_LTEOF lt_cl_silent=false exec AS_MESSAGE_LOG_FD>>config.log { echo AS_BOX([Running $as_me.]) } >&AS_MESSAGE_LOG_FD lt_cl_help="\ \`$as_me' creates a local libtool stub from the current configuration, for use in further configure time tests before the real libtool is generated. Usage: $[0] [[OPTIONS]] -h, --help print this help, then exit -V, --version print version number, then exit -q, --quiet do not print progress messages -d, --debug don't remove temporary files Report bugs to ." lt_cl_version="\ m4_ifset([AC_PACKAGE_NAME], [AC_PACKAGE_NAME ])config.lt[]dnl m4_ifset([AC_PACKAGE_VERSION], [ AC_PACKAGE_VERSION]) configured by $[0], generated by m4_PACKAGE_STRING. Copyright (C) 2011 Free Software Foundation, Inc. This config.lt script is free software; the Free Software Foundation gives unlimited permision to copy, distribute and modify it." while test $[#] != 0 do case $[1] in --version | --v* | -V ) echo "$lt_cl_version"; exit 0 ;; --help | --h* | -h ) echo "$lt_cl_help"; exit 0 ;; --debug | --d* | -d ) debug=: ;; --quiet | --q* | --silent | --s* | -q ) lt_cl_silent=: ;; -*) AC_MSG_ERROR([unrecognized option: $[1] Try \`$[0] --help' for more information.]) ;; *) AC_MSG_ERROR([unrecognized argument: $[1] Try \`$[0] --help' for more information.]) ;; esac shift done if $lt_cl_silent; then exec AS_MESSAGE_FD>/dev/null fi _LTEOF cat >>"$CONFIG_LT" <<_LTEOF _LT_OUTPUT_LIBTOOL_COMMANDS_INIT _LTEOF cat >>"$CONFIG_LT" <<\_LTEOF AC_MSG_NOTICE([creating $ofile]) _LT_OUTPUT_LIBTOOL_COMMANDS AS_EXIT(0) _LTEOF chmod +x "$CONFIG_LT" # configure is writing to config.log, but config.lt does its own redirection, # appending to config.log, which fails on DOS, as config.log is still kept # open by configure. Here we exec the FD to /dev/null, effectively closing # config.log, so it can be properly (re)opened and appended to by config.lt. lt_cl_success=: test "$silent" = yes && lt_config_lt_args="$lt_config_lt_args --quiet" exec AS_MESSAGE_LOG_FD>/dev/null $SHELL "$CONFIG_LT" $lt_config_lt_args || lt_cl_success=false exec AS_MESSAGE_LOG_FD>>config.log $lt_cl_success || AS_EXIT(1) ])# LT_OUTPUT # _LT_CONFIG(TAG) # --------------- # If TAG is the built-in tag, create an initial libtool script with a # default configuration from the untagged config vars. Otherwise add code # to config.status for appending the configuration named by TAG from the # matching tagged config vars. m4_defun([_LT_CONFIG], [m4_require([_LT_FILEUTILS_DEFAULTS])dnl _LT_CONFIG_SAVE_COMMANDS([ m4_define([_LT_TAG], m4_if([$1], [], [C], [$1]))dnl m4_if(_LT_TAG, [C], [ # See if we are running on zsh, and set the options which allow our # commands through without removal of \ escapes. if test -n "${ZSH_VERSION+set}" ; then setopt NO_GLOB_SUBST fi cfgfile="${ofile}T" trap "$RM \"$cfgfile\"; exit 1" 1 2 15 $RM "$cfgfile" cat <<_LT_EOF >> "$cfgfile" #! $SHELL # `$ECHO "$ofile" | sed 's%^.*/%%'` - Provide generalized library-building support services. # Generated automatically by $as_me ($PACKAGE$TIMESTAMP) $VERSION # Libtool was configured on host `(hostname || uname -n) 2>/dev/null | sed 1q`: # NOTE: Changes made to this file will be lost: look at ltmain.sh. # _LT_COPYING _LT_LIBTOOL_TAGS # ### BEGIN LIBTOOL CONFIG _LT_LIBTOOL_CONFIG_VARS _LT_LIBTOOL_TAG_VARS # ### END LIBTOOL CONFIG _LT_EOF case $host_os in aix3*) cat <<\_LT_EOF >> "$cfgfile" # AIX sometimes has problems with the GCC collect2 program. For some # reason, if we set the COLLECT_NAMES environment variable, the problems # vanish in a puff of smoke. if test "X${COLLECT_NAMES+set}" != Xset; then COLLECT_NAMES= export COLLECT_NAMES fi _LT_EOF ;; esac _LT_PROG_LTMAIN # We use sed instead of cat because bash on DJGPP gets confused if # if finds mixed CR/LF and LF-only lines. Since sed operates in # text mode, it properly converts lines to CR/LF. This bash problem # is reportedly fixed, but why not run on old versions too? sed '$q' "$ltmain" >> "$cfgfile" \ || (rm -f "$cfgfile"; exit 1) _LT_PROG_REPLACE_SHELLFNS mv -f "$cfgfile" "$ofile" || (rm -f "$ofile" && cp "$cfgfile" "$ofile" && rm -f "$cfgfile") chmod +x "$ofile" ], [cat <<_LT_EOF >> "$ofile" dnl Unfortunately we have to use $1 here, since _LT_TAG is not expanded dnl in a comment (ie after a #). # ### BEGIN LIBTOOL TAG CONFIG: $1 _LT_LIBTOOL_TAG_VARS(_LT_TAG) # ### END LIBTOOL TAG CONFIG: $1 _LT_EOF ])dnl /m4_if ], [m4_if([$1], [], [ PACKAGE='$PACKAGE' VERSION='$VERSION' TIMESTAMP='$TIMESTAMP' RM='$RM' ofile='$ofile'], []) ])dnl /_LT_CONFIG_SAVE_COMMANDS ])# _LT_CONFIG # LT_SUPPORTED_TAG(TAG) # --------------------- # Trace this macro to discover what tags are supported by the libtool # --tag option, using: # autoconf --trace 'LT_SUPPORTED_TAG:$1' AC_DEFUN([LT_SUPPORTED_TAG], []) # C support is built-in for now m4_define([_LT_LANG_C_enabled], []) m4_define([_LT_TAGS], []) # LT_LANG(LANG) # ------------- # Enable libtool support for the given language if not already enabled. AC_DEFUN([LT_LANG], [AC_BEFORE([$0], [LT_OUTPUT])dnl m4_case([$1], [C], [_LT_LANG(C)], [C++], [_LT_LANG(CXX)], [Go], [_LT_LANG(GO)], [Java], [_LT_LANG(GCJ)], [Fortran 77], [_LT_LANG(F77)], [Fortran], [_LT_LANG(FC)], [Windows Resource], [_LT_LANG(RC)], [m4_ifdef([_LT_LANG_]$1[_CONFIG], [_LT_LANG($1)], [m4_fatal([$0: unsupported language: "$1"])])])dnl ])# LT_LANG # _LT_LANG(LANGNAME) # ------------------ m4_defun([_LT_LANG], [m4_ifdef([_LT_LANG_]$1[_enabled], [], [LT_SUPPORTED_TAG([$1])dnl m4_append([_LT_TAGS], [$1 ])dnl m4_define([_LT_LANG_]$1[_enabled], [])dnl _LT_LANG_$1_CONFIG($1)])dnl ])# _LT_LANG m4_ifndef([AC_PROG_GO], [ ############################################################ # NOTE: This macro has been submitted for inclusion into # # GNU Autoconf as AC_PROG_GO. When it is available in # # a released version of Autoconf we should remove this # # macro and use it instead. # ############################################################ m4_defun([AC_PROG_GO], [AC_LANG_PUSH(Go)dnl AC_ARG_VAR([GOC], [Go compiler command])dnl AC_ARG_VAR([GOFLAGS], [Go compiler flags])dnl _AC_ARG_VAR_LDFLAGS()dnl AC_CHECK_TOOL(GOC, gccgo) if test -z "$GOC"; then if test -n "$ac_tool_prefix"; then AC_CHECK_PROG(GOC, [${ac_tool_prefix}gccgo], [${ac_tool_prefix}gccgo]) fi fi if test -z "$GOC"; then AC_CHECK_PROG(GOC, gccgo, gccgo, false) fi ])#m4_defun ])#m4_ifndef # _LT_LANG_DEFAULT_CONFIG # ----------------------- m4_defun([_LT_LANG_DEFAULT_CONFIG], [AC_PROVIDE_IFELSE([AC_PROG_CXX], [LT_LANG(CXX)], [m4_define([AC_PROG_CXX], defn([AC_PROG_CXX])[LT_LANG(CXX)])]) AC_PROVIDE_IFELSE([AC_PROG_F77], [LT_LANG(F77)], [m4_define([AC_PROG_F77], defn([AC_PROG_F77])[LT_LANG(F77)])]) AC_PROVIDE_IFELSE([AC_PROG_FC], [LT_LANG(FC)], [m4_define([AC_PROG_FC], defn([AC_PROG_FC])[LT_LANG(FC)])]) dnl The call to [A][M_PROG_GCJ] is quoted like that to stop aclocal dnl pulling things in needlessly. AC_PROVIDE_IFELSE([AC_PROG_GCJ], [LT_LANG(GCJ)], [AC_PROVIDE_IFELSE([A][M_PROG_GCJ], [LT_LANG(GCJ)], [AC_PROVIDE_IFELSE([LT_PROG_GCJ], [LT_LANG(GCJ)], [m4_ifdef([AC_PROG_GCJ], [m4_define([AC_PROG_GCJ], defn([AC_PROG_GCJ])[LT_LANG(GCJ)])]) m4_ifdef([A][M_PROG_GCJ], [m4_define([A][M_PROG_GCJ], defn([A][M_PROG_GCJ])[LT_LANG(GCJ)])]) m4_ifdef([LT_PROG_GCJ], [m4_define([LT_PROG_GCJ], defn([LT_PROG_GCJ])[LT_LANG(GCJ)])])])])]) AC_PROVIDE_IFELSE([AC_PROG_GO], [LT_LANG(GO)], [m4_define([AC_PROG_GO], defn([AC_PROG_GO])[LT_LANG(GO)])]) AC_PROVIDE_IFELSE([LT_PROG_RC], [LT_LANG(RC)], [m4_define([LT_PROG_RC], defn([LT_PROG_RC])[LT_LANG(RC)])]) ])# _LT_LANG_DEFAULT_CONFIG # Obsolete macros: AU_DEFUN([AC_LIBTOOL_CXX], [LT_LANG(C++)]) AU_DEFUN([AC_LIBTOOL_F77], [LT_LANG(Fortran 77)]) AU_DEFUN([AC_LIBTOOL_FC], [LT_LANG(Fortran)]) AU_DEFUN([AC_LIBTOOL_GCJ], [LT_LANG(Java)]) AU_DEFUN([AC_LIBTOOL_RC], [LT_LANG(Windows Resource)]) dnl aclocal-1.4 backwards compatibility: dnl AC_DEFUN([AC_LIBTOOL_CXX], []) dnl AC_DEFUN([AC_LIBTOOL_F77], []) dnl AC_DEFUN([AC_LIBTOOL_FC], []) dnl AC_DEFUN([AC_LIBTOOL_GCJ], []) dnl AC_DEFUN([AC_LIBTOOL_RC], []) # _LT_TAG_COMPILER # ---------------- m4_defun([_LT_TAG_COMPILER], [AC_REQUIRE([AC_PROG_CC])dnl _LT_DECL([LTCC], [CC], [1], [A C compiler])dnl _LT_DECL([LTCFLAGS], [CFLAGS], [1], [LTCC compiler flags])dnl _LT_TAGDECL([CC], [compiler], [1], [A language specific compiler])dnl _LT_TAGDECL([with_gcc], [GCC], [0], [Is the compiler the GNU compiler?])dnl # If no C compiler was specified, use CC. LTCC=${LTCC-"$CC"} # If no C compiler flags were specified, use CFLAGS. LTCFLAGS=${LTCFLAGS-"$CFLAGS"} # Allow CC to be a program name with arguments. compiler=$CC ])# _LT_TAG_COMPILER # _LT_COMPILER_BOILERPLATE # ------------------------ # Check for compiler boilerplate output or warnings with # the simple compiler test code. m4_defun([_LT_COMPILER_BOILERPLATE], [m4_require([_LT_DECL_SED])dnl ac_outfile=conftest.$ac_objext echo "$lt_simple_compile_test_code" >conftest.$ac_ext eval "$ac_compile" 2>&1 >/dev/null | $SED '/^$/d; /^ *+/d' >conftest.err _lt_compiler_boilerplate=`cat conftest.err` $RM conftest* ])# _LT_COMPILER_BOILERPLATE # _LT_LINKER_BOILERPLATE # ---------------------- # Check for linker boilerplate output or warnings with # the simple link test code. m4_defun([_LT_LINKER_BOILERPLATE], [m4_require([_LT_DECL_SED])dnl ac_outfile=conftest.$ac_objext echo "$lt_simple_link_test_code" >conftest.$ac_ext eval "$ac_link" 2>&1 >/dev/null | $SED '/^$/d; /^ *+/d' >conftest.err _lt_linker_boilerplate=`cat conftest.err` $RM -r conftest* ])# _LT_LINKER_BOILERPLATE # _LT_REQUIRED_DARWIN_CHECKS # ------------------------- m4_defun_once([_LT_REQUIRED_DARWIN_CHECKS],[ case $host_os in rhapsody* | darwin*) AC_CHECK_TOOL([DSYMUTIL], [dsymutil], [:]) AC_CHECK_TOOL([NMEDIT], [nmedit], [:]) AC_CHECK_TOOL([LIPO], [lipo], [:]) AC_CHECK_TOOL([OTOOL], [otool], [:]) AC_CHECK_TOOL([OTOOL64], [otool64], [:]) _LT_DECL([], [DSYMUTIL], [1], [Tool to manipulate archived DWARF debug symbol files on Mac OS X]) _LT_DECL([], [NMEDIT], [1], [Tool to change global to local symbols on Mac OS X]) _LT_DECL([], [LIPO], [1], [Tool to manipulate fat objects and archives on Mac OS X]) _LT_DECL([], [OTOOL], [1], [ldd/readelf like tool for Mach-O binaries on Mac OS X]) _LT_DECL([], [OTOOL64], [1], [ldd/readelf like tool for 64 bit Mach-O binaries on Mac OS X 10.4]) AC_CACHE_CHECK([for -single_module linker flag],[lt_cv_apple_cc_single_mod], [lt_cv_apple_cc_single_mod=no if test -z "${LT_MULTI_MODULE}"; then # By default we will add the -single_module flag. You can override # by either setting the environment variable LT_MULTI_MODULE # non-empty at configure time, or by adding -multi_module to the # link flags. rm -rf libconftest.dylib* echo "int foo(void){return 1;}" > conftest.c echo "$LTCC $LTCFLAGS $LDFLAGS -o libconftest.dylib \ -dynamiclib -Wl,-single_module conftest.c" >&AS_MESSAGE_LOG_FD $LTCC $LTCFLAGS $LDFLAGS -o libconftest.dylib \ -dynamiclib -Wl,-single_module conftest.c 2>conftest.err _lt_result=$? # If there is a non-empty error log, and "single_module" # appears in it, assume the flag caused a linker warning if test -s conftest.err && $GREP single_module conftest.err; then cat conftest.err >&AS_MESSAGE_LOG_FD # Otherwise, if the output was created with a 0 exit code from # the compiler, it worked. elif test -f libconftest.dylib && test $_lt_result -eq 0; then lt_cv_apple_cc_single_mod=yes else cat conftest.err >&AS_MESSAGE_LOG_FD fi rm -rf libconftest.dylib* rm -f conftest.* fi]) AC_CACHE_CHECK([for -exported_symbols_list linker flag], [lt_cv_ld_exported_symbols_list], [lt_cv_ld_exported_symbols_list=no save_LDFLAGS=$LDFLAGS echo "_main" > conftest.sym LDFLAGS="$LDFLAGS -Wl,-exported_symbols_list,conftest.sym" AC_LINK_IFELSE([AC_LANG_PROGRAM([],[])], [lt_cv_ld_exported_symbols_list=yes], [lt_cv_ld_exported_symbols_list=no]) LDFLAGS="$save_LDFLAGS" ]) AC_CACHE_CHECK([for -force_load linker flag],[lt_cv_ld_force_load], [lt_cv_ld_force_load=no cat > conftest.c << _LT_EOF int forced_loaded() { return 2;} _LT_EOF echo "$LTCC $LTCFLAGS -c -o conftest.o conftest.c" >&AS_MESSAGE_LOG_FD $LTCC $LTCFLAGS -c -o conftest.o conftest.c 2>&AS_MESSAGE_LOG_FD echo "$AR cru libconftest.a conftest.o" >&AS_MESSAGE_LOG_FD $AR cru libconftest.a conftest.o 2>&AS_MESSAGE_LOG_FD echo "$RANLIB libconftest.a" >&AS_MESSAGE_LOG_FD $RANLIB libconftest.a 2>&AS_MESSAGE_LOG_FD cat > conftest.c << _LT_EOF int main() { return 0;} _LT_EOF echo "$LTCC $LTCFLAGS $LDFLAGS -o conftest conftest.c -Wl,-force_load,./libconftest.a" >&AS_MESSAGE_LOG_FD $LTCC $LTCFLAGS $LDFLAGS -o conftest conftest.c -Wl,-force_load,./libconftest.a 2>conftest.err _lt_result=$? if test -s conftest.err && $GREP force_load conftest.err; then cat conftest.err >&AS_MESSAGE_LOG_FD elif test -f conftest && test $_lt_result -eq 0 && $GREP forced_load conftest >/dev/null 2>&1 ; then lt_cv_ld_force_load=yes else cat conftest.err >&AS_MESSAGE_LOG_FD fi rm -f conftest.err libconftest.a conftest conftest.c rm -rf conftest.dSYM ]) case $host_os in rhapsody* | darwin1.[[012]]) _lt_dar_allow_undefined='${wl}-undefined ${wl}suppress' ;; darwin1.*) _lt_dar_allow_undefined='${wl}-flat_namespace ${wl}-undefined ${wl}suppress' ;; darwin*) # darwin 5.x on # if running on 10.5 or later, the deployment target defaults # to the OS version, if on x86, and 10.4, the deployment # target defaults to 10.4. Don't you love it? case ${MACOSX_DEPLOYMENT_TARGET-10.0},$host in 10.0,*86*-darwin8*|10.0,*-darwin[[91]]*) _lt_dar_allow_undefined='${wl}-undefined ${wl}dynamic_lookup' ;; 10.[[012]]*) _lt_dar_allow_undefined='${wl}-flat_namespace ${wl}-undefined ${wl}suppress' ;; 10.*) _lt_dar_allow_undefined='${wl}-undefined ${wl}dynamic_lookup' ;; esac ;; esac if test "$lt_cv_apple_cc_single_mod" = "yes"; then _lt_dar_single_mod='$single_module' fi if test "$lt_cv_ld_exported_symbols_list" = "yes"; then _lt_dar_export_syms=' ${wl}-exported_symbols_list,$output_objdir/${libname}-symbols.expsym' else _lt_dar_export_syms='~$NMEDIT -s $output_objdir/${libname}-symbols.expsym ${lib}' fi if test "$DSYMUTIL" != ":" && test "$lt_cv_ld_force_load" = "no"; then _lt_dsymutil='~$DSYMUTIL $lib || :' else _lt_dsymutil= fi ;; esac ]) # _LT_DARWIN_LINKER_FEATURES([TAG]) # --------------------------------- # Checks for linker and compiler features on darwin m4_defun([_LT_DARWIN_LINKER_FEATURES], [ m4_require([_LT_REQUIRED_DARWIN_CHECKS]) _LT_TAGVAR(archive_cmds_need_lc, $1)=no _LT_TAGVAR(hardcode_direct, $1)=no _LT_TAGVAR(hardcode_automatic, $1)=yes _LT_TAGVAR(hardcode_shlibpath_var, $1)=unsupported if test "$lt_cv_ld_force_load" = "yes"; then _LT_TAGVAR(whole_archive_flag_spec, $1)='`for conv in $convenience\"\"; do test -n \"$conv\" && new_convenience=\"$new_convenience ${wl}-force_load,$conv\"; done; func_echo_all \"$new_convenience\"`' m4_case([$1], [F77], [_LT_TAGVAR(compiler_needs_object, $1)=yes], [FC], [_LT_TAGVAR(compiler_needs_object, $1)=yes]) else _LT_TAGVAR(whole_archive_flag_spec, $1)='' fi _LT_TAGVAR(link_all_deplibs, $1)=yes _LT_TAGVAR(allow_undefined_flag, $1)="$_lt_dar_allow_undefined" case $cc_basename in ifort*) _lt_dar_can_shared=yes ;; *) _lt_dar_can_shared=$GCC ;; esac if test "$_lt_dar_can_shared" = "yes"; then output_verbose_link_cmd=func_echo_all _LT_TAGVAR(archive_cmds, $1)="\$CC -dynamiclib \$allow_undefined_flag -o \$lib \$libobjs \$deplibs \$compiler_flags -install_name \$rpath/\$soname \$verstring $_lt_dar_single_mod${_lt_dsymutil}" _LT_TAGVAR(module_cmds, $1)="\$CC \$allow_undefined_flag -o \$lib -bundle \$libobjs \$deplibs \$compiler_flags${_lt_dsymutil}" _LT_TAGVAR(archive_expsym_cmds, $1)="sed 's,^,_,' < \$export_symbols > \$output_objdir/\${libname}-symbols.expsym~\$CC -dynamiclib \$allow_undefined_flag -o \$lib \$libobjs \$deplibs \$compiler_flags -install_name \$rpath/\$soname \$verstring ${_lt_dar_single_mod}${_lt_dar_export_syms}${_lt_dsymutil}" _LT_TAGVAR(module_expsym_cmds, $1)="sed -e 's,^,_,' < \$export_symbols > \$output_objdir/\${libname}-symbols.expsym~\$CC \$allow_undefined_flag -o \$lib -bundle \$libobjs \$deplibs \$compiler_flags${_lt_dar_export_syms}${_lt_dsymutil}" m4_if([$1], [CXX], [ if test "$lt_cv_apple_cc_single_mod" != "yes"; then _LT_TAGVAR(archive_cmds, $1)="\$CC -r -keep_private_externs -nostdlib -o \${lib}-master.o \$libobjs~\$CC -dynamiclib \$allow_undefined_flag -o \$lib \${lib}-master.o \$deplibs \$compiler_flags -install_name \$rpath/\$soname \$verstring${_lt_dsymutil}" _LT_TAGVAR(archive_expsym_cmds, $1)="sed 's,^,_,' < \$export_symbols > \$output_objdir/\${libname}-symbols.expsym~\$CC -r -keep_private_externs -nostdlib -o \${lib}-master.o \$libobjs~\$CC -dynamiclib \$allow_undefined_flag -o \$lib \${lib}-master.o \$deplibs \$compiler_flags -install_name \$rpath/\$soname \$verstring${_lt_dar_export_syms}${_lt_dsymutil}" fi ],[]) else _LT_TAGVAR(ld_shlibs, $1)=no fi ]) # _LT_SYS_MODULE_PATH_AIX([TAGNAME]) # ---------------------------------- # Links a minimal program and checks the executable # for the system default hardcoded library path. In most cases, # this is /usr/lib:/lib, but when the MPI compilers are used # the location of the communication and MPI libs are included too. # If we don't find anything, use the default library path according # to the aix ld manual. # Store the results from the different compilers for each TAGNAME. # Allow to override them for all tags through lt_cv_aix_libpath. m4_defun([_LT_SYS_MODULE_PATH_AIX], [m4_require([_LT_DECL_SED])dnl if test "${lt_cv_aix_libpath+set}" = set; then aix_libpath=$lt_cv_aix_libpath else AC_CACHE_VAL([_LT_TAGVAR([lt_cv_aix_libpath_], [$1])], [AC_LINK_IFELSE([AC_LANG_PROGRAM],[ lt_aix_libpath_sed='[ /Import File Strings/,/^$/ { /^0/ { s/^0 *\([^ ]*\) *$/\1/ p } }]' _LT_TAGVAR([lt_cv_aix_libpath_], [$1])=`dump -H conftest$ac_exeext 2>/dev/null | $SED -n -e "$lt_aix_libpath_sed"` # Check for a 64-bit object if we didn't find anything. if test -z "$_LT_TAGVAR([lt_cv_aix_libpath_], [$1])"; then _LT_TAGVAR([lt_cv_aix_libpath_], [$1])=`dump -HX64 conftest$ac_exeext 2>/dev/null | $SED -n -e "$lt_aix_libpath_sed"` fi],[]) if test -z "$_LT_TAGVAR([lt_cv_aix_libpath_], [$1])"; then _LT_TAGVAR([lt_cv_aix_libpath_], [$1])="/usr/lib:/lib" fi ]) aix_libpath=$_LT_TAGVAR([lt_cv_aix_libpath_], [$1]) fi ])# _LT_SYS_MODULE_PATH_AIX # _LT_SHELL_INIT(ARG) # ------------------- m4_define([_LT_SHELL_INIT], [m4_divert_text([M4SH-INIT], [$1 ])])# _LT_SHELL_INIT # _LT_PROG_ECHO_BACKSLASH # ----------------------- # Find how we can fake an echo command that does not interpret backslash. # In particular, with Autoconf 2.60 or later we add some code to the start # of the generated configure script which will find a shell with a builtin # printf (which we can use as an echo command). m4_defun([_LT_PROG_ECHO_BACKSLASH], [ECHO='\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\' ECHO=$ECHO$ECHO$ECHO$ECHO$ECHO ECHO=$ECHO$ECHO$ECHO$ECHO$ECHO$ECHO AC_MSG_CHECKING([how to print strings]) # Test print first, because it will be a builtin if present. if test "X`( print -r -- -n ) 2>/dev/null`" = X-n && \ test "X`print -r -- $ECHO 2>/dev/null`" = "X$ECHO"; then ECHO='print -r --' elif test "X`printf %s $ECHO 2>/dev/null`" = "X$ECHO"; then ECHO='printf %s\n' else # Use this function as a fallback that always works. func_fallback_echo () { eval 'cat <<_LTECHO_EOF $[]1 _LTECHO_EOF' } ECHO='func_fallback_echo' fi # func_echo_all arg... # Invoke $ECHO with all args, space-separated. func_echo_all () { $ECHO "$*" } case "$ECHO" in printf*) AC_MSG_RESULT([printf]) ;; print*) AC_MSG_RESULT([print -r]) ;; *) AC_MSG_RESULT([cat]) ;; esac m4_ifdef([_AS_DETECT_SUGGESTED], [_AS_DETECT_SUGGESTED([ test -n "${ZSH_VERSION+set}${BASH_VERSION+set}" || ( ECHO='\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\' ECHO=$ECHO$ECHO$ECHO$ECHO$ECHO ECHO=$ECHO$ECHO$ECHO$ECHO$ECHO$ECHO PATH=/empty FPATH=/empty; export PATH FPATH test "X`printf %s $ECHO`" = "X$ECHO" \ || test "X`print -r -- $ECHO`" = "X$ECHO" )])]) _LT_DECL([], [SHELL], [1], [Shell to use when invoking shell scripts]) _LT_DECL([], [ECHO], [1], [An echo program that protects backslashes]) ])# _LT_PROG_ECHO_BACKSLASH # _LT_WITH_SYSROOT # ---------------- AC_DEFUN([_LT_WITH_SYSROOT], [AC_MSG_CHECKING([for sysroot]) AC_ARG_WITH([sysroot], [ --with-sysroot[=DIR] Search for dependent libraries within DIR (or the compiler's sysroot if not specified).], [], [with_sysroot=no]) dnl lt_sysroot will always be passed unquoted. We quote it here dnl in case the user passed a directory name. lt_sysroot= case ${with_sysroot} in #( yes) if test "$GCC" = yes; then lt_sysroot=`$CC --print-sysroot 2>/dev/null` fi ;; #( /*) lt_sysroot=`echo "$with_sysroot" | sed -e "$sed_quote_subst"` ;; #( no|'') ;; #( *) AC_MSG_RESULT([${with_sysroot}]) AC_MSG_ERROR([The sysroot must be an absolute path.]) ;; esac AC_MSG_RESULT([${lt_sysroot:-no}]) _LT_DECL([], [lt_sysroot], [0], [The root where to search for ]dnl [dependent libraries, and in which our libraries should be installed.])]) # _LT_ENABLE_LOCK # --------------- m4_defun([_LT_ENABLE_LOCK], [AC_ARG_ENABLE([libtool-lock], [AS_HELP_STRING([--disable-libtool-lock], [avoid locking (might break parallel builds)])]) test "x$enable_libtool_lock" != xno && enable_libtool_lock=yes # Some flags need to be propagated to the compiler or linker for good # libtool support. case $host in ia64-*-hpux*) # Find out which ABI we are using. echo 'int i;' > conftest.$ac_ext if AC_TRY_EVAL(ac_compile); then case `/usr/bin/file conftest.$ac_objext` in *ELF-32*) HPUX_IA64_MODE="32" ;; *ELF-64*) HPUX_IA64_MODE="64" ;; esac fi rm -rf conftest* ;; *-*-irix6*) # Find out which ABI we are using. echo '[#]line '$LINENO' "configure"' > conftest.$ac_ext if AC_TRY_EVAL(ac_compile); then if test "$lt_cv_prog_gnu_ld" = yes; then case `/usr/bin/file conftest.$ac_objext` in *32-bit*) LD="${LD-ld} -melf32bsmip" ;; *N32*) LD="${LD-ld} -melf32bmipn32" ;; *64-bit*) LD="${LD-ld} -melf64bmip" ;; esac else case `/usr/bin/file conftest.$ac_objext` in *32-bit*) LD="${LD-ld} -32" ;; *N32*) LD="${LD-ld} -n32" ;; *64-bit*) LD="${LD-ld} -64" ;; esac fi fi rm -rf conftest* ;; x86_64-*kfreebsd*-gnu|x86_64-*linux*|ppc*-*linux*|powerpc*-*linux*| \ s390*-*linux*|s390*-*tpf*|sparc*-*linux*) # Find out which ABI we are using. echo 'int i;' > conftest.$ac_ext if AC_TRY_EVAL(ac_compile); then case `/usr/bin/file conftest.o` in *32-bit*) case $host in x86_64-*kfreebsd*-gnu) LD="${LD-ld} -m elf_i386_fbsd" ;; x86_64-*linux*) LD="${LD-ld} -m elf_i386" ;; ppc64-*linux*|powerpc64-*linux*) LD="${LD-ld} -m elf32ppclinux" ;; s390x-*linux*) LD="${LD-ld} -m elf_s390" ;; sparc64-*linux*) LD="${LD-ld} -m elf32_sparc" ;; esac ;; *64-bit*) case $host in x86_64-*kfreebsd*-gnu) LD="${LD-ld} -m elf_x86_64_fbsd" ;; x86_64-*linux*) LD="${LD-ld} -m elf_x86_64" ;; ppc*-*linux*|powerpc*-*linux*) LD="${LD-ld} -m elf64ppc" ;; s390*-*linux*|s390*-*tpf*) LD="${LD-ld} -m elf64_s390" ;; sparc*-*linux*) LD="${LD-ld} -m elf64_sparc" ;; esac ;; esac fi rm -rf conftest* ;; *-*-sco3.2v5*) # On SCO OpenServer 5, we need -belf to get full-featured binaries. SAVE_CFLAGS="$CFLAGS" CFLAGS="$CFLAGS -belf" AC_CACHE_CHECK([whether the C compiler needs -belf], lt_cv_cc_needs_belf, [AC_LANG_PUSH(C) AC_LINK_IFELSE([AC_LANG_PROGRAM([[]],[[]])],[lt_cv_cc_needs_belf=yes],[lt_cv_cc_needs_belf=no]) AC_LANG_POP]) if test x"$lt_cv_cc_needs_belf" != x"yes"; then # this is probably gcc 2.8.0, egcs 1.0 or newer; no need for -belf CFLAGS="$SAVE_CFLAGS" fi ;; *-*solaris*) # Find out which ABI we are using. echo 'int i;' > conftest.$ac_ext if AC_TRY_EVAL(ac_compile); then case `/usr/bin/file conftest.o` in *64-bit*) case $lt_cv_prog_gnu_ld in yes*) case $host in i?86-*-solaris*) LD="${LD-ld} -m elf_x86_64" ;; sparc*-*-solaris*) LD="${LD-ld} -m elf64_sparc" ;; esac # GNU ld 2.21 introduced _sol2 emulations. Use them if available. if ${LD-ld} -V | grep _sol2 >/dev/null 2>&1; then LD="${LD-ld}_sol2" fi ;; *) if ${LD-ld} -64 -r -o conftest2.o conftest.o >/dev/null 2>&1; then LD="${LD-ld} -64" fi ;; esac ;; esac fi rm -rf conftest* ;; esac need_locks="$enable_libtool_lock" ])# _LT_ENABLE_LOCK # _LT_PROG_AR # ----------- m4_defun([_LT_PROG_AR], [AC_CHECK_TOOLS(AR, [ar], false) : ${AR=ar} : ${AR_FLAGS=cru} _LT_DECL([], [AR], [1], [The archiver]) _LT_DECL([], [AR_FLAGS], [1], [Flags to create an archive]) AC_CACHE_CHECK([for archiver @FILE support], [lt_cv_ar_at_file], [lt_cv_ar_at_file=no AC_COMPILE_IFELSE([AC_LANG_PROGRAM], [echo conftest.$ac_objext > conftest.lst lt_ar_try='$AR $AR_FLAGS libconftest.a @conftest.lst >&AS_MESSAGE_LOG_FD' AC_TRY_EVAL([lt_ar_try]) if test "$ac_status" -eq 0; then # Ensure the archiver fails upon bogus file names. rm -f conftest.$ac_objext libconftest.a AC_TRY_EVAL([lt_ar_try]) if test "$ac_status" -ne 0; then lt_cv_ar_at_file=@ fi fi rm -f conftest.* libconftest.a ]) ]) if test "x$lt_cv_ar_at_file" = xno; then archiver_list_spec= else archiver_list_spec=$lt_cv_ar_at_file fi _LT_DECL([], [archiver_list_spec], [1], [How to feed a file listing to the archiver]) ])# _LT_PROG_AR # _LT_CMD_OLD_ARCHIVE # ------------------- m4_defun([_LT_CMD_OLD_ARCHIVE], [_LT_PROG_AR AC_CHECK_TOOL(STRIP, strip, :) test -z "$STRIP" && STRIP=: _LT_DECL([], [STRIP], [1], [A symbol stripping program]) AC_CHECK_TOOL(RANLIB, ranlib, :) test -z "$RANLIB" && RANLIB=: _LT_DECL([], [RANLIB], [1], [Commands used to install an old-style archive]) # Determine commands to create old-style static archives. old_archive_cmds='$AR $AR_FLAGS $oldlib$oldobjs' old_postinstall_cmds='chmod 644 $oldlib' old_postuninstall_cmds= if test -n "$RANLIB"; then case $host_os in openbsd*) old_postinstall_cmds="$old_postinstall_cmds~\$RANLIB -t \$tool_oldlib" ;; *) old_postinstall_cmds="$old_postinstall_cmds~\$RANLIB \$tool_oldlib" ;; esac old_archive_cmds="$old_archive_cmds~\$RANLIB \$tool_oldlib" fi case $host_os in darwin*) lock_old_archive_extraction=yes ;; *) lock_old_archive_extraction=no ;; esac _LT_DECL([], [old_postinstall_cmds], [2]) _LT_DECL([], [old_postuninstall_cmds], [2]) _LT_TAGDECL([], [old_archive_cmds], [2], [Commands used to build an old-style archive]) _LT_DECL([], [lock_old_archive_extraction], [0], [Whether to use a lock for old archive extraction]) ])# _LT_CMD_OLD_ARCHIVE # _LT_COMPILER_OPTION(MESSAGE, VARIABLE-NAME, FLAGS, # [OUTPUT-FILE], [ACTION-SUCCESS], [ACTION-FAILURE]) # ---------------------------------------------------------------- # Check whether the given compiler option works AC_DEFUN([_LT_COMPILER_OPTION], [m4_require([_LT_FILEUTILS_DEFAULTS])dnl m4_require([_LT_DECL_SED])dnl AC_CACHE_CHECK([$1], [$2], [$2=no m4_if([$4], , [ac_outfile=conftest.$ac_objext], [ac_outfile=$4]) echo "$lt_simple_compile_test_code" > conftest.$ac_ext lt_compiler_flag="$3" # Insert the option either (1) after the last *FLAGS variable, or # (2) before a word containing "conftest.", or (3) at the end. # Note that $ac_compile itself does not contain backslashes and begins # with a dollar sign (not a hyphen), so the echo should work correctly. # The option is referenced via a variable to avoid confusing sed. lt_compile=`echo "$ac_compile" | $SED \ -e 's:.*FLAGS}\{0,1\} :&$lt_compiler_flag :; t' \ -e 's: [[^ ]]*conftest\.: $lt_compiler_flag&:; t' \ -e 's:$: $lt_compiler_flag:'` (eval echo "\"\$as_me:$LINENO: $lt_compile\"" >&AS_MESSAGE_LOG_FD) (eval "$lt_compile" 2>conftest.err) ac_status=$? cat conftest.err >&AS_MESSAGE_LOG_FD echo "$as_me:$LINENO: \$? = $ac_status" >&AS_MESSAGE_LOG_FD if (exit $ac_status) && test -s "$ac_outfile"; then # The compiler can only warn and ignore the option if not recognized # So say no if there are warnings other than the usual output. $ECHO "$_lt_compiler_boilerplate" | $SED '/^$/d' >conftest.exp $SED '/^$/d; /^ *+/d' conftest.err >conftest.er2 if test ! -s conftest.er2 || diff conftest.exp conftest.er2 >/dev/null; then $2=yes fi fi $RM conftest* ]) if test x"[$]$2" = xyes; then m4_if([$5], , :, [$5]) else m4_if([$6], , :, [$6]) fi ])# _LT_COMPILER_OPTION # Old name: AU_ALIAS([AC_LIBTOOL_COMPILER_OPTION], [_LT_COMPILER_OPTION]) dnl aclocal-1.4 backwards compatibility: dnl AC_DEFUN([AC_LIBTOOL_COMPILER_OPTION], []) # _LT_LINKER_OPTION(MESSAGE, VARIABLE-NAME, FLAGS, # [ACTION-SUCCESS], [ACTION-FAILURE]) # ---------------------------------------------------- # Check whether the given linker option works AC_DEFUN([_LT_LINKER_OPTION], [m4_require([_LT_FILEUTILS_DEFAULTS])dnl m4_require([_LT_DECL_SED])dnl AC_CACHE_CHECK([$1], [$2], [$2=no save_LDFLAGS="$LDFLAGS" LDFLAGS="$LDFLAGS $3" echo "$lt_simple_link_test_code" > conftest.$ac_ext if (eval $ac_link 2>conftest.err) && test -s conftest$ac_exeext; then # The linker can only warn and ignore the option if not recognized # So say no if there are warnings if test -s conftest.err; then # Append any errors to the config.log. cat conftest.err 1>&AS_MESSAGE_LOG_FD $ECHO "$_lt_linker_boilerplate" | $SED '/^$/d' > conftest.exp $SED '/^$/d; /^ *+/d' conftest.err >conftest.er2 if diff conftest.exp conftest.er2 >/dev/null; then $2=yes fi else $2=yes fi fi $RM -r conftest* LDFLAGS="$save_LDFLAGS" ]) if test x"[$]$2" = xyes; then m4_if([$4], , :, [$4]) else m4_if([$5], , :, [$5]) fi ])# _LT_LINKER_OPTION # Old name: AU_ALIAS([AC_LIBTOOL_LINKER_OPTION], [_LT_LINKER_OPTION]) dnl aclocal-1.4 backwards compatibility: dnl AC_DEFUN([AC_LIBTOOL_LINKER_OPTION], []) # LT_CMD_MAX_LEN #--------------- AC_DEFUN([LT_CMD_MAX_LEN], [AC_REQUIRE([AC_CANONICAL_HOST])dnl # find the maximum length of command line arguments AC_MSG_CHECKING([the maximum length of command line arguments]) AC_CACHE_VAL([lt_cv_sys_max_cmd_len], [dnl i=0 teststring="ABCD" case $build_os in msdosdjgpp*) # On DJGPP, this test can blow up pretty badly due to problems in libc # (any single argument exceeding 2000 bytes causes a buffer overrun # during glob expansion). Even if it were fixed, the result of this # check would be larger than it should be. lt_cv_sys_max_cmd_len=12288; # 12K is about right ;; gnu*) # Under GNU Hurd, this test is not required because there is # no limit to the length of command line arguments. # Libtool will interpret -1 as no limit whatsoever lt_cv_sys_max_cmd_len=-1; ;; cygwin* | mingw* | cegcc*) # On Win9x/ME, this test blows up -- it succeeds, but takes # about 5 minutes as the teststring grows exponentially. # Worse, since 9x/ME are not pre-emptively multitasking, # you end up with a "frozen" computer, even though with patience # the test eventually succeeds (with a max line length of 256k). # Instead, let's just punt: use the minimum linelength reported by # all of the supported platforms: 8192 (on NT/2K/XP). lt_cv_sys_max_cmd_len=8192; ;; mint*) # On MiNT this can take a long time and run out of memory. lt_cv_sys_max_cmd_len=8192; ;; amigaos*) # On AmigaOS with pdksh, this test takes hours, literally. # So we just punt and use a minimum line length of 8192. lt_cv_sys_max_cmd_len=8192; ;; netbsd* | freebsd* | openbsd* | darwin* | dragonfly*) # This has been around since 386BSD, at least. Likely further. if test -x /sbin/sysctl; then lt_cv_sys_max_cmd_len=`/sbin/sysctl -n kern.argmax` elif test -x /usr/sbin/sysctl; then lt_cv_sys_max_cmd_len=`/usr/sbin/sysctl -n kern.argmax` else lt_cv_sys_max_cmd_len=65536 # usable default for all BSDs fi # And add a safety zone lt_cv_sys_max_cmd_len=`expr $lt_cv_sys_max_cmd_len \/ 4` lt_cv_sys_max_cmd_len=`expr $lt_cv_sys_max_cmd_len \* 3` ;; interix*) # We know the value 262144 and hardcode it with a safety zone (like BSD) lt_cv_sys_max_cmd_len=196608 ;; os2*) # The test takes a long time on OS/2. lt_cv_sys_max_cmd_len=8192 ;; osf*) # Dr. Hans Ekkehard Plesser reports seeing a kernel panic running configure # due to this test when exec_disable_arg_limit is 1 on Tru64. It is not # nice to cause kernel panics so lets avoid the loop below. # First set a reasonable default. lt_cv_sys_max_cmd_len=16384 # if test -x /sbin/sysconfig; then case `/sbin/sysconfig -q proc exec_disable_arg_limit` in *1*) lt_cv_sys_max_cmd_len=-1 ;; esac fi ;; sco3.2v5*) lt_cv_sys_max_cmd_len=102400 ;; sysv5* | sco5v6* | sysv4.2uw2*) kargmax=`grep ARG_MAX /etc/conf/cf.d/stune 2>/dev/null` if test -n "$kargmax"; then lt_cv_sys_max_cmd_len=`echo $kargmax | sed 's/.*[[ ]]//'` else lt_cv_sys_max_cmd_len=32768 fi ;; *) lt_cv_sys_max_cmd_len=`(getconf ARG_MAX) 2> /dev/null` if test -n "$lt_cv_sys_max_cmd_len"; then lt_cv_sys_max_cmd_len=`expr $lt_cv_sys_max_cmd_len \/ 4` lt_cv_sys_max_cmd_len=`expr $lt_cv_sys_max_cmd_len \* 3` else # Make teststring a little bigger before we do anything with it. # a 1K string should be a reasonable start. for i in 1 2 3 4 5 6 7 8 ; do teststring=$teststring$teststring done SHELL=${SHELL-${CONFIG_SHELL-/bin/sh}} # If test is not a shell built-in, we'll probably end up computing a # maximum length that is only half of the actual maximum length, but # we can't tell. while { test "X"`env echo "$teststring$teststring" 2>/dev/null` \ = "X$teststring$teststring"; } >/dev/null 2>&1 && test $i != 17 # 1/2 MB should be enough do i=`expr $i + 1` teststring=$teststring$teststring done # Only check the string length outside the loop. lt_cv_sys_max_cmd_len=`expr "X$teststring" : ".*" 2>&1` teststring= # Add a significant safety factor because C++ compilers can tack on # massive amounts of additional arguments before passing them to the # linker. It appears as though 1/2 is a usable value. lt_cv_sys_max_cmd_len=`expr $lt_cv_sys_max_cmd_len \/ 2` fi ;; esac ]) if test -n $lt_cv_sys_max_cmd_len ; then AC_MSG_RESULT($lt_cv_sys_max_cmd_len) else AC_MSG_RESULT(none) fi max_cmd_len=$lt_cv_sys_max_cmd_len _LT_DECL([], [max_cmd_len], [0], [What is the maximum length of a command?]) ])# LT_CMD_MAX_LEN # Old name: AU_ALIAS([AC_LIBTOOL_SYS_MAX_CMD_LEN], [LT_CMD_MAX_LEN]) dnl aclocal-1.4 backwards compatibility: dnl AC_DEFUN([AC_LIBTOOL_SYS_MAX_CMD_LEN], []) # _LT_HEADER_DLFCN # ---------------- m4_defun([_LT_HEADER_DLFCN], [AC_CHECK_HEADERS([dlfcn.h], [], [], [AC_INCLUDES_DEFAULT])dnl ])# _LT_HEADER_DLFCN # _LT_TRY_DLOPEN_SELF (ACTION-IF-TRUE, ACTION-IF-TRUE-W-USCORE, # ACTION-IF-FALSE, ACTION-IF-CROSS-COMPILING) # ---------------------------------------------------------------- m4_defun([_LT_TRY_DLOPEN_SELF], [m4_require([_LT_HEADER_DLFCN])dnl if test "$cross_compiling" = yes; then : [$4] else lt_dlunknown=0; lt_dlno_uscore=1; lt_dlneed_uscore=2 lt_status=$lt_dlunknown cat > conftest.$ac_ext <<_LT_EOF [#line $LINENO "configure" #include "confdefs.h" #if HAVE_DLFCN_H #include #endif #include #ifdef RTLD_GLOBAL # define LT_DLGLOBAL RTLD_GLOBAL #else # ifdef DL_GLOBAL # define LT_DLGLOBAL DL_GLOBAL # else # define LT_DLGLOBAL 0 # endif #endif /* We may have to define LT_DLLAZY_OR_NOW in the command line if we find out it does not work in some platform. */ #ifndef LT_DLLAZY_OR_NOW # ifdef RTLD_LAZY # define LT_DLLAZY_OR_NOW RTLD_LAZY # else # ifdef DL_LAZY # define LT_DLLAZY_OR_NOW DL_LAZY # else # ifdef RTLD_NOW # define LT_DLLAZY_OR_NOW RTLD_NOW # else # ifdef DL_NOW # define LT_DLLAZY_OR_NOW DL_NOW # else # define LT_DLLAZY_OR_NOW 0 # endif # endif # endif # endif #endif /* When -fvisbility=hidden is used, assume the code has been annotated correspondingly for the symbols needed. */ #if defined(__GNUC__) && (((__GNUC__ == 3) && (__GNUC_MINOR__ >= 3)) || (__GNUC__ > 3)) int fnord () __attribute__((visibility("default"))); #endif int fnord () { return 42; } int main () { void *self = dlopen (0, LT_DLGLOBAL|LT_DLLAZY_OR_NOW); int status = $lt_dlunknown; if (self) { if (dlsym (self,"fnord")) status = $lt_dlno_uscore; else { if (dlsym( self,"_fnord")) status = $lt_dlneed_uscore; else puts (dlerror ()); } /* dlclose (self); */ } else puts (dlerror ()); return status; }] _LT_EOF if AC_TRY_EVAL(ac_link) && test -s conftest${ac_exeext} 2>/dev/null; then (./conftest; exit; ) >&AS_MESSAGE_LOG_FD 2>/dev/null lt_status=$? case x$lt_status in x$lt_dlno_uscore) $1 ;; x$lt_dlneed_uscore) $2 ;; x$lt_dlunknown|x*) $3 ;; esac else : # compilation failed $3 fi fi rm -fr conftest* ])# _LT_TRY_DLOPEN_SELF # LT_SYS_DLOPEN_SELF # ------------------ AC_DEFUN([LT_SYS_DLOPEN_SELF], [m4_require([_LT_HEADER_DLFCN])dnl if test "x$enable_dlopen" != xyes; then enable_dlopen=unknown enable_dlopen_self=unknown enable_dlopen_self_static=unknown else lt_cv_dlopen=no lt_cv_dlopen_libs= case $host_os in beos*) lt_cv_dlopen="load_add_on" lt_cv_dlopen_libs= lt_cv_dlopen_self=yes ;; mingw* | pw32* | cegcc*) lt_cv_dlopen="LoadLibrary" lt_cv_dlopen_libs= ;; cygwin*) lt_cv_dlopen="dlopen" lt_cv_dlopen_libs= ;; darwin*) # if libdl is installed we need to link against it AC_CHECK_LIB([dl], [dlopen], [lt_cv_dlopen="dlopen" lt_cv_dlopen_libs="-ldl"],[ lt_cv_dlopen="dyld" lt_cv_dlopen_libs= lt_cv_dlopen_self=yes ]) ;; *) AC_CHECK_FUNC([shl_load], [lt_cv_dlopen="shl_load"], [AC_CHECK_LIB([dld], [shl_load], [lt_cv_dlopen="shl_load" lt_cv_dlopen_libs="-ldld"], [AC_CHECK_FUNC([dlopen], [lt_cv_dlopen="dlopen"], [AC_CHECK_LIB([dl], [dlopen], [lt_cv_dlopen="dlopen" lt_cv_dlopen_libs="-ldl"], [AC_CHECK_LIB([svld], [dlopen], [lt_cv_dlopen="dlopen" lt_cv_dlopen_libs="-lsvld"], [AC_CHECK_LIB([dld], [dld_link], [lt_cv_dlopen="dld_link" lt_cv_dlopen_libs="-ldld"]) ]) ]) ]) ]) ]) ;; esac if test "x$lt_cv_dlopen" != xno; then enable_dlopen=yes else enable_dlopen=no fi case $lt_cv_dlopen in dlopen) save_CPPFLAGS="$CPPFLAGS" test "x$ac_cv_header_dlfcn_h" = xyes && CPPFLAGS="$CPPFLAGS -DHAVE_DLFCN_H" save_LDFLAGS="$LDFLAGS" wl=$lt_prog_compiler_wl eval LDFLAGS=\"\$LDFLAGS $export_dynamic_flag_spec\" save_LIBS="$LIBS" LIBS="$lt_cv_dlopen_libs $LIBS" AC_CACHE_CHECK([whether a program can dlopen itself], lt_cv_dlopen_self, [dnl _LT_TRY_DLOPEN_SELF( lt_cv_dlopen_self=yes, lt_cv_dlopen_self=yes, lt_cv_dlopen_self=no, lt_cv_dlopen_self=cross) ]) if test "x$lt_cv_dlopen_self" = xyes; then wl=$lt_prog_compiler_wl eval LDFLAGS=\"\$LDFLAGS $lt_prog_compiler_static\" AC_CACHE_CHECK([whether a statically linked program can dlopen itself], lt_cv_dlopen_self_static, [dnl _LT_TRY_DLOPEN_SELF( lt_cv_dlopen_self_static=yes, lt_cv_dlopen_self_static=yes, lt_cv_dlopen_self_static=no, lt_cv_dlopen_self_static=cross) ]) fi CPPFLAGS="$save_CPPFLAGS" LDFLAGS="$save_LDFLAGS" LIBS="$save_LIBS" ;; esac case $lt_cv_dlopen_self in yes|no) enable_dlopen_self=$lt_cv_dlopen_self ;; *) enable_dlopen_self=unknown ;; esac case $lt_cv_dlopen_self_static in yes|no) enable_dlopen_self_static=$lt_cv_dlopen_self_static ;; *) enable_dlopen_self_static=unknown ;; esac fi _LT_DECL([dlopen_support], [enable_dlopen], [0], [Whether dlopen is supported]) _LT_DECL([dlopen_self], [enable_dlopen_self], [0], [Whether dlopen of programs is supported]) _LT_DECL([dlopen_self_static], [enable_dlopen_self_static], [0], [Whether dlopen of statically linked programs is supported]) ])# LT_SYS_DLOPEN_SELF # Old name: AU_ALIAS([AC_LIBTOOL_DLOPEN_SELF], [LT_SYS_DLOPEN_SELF]) dnl aclocal-1.4 backwards compatibility: dnl AC_DEFUN([AC_LIBTOOL_DLOPEN_SELF], []) # _LT_COMPILER_C_O([TAGNAME]) # --------------------------- # Check to see if options -c and -o are simultaneously supported by compiler. # This macro does not hard code the compiler like AC_PROG_CC_C_O. m4_defun([_LT_COMPILER_C_O], [m4_require([_LT_DECL_SED])dnl m4_require([_LT_FILEUTILS_DEFAULTS])dnl m4_require([_LT_TAG_COMPILER])dnl AC_CACHE_CHECK([if $compiler supports -c -o file.$ac_objext], [_LT_TAGVAR(lt_cv_prog_compiler_c_o, $1)], [_LT_TAGVAR(lt_cv_prog_compiler_c_o, $1)=no $RM -r conftest 2>/dev/null mkdir conftest cd conftest mkdir out echo "$lt_simple_compile_test_code" > conftest.$ac_ext lt_compiler_flag="-o out/conftest2.$ac_objext" # Insert the option either (1) after the last *FLAGS variable, or # (2) before a word containing "conftest.", or (3) at the end. # Note that $ac_compile itself does not contain backslashes and begins # with a dollar sign (not a hyphen), so the echo should work correctly. lt_compile=`echo "$ac_compile" | $SED \ -e 's:.*FLAGS}\{0,1\} :&$lt_compiler_flag :; t' \ -e 's: [[^ ]]*conftest\.: $lt_compiler_flag&:; t' \ -e 's:$: $lt_compiler_flag:'` (eval echo "\"\$as_me:$LINENO: $lt_compile\"" >&AS_MESSAGE_LOG_FD) (eval "$lt_compile" 2>out/conftest.err) ac_status=$? cat out/conftest.err >&AS_MESSAGE_LOG_FD echo "$as_me:$LINENO: \$? = $ac_status" >&AS_MESSAGE_LOG_FD if (exit $ac_status) && test -s out/conftest2.$ac_objext then # The compiler can only warn and ignore the option if not recognized # So say no if there are warnings $ECHO "$_lt_compiler_boilerplate" | $SED '/^$/d' > out/conftest.exp $SED '/^$/d; /^ *+/d' out/conftest.err >out/conftest.er2 if test ! -s out/conftest.er2 || diff out/conftest.exp out/conftest.er2 >/dev/null; then _LT_TAGVAR(lt_cv_prog_compiler_c_o, $1)=yes fi fi chmod u+w . 2>&AS_MESSAGE_LOG_FD $RM conftest* # SGI C++ compiler will create directory out/ii_files/ for # template instantiation test -d out/ii_files && $RM out/ii_files/* && rmdir out/ii_files $RM out/* && rmdir out cd .. $RM -r conftest $RM conftest* ]) _LT_TAGDECL([compiler_c_o], [lt_cv_prog_compiler_c_o], [1], [Does compiler simultaneously support -c and -o options?]) ])# _LT_COMPILER_C_O # _LT_COMPILER_FILE_LOCKS([TAGNAME]) # ---------------------------------- # Check to see if we can do hard links to lock some files if needed m4_defun([_LT_COMPILER_FILE_LOCKS], [m4_require([_LT_ENABLE_LOCK])dnl m4_require([_LT_FILEUTILS_DEFAULTS])dnl _LT_COMPILER_C_O([$1]) hard_links="nottested" if test "$_LT_TAGVAR(lt_cv_prog_compiler_c_o, $1)" = no && test "$need_locks" != no; then # do not overwrite the value of need_locks provided by the user AC_MSG_CHECKING([if we can lock with hard links]) hard_links=yes $RM conftest* ln conftest.a conftest.b 2>/dev/null && hard_links=no touch conftest.a ln conftest.a conftest.b 2>&5 || hard_links=no ln conftest.a conftest.b 2>/dev/null && hard_links=no AC_MSG_RESULT([$hard_links]) if test "$hard_links" = no; then AC_MSG_WARN([`$CC' does not support `-c -o', so `make -j' may be unsafe]) need_locks=warn fi else need_locks=no fi _LT_DECL([], [need_locks], [1], [Must we lock files when doing compilation?]) ])# _LT_COMPILER_FILE_LOCKS # _LT_CHECK_OBJDIR # ---------------- m4_defun([_LT_CHECK_OBJDIR], [AC_CACHE_CHECK([for objdir], [lt_cv_objdir], [rm -f .libs 2>/dev/null mkdir .libs 2>/dev/null if test -d .libs; then lt_cv_objdir=.libs else # MS-DOS does not allow filenames that begin with a dot. lt_cv_objdir=_libs fi rmdir .libs 2>/dev/null]) objdir=$lt_cv_objdir _LT_DECL([], [objdir], [0], [The name of the directory that contains temporary libtool files])dnl m4_pattern_allow([LT_OBJDIR])dnl AC_DEFINE_UNQUOTED(LT_OBJDIR, "$lt_cv_objdir/", [Define to the sub-directory in which libtool stores uninstalled libraries.]) ])# _LT_CHECK_OBJDIR # _LT_LINKER_HARDCODE_LIBPATH([TAGNAME]) # -------------------------------------- # Check hardcoding attributes. m4_defun([_LT_LINKER_HARDCODE_LIBPATH], [AC_MSG_CHECKING([how to hardcode library paths into programs]) _LT_TAGVAR(hardcode_action, $1)= if test -n "$_LT_TAGVAR(hardcode_libdir_flag_spec, $1)" || test -n "$_LT_TAGVAR(runpath_var, $1)" || test "X$_LT_TAGVAR(hardcode_automatic, $1)" = "Xyes" ; then # We can hardcode non-existent directories. if test "$_LT_TAGVAR(hardcode_direct, $1)" != no && # If the only mechanism to avoid hardcoding is shlibpath_var, we # have to relink, otherwise we might link with an installed library # when we should be linking with a yet-to-be-installed one ## test "$_LT_TAGVAR(hardcode_shlibpath_var, $1)" != no && test "$_LT_TAGVAR(hardcode_minus_L, $1)" != no; then # Linking always hardcodes the temporary library directory. _LT_TAGVAR(hardcode_action, $1)=relink else # We can link without hardcoding, and we can hardcode nonexisting dirs. _LT_TAGVAR(hardcode_action, $1)=immediate fi else # We cannot hardcode anything, or else we can only hardcode existing # directories. _LT_TAGVAR(hardcode_action, $1)=unsupported fi AC_MSG_RESULT([$_LT_TAGVAR(hardcode_action, $1)]) if test "$_LT_TAGVAR(hardcode_action, $1)" = relink || test "$_LT_TAGVAR(inherit_rpath, $1)" = yes; then # Fast installation is not supported enable_fast_install=no elif test "$shlibpath_overrides_runpath" = yes || test "$enable_shared" = no; then # Fast installation is not necessary enable_fast_install=needless fi _LT_TAGDECL([], [hardcode_action], [0], [How to hardcode a shared library path into an executable]) ])# _LT_LINKER_HARDCODE_LIBPATH # _LT_CMD_STRIPLIB # ---------------- m4_defun([_LT_CMD_STRIPLIB], [m4_require([_LT_DECL_EGREP]) striplib= old_striplib= AC_MSG_CHECKING([whether stripping libraries is possible]) if test -n "$STRIP" && $STRIP -V 2>&1 | $GREP "GNU strip" >/dev/null; then test -z "$old_striplib" && old_striplib="$STRIP --strip-debug" test -z "$striplib" && striplib="$STRIP --strip-unneeded" AC_MSG_RESULT([yes]) else # FIXME - insert some real tests, host_os isn't really good enough case $host_os in darwin*) if test -n "$STRIP" ; then striplib="$STRIP -x" old_striplib="$STRIP -S" AC_MSG_RESULT([yes]) else AC_MSG_RESULT([no]) fi ;; *) AC_MSG_RESULT([no]) ;; esac fi _LT_DECL([], [old_striplib], [1], [Commands to strip libraries]) _LT_DECL([], [striplib], [1]) ])# _LT_CMD_STRIPLIB # _LT_SYS_DYNAMIC_LINKER([TAG]) # ----------------------------- # PORTME Fill in your ld.so characteristics m4_defun([_LT_SYS_DYNAMIC_LINKER], [AC_REQUIRE([AC_CANONICAL_HOST])dnl m4_require([_LT_DECL_EGREP])dnl m4_require([_LT_FILEUTILS_DEFAULTS])dnl m4_require([_LT_DECL_OBJDUMP])dnl m4_require([_LT_DECL_SED])dnl m4_require([_LT_CHECK_SHELL_FEATURES])dnl AC_MSG_CHECKING([dynamic linker characteristics]) m4_if([$1], [], [ if test "$GCC" = yes; then case $host_os in darwin*) lt_awk_arg="/^libraries:/,/LR/" ;; *) lt_awk_arg="/^libraries:/" ;; esac case $host_os in mingw* | cegcc*) lt_sed_strip_eq="s,=\([[A-Za-z]]:\),\1,g" ;; *) lt_sed_strip_eq="s,=/,/,g" ;; esac lt_search_path_spec=`$CC -print-search-dirs | awk $lt_awk_arg | $SED -e "s/^libraries://" -e $lt_sed_strip_eq` case $lt_search_path_spec in *\;*) # if the path contains ";" then we assume it to be the separator # otherwise default to the standard path separator (i.e. ":") - it is # assumed that no part of a normal pathname contains ";" but that should # okay in the real world where ";" in dirpaths is itself problematic. lt_search_path_spec=`$ECHO "$lt_search_path_spec" | $SED 's/;/ /g'` ;; *) lt_search_path_spec=`$ECHO "$lt_search_path_spec" | $SED "s/$PATH_SEPARATOR/ /g"` ;; esac # Ok, now we have the path, separated by spaces, we can step through it # and add multilib dir if necessary. lt_tmp_lt_search_path_spec= lt_multi_os_dir=`$CC $CPPFLAGS $CFLAGS $LDFLAGS -print-multi-os-directory 2>/dev/null` for lt_sys_path in $lt_search_path_spec; do if test -d "$lt_sys_path/$lt_multi_os_dir"; then lt_tmp_lt_search_path_spec="$lt_tmp_lt_search_path_spec $lt_sys_path/$lt_multi_os_dir" else test -d "$lt_sys_path" && \ lt_tmp_lt_search_path_spec="$lt_tmp_lt_search_path_spec $lt_sys_path" fi done lt_search_path_spec=`$ECHO "$lt_tmp_lt_search_path_spec" | awk ' BEGIN {RS=" "; FS="/|\n";} { lt_foo=""; lt_count=0; for (lt_i = NF; lt_i > 0; lt_i--) { if ($lt_i != "" && $lt_i != ".") { if ($lt_i == "..") { lt_count++; } else { if (lt_count == 0) { lt_foo="/" $lt_i lt_foo; } else { lt_count--; } } } } if (lt_foo != "") { lt_freq[[lt_foo]]++; } if (lt_freq[[lt_foo]] == 1) { print lt_foo; } }'` # AWK program above erroneously prepends '/' to C:/dos/paths # for these hosts. case $host_os in mingw* | cegcc*) lt_search_path_spec=`$ECHO "$lt_search_path_spec" |\ $SED 's,/\([[A-Za-z]]:\),\1,g'` ;; esac sys_lib_search_path_spec=`$ECHO "$lt_search_path_spec" | $lt_NL2SP` else sys_lib_search_path_spec="/lib /usr/lib /usr/local/lib" fi]) library_names_spec= libname_spec='lib$name' soname_spec= shrext_cmds=".so" postinstall_cmds= postuninstall_cmds= finish_cmds= finish_eval= shlibpath_var= shlibpath_overrides_runpath=unknown version_type=none dynamic_linker="$host_os ld.so" sys_lib_dlsearch_path_spec="/lib /usr/lib" need_lib_prefix=unknown hardcode_into_libs=no # when you set need_version to no, make sure it does not cause -set_version # flags to be left without arguments need_version=unknown case $host_os in aix3*) version_type=linux # correct to gnu/linux during the next big refactor library_names_spec='${libname}${release}${shared_ext}$versuffix $libname.a' shlibpath_var=LIBPATH # AIX 3 has no versioning support, so we append a major version to the name. soname_spec='${libname}${release}${shared_ext}$major' ;; aix[[4-9]]*) version_type=linux # correct to gnu/linux during the next big refactor need_lib_prefix=no need_version=no hardcode_into_libs=yes if test "$host_cpu" = ia64; then # AIX 5 supports IA64 library_names_spec='${libname}${release}${shared_ext}$major ${libname}${release}${shared_ext}$versuffix $libname${shared_ext}' shlibpath_var=LD_LIBRARY_PATH else # With GCC up to 2.95.x, collect2 would create an import file # for dependence libraries. The import file would start with # the line `#! .'. This would cause the generated library to # depend on `.', always an invalid library. This was fixed in # development snapshots of GCC prior to 3.0. case $host_os in aix4 | aix4.[[01]] | aix4.[[01]].*) if { echo '#if __GNUC__ > 2 || (__GNUC__ == 2 && __GNUC_MINOR__ >= 97)' echo ' yes ' echo '#endif'; } | ${CC} -E - | $GREP yes > /dev/null; then : else can_build_shared=no fi ;; esac # AIX (on Power*) has no versioning support, so currently we can not hardcode correct # soname into executable. Probably we can add versioning support to # collect2, so additional links can be useful in future. if test "$aix_use_runtimelinking" = yes; then # If using run time linking (on AIX 4.2 or later) use lib.so # instead of lib.a to let people know that these are not # typical AIX shared libraries. library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}' else # We preserve .a as extension for shared libraries through AIX4.2 # and later when we are not doing run time linking. library_names_spec='${libname}${release}.a $libname.a' soname_spec='${libname}${release}${shared_ext}$major' fi shlibpath_var=LIBPATH fi ;; amigaos*) case $host_cpu in powerpc) # Since July 2007 AmigaOS4 officially supports .so libraries. # When compiling the executable, add -use-dynld -Lsobjs: to the compileline. library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}' ;; m68k) library_names_spec='$libname.ixlibrary $libname.a' # Create ${libname}_ixlibrary.a entries in /sys/libs. finish_eval='for lib in `ls $libdir/*.ixlibrary 2>/dev/null`; do libname=`func_echo_all "$lib" | $SED '\''s%^.*/\([[^/]]*\)\.ixlibrary$%\1%'\''`; test $RM /sys/libs/${libname}_ixlibrary.a; $show "cd /sys/libs && $LN_S $lib ${libname}_ixlibrary.a"; cd /sys/libs && $LN_S $lib ${libname}_ixlibrary.a || exit 1; done' ;; esac ;; beos*) library_names_spec='${libname}${shared_ext}' dynamic_linker="$host_os ld.so" shlibpath_var=LIBRARY_PATH ;; bsdi[[45]]*) version_type=linux # correct to gnu/linux during the next big refactor need_version=no library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}' soname_spec='${libname}${release}${shared_ext}$major' finish_cmds='PATH="\$PATH:/sbin" ldconfig $libdir' shlibpath_var=LD_LIBRARY_PATH sys_lib_search_path_spec="/shlib /usr/lib /usr/X11/lib /usr/contrib/lib /lib /usr/local/lib" sys_lib_dlsearch_path_spec="/shlib /usr/lib /usr/local/lib" # the default ld.so.conf also contains /usr/contrib/lib and # /usr/X11R6/lib (/usr/X11 is a link to /usr/X11R6), but let us allow # libtool to hard-code these into programs ;; cygwin* | mingw* | pw32* | cegcc*) version_type=windows shrext_cmds=".dll" need_version=no need_lib_prefix=no case $GCC,$cc_basename in yes,*) # gcc library_names_spec='$libname.dll.a' # DLL is installed to $(libdir)/../bin by postinstall_cmds postinstall_cmds='base_file=`basename \${file}`~ dlpath=`$SHELL 2>&1 -c '\''. $dir/'\''\${base_file}'\''i; echo \$dlname'\''`~ dldir=$destdir/`dirname \$dlpath`~ test -d \$dldir || mkdir -p \$dldir~ $install_prog $dir/$dlname \$dldir/$dlname~ chmod a+x \$dldir/$dlname~ if test -n '\''$stripme'\'' && test -n '\''$striplib'\''; then eval '\''$striplib \$dldir/$dlname'\'' || exit \$?; fi' postuninstall_cmds='dldll=`$SHELL 2>&1 -c '\''. $file; echo \$dlname'\''`~ dlpath=$dir/\$dldll~ $RM \$dlpath' shlibpath_overrides_runpath=yes case $host_os in cygwin*) # Cygwin DLLs use 'cyg' prefix rather than 'lib' soname_spec='`echo ${libname} | sed -e 's/^lib/cyg/'``echo ${release} | $SED -e 's/[[.]]/-/g'`${versuffix}${shared_ext}' m4_if([$1], [],[ sys_lib_search_path_spec="$sys_lib_search_path_spec /usr/lib/w32api"]) ;; mingw* | cegcc*) # MinGW DLLs use traditional 'lib' prefix soname_spec='${libname}`echo ${release} | $SED -e 's/[[.]]/-/g'`${versuffix}${shared_ext}' ;; pw32*) # pw32 DLLs use 'pw' prefix rather than 'lib' library_names_spec='`echo ${libname} | sed -e 's/^lib/pw/'``echo ${release} | $SED -e 's/[[.]]/-/g'`${versuffix}${shared_ext}' ;; esac dynamic_linker='Win32 ld.exe' ;; *,cl*) # Native MSVC libname_spec='$name' soname_spec='${libname}`echo ${release} | $SED -e 's/[[.]]/-/g'`${versuffix}${shared_ext}' library_names_spec='${libname}.dll.lib' case $build_os in mingw*) sys_lib_search_path_spec= lt_save_ifs=$IFS IFS=';' for lt_path in $LIB do IFS=$lt_save_ifs # Let DOS variable expansion print the short 8.3 style file name. lt_path=`cd "$lt_path" 2>/dev/null && cmd //C "for %i in (".") do @echo %~si"` sys_lib_search_path_spec="$sys_lib_search_path_spec $lt_path" done IFS=$lt_save_ifs # Convert to MSYS style. sys_lib_search_path_spec=`$ECHO "$sys_lib_search_path_spec" | sed -e 's|\\\\|/|g' -e 's| \\([[a-zA-Z]]\\):| /\\1|g' -e 's|^ ||'` ;; cygwin*) # Convert to unix form, then to dos form, then back to unix form # but this time dos style (no spaces!) so that the unix form looks # like /cygdrive/c/PROGRA~1:/cygdr... sys_lib_search_path_spec=`cygpath --path --unix "$LIB"` sys_lib_search_path_spec=`cygpath --path --dos "$sys_lib_search_path_spec" 2>/dev/null` sys_lib_search_path_spec=`cygpath --path --unix "$sys_lib_search_path_spec" | $SED -e "s/$PATH_SEPARATOR/ /g"` ;; *) sys_lib_search_path_spec="$LIB" if $ECHO "$sys_lib_search_path_spec" | [$GREP ';[c-zC-Z]:/' >/dev/null]; then # It is most probably a Windows format PATH. sys_lib_search_path_spec=`$ECHO "$sys_lib_search_path_spec" | $SED -e 's/;/ /g'` else sys_lib_search_path_spec=`$ECHO "$sys_lib_search_path_spec" | $SED -e "s/$PATH_SEPARATOR/ /g"` fi # FIXME: find the short name or the path components, as spaces are # common. (e.g. "Program Files" -> "PROGRA~1") ;; esac # DLL is installed to $(libdir)/../bin by postinstall_cmds postinstall_cmds='base_file=`basename \${file}`~ dlpath=`$SHELL 2>&1 -c '\''. $dir/'\''\${base_file}'\''i; echo \$dlname'\''`~ dldir=$destdir/`dirname \$dlpath`~ test -d \$dldir || mkdir -p \$dldir~ $install_prog $dir/$dlname \$dldir/$dlname' postuninstall_cmds='dldll=`$SHELL 2>&1 -c '\''. $file; echo \$dlname'\''`~ dlpath=$dir/\$dldll~ $RM \$dlpath' shlibpath_overrides_runpath=yes dynamic_linker='Win32 link.exe' ;; *) # Assume MSVC wrapper library_names_spec='${libname}`echo ${release} | $SED -e 's/[[.]]/-/g'`${versuffix}${shared_ext} $libname.lib' dynamic_linker='Win32 ld.exe' ;; esac # FIXME: first we should search . and the directory the executable is in shlibpath_var=PATH ;; darwin* | rhapsody*) dynamic_linker="$host_os dyld" version_type=darwin need_lib_prefix=no need_version=no library_names_spec='${libname}${release}${major}$shared_ext ${libname}$shared_ext' soname_spec='${libname}${release}${major}$shared_ext' shlibpath_overrides_runpath=yes shlibpath_var=DYLD_LIBRARY_PATH shrext_cmds='`test .$module = .yes && echo .so || echo .dylib`' m4_if([$1], [],[ sys_lib_search_path_spec="$sys_lib_search_path_spec /usr/local/lib"]) sys_lib_dlsearch_path_spec='/usr/local/lib /lib /usr/lib' ;; dgux*) version_type=linux # correct to gnu/linux during the next big refactor need_lib_prefix=no need_version=no library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname$shared_ext' soname_spec='${libname}${release}${shared_ext}$major' shlibpath_var=LD_LIBRARY_PATH ;; freebsd* | dragonfly*) # DragonFly does not have aout. When/if they implement a new # versioning mechanism, adjust this. if test -x /usr/bin/objformat; then objformat=`/usr/bin/objformat` else case $host_os in freebsd[[23]].*) objformat=aout ;; *) objformat=elf ;; esac fi # Handle Gentoo/FreeBSD as it was Linux case $host_vendor in gentoo) version_type=linux ;; *) version_type=freebsd-$objformat ;; esac case $version_type in freebsd-elf*) library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext} $libname${shared_ext}' need_version=no need_lib_prefix=no ;; freebsd-*) library_names_spec='${libname}${release}${shared_ext}$versuffix $libname${shared_ext}$versuffix' need_version=yes ;; linux) library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major ${libname}${shared_ext}' soname_spec='${libname}${release}${shared_ext}$major' need_lib_prefix=no need_version=no ;; esac shlibpath_var=LD_LIBRARY_PATH case $host_os in freebsd2.*) shlibpath_overrides_runpath=yes ;; freebsd3.[[01]]* | freebsdelf3.[[01]]*) shlibpath_overrides_runpath=yes hardcode_into_libs=yes ;; freebsd3.[[2-9]]* | freebsdelf3.[[2-9]]* | \ freebsd4.[[0-5]] | freebsdelf4.[[0-5]] | freebsd4.1.1 | freebsdelf4.1.1) shlibpath_overrides_runpath=no hardcode_into_libs=yes ;; *) # from 4.6 on, and DragonFly shlibpath_overrides_runpath=yes hardcode_into_libs=yes ;; esac ;; gnu*) version_type=linux # correct to gnu/linux during the next big refactor need_lib_prefix=no need_version=no library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}${major} ${libname}${shared_ext}' soname_spec='${libname}${release}${shared_ext}$major' shlibpath_var=LD_LIBRARY_PATH shlibpath_overrides_runpath=no hardcode_into_libs=yes ;; haiku*) version_type=linux # correct to gnu/linux during the next big refactor need_lib_prefix=no need_version=no dynamic_linker="$host_os runtime_loader" library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}${major} ${libname}${shared_ext}' soname_spec='${libname}${release}${shared_ext}$major' shlibpath_var=LIBRARY_PATH shlibpath_overrides_runpath=yes sys_lib_dlsearch_path_spec='/boot/home/config/lib /boot/common/lib /boot/system/lib' hardcode_into_libs=yes ;; hpux9* | hpux10* | hpux11*) # Give a soname corresponding to the major version so that dld.sl refuses to # link against other versions. version_type=sunos need_lib_prefix=no need_version=no case $host_cpu in ia64*) shrext_cmds='.so' hardcode_into_libs=yes dynamic_linker="$host_os dld.so" shlibpath_var=LD_LIBRARY_PATH shlibpath_overrides_runpath=yes # Unless +noenvvar is specified. library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}' soname_spec='${libname}${release}${shared_ext}$major' if test "X$HPUX_IA64_MODE" = X32; then sys_lib_search_path_spec="/usr/lib/hpux32 /usr/local/lib/hpux32 /usr/local/lib" else sys_lib_search_path_spec="/usr/lib/hpux64 /usr/local/lib/hpux64" fi sys_lib_dlsearch_path_spec=$sys_lib_search_path_spec ;; hppa*64*) shrext_cmds='.sl' hardcode_into_libs=yes dynamic_linker="$host_os dld.sl" shlibpath_var=LD_LIBRARY_PATH # How should we handle SHLIB_PATH shlibpath_overrides_runpath=yes # Unless +noenvvar is specified. library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}' soname_spec='${libname}${release}${shared_ext}$major' sys_lib_search_path_spec="/usr/lib/pa20_64 /usr/ccs/lib/pa20_64" sys_lib_dlsearch_path_spec=$sys_lib_search_path_spec ;; *) shrext_cmds='.sl' dynamic_linker="$host_os dld.sl" shlibpath_var=SHLIB_PATH shlibpath_overrides_runpath=no # +s is required to enable SHLIB_PATH library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}' soname_spec='${libname}${release}${shared_ext}$major' ;; esac # HP-UX runs *really* slowly unless shared libraries are mode 555, ... postinstall_cmds='chmod 555 $lib' # or fails outright, so override atomically: install_override_mode=555 ;; interix[[3-9]]*) version_type=linux # correct to gnu/linux during the next big refactor need_lib_prefix=no need_version=no library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major ${libname}${shared_ext}' soname_spec='${libname}${release}${shared_ext}$major' dynamic_linker='Interix 3.x ld.so.1 (PE, like ELF)' shlibpath_var=LD_LIBRARY_PATH shlibpath_overrides_runpath=no hardcode_into_libs=yes ;; irix5* | irix6* | nonstopux*) case $host_os in nonstopux*) version_type=nonstopux ;; *) if test "$lt_cv_prog_gnu_ld" = yes; then version_type=linux # correct to gnu/linux during the next big refactor else version_type=irix fi ;; esac need_lib_prefix=no need_version=no soname_spec='${libname}${release}${shared_ext}$major' library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major ${libname}${release}${shared_ext} $libname${shared_ext}' case $host_os in irix5* | nonstopux*) libsuff= shlibsuff= ;; *) case $LD in # libtool.m4 will add one of these switches to LD *-32|*"-32 "|*-melf32bsmip|*"-melf32bsmip ") libsuff= shlibsuff= libmagic=32-bit;; *-n32|*"-n32 "|*-melf32bmipn32|*"-melf32bmipn32 ") libsuff=32 shlibsuff=N32 libmagic=N32;; *-64|*"-64 "|*-melf64bmip|*"-melf64bmip ") libsuff=64 shlibsuff=64 libmagic=64-bit;; *) libsuff= shlibsuff= libmagic=never-match;; esac ;; esac shlibpath_var=LD_LIBRARY${shlibsuff}_PATH shlibpath_overrides_runpath=no sys_lib_search_path_spec="/usr/lib${libsuff} /lib${libsuff} /usr/local/lib${libsuff}" sys_lib_dlsearch_path_spec="/usr/lib${libsuff} /lib${libsuff}" hardcode_into_libs=yes ;; # No shared lib support for Linux oldld, aout, or coff. linux*oldld* | linux*aout* | linux*coff*) dynamic_linker=no ;; # This must be glibc/ELF. linux* | k*bsd*-gnu | kopensolaris*-gnu) version_type=linux # correct to gnu/linux during the next big refactor need_lib_prefix=no need_version=no library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}' soname_spec='${libname}${release}${shared_ext}$major' finish_cmds='PATH="\$PATH:/sbin" ldconfig -n $libdir' shlibpath_var=LD_LIBRARY_PATH shlibpath_overrides_runpath=no # Some binutils ld are patched to set DT_RUNPATH AC_CACHE_VAL([lt_cv_shlibpath_overrides_runpath], [lt_cv_shlibpath_overrides_runpath=no save_LDFLAGS=$LDFLAGS save_libdir=$libdir eval "libdir=/foo; wl=\"$_LT_TAGVAR(lt_prog_compiler_wl, $1)\"; \ LDFLAGS=\"\$LDFLAGS $_LT_TAGVAR(hardcode_libdir_flag_spec, $1)\"" AC_LINK_IFELSE([AC_LANG_PROGRAM([],[])], [AS_IF([ ($OBJDUMP -p conftest$ac_exeext) 2>/dev/null | grep "RUNPATH.*$libdir" >/dev/null], [lt_cv_shlibpath_overrides_runpath=yes])]) LDFLAGS=$save_LDFLAGS libdir=$save_libdir ]) shlibpath_overrides_runpath=$lt_cv_shlibpath_overrides_runpath # This implies no fast_install, which is unacceptable. # Some rework will be needed to allow for fast_install # before this can be enabled. hardcode_into_libs=yes # Append ld.so.conf contents to the search path if test -f /etc/ld.so.conf; then lt_ld_extra=`awk '/^include / { system(sprintf("cd /etc; cat %s 2>/dev/null", \[$]2)); skip = 1; } { if (!skip) print \[$]0; skip = 0; }' < /etc/ld.so.conf | $SED -e 's/#.*//;/^[ ]*hwcap[ ]/d;s/[:, ]/ /g;s/=[^=]*$//;s/=[^= ]* / /g;s/"//g;/^$/d' | tr '\n' ' '` sys_lib_dlsearch_path_spec="/lib /usr/lib $lt_ld_extra" fi # We used to test for /lib/ld.so.1 and disable shared libraries on # powerpc, because MkLinux only supported shared libraries with the # GNU dynamic linker. Since this was broken with cross compilers, # most powerpc-linux boxes support dynamic linking these days and # people can always --disable-shared, the test was removed, and we # assume the GNU/Linux dynamic linker is in use. dynamic_linker='GNU/Linux ld.so' ;; netbsd*) version_type=sunos need_lib_prefix=no need_version=no if echo __ELF__ | $CC -E - | $GREP __ELF__ >/dev/null; then library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${shared_ext}$versuffix' finish_cmds='PATH="\$PATH:/sbin" ldconfig -m $libdir' dynamic_linker='NetBSD (a.out) ld.so' else library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major ${libname}${shared_ext}' soname_spec='${libname}${release}${shared_ext}$major' dynamic_linker='NetBSD ld.elf_so' fi shlibpath_var=LD_LIBRARY_PATH shlibpath_overrides_runpath=yes hardcode_into_libs=yes ;; newsos6) version_type=linux # correct to gnu/linux during the next big refactor library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}' shlibpath_var=LD_LIBRARY_PATH shlibpath_overrides_runpath=yes ;; *nto* | *qnx*) version_type=qnx need_lib_prefix=no need_version=no library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}' soname_spec='${libname}${release}${shared_ext}$major' shlibpath_var=LD_LIBRARY_PATH shlibpath_overrides_runpath=no hardcode_into_libs=yes dynamic_linker='ldqnx.so' ;; openbsd*) version_type=sunos sys_lib_dlsearch_path_spec="/usr/lib" need_lib_prefix=no # Some older versions of OpenBSD (3.3 at least) *do* need versioned libs. case $host_os in openbsd3.3 | openbsd3.3.*) need_version=yes ;; *) need_version=no ;; esac library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${shared_ext}$versuffix' finish_cmds='PATH="\$PATH:/sbin" ldconfig -m $libdir' shlibpath_var=LD_LIBRARY_PATH if test -z "`echo __ELF__ | $CC -E - | $GREP __ELF__`" || test "$host_os-$host_cpu" = "openbsd2.8-powerpc"; then case $host_os in openbsd2.[[89]] | openbsd2.[[89]].*) shlibpath_overrides_runpath=no ;; *) shlibpath_overrides_runpath=yes ;; esac else shlibpath_overrides_runpath=yes fi ;; os2*) libname_spec='$name' shrext_cmds=".dll" need_lib_prefix=no library_names_spec='$libname${shared_ext} $libname.a' dynamic_linker='OS/2 ld.exe' shlibpath_var=LIBPATH ;; osf3* | osf4* | osf5*) version_type=osf need_lib_prefix=no need_version=no soname_spec='${libname}${release}${shared_ext}$major' library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}' shlibpath_var=LD_LIBRARY_PATH sys_lib_search_path_spec="/usr/shlib /usr/ccs/lib /usr/lib/cmplrs/cc /usr/lib /usr/local/lib /var/shlib" sys_lib_dlsearch_path_spec="$sys_lib_search_path_spec" ;; rdos*) dynamic_linker=no ;; solaris*) version_type=linux # correct to gnu/linux during the next big refactor need_lib_prefix=no need_version=no library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}' soname_spec='${libname}${release}${shared_ext}$major' shlibpath_var=LD_LIBRARY_PATH shlibpath_overrides_runpath=yes hardcode_into_libs=yes # ldd complains unless libraries are executable postinstall_cmds='chmod +x $lib' ;; sunos4*) version_type=sunos library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${shared_ext}$versuffix' finish_cmds='PATH="\$PATH:/usr/etc" ldconfig $libdir' shlibpath_var=LD_LIBRARY_PATH shlibpath_overrides_runpath=yes if test "$with_gnu_ld" = yes; then need_lib_prefix=no fi need_version=yes ;; sysv4 | sysv4.3*) version_type=linux # correct to gnu/linux during the next big refactor library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}' soname_spec='${libname}${release}${shared_ext}$major' shlibpath_var=LD_LIBRARY_PATH case $host_vendor in sni) shlibpath_overrides_runpath=no need_lib_prefix=no runpath_var=LD_RUN_PATH ;; siemens) need_lib_prefix=no ;; motorola) need_lib_prefix=no need_version=no shlibpath_overrides_runpath=no sys_lib_search_path_spec='/lib /usr/lib /usr/ccs/lib' ;; esac ;; sysv4*MP*) if test -d /usr/nec ;then version_type=linux # correct to gnu/linux during the next big refactor library_names_spec='$libname${shared_ext}.$versuffix $libname${shared_ext}.$major $libname${shared_ext}' soname_spec='$libname${shared_ext}.$major' shlibpath_var=LD_LIBRARY_PATH fi ;; sysv5* | sco3.2v5* | sco5v6* | unixware* | OpenUNIX* | sysv4*uw2*) version_type=freebsd-elf need_lib_prefix=no need_version=no library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext} $libname${shared_ext}' soname_spec='${libname}${release}${shared_ext}$major' shlibpath_var=LD_LIBRARY_PATH shlibpath_overrides_runpath=yes hardcode_into_libs=yes if test "$with_gnu_ld" = yes; then sys_lib_search_path_spec='/usr/local/lib /usr/gnu/lib /usr/ccs/lib /usr/lib /lib' else sys_lib_search_path_spec='/usr/ccs/lib /usr/lib' case $host_os in sco3.2v5*) sys_lib_search_path_spec="$sys_lib_search_path_spec /lib" ;; esac fi sys_lib_dlsearch_path_spec='/usr/lib' ;; tpf*) # TPF is a cross-target only. Preferred cross-host = GNU/Linux. version_type=linux # correct to gnu/linux during the next big refactor need_lib_prefix=no need_version=no library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}' shlibpath_var=LD_LIBRARY_PATH shlibpath_overrides_runpath=no hardcode_into_libs=yes ;; uts4*) version_type=linux # correct to gnu/linux during the next big refactor library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}' soname_spec='${libname}${release}${shared_ext}$major' shlibpath_var=LD_LIBRARY_PATH ;; *) dynamic_linker=no ;; esac AC_MSG_RESULT([$dynamic_linker]) test "$dynamic_linker" = no && can_build_shared=no variables_saved_for_relink="PATH $shlibpath_var $runpath_var" if test "$GCC" = yes; then variables_saved_for_relink="$variables_saved_for_relink GCC_EXEC_PREFIX COMPILER_PATH LIBRARY_PATH" fi if test "${lt_cv_sys_lib_search_path_spec+set}" = set; then sys_lib_search_path_spec="$lt_cv_sys_lib_search_path_spec" fi if test "${lt_cv_sys_lib_dlsearch_path_spec+set}" = set; then sys_lib_dlsearch_path_spec="$lt_cv_sys_lib_dlsearch_path_spec" fi _LT_DECL([], [variables_saved_for_relink], [1], [Variables whose values should be saved in libtool wrapper scripts and restored at link time]) _LT_DECL([], [need_lib_prefix], [0], [Do we need the "lib" prefix for modules?]) _LT_DECL([], [need_version], [0], [Do we need a version for libraries?]) _LT_DECL([], [version_type], [0], [Library versioning type]) _LT_DECL([], [runpath_var], [0], [Shared library runtime path variable]) _LT_DECL([], [shlibpath_var], [0],[Shared library path variable]) _LT_DECL([], [shlibpath_overrides_runpath], [0], [Is shlibpath searched before the hard-coded library search path?]) _LT_DECL([], [libname_spec], [1], [Format of library name prefix]) _LT_DECL([], [library_names_spec], [1], [[List of archive names. First name is the real one, the rest are links. The last name is the one that the linker finds with -lNAME]]) _LT_DECL([], [soname_spec], [1], [[The coded name of the library, if different from the real name]]) _LT_DECL([], [install_override_mode], [1], [Permission mode override for installation of shared libraries]) _LT_DECL([], [postinstall_cmds], [2], [Command to use after installation of a shared archive]) _LT_DECL([], [postuninstall_cmds], [2], [Command to use after uninstallation of a shared archive]) _LT_DECL([], [finish_cmds], [2], [Commands used to finish a libtool library installation in a directory]) _LT_DECL([], [finish_eval], [1], [[As "finish_cmds", except a single script fragment to be evaled but not shown]]) _LT_DECL([], [hardcode_into_libs], [0], [Whether we should hardcode library paths into libraries]) _LT_DECL([], [sys_lib_search_path_spec], [2], [Compile-time system search path for libraries]) _LT_DECL([], [sys_lib_dlsearch_path_spec], [2], [Run-time system search path for libraries]) ])# _LT_SYS_DYNAMIC_LINKER # _LT_PATH_TOOL_PREFIX(TOOL) # -------------------------- # find a file program which can recognize shared library AC_DEFUN([_LT_PATH_TOOL_PREFIX], [m4_require([_LT_DECL_EGREP])dnl AC_MSG_CHECKING([for $1]) AC_CACHE_VAL(lt_cv_path_MAGIC_CMD, [case $MAGIC_CMD in [[\\/*] | ?:[\\/]*]) lt_cv_path_MAGIC_CMD="$MAGIC_CMD" # Let the user override the test with a path. ;; *) lt_save_MAGIC_CMD="$MAGIC_CMD" lt_save_ifs="$IFS"; IFS=$PATH_SEPARATOR dnl $ac_dummy forces splitting on constant user-supplied paths. dnl POSIX.2 word splitting is done only on the output of word expansions, dnl not every word. This closes a longstanding sh security hole. ac_dummy="m4_if([$2], , $PATH, [$2])" for ac_dir in $ac_dummy; do IFS="$lt_save_ifs" test -z "$ac_dir" && ac_dir=. if test -f $ac_dir/$1; then lt_cv_path_MAGIC_CMD="$ac_dir/$1" if test -n "$file_magic_test_file"; then case $deplibs_check_method in "file_magic "*) file_magic_regex=`expr "$deplibs_check_method" : "file_magic \(.*\)"` MAGIC_CMD="$lt_cv_path_MAGIC_CMD" if eval $file_magic_cmd \$file_magic_test_file 2> /dev/null | $EGREP "$file_magic_regex" > /dev/null; then : else cat <<_LT_EOF 1>&2 *** Warning: the command libtool uses to detect shared libraries, *** $file_magic_cmd, produces output that libtool cannot recognize. *** The result is that libtool may fail to recognize shared libraries *** as such. This will affect the creation of libtool libraries that *** depend on shared libraries, but programs linked with such libtool *** libraries will work regardless of this problem. Nevertheless, you *** may want to report the problem to your system manager and/or to *** bug-libtool@gnu.org _LT_EOF fi ;; esac fi break fi done IFS="$lt_save_ifs" MAGIC_CMD="$lt_save_MAGIC_CMD" ;; esac]) MAGIC_CMD="$lt_cv_path_MAGIC_CMD" if test -n "$MAGIC_CMD"; then AC_MSG_RESULT($MAGIC_CMD) else AC_MSG_RESULT(no) fi _LT_DECL([], [MAGIC_CMD], [0], [Used to examine libraries when file_magic_cmd begins with "file"])dnl ])# _LT_PATH_TOOL_PREFIX # Old name: AU_ALIAS([AC_PATH_TOOL_PREFIX], [_LT_PATH_TOOL_PREFIX]) dnl aclocal-1.4 backwards compatibility: dnl AC_DEFUN([AC_PATH_TOOL_PREFIX], []) # _LT_PATH_MAGIC # -------------- # find a file program which can recognize a shared library m4_defun([_LT_PATH_MAGIC], [_LT_PATH_TOOL_PREFIX(${ac_tool_prefix}file, /usr/bin$PATH_SEPARATOR$PATH) if test -z "$lt_cv_path_MAGIC_CMD"; then if test -n "$ac_tool_prefix"; then _LT_PATH_TOOL_PREFIX(file, /usr/bin$PATH_SEPARATOR$PATH) else MAGIC_CMD=: fi fi ])# _LT_PATH_MAGIC # LT_PATH_LD # ---------- # find the pathname to the GNU or non-GNU linker AC_DEFUN([LT_PATH_LD], [AC_REQUIRE([AC_PROG_CC])dnl AC_REQUIRE([AC_CANONICAL_HOST])dnl AC_REQUIRE([AC_CANONICAL_BUILD])dnl m4_require([_LT_DECL_SED])dnl m4_require([_LT_DECL_EGREP])dnl m4_require([_LT_PROG_ECHO_BACKSLASH])dnl AC_ARG_WITH([gnu-ld], [AS_HELP_STRING([--with-gnu-ld], [assume the C compiler uses GNU ld @<:@default=no@:>@])], [test "$withval" = no || with_gnu_ld=yes], [with_gnu_ld=no])dnl ac_prog=ld if test "$GCC" = yes; then # Check if gcc -print-prog-name=ld gives a path. AC_MSG_CHECKING([for ld used by $CC]) case $host in *-*-mingw*) # gcc leaves a trailing carriage return which upsets mingw ac_prog=`($CC -print-prog-name=ld) 2>&5 | tr -d '\015'` ;; *) ac_prog=`($CC -print-prog-name=ld) 2>&5` ;; esac case $ac_prog in # Accept absolute paths. [[\\/]]* | ?:[[\\/]]*) re_direlt='/[[^/]][[^/]]*/\.\./' # Canonicalize the pathname of ld ac_prog=`$ECHO "$ac_prog"| $SED 's%\\\\%/%g'` while $ECHO "$ac_prog" | $GREP "$re_direlt" > /dev/null 2>&1; do ac_prog=`$ECHO $ac_prog| $SED "s%$re_direlt%/%"` done test -z "$LD" && LD="$ac_prog" ;; "") # If it fails, then pretend we aren't using GCC. ac_prog=ld ;; *) # If it is relative, then search for the first ld in PATH. with_gnu_ld=unknown ;; esac elif test "$with_gnu_ld" = yes; then AC_MSG_CHECKING([for GNU ld]) else AC_MSG_CHECKING([for non-GNU ld]) fi AC_CACHE_VAL(lt_cv_path_LD, [if test -z "$LD"; then lt_save_ifs="$IFS"; IFS=$PATH_SEPARATOR for ac_dir in $PATH; do IFS="$lt_save_ifs" test -z "$ac_dir" && ac_dir=. if test -f "$ac_dir/$ac_prog" || test -f "$ac_dir/$ac_prog$ac_exeext"; then lt_cv_path_LD="$ac_dir/$ac_prog" # Check to see if the program is GNU ld. I'd rather use --version, # but apparently some variants of GNU ld only accept -v. # Break only if it was the GNU/non-GNU ld that we prefer. case `"$lt_cv_path_LD" -v 2>&1 &1 /dev/null 2>&1; then lt_cv_deplibs_check_method='file_magic ^x86 archive import|^x86 DLL' lt_cv_file_magic_cmd='func_win32_libid' else # Keep this pattern in sync with the one in func_win32_libid. lt_cv_deplibs_check_method='file_magic file format (pei*-i386(.*architecture: i386)?|pe-arm-wince|pe-x86-64)' lt_cv_file_magic_cmd='$OBJDUMP -f' fi ;; cegcc*) # use the weaker test based on 'objdump'. See mingw*. lt_cv_deplibs_check_method='file_magic file format pe-arm-.*little(.*architecture: arm)?' lt_cv_file_magic_cmd='$OBJDUMP -f' ;; darwin* | rhapsody*) lt_cv_deplibs_check_method=pass_all ;; freebsd* | dragonfly*) if echo __ELF__ | $CC -E - | $GREP __ELF__ > /dev/null; then case $host_cpu in i*86 ) # Not sure whether the presence of OpenBSD here was a mistake. # Let's accept both of them until this is cleared up. lt_cv_deplibs_check_method='file_magic (FreeBSD|OpenBSD|DragonFly)/i[[3-9]]86 (compact )?demand paged shared library' lt_cv_file_magic_cmd=/usr/bin/file lt_cv_file_magic_test_file=`echo /usr/lib/libc.so.*` ;; esac else lt_cv_deplibs_check_method=pass_all fi ;; gnu*) lt_cv_deplibs_check_method=pass_all ;; haiku*) lt_cv_deplibs_check_method=pass_all ;; hpux10.20* | hpux11*) lt_cv_file_magic_cmd=/usr/bin/file case $host_cpu in ia64*) lt_cv_deplibs_check_method='file_magic (s[[0-9]][[0-9]][[0-9]]|ELF-[[0-9]][[0-9]]) shared object file - IA64' lt_cv_file_magic_test_file=/usr/lib/hpux32/libc.so ;; hppa*64*) [lt_cv_deplibs_check_method='file_magic (s[0-9][0-9][0-9]|ELF[ -][0-9][0-9])(-bit)?( [LM]SB)? shared object( file)?[, -]* PA-RISC [0-9]\.[0-9]'] lt_cv_file_magic_test_file=/usr/lib/pa20_64/libc.sl ;; *) lt_cv_deplibs_check_method='file_magic (s[[0-9]][[0-9]][[0-9]]|PA-RISC[[0-9]]\.[[0-9]]) shared library' lt_cv_file_magic_test_file=/usr/lib/libc.sl ;; esac ;; interix[[3-9]]*) # PIC code is broken on Interix 3.x, that's why |\.a not |_pic\.a here lt_cv_deplibs_check_method='match_pattern /lib[[^/]]+(\.so|\.a)$' ;; irix5* | irix6* | nonstopux*) case $LD in *-32|*"-32 ") libmagic=32-bit;; *-n32|*"-n32 ") libmagic=N32;; *-64|*"-64 ") libmagic=64-bit;; *) libmagic=never-match;; esac lt_cv_deplibs_check_method=pass_all ;; # This must be glibc/ELF. linux* | k*bsd*-gnu | kopensolaris*-gnu) lt_cv_deplibs_check_method=pass_all ;; netbsd*) if echo __ELF__ | $CC -E - | $GREP __ELF__ > /dev/null; then lt_cv_deplibs_check_method='match_pattern /lib[[^/]]+(\.so\.[[0-9]]+\.[[0-9]]+|_pic\.a)$' else lt_cv_deplibs_check_method='match_pattern /lib[[^/]]+(\.so|_pic\.a)$' fi ;; newos6*) lt_cv_deplibs_check_method='file_magic ELF [[0-9]][[0-9]]*-bit [[ML]]SB (executable|dynamic lib)' lt_cv_file_magic_cmd=/usr/bin/file lt_cv_file_magic_test_file=/usr/lib/libnls.so ;; *nto* | *qnx*) lt_cv_deplibs_check_method=pass_all ;; openbsd*) if test -z "`echo __ELF__ | $CC -E - | $GREP __ELF__`" || test "$host_os-$host_cpu" = "openbsd2.8-powerpc"; then lt_cv_deplibs_check_method='match_pattern /lib[[^/]]+(\.so\.[[0-9]]+\.[[0-9]]+|\.so|_pic\.a)$' else lt_cv_deplibs_check_method='match_pattern /lib[[^/]]+(\.so\.[[0-9]]+\.[[0-9]]+|_pic\.a)$' fi ;; osf3* | osf4* | osf5*) lt_cv_deplibs_check_method=pass_all ;; rdos*) lt_cv_deplibs_check_method=pass_all ;; solaris*) lt_cv_deplibs_check_method=pass_all ;; sysv5* | sco3.2v5* | sco5v6* | unixware* | OpenUNIX* | sysv4*uw2*) lt_cv_deplibs_check_method=pass_all ;; sysv4 | sysv4.3*) case $host_vendor in motorola) lt_cv_deplibs_check_method='file_magic ELF [[0-9]][[0-9]]*-bit [[ML]]SB (shared object|dynamic lib) M[[0-9]][[0-9]]* Version [[0-9]]' lt_cv_file_magic_test_file=`echo /usr/lib/libc.so*` ;; ncr) lt_cv_deplibs_check_method=pass_all ;; sequent) lt_cv_file_magic_cmd='/bin/file' lt_cv_deplibs_check_method='file_magic ELF [[0-9]][[0-9]]*-bit [[LM]]SB (shared object|dynamic lib )' ;; sni) lt_cv_file_magic_cmd='/bin/file' lt_cv_deplibs_check_method="file_magic ELF [[0-9]][[0-9]]*-bit [[LM]]SB dynamic lib" lt_cv_file_magic_test_file=/lib/libc.so ;; siemens) lt_cv_deplibs_check_method=pass_all ;; pc) lt_cv_deplibs_check_method=pass_all ;; esac ;; tpf*) lt_cv_deplibs_check_method=pass_all ;; esac ]) file_magic_glob= want_nocaseglob=no if test "$build" = "$host"; then case $host_os in mingw* | pw32*) if ( shopt | grep nocaseglob ) >/dev/null 2>&1; then want_nocaseglob=yes else file_magic_glob=`echo aAbBcCdDeEfFgGhHiIjJkKlLmMnNoOpPqQrRsStTuUvVwWxXyYzZ | $SED -e "s/\(..\)/s\/[[\1]]\/[[\1]]\/g;/g"` fi ;; esac fi file_magic_cmd=$lt_cv_file_magic_cmd deplibs_check_method=$lt_cv_deplibs_check_method test -z "$deplibs_check_method" && deplibs_check_method=unknown _LT_DECL([], [deplibs_check_method], [1], [Method to check whether dependent libraries are shared objects]) _LT_DECL([], [file_magic_cmd], [1], [Command to use when deplibs_check_method = "file_magic"]) _LT_DECL([], [file_magic_glob], [1], [How to find potential files when deplibs_check_method = "file_magic"]) _LT_DECL([], [want_nocaseglob], [1], [Find potential files using nocaseglob when deplibs_check_method = "file_magic"]) ])# _LT_CHECK_MAGIC_METHOD # LT_PATH_NM # ---------- # find the pathname to a BSD- or MS-compatible name lister AC_DEFUN([LT_PATH_NM], [AC_REQUIRE([AC_PROG_CC])dnl AC_CACHE_CHECK([for BSD- or MS-compatible name lister (nm)], lt_cv_path_NM, [if test -n "$NM"; then # Let the user override the test. lt_cv_path_NM="$NM" else lt_nm_to_check="${ac_tool_prefix}nm" if test -n "$ac_tool_prefix" && test "$build" = "$host"; then lt_nm_to_check="$lt_nm_to_check nm" fi for lt_tmp_nm in $lt_nm_to_check; do lt_save_ifs="$IFS"; IFS=$PATH_SEPARATOR for ac_dir in $PATH /usr/ccs/bin/elf /usr/ccs/bin /usr/ucb /bin; do IFS="$lt_save_ifs" test -z "$ac_dir" && ac_dir=. tmp_nm="$ac_dir/$lt_tmp_nm" if test -f "$tmp_nm" || test -f "$tmp_nm$ac_exeext" ; then # Check to see if the nm accepts a BSD-compat flag. # Adding the `sed 1q' prevents false positives on HP-UX, which says: # nm: unknown option "B" ignored # Tru64's nm complains that /dev/null is an invalid object file case `"$tmp_nm" -B /dev/null 2>&1 | sed '1q'` in */dev/null* | *'Invalid file or object type'*) lt_cv_path_NM="$tmp_nm -B" break ;; *) case `"$tmp_nm" -p /dev/null 2>&1 | sed '1q'` in */dev/null*) lt_cv_path_NM="$tmp_nm -p" break ;; *) lt_cv_path_NM=${lt_cv_path_NM="$tmp_nm"} # keep the first match, but continue # so that we can try to find one that supports BSD flags ;; esac ;; esac fi done IFS="$lt_save_ifs" done : ${lt_cv_path_NM=no} fi]) if test "$lt_cv_path_NM" != "no"; then NM="$lt_cv_path_NM" else # Didn't find any BSD compatible name lister, look for dumpbin. if test -n "$DUMPBIN"; then : # Let the user override the test. else AC_CHECK_TOOLS(DUMPBIN, [dumpbin "link -dump"], :) case `$DUMPBIN -symbols /dev/null 2>&1 | sed '1q'` in *COFF*) DUMPBIN="$DUMPBIN -symbols" ;; *) DUMPBIN=: ;; esac fi AC_SUBST([DUMPBIN]) if test "$DUMPBIN" != ":"; then NM="$DUMPBIN" fi fi test -z "$NM" && NM=nm AC_SUBST([NM]) _LT_DECL([], [NM], [1], [A BSD- or MS-compatible name lister])dnl AC_CACHE_CHECK([the name lister ($NM) interface], [lt_cv_nm_interface], [lt_cv_nm_interface="BSD nm" echo "int some_variable = 0;" > conftest.$ac_ext (eval echo "\"\$as_me:$LINENO: $ac_compile\"" >&AS_MESSAGE_LOG_FD) (eval "$ac_compile" 2>conftest.err) cat conftest.err >&AS_MESSAGE_LOG_FD (eval echo "\"\$as_me:$LINENO: $NM \\\"conftest.$ac_objext\\\"\"" >&AS_MESSAGE_LOG_FD) (eval "$NM \"conftest.$ac_objext\"" 2>conftest.err > conftest.out) cat conftest.err >&AS_MESSAGE_LOG_FD (eval echo "\"\$as_me:$LINENO: output\"" >&AS_MESSAGE_LOG_FD) cat conftest.out >&AS_MESSAGE_LOG_FD if $GREP 'External.*some_variable' conftest.out > /dev/null; then lt_cv_nm_interface="MS dumpbin" fi rm -f conftest*]) ])# LT_PATH_NM # Old names: AU_ALIAS([AM_PROG_NM], [LT_PATH_NM]) AU_ALIAS([AC_PROG_NM], [LT_PATH_NM]) dnl aclocal-1.4 backwards compatibility: dnl AC_DEFUN([AM_PROG_NM], []) dnl AC_DEFUN([AC_PROG_NM], []) # _LT_CHECK_SHAREDLIB_FROM_LINKLIB # -------------------------------- # how to determine the name of the shared library # associated with a specific link library. # -- PORTME fill in with the dynamic library characteristics m4_defun([_LT_CHECK_SHAREDLIB_FROM_LINKLIB], [m4_require([_LT_DECL_EGREP]) m4_require([_LT_DECL_OBJDUMP]) m4_require([_LT_DECL_DLLTOOL]) AC_CACHE_CHECK([how to associate runtime and link libraries], lt_cv_sharedlib_from_linklib_cmd, [lt_cv_sharedlib_from_linklib_cmd='unknown' case $host_os in cygwin* | mingw* | pw32* | cegcc*) # two different shell functions defined in ltmain.sh # decide which to use based on capabilities of $DLLTOOL case `$DLLTOOL --help 2>&1` in *--identify-strict*) lt_cv_sharedlib_from_linklib_cmd=func_cygming_dll_for_implib ;; *) lt_cv_sharedlib_from_linklib_cmd=func_cygming_dll_for_implib_fallback ;; esac ;; *) # fallback: assume linklib IS sharedlib lt_cv_sharedlib_from_linklib_cmd="$ECHO" ;; esac ]) sharedlib_from_linklib_cmd=$lt_cv_sharedlib_from_linklib_cmd test -z "$sharedlib_from_linklib_cmd" && sharedlib_from_linklib_cmd=$ECHO _LT_DECL([], [sharedlib_from_linklib_cmd], [1], [Command to associate shared and link libraries]) ])# _LT_CHECK_SHAREDLIB_FROM_LINKLIB # _LT_PATH_MANIFEST_TOOL # ---------------------- # locate the manifest tool m4_defun([_LT_PATH_MANIFEST_TOOL], [AC_CHECK_TOOL(MANIFEST_TOOL, mt, :) test -z "$MANIFEST_TOOL" && MANIFEST_TOOL=mt AC_CACHE_CHECK([if $MANIFEST_TOOL is a manifest tool], [lt_cv_path_mainfest_tool], [lt_cv_path_mainfest_tool=no echo "$as_me:$LINENO: $MANIFEST_TOOL '-?'" >&AS_MESSAGE_LOG_FD $MANIFEST_TOOL '-?' 2>conftest.err > conftest.out cat conftest.err >&AS_MESSAGE_LOG_FD if $GREP 'Manifest Tool' conftest.out > /dev/null; then lt_cv_path_mainfest_tool=yes fi rm -f conftest*]) if test "x$lt_cv_path_mainfest_tool" != xyes; then MANIFEST_TOOL=: fi _LT_DECL([], [MANIFEST_TOOL], [1], [Manifest tool])dnl ])# _LT_PATH_MANIFEST_TOOL # LT_LIB_M # -------- # check for math library AC_DEFUN([LT_LIB_M], [AC_REQUIRE([AC_CANONICAL_HOST])dnl LIBM= case $host in *-*-beos* | *-*-cegcc* | *-*-cygwin* | *-*-haiku* | *-*-pw32* | *-*-darwin*) # These system don't have libm, or don't need it ;; *-ncr-sysv4.3*) AC_CHECK_LIB(mw, _mwvalidcheckl, LIBM="-lmw") AC_CHECK_LIB(m, cos, LIBM="$LIBM -lm") ;; *) AC_CHECK_LIB(m, cos, LIBM="-lm") ;; esac AC_SUBST([LIBM]) ])# LT_LIB_M # Old name: AU_ALIAS([AC_CHECK_LIBM], [LT_LIB_M]) dnl aclocal-1.4 backwards compatibility: dnl AC_DEFUN([AC_CHECK_LIBM], []) # _LT_COMPILER_NO_RTTI([TAGNAME]) # ------------------------------- m4_defun([_LT_COMPILER_NO_RTTI], [m4_require([_LT_TAG_COMPILER])dnl _LT_TAGVAR(lt_prog_compiler_no_builtin_flag, $1)= if test "$GCC" = yes; then case $cc_basename in nvcc*) _LT_TAGVAR(lt_prog_compiler_no_builtin_flag, $1)=' -Xcompiler -fno-builtin' ;; *) _LT_TAGVAR(lt_prog_compiler_no_builtin_flag, $1)=' -fno-builtin' ;; esac _LT_COMPILER_OPTION([if $compiler supports -fno-rtti -fno-exceptions], lt_cv_prog_compiler_rtti_exceptions, [-fno-rtti -fno-exceptions], [], [_LT_TAGVAR(lt_prog_compiler_no_builtin_flag, $1)="$_LT_TAGVAR(lt_prog_compiler_no_builtin_flag, $1) -fno-rtti -fno-exceptions"]) fi _LT_TAGDECL([no_builtin_flag], [lt_prog_compiler_no_builtin_flag], [1], [Compiler flag to turn off builtin functions]) ])# _LT_COMPILER_NO_RTTI # _LT_CMD_GLOBAL_SYMBOLS # ---------------------- m4_defun([_LT_CMD_GLOBAL_SYMBOLS], [AC_REQUIRE([AC_CANONICAL_HOST])dnl AC_REQUIRE([AC_PROG_CC])dnl AC_REQUIRE([AC_PROG_AWK])dnl AC_REQUIRE([LT_PATH_NM])dnl AC_REQUIRE([LT_PATH_LD])dnl m4_require([_LT_DECL_SED])dnl m4_require([_LT_DECL_EGREP])dnl m4_require([_LT_TAG_COMPILER])dnl # Check for command to grab the raw symbol name followed by C symbol from nm. AC_MSG_CHECKING([command to parse $NM output from $compiler object]) AC_CACHE_VAL([lt_cv_sys_global_symbol_pipe], [ # These are sane defaults that work on at least a few old systems. # [They come from Ultrix. What could be older than Ultrix?!! ;)] # Character class describing NM global symbol codes. symcode='[[BCDEGRST]]' # Regexp to match symbols that can be accessed directly from C. sympat='\([[_A-Za-z]][[_A-Za-z0-9]]*\)' # Define system-specific variables. case $host_os in aix*) symcode='[[BCDT]]' ;; cygwin* | mingw* | pw32* | cegcc*) symcode='[[ABCDGISTW]]' ;; hpux*) if test "$host_cpu" = ia64; then symcode='[[ABCDEGRST]]' fi ;; irix* | nonstopux*) symcode='[[BCDEGRST]]' ;; osf*) symcode='[[BCDEGQRST]]' ;; solaris*) symcode='[[BDRT]]' ;; sco3.2v5*) symcode='[[DT]]' ;; sysv4.2uw2*) symcode='[[DT]]' ;; sysv5* | sco5v6* | unixware* | OpenUNIX*) symcode='[[ABDT]]' ;; sysv4) symcode='[[DFNSTU]]' ;; esac # If we're using GNU nm, then use its standard symbol codes. case `$NM -V 2>&1` in *GNU* | *'with BFD'*) symcode='[[ABCDGIRSTW]]' ;; esac # Transform an extracted symbol line into a proper C declaration. # Some systems (esp. on ia64) link data and code symbols differently, # so use this general approach. lt_cv_sys_global_symbol_to_cdecl="sed -n -e 's/^T .* \(.*\)$/extern int \1();/p' -e 's/^$symcode* .* \(.*\)$/extern char \1;/p'" # Transform an extracted symbol line into symbol name and symbol address lt_cv_sys_global_symbol_to_c_name_address="sed -n -e 's/^: \([[^ ]]*\)[[ ]]*$/ {\\\"\1\\\", (void *) 0},/p' -e 's/^$symcode* \([[^ ]]*\) \([[^ ]]*\)$/ {\"\2\", (void *) \&\2},/p'" lt_cv_sys_global_symbol_to_c_name_address_lib_prefix="sed -n -e 's/^: \([[^ ]]*\)[[ ]]*$/ {\\\"\1\\\", (void *) 0},/p' -e 's/^$symcode* \([[^ ]]*\) \(lib[[^ ]]*\)$/ {\"\2\", (void *) \&\2},/p' -e 's/^$symcode* \([[^ ]]*\) \([[^ ]]*\)$/ {\"lib\2\", (void *) \&\2},/p'" # Handle CRLF in mingw tool chain opt_cr= case $build_os in mingw*) opt_cr=`$ECHO 'x\{0,1\}' | tr x '\015'` # option cr in regexp ;; esac # Try without a prefix underscore, then with it. for ac_symprfx in "" "_"; do # Transform symcode, sympat, and symprfx into a raw symbol and a C symbol. symxfrm="\\1 $ac_symprfx\\2 \\2" # Write the raw and C identifiers. if test "$lt_cv_nm_interface" = "MS dumpbin"; then # Fake it for dumpbin and say T for any non-static function # and D for any global variable. # Also find C++ and __fastcall symbols from MSVC++, # which start with @ or ?. lt_cv_sys_global_symbol_pipe="$AWK ['"\ " {last_section=section; section=\$ 3};"\ " /^COFF SYMBOL TABLE/{for(i in hide) delete hide[i]};"\ " /Section length .*#relocs.*(pick any)/{hide[last_section]=1};"\ " \$ 0!~/External *\|/{next};"\ " / 0+ UNDEF /{next}; / UNDEF \([^|]\)*()/{next};"\ " {if(hide[section]) next};"\ " {f=0}; \$ 0~/\(\).*\|/{f=1}; {printf f ? \"T \" : \"D \"};"\ " {split(\$ 0, a, /\||\r/); split(a[2], s)};"\ " s[1]~/^[@?]/{print s[1], s[1]; next};"\ " s[1]~prfx {split(s[1],t,\"@\"); print t[1], substr(t[1],length(prfx))}"\ " ' prfx=^$ac_symprfx]" else lt_cv_sys_global_symbol_pipe="sed -n -e 's/^.*[[ ]]\($symcode$symcode*\)[[ ]][[ ]]*$ac_symprfx$sympat$opt_cr$/$symxfrm/p'" fi lt_cv_sys_global_symbol_pipe="$lt_cv_sys_global_symbol_pipe | sed '/ __gnu_lto/d'" # Check to see that the pipe works correctly. pipe_works=no rm -f conftest* cat > conftest.$ac_ext <<_LT_EOF #ifdef __cplusplus extern "C" { #endif char nm_test_var; void nm_test_func(void); void nm_test_func(void){} #ifdef __cplusplus } #endif int main(){nm_test_var='a';nm_test_func();return(0);} _LT_EOF if AC_TRY_EVAL(ac_compile); then # Now try to grab the symbols. nlist=conftest.nm if AC_TRY_EVAL(NM conftest.$ac_objext \| "$lt_cv_sys_global_symbol_pipe" \> $nlist) && test -s "$nlist"; then # Try sorting and uniquifying the output. if sort "$nlist" | uniq > "$nlist"T; then mv -f "$nlist"T "$nlist" else rm -f "$nlist"T fi # Make sure that we snagged all the symbols we need. if $GREP ' nm_test_var$' "$nlist" >/dev/null; then if $GREP ' nm_test_func$' "$nlist" >/dev/null; then cat <<_LT_EOF > conftest.$ac_ext /* Keep this code in sync between libtool.m4, ltmain, lt_system.h, and tests. */ #if defined(_WIN32) || defined(__CYGWIN__) || defined(_WIN32_WCE) /* DATA imports from DLLs on WIN32 con't be const, because runtime relocations are performed -- see ld's documentation on pseudo-relocs. */ # define LT@&t@_DLSYM_CONST #elif defined(__osf__) /* This system does not cope well with relocations in const data. */ # define LT@&t@_DLSYM_CONST #else # define LT@&t@_DLSYM_CONST const #endif #ifdef __cplusplus extern "C" { #endif _LT_EOF # Now generate the symbol file. eval "$lt_cv_sys_global_symbol_to_cdecl"' < "$nlist" | $GREP -v main >> conftest.$ac_ext' cat <<_LT_EOF >> conftest.$ac_ext /* The mapping between symbol names and symbols. */ LT@&t@_DLSYM_CONST struct { const char *name; void *address; } lt__PROGRAM__LTX_preloaded_symbols[[]] = { { "@PROGRAM@", (void *) 0 }, _LT_EOF $SED "s/^$symcode$symcode* \(.*\) \(.*\)$/ {\"\2\", (void *) \&\2},/" < "$nlist" | $GREP -v main >> conftest.$ac_ext cat <<\_LT_EOF >> conftest.$ac_ext {0, (void *) 0} }; /* This works around a problem in FreeBSD linker */ #ifdef FREEBSD_WORKAROUND static const void *lt_preloaded_setup() { return lt__PROGRAM__LTX_preloaded_symbols; } #endif #ifdef __cplusplus } #endif _LT_EOF # Now try linking the two files. mv conftest.$ac_objext conftstm.$ac_objext lt_globsym_save_LIBS=$LIBS lt_globsym_save_CFLAGS=$CFLAGS LIBS="conftstm.$ac_objext" CFLAGS="$CFLAGS$_LT_TAGVAR(lt_prog_compiler_no_builtin_flag, $1)" if AC_TRY_EVAL(ac_link) && test -s conftest${ac_exeext}; then pipe_works=yes fi LIBS=$lt_globsym_save_LIBS CFLAGS=$lt_globsym_save_CFLAGS else echo "cannot find nm_test_func in $nlist" >&AS_MESSAGE_LOG_FD fi else echo "cannot find nm_test_var in $nlist" >&AS_MESSAGE_LOG_FD fi else echo "cannot run $lt_cv_sys_global_symbol_pipe" >&AS_MESSAGE_LOG_FD fi else echo "$progname: failed program was:" >&AS_MESSAGE_LOG_FD cat conftest.$ac_ext >&5 fi rm -rf conftest* conftst* # Do not use the global_symbol_pipe unless it works. if test "$pipe_works" = yes; then break else lt_cv_sys_global_symbol_pipe= fi done ]) if test -z "$lt_cv_sys_global_symbol_pipe"; then lt_cv_sys_global_symbol_to_cdecl= fi if test -z "$lt_cv_sys_global_symbol_pipe$lt_cv_sys_global_symbol_to_cdecl"; then AC_MSG_RESULT(failed) else AC_MSG_RESULT(ok) fi # Response file support. if test "$lt_cv_nm_interface" = "MS dumpbin"; then nm_file_list_spec='@' elif $NM --help 2>/dev/null | grep '[[@]]FILE' >/dev/null; then nm_file_list_spec='@' fi _LT_DECL([global_symbol_pipe], [lt_cv_sys_global_symbol_pipe], [1], [Take the output of nm and produce a listing of raw symbols and C names]) _LT_DECL([global_symbol_to_cdecl], [lt_cv_sys_global_symbol_to_cdecl], [1], [Transform the output of nm in a proper C declaration]) _LT_DECL([global_symbol_to_c_name_address], [lt_cv_sys_global_symbol_to_c_name_address], [1], [Transform the output of nm in a C name address pair]) _LT_DECL([global_symbol_to_c_name_address_lib_prefix], [lt_cv_sys_global_symbol_to_c_name_address_lib_prefix], [1], [Transform the output of nm in a C name address pair when lib prefix is needed]) _LT_DECL([], [nm_file_list_spec], [1], [Specify filename containing input files for $NM]) ]) # _LT_CMD_GLOBAL_SYMBOLS # _LT_COMPILER_PIC([TAGNAME]) # --------------------------- m4_defun([_LT_COMPILER_PIC], [m4_require([_LT_TAG_COMPILER])dnl _LT_TAGVAR(lt_prog_compiler_wl, $1)= _LT_TAGVAR(lt_prog_compiler_pic, $1)= _LT_TAGVAR(lt_prog_compiler_static, $1)= m4_if([$1], [CXX], [ # C++ specific cases for pic, static, wl, etc. if test "$GXX" = yes; then _LT_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,' _LT_TAGVAR(lt_prog_compiler_static, $1)='-static' case $host_os in aix*) # All AIX code is PIC. if test "$host_cpu" = ia64; then # AIX 5 now supports IA64 processor _LT_TAGVAR(lt_prog_compiler_static, $1)='-Bstatic' fi ;; amigaos*) case $host_cpu in powerpc) # see comment about AmigaOS4 .so support _LT_TAGVAR(lt_prog_compiler_pic, $1)='-fPIC' ;; m68k) # FIXME: we need at least 68020 code to build shared libraries, but # adding the `-m68020' flag to GCC prevents building anything better, # like `-m68040'. _LT_TAGVAR(lt_prog_compiler_pic, $1)='-m68020 -resident32 -malways-restore-a4' ;; esac ;; beos* | irix5* | irix6* | nonstopux* | osf3* | osf4* | osf5*) # PIC is the default for these OSes. ;; mingw* | cygwin* | os2* | pw32* | cegcc*) # This hack is so that the source file can tell whether it is being # built for inclusion in a dll (and should export symbols for example). # Although the cygwin gcc ignores -fPIC, still need this for old-style # (--disable-auto-import) libraries m4_if([$1], [GCJ], [], [_LT_TAGVAR(lt_prog_compiler_pic, $1)='-DDLL_EXPORT']) ;; darwin* | rhapsody*) # PIC is the default on this platform # Common symbols not allowed in MH_DYLIB files _LT_TAGVAR(lt_prog_compiler_pic, $1)='-fno-common' ;; *djgpp*) # DJGPP does not support shared libraries at all _LT_TAGVAR(lt_prog_compiler_pic, $1)= ;; haiku*) # PIC is the default for Haiku. # The "-static" flag exists, but is broken. _LT_TAGVAR(lt_prog_compiler_static, $1)= ;; interix[[3-9]]*) # Interix 3.x gcc -fpic/-fPIC options generate broken code. # Instead, we relocate shared libraries at runtime. ;; sysv4*MP*) if test -d /usr/nec; then _LT_TAGVAR(lt_prog_compiler_pic, $1)=-Kconform_pic fi ;; hpux*) # PIC is the default for 64-bit PA HP-UX, but not for 32-bit # PA HP-UX. On IA64 HP-UX, PIC is the default but the pic flag # sets the default TLS model and affects inlining. case $host_cpu in hppa*64*) ;; *) _LT_TAGVAR(lt_prog_compiler_pic, $1)='-fPIC' ;; esac ;; *qnx* | *nto*) # QNX uses GNU C++, but need to define -shared option too, otherwise # it will coredump. _LT_TAGVAR(lt_prog_compiler_pic, $1)='-fPIC -shared' ;; *) _LT_TAGVAR(lt_prog_compiler_pic, $1)='-fPIC' ;; esac else case $host_os in aix[[4-9]]*) # All AIX code is PIC. if test "$host_cpu" = ia64; then # AIX 5 now supports IA64 processor _LT_TAGVAR(lt_prog_compiler_static, $1)='-Bstatic' else _LT_TAGVAR(lt_prog_compiler_static, $1)='-bnso -bI:/lib/syscalls.exp' fi ;; chorus*) case $cc_basename in cxch68*) # Green Hills C++ Compiler # _LT_TAGVAR(lt_prog_compiler_static, $1)="--no_auto_instantiation -u __main -u __premain -u _abort -r $COOL_DIR/lib/libOrb.a $MVME_DIR/lib/CC/libC.a $MVME_DIR/lib/classix/libcx.s.a" ;; esac ;; mingw* | cygwin* | os2* | pw32* | cegcc*) # This hack is so that the source file can tell whether it is being # built for inclusion in a dll (and should export symbols for example). m4_if([$1], [GCJ], [], [_LT_TAGVAR(lt_prog_compiler_pic, $1)='-DDLL_EXPORT']) ;; dgux*) case $cc_basename in ec++*) _LT_TAGVAR(lt_prog_compiler_pic, $1)='-KPIC' ;; ghcx*) # Green Hills C++ Compiler _LT_TAGVAR(lt_prog_compiler_pic, $1)='-pic' ;; *) ;; esac ;; freebsd* | dragonfly*) # FreeBSD uses GNU C++ ;; hpux9* | hpux10* | hpux11*) case $cc_basename in CC*) _LT_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,' _LT_TAGVAR(lt_prog_compiler_static, $1)='${wl}-a ${wl}archive' if test "$host_cpu" != ia64; then _LT_TAGVAR(lt_prog_compiler_pic, $1)='+Z' fi ;; aCC*) _LT_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,' _LT_TAGVAR(lt_prog_compiler_static, $1)='${wl}-a ${wl}archive' case $host_cpu in hppa*64*|ia64*) # +Z the default ;; *) _LT_TAGVAR(lt_prog_compiler_pic, $1)='+Z' ;; esac ;; *) ;; esac ;; interix*) # This is c89, which is MS Visual C++ (no shared libs) # Anyone wants to do a port? ;; irix5* | irix6* | nonstopux*) case $cc_basename in CC*) _LT_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,' _LT_TAGVAR(lt_prog_compiler_static, $1)='-non_shared' # CC pic flag -KPIC is the default. ;; *) ;; esac ;; linux* | k*bsd*-gnu | kopensolaris*-gnu) case $cc_basename in KCC*) # KAI C++ Compiler _LT_TAGVAR(lt_prog_compiler_wl, $1)='--backend -Wl,' _LT_TAGVAR(lt_prog_compiler_pic, $1)='-fPIC' ;; ecpc* ) # old Intel C++ for x86_64 which still supported -KPIC. _LT_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,' _LT_TAGVAR(lt_prog_compiler_pic, $1)='-KPIC' _LT_TAGVAR(lt_prog_compiler_static, $1)='-static' ;; icpc* ) # Intel C++, used to be incompatible with GCC. # ICC 10 doesn't accept -KPIC any more. _LT_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,' _LT_TAGVAR(lt_prog_compiler_pic, $1)='-fPIC' _LT_TAGVAR(lt_prog_compiler_static, $1)='-static' ;; pgCC* | pgcpp*) # Portland Group C++ compiler _LT_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,' _LT_TAGVAR(lt_prog_compiler_pic, $1)='-fpic' _LT_TAGVAR(lt_prog_compiler_static, $1)='-Bstatic' ;; cxx*) # Compaq C++ # Make sure the PIC flag is empty. It appears that all Alpha # Linux and Compaq Tru64 Unix objects are PIC. _LT_TAGVAR(lt_prog_compiler_pic, $1)= _LT_TAGVAR(lt_prog_compiler_static, $1)='-non_shared' ;; xlc* | xlC* | bgxl[[cC]]* | mpixl[[cC]]*) # IBM XL 8.0, 9.0 on PPC and BlueGene _LT_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,' _LT_TAGVAR(lt_prog_compiler_pic, $1)='-qpic' _LT_TAGVAR(lt_prog_compiler_static, $1)='-qstaticlink' ;; *) case `$CC -V 2>&1 | sed 5q` in *Sun\ C*) # Sun C++ 5.9 _LT_TAGVAR(lt_prog_compiler_pic, $1)='-KPIC' _LT_TAGVAR(lt_prog_compiler_static, $1)='-Bstatic' _LT_TAGVAR(lt_prog_compiler_wl, $1)='-Qoption ld ' ;; esac ;; esac ;; lynxos*) ;; m88k*) ;; mvs*) case $cc_basename in cxx*) _LT_TAGVAR(lt_prog_compiler_pic, $1)='-W c,exportall' ;; *) ;; esac ;; netbsd*) ;; *qnx* | *nto*) # QNX uses GNU C++, but need to define -shared option too, otherwise # it will coredump. _LT_TAGVAR(lt_prog_compiler_pic, $1)='-fPIC -shared' ;; osf3* | osf4* | osf5*) case $cc_basename in KCC*) _LT_TAGVAR(lt_prog_compiler_wl, $1)='--backend -Wl,' ;; RCC*) # Rational C++ 2.4.1 _LT_TAGVAR(lt_prog_compiler_pic, $1)='-pic' ;; cxx*) # Digital/Compaq C++ _LT_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,' # Make sure the PIC flag is empty. It appears that all Alpha # Linux and Compaq Tru64 Unix objects are PIC. _LT_TAGVAR(lt_prog_compiler_pic, $1)= _LT_TAGVAR(lt_prog_compiler_static, $1)='-non_shared' ;; *) ;; esac ;; psos*) ;; solaris*) case $cc_basename in CC* | sunCC*) # Sun C++ 4.2, 5.x and Centerline C++ _LT_TAGVAR(lt_prog_compiler_pic, $1)='-KPIC' _LT_TAGVAR(lt_prog_compiler_static, $1)='-Bstatic' _LT_TAGVAR(lt_prog_compiler_wl, $1)='-Qoption ld ' ;; gcx*) # Green Hills C++ Compiler _LT_TAGVAR(lt_prog_compiler_pic, $1)='-PIC' ;; *) ;; esac ;; sunos4*) case $cc_basename in CC*) # Sun C++ 4.x _LT_TAGVAR(lt_prog_compiler_pic, $1)='-pic' _LT_TAGVAR(lt_prog_compiler_static, $1)='-Bstatic' ;; lcc*) # Lucid _LT_TAGVAR(lt_prog_compiler_pic, $1)='-pic' ;; *) ;; esac ;; sysv5* | unixware* | sco3.2v5* | sco5v6* | OpenUNIX*) case $cc_basename in CC*) _LT_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,' _LT_TAGVAR(lt_prog_compiler_pic, $1)='-KPIC' _LT_TAGVAR(lt_prog_compiler_static, $1)='-Bstatic' ;; esac ;; tandem*) case $cc_basename in NCC*) # NonStop-UX NCC 3.20 _LT_TAGVAR(lt_prog_compiler_pic, $1)='-KPIC' ;; *) ;; esac ;; vxworks*) ;; *) _LT_TAGVAR(lt_prog_compiler_can_build_shared, $1)=no ;; esac fi ], [ if test "$GCC" = yes; then _LT_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,' _LT_TAGVAR(lt_prog_compiler_static, $1)='-static' case $host_os in aix*) # All AIX code is PIC. if test "$host_cpu" = ia64; then # AIX 5 now supports IA64 processor _LT_TAGVAR(lt_prog_compiler_static, $1)='-Bstatic' fi ;; amigaos*) case $host_cpu in powerpc) # see comment about AmigaOS4 .so support _LT_TAGVAR(lt_prog_compiler_pic, $1)='-fPIC' ;; m68k) # FIXME: we need at least 68020 code to build shared libraries, but # adding the `-m68020' flag to GCC prevents building anything better, # like `-m68040'. _LT_TAGVAR(lt_prog_compiler_pic, $1)='-m68020 -resident32 -malways-restore-a4' ;; esac ;; beos* | irix5* | irix6* | nonstopux* | osf3* | osf4* | osf5*) # PIC is the default for these OSes. ;; mingw* | cygwin* | pw32* | os2* | cegcc*) # This hack is so that the source file can tell whether it is being # built for inclusion in a dll (and should export symbols for example). # Although the cygwin gcc ignores -fPIC, still need this for old-style # (--disable-auto-import) libraries m4_if([$1], [GCJ], [], [_LT_TAGVAR(lt_prog_compiler_pic, $1)='-DDLL_EXPORT']) ;; darwin* | rhapsody*) # PIC is the default on this platform # Common symbols not allowed in MH_DYLIB files _LT_TAGVAR(lt_prog_compiler_pic, $1)='-fno-common' ;; haiku*) # PIC is the default for Haiku. # The "-static" flag exists, but is broken. _LT_TAGVAR(lt_prog_compiler_static, $1)= ;; hpux*) # PIC is the default for 64-bit PA HP-UX, but not for 32-bit # PA HP-UX. On IA64 HP-UX, PIC is the default but the pic flag # sets the default TLS model and affects inlining. case $host_cpu in hppa*64*) # +Z the default ;; *) _LT_TAGVAR(lt_prog_compiler_pic, $1)='-fPIC' ;; esac ;; interix[[3-9]]*) # Interix 3.x gcc -fpic/-fPIC options generate broken code. # Instead, we relocate shared libraries at runtime. ;; msdosdjgpp*) # Just because we use GCC doesn't mean we suddenly get shared libraries # on systems that don't support them. _LT_TAGVAR(lt_prog_compiler_can_build_shared, $1)=no enable_shared=no ;; *nto* | *qnx*) # QNX uses GNU C++, but need to define -shared option too, otherwise # it will coredump. _LT_TAGVAR(lt_prog_compiler_pic, $1)='-fPIC -shared' ;; sysv4*MP*) if test -d /usr/nec; then _LT_TAGVAR(lt_prog_compiler_pic, $1)=-Kconform_pic fi ;; *) _LT_TAGVAR(lt_prog_compiler_pic, $1)='-fPIC' ;; esac case $cc_basename in nvcc*) # Cuda Compiler Driver 2.2 _LT_TAGVAR(lt_prog_compiler_wl, $1)='-Xlinker ' if test -n "$_LT_TAGVAR(lt_prog_compiler_pic, $1)"; then _LT_TAGVAR(lt_prog_compiler_pic, $1)="-Xcompiler $_LT_TAGVAR(lt_prog_compiler_pic, $1)" fi ;; esac else # PORTME Check for flag to pass linker flags through the system compiler. case $host_os in aix*) _LT_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,' if test "$host_cpu" = ia64; then # AIX 5 now supports IA64 processor _LT_TAGVAR(lt_prog_compiler_static, $1)='-Bstatic' else _LT_TAGVAR(lt_prog_compiler_static, $1)='-bnso -bI:/lib/syscalls.exp' fi ;; mingw* | cygwin* | pw32* | os2* | cegcc*) # This hack is so that the source file can tell whether it is being # built for inclusion in a dll (and should export symbols for example). m4_if([$1], [GCJ], [], [_LT_TAGVAR(lt_prog_compiler_pic, $1)='-DDLL_EXPORT']) ;; hpux9* | hpux10* | hpux11*) _LT_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,' # PIC is the default for IA64 HP-UX and 64-bit HP-UX, but # not for PA HP-UX. case $host_cpu in hppa*64*|ia64*) # +Z the default ;; *) _LT_TAGVAR(lt_prog_compiler_pic, $1)='+Z' ;; esac # Is there a better lt_prog_compiler_static that works with the bundled CC? _LT_TAGVAR(lt_prog_compiler_static, $1)='${wl}-a ${wl}archive' ;; irix5* | irix6* | nonstopux*) _LT_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,' # PIC (with -KPIC) is the default. _LT_TAGVAR(lt_prog_compiler_static, $1)='-non_shared' ;; linux* | k*bsd*-gnu | kopensolaris*-gnu) case $cc_basename in # old Intel for x86_64 which still supported -KPIC. ecc*) _LT_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,' _LT_TAGVAR(lt_prog_compiler_pic, $1)='-KPIC' _LT_TAGVAR(lt_prog_compiler_static, $1)='-static' ;; # icc used to be incompatible with GCC. # ICC 10 doesn't accept -KPIC any more. icc* | ifort*) _LT_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,' _LT_TAGVAR(lt_prog_compiler_pic, $1)='-fPIC' _LT_TAGVAR(lt_prog_compiler_static, $1)='-static' ;; # Lahey Fortran 8.1. lf95*) _LT_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,' _LT_TAGVAR(lt_prog_compiler_pic, $1)='--shared' _LT_TAGVAR(lt_prog_compiler_static, $1)='--static' ;; nagfor*) # NAG Fortran compiler _LT_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,-Wl,,' _LT_TAGVAR(lt_prog_compiler_pic, $1)='-PIC' _LT_TAGVAR(lt_prog_compiler_static, $1)='-Bstatic' ;; pgcc* | pgf77* | pgf90* | pgf95* | pgfortran*) # Portland Group compilers (*not* the Pentium gcc compiler, # which looks to be a dead project) _LT_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,' _LT_TAGVAR(lt_prog_compiler_pic, $1)='-fpic' _LT_TAGVAR(lt_prog_compiler_static, $1)='-Bstatic' ;; ccc*) _LT_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,' # All Alpha code is PIC. _LT_TAGVAR(lt_prog_compiler_static, $1)='-non_shared' ;; xl* | bgxl* | bgf* | mpixl*) # IBM XL C 8.0/Fortran 10.1, 11.1 on PPC and BlueGene _LT_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,' _LT_TAGVAR(lt_prog_compiler_pic, $1)='-qpic' _LT_TAGVAR(lt_prog_compiler_static, $1)='-qstaticlink' ;; *) case `$CC -V 2>&1 | sed 5q` in *Sun\ Ceres\ Fortran* | *Sun*Fortran*\ [[1-7]].* | *Sun*Fortran*\ 8.[[0-3]]*) # Sun Fortran 8.3 passes all unrecognized flags to the linker _LT_TAGVAR(lt_prog_compiler_pic, $1)='-KPIC' _LT_TAGVAR(lt_prog_compiler_static, $1)='-Bstatic' _LT_TAGVAR(lt_prog_compiler_wl, $1)='' ;; *Sun\ F* | *Sun*Fortran*) _LT_TAGVAR(lt_prog_compiler_pic, $1)='-KPIC' _LT_TAGVAR(lt_prog_compiler_static, $1)='-Bstatic' _LT_TAGVAR(lt_prog_compiler_wl, $1)='-Qoption ld ' ;; *Sun\ C*) # Sun C 5.9 _LT_TAGVAR(lt_prog_compiler_pic, $1)='-KPIC' _LT_TAGVAR(lt_prog_compiler_static, $1)='-Bstatic' _LT_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,' ;; *Intel*\ [[CF]]*Compiler*) _LT_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,' _LT_TAGVAR(lt_prog_compiler_pic, $1)='-fPIC' _LT_TAGVAR(lt_prog_compiler_static, $1)='-static' ;; *Portland\ Group*) _LT_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,' _LT_TAGVAR(lt_prog_compiler_pic, $1)='-fpic' _LT_TAGVAR(lt_prog_compiler_static, $1)='-Bstatic' ;; esac ;; esac ;; newsos6) _LT_TAGVAR(lt_prog_compiler_pic, $1)='-KPIC' _LT_TAGVAR(lt_prog_compiler_static, $1)='-Bstatic' ;; *nto* | *qnx*) # QNX uses GNU C++, but need to define -shared option too, otherwise # it will coredump. _LT_TAGVAR(lt_prog_compiler_pic, $1)='-fPIC -shared' ;; osf3* | osf4* | osf5*) _LT_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,' # All OSF/1 code is PIC. _LT_TAGVAR(lt_prog_compiler_static, $1)='-non_shared' ;; rdos*) _LT_TAGVAR(lt_prog_compiler_static, $1)='-non_shared' ;; solaris*) _LT_TAGVAR(lt_prog_compiler_pic, $1)='-KPIC' _LT_TAGVAR(lt_prog_compiler_static, $1)='-Bstatic' case $cc_basename in f77* | f90* | f95* | sunf77* | sunf90* | sunf95*) _LT_TAGVAR(lt_prog_compiler_wl, $1)='-Qoption ld ';; *) _LT_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,';; esac ;; sunos4*) _LT_TAGVAR(lt_prog_compiler_wl, $1)='-Qoption ld ' _LT_TAGVAR(lt_prog_compiler_pic, $1)='-PIC' _LT_TAGVAR(lt_prog_compiler_static, $1)='-Bstatic' ;; sysv4 | sysv4.2uw2* | sysv4.3*) _LT_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,' _LT_TAGVAR(lt_prog_compiler_pic, $1)='-KPIC' _LT_TAGVAR(lt_prog_compiler_static, $1)='-Bstatic' ;; sysv4*MP*) if test -d /usr/nec ;then _LT_TAGVAR(lt_prog_compiler_pic, $1)='-Kconform_pic' _LT_TAGVAR(lt_prog_compiler_static, $1)='-Bstatic' fi ;; sysv5* | unixware* | sco3.2v5* | sco5v6* | OpenUNIX*) _LT_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,' _LT_TAGVAR(lt_prog_compiler_pic, $1)='-KPIC' _LT_TAGVAR(lt_prog_compiler_static, $1)='-Bstatic' ;; unicos*) _LT_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,' _LT_TAGVAR(lt_prog_compiler_can_build_shared, $1)=no ;; uts4*) _LT_TAGVAR(lt_prog_compiler_pic, $1)='-pic' _LT_TAGVAR(lt_prog_compiler_static, $1)='-Bstatic' ;; *) _LT_TAGVAR(lt_prog_compiler_can_build_shared, $1)=no ;; esac fi ]) case $host_os in # For platforms which do not support PIC, -DPIC is meaningless: *djgpp*) _LT_TAGVAR(lt_prog_compiler_pic, $1)= ;; *) _LT_TAGVAR(lt_prog_compiler_pic, $1)="$_LT_TAGVAR(lt_prog_compiler_pic, $1)@&t@m4_if([$1],[],[ -DPIC],[m4_if([$1],[CXX],[ -DPIC],[])])" ;; esac AC_CACHE_CHECK([for $compiler option to produce PIC], [_LT_TAGVAR(lt_cv_prog_compiler_pic, $1)], [_LT_TAGVAR(lt_cv_prog_compiler_pic, $1)=$_LT_TAGVAR(lt_prog_compiler_pic, $1)]) _LT_TAGVAR(lt_prog_compiler_pic, $1)=$_LT_TAGVAR(lt_cv_prog_compiler_pic, $1) # # Check to make sure the PIC flag actually works. # if test -n "$_LT_TAGVAR(lt_prog_compiler_pic, $1)"; then _LT_COMPILER_OPTION([if $compiler PIC flag $_LT_TAGVAR(lt_prog_compiler_pic, $1) works], [_LT_TAGVAR(lt_cv_prog_compiler_pic_works, $1)], [$_LT_TAGVAR(lt_prog_compiler_pic, $1)@&t@m4_if([$1],[],[ -DPIC],[m4_if([$1],[CXX],[ -DPIC],[])])], [], [case $_LT_TAGVAR(lt_prog_compiler_pic, $1) in "" | " "*) ;; *) _LT_TAGVAR(lt_prog_compiler_pic, $1)=" $_LT_TAGVAR(lt_prog_compiler_pic, $1)" ;; esac], [_LT_TAGVAR(lt_prog_compiler_pic, $1)= _LT_TAGVAR(lt_prog_compiler_can_build_shared, $1)=no]) fi _LT_TAGDECL([pic_flag], [lt_prog_compiler_pic], [1], [Additional compiler flags for building library objects]) _LT_TAGDECL([wl], [lt_prog_compiler_wl], [1], [How to pass a linker flag through the compiler]) # # Check to make sure the static flag actually works. # wl=$_LT_TAGVAR(lt_prog_compiler_wl, $1) eval lt_tmp_static_flag=\"$_LT_TAGVAR(lt_prog_compiler_static, $1)\" _LT_LINKER_OPTION([if $compiler static flag $lt_tmp_static_flag works], _LT_TAGVAR(lt_cv_prog_compiler_static_works, $1), $lt_tmp_static_flag, [], [_LT_TAGVAR(lt_prog_compiler_static, $1)=]) _LT_TAGDECL([link_static_flag], [lt_prog_compiler_static], [1], [Compiler flag to prevent dynamic linking]) ])# _LT_COMPILER_PIC # _LT_LINKER_SHLIBS([TAGNAME]) # ---------------------------- # See if the linker supports building shared libraries. m4_defun([_LT_LINKER_SHLIBS], [AC_REQUIRE([LT_PATH_LD])dnl AC_REQUIRE([LT_PATH_NM])dnl m4_require([_LT_PATH_MANIFEST_TOOL])dnl m4_require([_LT_FILEUTILS_DEFAULTS])dnl m4_require([_LT_DECL_EGREP])dnl m4_require([_LT_DECL_SED])dnl m4_require([_LT_CMD_GLOBAL_SYMBOLS])dnl m4_require([_LT_TAG_COMPILER])dnl AC_MSG_CHECKING([whether the $compiler linker ($LD) supports shared libraries]) m4_if([$1], [CXX], [ _LT_TAGVAR(export_symbols_cmds, $1)='$NM $libobjs $convenience | $global_symbol_pipe | $SED '\''s/.* //'\'' | sort | uniq > $export_symbols' _LT_TAGVAR(exclude_expsyms, $1)=['_GLOBAL_OFFSET_TABLE_|_GLOBAL__F[ID]_.*'] case $host_os in aix[[4-9]]*) # If we're using GNU nm, then we don't want the "-C" option. # -C means demangle to AIX nm, but means don't demangle with GNU nm # Also, AIX nm treats weak defined symbols like other global defined # symbols, whereas GNU nm marks them as "W". if $NM -V 2>&1 | $GREP 'GNU' > /dev/null; then _LT_TAGVAR(export_symbols_cmds, $1)='$NM -Bpg $libobjs $convenience | awk '\''{ if (((\$ 2 == "T") || (\$ 2 == "D") || (\$ 2 == "B") || (\$ 2 == "W")) && ([substr](\$ 3,1,1) != ".")) { print \$ 3 } }'\'' | sort -u > $export_symbols' else _LT_TAGVAR(export_symbols_cmds, $1)='$NM -BCpg $libobjs $convenience | awk '\''{ if (((\$ 2 == "T") || (\$ 2 == "D") || (\$ 2 == "B")) && ([substr](\$ 3,1,1) != ".")) { print \$ 3 } }'\'' | sort -u > $export_symbols' fi ;; pw32*) _LT_TAGVAR(export_symbols_cmds, $1)="$ltdll_cmds" ;; cygwin* | mingw* | cegcc*) case $cc_basename in cl*) _LT_TAGVAR(exclude_expsyms, $1)='_NULL_IMPORT_DESCRIPTOR|_IMPORT_DESCRIPTOR_.*' ;; *) _LT_TAGVAR(export_symbols_cmds, $1)='$NM $libobjs $convenience | $global_symbol_pipe | $SED -e '\''/^[[BCDGRS]][[ ]]/s/.*[[ ]]\([[^ ]]*\)/\1 DATA/;s/^.*[[ ]]__nm__\([[^ ]]*\)[[ ]][[^ ]]*/\1 DATA/;/^I[[ ]]/d;/^[[AITW]][[ ]]/s/.* //'\'' | sort | uniq > $export_symbols' _LT_TAGVAR(exclude_expsyms, $1)=['[_]+GLOBAL_OFFSET_TABLE_|[_]+GLOBAL__[FID]_.*|[_]+head_[A-Za-z0-9_]+_dll|[A-Za-z0-9_]+_dll_iname'] ;; esac ;; *) _LT_TAGVAR(export_symbols_cmds, $1)='$NM $libobjs $convenience | $global_symbol_pipe | $SED '\''s/.* //'\'' | sort | uniq > $export_symbols' ;; esac ], [ runpath_var= _LT_TAGVAR(allow_undefined_flag, $1)= _LT_TAGVAR(always_export_symbols, $1)=no _LT_TAGVAR(archive_cmds, $1)= _LT_TAGVAR(archive_expsym_cmds, $1)= _LT_TAGVAR(compiler_needs_object, $1)=no _LT_TAGVAR(enable_shared_with_static_runtimes, $1)=no _LT_TAGVAR(export_dynamic_flag_spec, $1)= _LT_TAGVAR(export_symbols_cmds, $1)='$NM $libobjs $convenience | $global_symbol_pipe | $SED '\''s/.* //'\'' | sort | uniq > $export_symbols' _LT_TAGVAR(hardcode_automatic, $1)=no _LT_TAGVAR(hardcode_direct, $1)=no _LT_TAGVAR(hardcode_direct_absolute, $1)=no _LT_TAGVAR(hardcode_libdir_flag_spec, $1)= _LT_TAGVAR(hardcode_libdir_separator, $1)= _LT_TAGVAR(hardcode_minus_L, $1)=no _LT_TAGVAR(hardcode_shlibpath_var, $1)=unsupported _LT_TAGVAR(inherit_rpath, $1)=no _LT_TAGVAR(link_all_deplibs, $1)=unknown _LT_TAGVAR(module_cmds, $1)= _LT_TAGVAR(module_expsym_cmds, $1)= _LT_TAGVAR(old_archive_from_new_cmds, $1)= _LT_TAGVAR(old_archive_from_expsyms_cmds, $1)= _LT_TAGVAR(thread_safe_flag_spec, $1)= _LT_TAGVAR(whole_archive_flag_spec, $1)= # include_expsyms should be a list of space-separated symbols to be *always* # included in the symbol list _LT_TAGVAR(include_expsyms, $1)= # exclude_expsyms can be an extended regexp of symbols to exclude # it will be wrapped by ` (' and `)$', so one must not match beginning or # end of line. Example: `a|bc|.*d.*' will exclude the symbols `a' and `bc', # as well as any symbol that contains `d'. _LT_TAGVAR(exclude_expsyms, $1)=['_GLOBAL_OFFSET_TABLE_|_GLOBAL__F[ID]_.*'] # Although _GLOBAL_OFFSET_TABLE_ is a valid symbol C name, most a.out # platforms (ab)use it in PIC code, but their linkers get confused if # the symbol is explicitly referenced. Since portable code cannot # rely on this symbol name, it's probably fine to never include it in # preloaded symbol tables. # Exclude shared library initialization/finalization symbols. dnl Note also adjust exclude_expsyms for C++ above. extract_expsyms_cmds= case $host_os in cygwin* | mingw* | pw32* | cegcc*) # FIXME: the MSVC++ port hasn't been tested in a loooong time # When not using gcc, we currently assume that we are using # Microsoft Visual C++. if test "$GCC" != yes; then with_gnu_ld=no fi ;; interix*) # we just hope/assume this is gcc and not c89 (= MSVC++) with_gnu_ld=yes ;; openbsd*) with_gnu_ld=no ;; esac _LT_TAGVAR(ld_shlibs, $1)=yes # On some targets, GNU ld is compatible enough with the native linker # that we're better off using the native interface for both. lt_use_gnu_ld_interface=no if test "$with_gnu_ld" = yes; then case $host_os in aix*) # The AIX port of GNU ld has always aspired to compatibility # with the native linker. However, as the warning in the GNU ld # block says, versions before 2.19.5* couldn't really create working # shared libraries, regardless of the interface used. case `$LD -v 2>&1` in *\ \(GNU\ Binutils\)\ 2.19.5*) ;; *\ \(GNU\ Binutils\)\ 2.[[2-9]]*) ;; *\ \(GNU\ Binutils\)\ [[3-9]]*) ;; *) lt_use_gnu_ld_interface=yes ;; esac ;; *) lt_use_gnu_ld_interface=yes ;; esac fi if test "$lt_use_gnu_ld_interface" = yes; then # If archive_cmds runs LD, not CC, wlarc should be empty wlarc='${wl}' # Set some defaults for GNU ld with shared library support. These # are reset later if shared libraries are not supported. Putting them # here allows them to be overridden if necessary. runpath_var=LD_RUN_PATH _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}-rpath ${wl}$libdir' _LT_TAGVAR(export_dynamic_flag_spec, $1)='${wl}--export-dynamic' # ancient GNU ld didn't support --whole-archive et. al. if $LD --help 2>&1 | $GREP 'no-whole-archive' > /dev/null; then _LT_TAGVAR(whole_archive_flag_spec, $1)="$wlarc"'--whole-archive$convenience '"$wlarc"'--no-whole-archive' else _LT_TAGVAR(whole_archive_flag_spec, $1)= fi supports_anon_versioning=no case `$LD -v 2>&1` in *GNU\ gold*) supports_anon_versioning=yes ;; *\ [[01]].* | *\ 2.[[0-9]].* | *\ 2.10.*) ;; # catch versions < 2.11 *\ 2.11.93.0.2\ *) supports_anon_versioning=yes ;; # RH7.3 ... *\ 2.11.92.0.12\ *) supports_anon_versioning=yes ;; # Mandrake 8.2 ... *\ 2.11.*) ;; # other 2.11 versions *) supports_anon_versioning=yes ;; esac # See if GNU ld supports shared libraries. case $host_os in aix[[3-9]]*) # On AIX/PPC, the GNU linker is very broken if test "$host_cpu" != ia64; then _LT_TAGVAR(ld_shlibs, $1)=no cat <<_LT_EOF 1>&2 *** Warning: the GNU linker, at least up to release 2.19, is reported *** to be unable to reliably create shared libraries on AIX. *** Therefore, libtool is disabling shared libraries support. If you *** really care for shared libraries, you may want to install binutils *** 2.20 or above, or modify your PATH so that a non-GNU linker is found. *** You will then need to restart the configuration process. _LT_EOF fi ;; amigaos*) case $host_cpu in powerpc) # see comment about AmigaOS4 .so support _LT_TAGVAR(archive_cmds, $1)='$CC -shared $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname -o $lib' _LT_TAGVAR(archive_expsym_cmds, $1)='' ;; m68k) _LT_TAGVAR(archive_cmds, $1)='$RM $output_objdir/a2ixlibrary.data~$ECHO "#define NAME $libname" > $output_objdir/a2ixlibrary.data~$ECHO "#define LIBRARY_ID 1" >> $output_objdir/a2ixlibrary.data~$ECHO "#define VERSION $major" >> $output_objdir/a2ixlibrary.data~$ECHO "#define REVISION $revision" >> $output_objdir/a2ixlibrary.data~$AR $AR_FLAGS $lib $libobjs~$RANLIB $lib~(cd $output_objdir && a2ixlibrary -32)' _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='-L$libdir' _LT_TAGVAR(hardcode_minus_L, $1)=yes ;; esac ;; beos*) if $LD --help 2>&1 | $GREP ': supported targets:.* elf' > /dev/null; then _LT_TAGVAR(allow_undefined_flag, $1)=unsupported # Joseph Beckenbach says some releases of gcc # support --undefined. This deserves some investigation. FIXME _LT_TAGVAR(archive_cmds, $1)='$CC -nostart $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname -o $lib' else _LT_TAGVAR(ld_shlibs, $1)=no fi ;; cygwin* | mingw* | pw32* | cegcc*) # _LT_TAGVAR(hardcode_libdir_flag_spec, $1) is actually meaningless, # as there is no search path for DLLs. _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='-L$libdir' _LT_TAGVAR(export_dynamic_flag_spec, $1)='${wl}--export-all-symbols' _LT_TAGVAR(allow_undefined_flag, $1)=unsupported _LT_TAGVAR(always_export_symbols, $1)=no _LT_TAGVAR(enable_shared_with_static_runtimes, $1)=yes _LT_TAGVAR(export_symbols_cmds, $1)='$NM $libobjs $convenience | $global_symbol_pipe | $SED -e '\''/^[[BCDGRS]][[ ]]/s/.*[[ ]]\([[^ ]]*\)/\1 DATA/;s/^.*[[ ]]__nm__\([[^ ]]*\)[[ ]][[^ ]]*/\1 DATA/;/^I[[ ]]/d;/^[[AITW]][[ ]]/s/.* //'\'' | sort | uniq > $export_symbols' _LT_TAGVAR(exclude_expsyms, $1)=['[_]+GLOBAL_OFFSET_TABLE_|[_]+GLOBAL__[FID]_.*|[_]+head_[A-Za-z0-9_]+_dll|[A-Za-z0-9_]+_dll_iname'] if $LD --help 2>&1 | $GREP 'auto-import' > /dev/null; then _LT_TAGVAR(archive_cmds, $1)='$CC -shared $libobjs $deplibs $compiler_flags -o $output_objdir/$soname ${wl}--enable-auto-image-base -Xlinker --out-implib -Xlinker $lib' # If the export-symbols file already is a .def file (1st line # is EXPORTS), use it as is; otherwise, prepend... _LT_TAGVAR(archive_expsym_cmds, $1)='if test "x`$SED 1q $export_symbols`" = xEXPORTS; then cp $export_symbols $output_objdir/$soname.def; else echo EXPORTS > $output_objdir/$soname.def; cat $export_symbols >> $output_objdir/$soname.def; fi~ $CC -shared $output_objdir/$soname.def $libobjs $deplibs $compiler_flags -o $output_objdir/$soname ${wl}--enable-auto-image-base -Xlinker --out-implib -Xlinker $lib' else _LT_TAGVAR(ld_shlibs, $1)=no fi ;; haiku*) _LT_TAGVAR(archive_cmds, $1)='$CC -shared $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname -o $lib' _LT_TAGVAR(link_all_deplibs, $1)=yes ;; interix[[3-9]]*) _LT_TAGVAR(hardcode_direct, $1)=no _LT_TAGVAR(hardcode_shlibpath_var, $1)=no _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}-rpath,$libdir' _LT_TAGVAR(export_dynamic_flag_spec, $1)='${wl}-E' # Hack: On Interix 3.x, we cannot compile PIC because of a broken gcc. # Instead, shared libraries are loaded at an image base (0x10000000 by # default) and relocated if they conflict, which is a slow very memory # consuming and fragmenting process. To avoid this, we pick a random, # 256 KiB-aligned image base between 0x50000000 and 0x6FFC0000 at link # time. Moving up from 0x10000000 also allows more sbrk(2) space. _LT_TAGVAR(archive_cmds, $1)='$CC -shared $pic_flag $libobjs $deplibs $compiler_flags ${wl}-h,$soname ${wl}--image-base,`expr ${RANDOM-$$} % 4096 / 2 \* 262144 + 1342177280` -o $lib' _LT_TAGVAR(archive_expsym_cmds, $1)='sed "s,^,_," $export_symbols >$output_objdir/$soname.expsym~$CC -shared $pic_flag $libobjs $deplibs $compiler_flags ${wl}-h,$soname ${wl}--retain-symbols-file,$output_objdir/$soname.expsym ${wl}--image-base,`expr ${RANDOM-$$} % 4096 / 2 \* 262144 + 1342177280` -o $lib' ;; gnu* | linux* | tpf* | k*bsd*-gnu | kopensolaris*-gnu) tmp_diet=no if test "$host_os" = linux-dietlibc; then case $cc_basename in diet\ *) tmp_diet=yes;; # linux-dietlibc with static linking (!diet-dyn) esac fi if $LD --help 2>&1 | $EGREP ': supported targets:.* elf' > /dev/null \ && test "$tmp_diet" = no then tmp_addflag=' $pic_flag' tmp_sharedflag='-shared' case $cc_basename,$host_cpu in pgcc*) # Portland Group C compiler _LT_TAGVAR(whole_archive_flag_spec, $1)='${wl}--whole-archive`for conv in $convenience\"\"; do test -n \"$conv\" && new_convenience=\"$new_convenience,$conv\"; done; func_echo_all \"$new_convenience\"` ${wl}--no-whole-archive' tmp_addflag=' $pic_flag' ;; pgf77* | pgf90* | pgf95* | pgfortran*) # Portland Group f77 and f90 compilers _LT_TAGVAR(whole_archive_flag_spec, $1)='${wl}--whole-archive`for conv in $convenience\"\"; do test -n \"$conv\" && new_convenience=\"$new_convenience,$conv\"; done; func_echo_all \"$new_convenience\"` ${wl}--no-whole-archive' tmp_addflag=' $pic_flag -Mnomain' ;; ecc*,ia64* | icc*,ia64*) # Intel C compiler on ia64 tmp_addflag=' -i_dynamic' ;; efc*,ia64* | ifort*,ia64*) # Intel Fortran compiler on ia64 tmp_addflag=' -i_dynamic -nofor_main' ;; ifc* | ifort*) # Intel Fortran compiler tmp_addflag=' -nofor_main' ;; lf95*) # Lahey Fortran 8.1 _LT_TAGVAR(whole_archive_flag_spec, $1)= tmp_sharedflag='--shared' ;; xl[[cC]]* | bgxl[[cC]]* | mpixl[[cC]]*) # IBM XL C 8.0 on PPC (deal with xlf below) tmp_sharedflag='-qmkshrobj' tmp_addflag= ;; nvcc*) # Cuda Compiler Driver 2.2 _LT_TAGVAR(whole_archive_flag_spec, $1)='${wl}--whole-archive`for conv in $convenience\"\"; do test -n \"$conv\" && new_convenience=\"$new_convenience,$conv\"; done; func_echo_all \"$new_convenience\"` ${wl}--no-whole-archive' _LT_TAGVAR(compiler_needs_object, $1)=yes ;; esac case `$CC -V 2>&1 | sed 5q` in *Sun\ C*) # Sun C 5.9 _LT_TAGVAR(whole_archive_flag_spec, $1)='${wl}--whole-archive`new_convenience=; for conv in $convenience\"\"; do test -z \"$conv\" || new_convenience=\"$new_convenience,$conv\"; done; func_echo_all \"$new_convenience\"` ${wl}--no-whole-archive' _LT_TAGVAR(compiler_needs_object, $1)=yes tmp_sharedflag='-G' ;; *Sun\ F*) # Sun Fortran 8.3 tmp_sharedflag='-G' ;; esac _LT_TAGVAR(archive_cmds, $1)='$CC '"$tmp_sharedflag""$tmp_addflag"' $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname -o $lib' if test "x$supports_anon_versioning" = xyes; then _LT_TAGVAR(archive_expsym_cmds, $1)='echo "{ global:" > $output_objdir/$libname.ver~ cat $export_symbols | sed -e "s/\(.*\)/\1;/" >> $output_objdir/$libname.ver~ echo "local: *; };" >> $output_objdir/$libname.ver~ $CC '"$tmp_sharedflag""$tmp_addflag"' $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname ${wl}-version-script ${wl}$output_objdir/$libname.ver -o $lib' fi case $cc_basename in xlf* | bgf* | bgxlf* | mpixlf*) # IBM XL Fortran 10.1 on PPC cannot create shared libs itself _LT_TAGVAR(whole_archive_flag_spec, $1)='--whole-archive$convenience --no-whole-archive' _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}-rpath ${wl}$libdir' _LT_TAGVAR(archive_cmds, $1)='$LD -shared $libobjs $deplibs $linker_flags -soname $soname -o $lib' if test "x$supports_anon_versioning" = xyes; then _LT_TAGVAR(archive_expsym_cmds, $1)='echo "{ global:" > $output_objdir/$libname.ver~ cat $export_symbols | sed -e "s/\(.*\)/\1;/" >> $output_objdir/$libname.ver~ echo "local: *; };" >> $output_objdir/$libname.ver~ $LD -shared $libobjs $deplibs $linker_flags -soname $soname -version-script $output_objdir/$libname.ver -o $lib' fi ;; esac else _LT_TAGVAR(ld_shlibs, $1)=no fi ;; netbsd*) if echo __ELF__ | $CC -E - | $GREP __ELF__ >/dev/null; then _LT_TAGVAR(archive_cmds, $1)='$LD -Bshareable $libobjs $deplibs $linker_flags -o $lib' wlarc= else _LT_TAGVAR(archive_cmds, $1)='$CC -shared $pic_flag $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname -o $lib' _LT_TAGVAR(archive_expsym_cmds, $1)='$CC -shared $pic_flag $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname ${wl}-retain-symbols-file $wl$export_symbols -o $lib' fi ;; solaris*) if $LD -v 2>&1 | $GREP 'BFD 2\.8' > /dev/null; then _LT_TAGVAR(ld_shlibs, $1)=no cat <<_LT_EOF 1>&2 *** Warning: The releases 2.8.* of the GNU linker cannot reliably *** create shared libraries on Solaris systems. Therefore, libtool *** is disabling shared libraries support. We urge you to upgrade GNU *** binutils to release 2.9.1 or newer. Another option is to modify *** your PATH or compiler configuration so that the native linker is *** used, and then restart. _LT_EOF elif $LD --help 2>&1 | $GREP ': supported targets:.* elf' > /dev/null; then _LT_TAGVAR(archive_cmds, $1)='$CC -shared $pic_flag $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname -o $lib' _LT_TAGVAR(archive_expsym_cmds, $1)='$CC -shared $pic_flag $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname ${wl}-retain-symbols-file $wl$export_symbols -o $lib' else _LT_TAGVAR(ld_shlibs, $1)=no fi ;; sysv5* | sco3.2v5* | sco5v6* | unixware* | OpenUNIX*) case `$LD -v 2>&1` in *\ [[01]].* | *\ 2.[[0-9]].* | *\ 2.1[[0-5]].*) _LT_TAGVAR(ld_shlibs, $1)=no cat <<_LT_EOF 1>&2 *** Warning: Releases of the GNU linker prior to 2.16.91.0.3 can not *** reliably create shared libraries on SCO systems. Therefore, libtool *** is disabling shared libraries support. We urge you to upgrade GNU *** binutils to release 2.16.91.0.3 or newer. Another option is to modify *** your PATH or compiler configuration so that the native linker is *** used, and then restart. _LT_EOF ;; *) # For security reasons, it is highly recommended that you always # use absolute paths for naming shared libraries, and exclude the # DT_RUNPATH tag from executables and libraries. But doing so # requires that you compile everything twice, which is a pain. if $LD --help 2>&1 | $GREP ': supported targets:.* elf' > /dev/null; then _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}-rpath ${wl}$libdir' _LT_TAGVAR(archive_cmds, $1)='$CC -shared $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname -o $lib' _LT_TAGVAR(archive_expsym_cmds, $1)='$CC -shared $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname ${wl}-retain-symbols-file $wl$export_symbols -o $lib' else _LT_TAGVAR(ld_shlibs, $1)=no fi ;; esac ;; sunos4*) _LT_TAGVAR(archive_cmds, $1)='$LD -assert pure-text -Bshareable -o $lib $libobjs $deplibs $linker_flags' wlarc= _LT_TAGVAR(hardcode_direct, $1)=yes _LT_TAGVAR(hardcode_shlibpath_var, $1)=no ;; *) if $LD --help 2>&1 | $GREP ': supported targets:.* elf' > /dev/null; then _LT_TAGVAR(archive_cmds, $1)='$CC -shared $pic_flag $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname -o $lib' _LT_TAGVAR(archive_expsym_cmds, $1)='$CC -shared $pic_flag $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname ${wl}-retain-symbols-file $wl$export_symbols -o $lib' else _LT_TAGVAR(ld_shlibs, $1)=no fi ;; esac if test "$_LT_TAGVAR(ld_shlibs, $1)" = no; then runpath_var= _LT_TAGVAR(hardcode_libdir_flag_spec, $1)= _LT_TAGVAR(export_dynamic_flag_spec, $1)= _LT_TAGVAR(whole_archive_flag_spec, $1)= fi else # PORTME fill in a description of your system's linker (not GNU ld) case $host_os in aix3*) _LT_TAGVAR(allow_undefined_flag, $1)=unsupported _LT_TAGVAR(always_export_symbols, $1)=yes _LT_TAGVAR(archive_expsym_cmds, $1)='$LD -o $output_objdir/$soname $libobjs $deplibs $linker_flags -bE:$export_symbols -T512 -H512 -bM:SRE~$AR $AR_FLAGS $lib $output_objdir/$soname' # Note: this linker hardcodes the directories in LIBPATH if there # are no directories specified by -L. _LT_TAGVAR(hardcode_minus_L, $1)=yes if test "$GCC" = yes && test -z "$lt_prog_compiler_static"; then # Neither direct hardcoding nor static linking is supported with a # broken collect2. _LT_TAGVAR(hardcode_direct, $1)=unsupported fi ;; aix[[4-9]]*) if test "$host_cpu" = ia64; then # On IA64, the linker does run time linking by default, so we don't # have to do anything special. aix_use_runtimelinking=no exp_sym_flag='-Bexport' no_entry_flag="" else # If we're using GNU nm, then we don't want the "-C" option. # -C means demangle to AIX nm, but means don't demangle with GNU nm # Also, AIX nm treats weak defined symbols like other global # defined symbols, whereas GNU nm marks them as "W". if $NM -V 2>&1 | $GREP 'GNU' > /dev/null; then _LT_TAGVAR(export_symbols_cmds, $1)='$NM -Bpg $libobjs $convenience | awk '\''{ if (((\$ 2 == "T") || (\$ 2 == "D") || (\$ 2 == "B") || (\$ 2 == "W")) && ([substr](\$ 3,1,1) != ".")) { print \$ 3 } }'\'' | sort -u > $export_symbols' else _LT_TAGVAR(export_symbols_cmds, $1)='$NM -BCpg $libobjs $convenience | awk '\''{ if (((\$ 2 == "T") || (\$ 2 == "D") || (\$ 2 == "B")) && ([substr](\$ 3,1,1) != ".")) { print \$ 3 } }'\'' | sort -u > $export_symbols' fi aix_use_runtimelinking=no # Test if we are trying to use run time linking or normal # AIX style linking. If -brtl is somewhere in LDFLAGS, we # need to do runtime linking. case $host_os in aix4.[[23]]|aix4.[[23]].*|aix[[5-9]]*) for ld_flag in $LDFLAGS; do if (test $ld_flag = "-brtl" || test $ld_flag = "-Wl,-brtl"); then aix_use_runtimelinking=yes break fi done ;; esac exp_sym_flag='-bexport' no_entry_flag='-bnoentry' fi # When large executables or shared objects are built, AIX ld can # have problems creating the table of contents. If linking a library # or program results in "error TOC overflow" add -mminimal-toc to # CXXFLAGS/CFLAGS for g++/gcc. In the cases where that is not # enough to fix the problem, add -Wl,-bbigtoc to LDFLAGS. _LT_TAGVAR(archive_cmds, $1)='' _LT_TAGVAR(hardcode_direct, $1)=yes _LT_TAGVAR(hardcode_direct_absolute, $1)=yes _LT_TAGVAR(hardcode_libdir_separator, $1)=':' _LT_TAGVAR(link_all_deplibs, $1)=yes _LT_TAGVAR(file_list_spec, $1)='${wl}-f,' if test "$GCC" = yes; then case $host_os in aix4.[[012]]|aix4.[[012]].*) # We only want to do this on AIX 4.2 and lower, the check # below for broken collect2 doesn't work under 4.3+ collect2name=`${CC} -print-prog-name=collect2` if test -f "$collect2name" && strings "$collect2name" | $GREP resolve_lib_name >/dev/null then # We have reworked collect2 : else # We have old collect2 _LT_TAGVAR(hardcode_direct, $1)=unsupported # It fails to find uninstalled libraries when the uninstalled # path is not listed in the libpath. Setting hardcode_minus_L # to unsupported forces relinking _LT_TAGVAR(hardcode_minus_L, $1)=yes _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='-L$libdir' _LT_TAGVAR(hardcode_libdir_separator, $1)= fi ;; esac shared_flag='-shared' if test "$aix_use_runtimelinking" = yes; then shared_flag="$shared_flag "'${wl}-G' fi else # not using gcc if test "$host_cpu" = ia64; then # VisualAge C++, Version 5.5 for AIX 5L for IA-64, Beta 3 Release # chokes on -Wl,-G. The following line is correct: shared_flag='-G' else if test "$aix_use_runtimelinking" = yes; then shared_flag='${wl}-G' else shared_flag='${wl}-bM:SRE' fi fi fi _LT_TAGVAR(export_dynamic_flag_spec, $1)='${wl}-bexpall' # It seems that -bexpall does not export symbols beginning with # underscore (_), so it is better to generate a list of symbols to export. _LT_TAGVAR(always_export_symbols, $1)=yes if test "$aix_use_runtimelinking" = yes; then # Warning - without using the other runtime loading flags (-brtl), # -berok will link without error, but may produce a broken library. _LT_TAGVAR(allow_undefined_flag, $1)='-berok' # Determine the default libpath from the value encoded in an # empty executable. _LT_SYS_MODULE_PATH_AIX([$1]) _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}-blibpath:$libdir:'"$aix_libpath" _LT_TAGVAR(archive_expsym_cmds, $1)='$CC -o $output_objdir/$soname $libobjs $deplibs '"\${wl}$no_entry_flag"' $compiler_flags `if test "x${allow_undefined_flag}" != "x"; then func_echo_all "${wl}${allow_undefined_flag}"; else :; fi` '"\${wl}$exp_sym_flag:\$export_symbols $shared_flag" else if test "$host_cpu" = ia64; then _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}-R $libdir:/usr/lib:/lib' _LT_TAGVAR(allow_undefined_flag, $1)="-z nodefs" _LT_TAGVAR(archive_expsym_cmds, $1)="\$CC $shared_flag"' -o $output_objdir/$soname $libobjs $deplibs '"\${wl}$no_entry_flag"' $compiler_flags ${wl}${allow_undefined_flag} '"\${wl}$exp_sym_flag:\$export_symbols" else # Determine the default libpath from the value encoded in an # empty executable. _LT_SYS_MODULE_PATH_AIX([$1]) _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}-blibpath:$libdir:'"$aix_libpath" # Warning - without using the other run time loading flags, # -berok will link without error, but may produce a broken library. _LT_TAGVAR(no_undefined_flag, $1)=' ${wl}-bernotok' _LT_TAGVAR(allow_undefined_flag, $1)=' ${wl}-berok' if test "$with_gnu_ld" = yes; then # We only use this code for GNU lds that support --whole-archive. _LT_TAGVAR(whole_archive_flag_spec, $1)='${wl}--whole-archive$convenience ${wl}--no-whole-archive' else # Exported symbols can be pulled into shared objects from archives _LT_TAGVAR(whole_archive_flag_spec, $1)='$convenience' fi _LT_TAGVAR(archive_cmds_need_lc, $1)=yes # This is similar to how AIX traditionally builds its shared libraries. _LT_TAGVAR(archive_expsym_cmds, $1)="\$CC $shared_flag"' -o $output_objdir/$soname $libobjs $deplibs ${wl}-bnoentry $compiler_flags ${wl}-bE:$export_symbols${allow_undefined_flag}~$AR $AR_FLAGS $output_objdir/$libname$release.a $output_objdir/$soname' fi fi ;; amigaos*) case $host_cpu in powerpc) # see comment about AmigaOS4 .so support _LT_TAGVAR(archive_cmds, $1)='$CC -shared $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname -o $lib' _LT_TAGVAR(archive_expsym_cmds, $1)='' ;; m68k) _LT_TAGVAR(archive_cmds, $1)='$RM $output_objdir/a2ixlibrary.data~$ECHO "#define NAME $libname" > $output_objdir/a2ixlibrary.data~$ECHO "#define LIBRARY_ID 1" >> $output_objdir/a2ixlibrary.data~$ECHO "#define VERSION $major" >> $output_objdir/a2ixlibrary.data~$ECHO "#define REVISION $revision" >> $output_objdir/a2ixlibrary.data~$AR $AR_FLAGS $lib $libobjs~$RANLIB $lib~(cd $output_objdir && a2ixlibrary -32)' _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='-L$libdir' _LT_TAGVAR(hardcode_minus_L, $1)=yes ;; esac ;; bsdi[[45]]*) _LT_TAGVAR(export_dynamic_flag_spec, $1)=-rdynamic ;; cygwin* | mingw* | pw32* | cegcc*) # When not using gcc, we currently assume that we are using # Microsoft Visual C++. # hardcode_libdir_flag_spec is actually meaningless, as there is # no search path for DLLs. case $cc_basename in cl*) # Native MSVC _LT_TAGVAR(hardcode_libdir_flag_spec, $1)=' ' _LT_TAGVAR(allow_undefined_flag, $1)=unsupported _LT_TAGVAR(always_export_symbols, $1)=yes _LT_TAGVAR(file_list_spec, $1)='@' # Tell ltmain to make .lib files, not .a files. libext=lib # Tell ltmain to make .dll files, not .so files. shrext_cmds=".dll" # FIXME: Setting linknames here is a bad hack. _LT_TAGVAR(archive_cmds, $1)='$CC -o $output_objdir/$soname $libobjs $compiler_flags $deplibs -Wl,-dll~linknames=' _LT_TAGVAR(archive_expsym_cmds, $1)='if test "x`$SED 1q $export_symbols`" = xEXPORTS; then sed -n -e 's/\\\\\\\(.*\\\\\\\)/-link\\\ -EXPORT:\\\\\\\1/' -e '1\\\!p' < $export_symbols > $output_objdir/$soname.exp; else sed -e 's/\\\\\\\(.*\\\\\\\)/-link\\\ -EXPORT:\\\\\\\1/' < $export_symbols > $output_objdir/$soname.exp; fi~ $CC -o $tool_output_objdir$soname $libobjs $compiler_flags $deplibs "@$tool_output_objdir$soname.exp" -Wl,-DLL,-IMPLIB:"$tool_output_objdir$libname.dll.lib"~ linknames=' # The linker will not automatically build a static lib if we build a DLL. # _LT_TAGVAR(old_archive_from_new_cmds, $1)='true' _LT_TAGVAR(enable_shared_with_static_runtimes, $1)=yes _LT_TAGVAR(exclude_expsyms, $1)='_NULL_IMPORT_DESCRIPTOR|_IMPORT_DESCRIPTOR_.*' _LT_TAGVAR(export_symbols_cmds, $1)='$NM $libobjs $convenience | $global_symbol_pipe | $SED -e '\''/^[[BCDGRS]][[ ]]/s/.*[[ ]]\([[^ ]]*\)/\1,DATA/'\'' | $SED -e '\''/^[[AITW]][[ ]]/s/.*[[ ]]//'\'' | sort | uniq > $export_symbols' # Don't use ranlib _LT_TAGVAR(old_postinstall_cmds, $1)='chmod 644 $oldlib' _LT_TAGVAR(postlink_cmds, $1)='lt_outputfile="@OUTPUT@"~ lt_tool_outputfile="@TOOL_OUTPUT@"~ case $lt_outputfile in *.exe|*.EXE) ;; *) lt_outputfile="$lt_outputfile.exe" lt_tool_outputfile="$lt_tool_outputfile.exe" ;; esac~ if test "$MANIFEST_TOOL" != ":" && test -f "$lt_outputfile.manifest"; then $MANIFEST_TOOL -manifest "$lt_tool_outputfile.manifest" -outputresource:"$lt_tool_outputfile" || exit 1; $RM "$lt_outputfile.manifest"; fi' ;; *) # Assume MSVC wrapper _LT_TAGVAR(hardcode_libdir_flag_spec, $1)=' ' _LT_TAGVAR(allow_undefined_flag, $1)=unsupported # Tell ltmain to make .lib files, not .a files. libext=lib # Tell ltmain to make .dll files, not .so files. shrext_cmds=".dll" # FIXME: Setting linknames here is a bad hack. _LT_TAGVAR(archive_cmds, $1)='$CC -o $lib $libobjs $compiler_flags `func_echo_all "$deplibs" | $SED '\''s/ -lc$//'\''` -link -dll~linknames=' # The linker will automatically build a .lib file if we build a DLL. _LT_TAGVAR(old_archive_from_new_cmds, $1)='true' # FIXME: Should let the user specify the lib program. _LT_TAGVAR(old_archive_cmds, $1)='lib -OUT:$oldlib$oldobjs$old_deplibs' _LT_TAGVAR(enable_shared_with_static_runtimes, $1)=yes ;; esac ;; darwin* | rhapsody*) _LT_DARWIN_LINKER_FEATURES($1) ;; dgux*) _LT_TAGVAR(archive_cmds, $1)='$LD -G -h $soname -o $lib $libobjs $deplibs $linker_flags' _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='-L$libdir' _LT_TAGVAR(hardcode_shlibpath_var, $1)=no ;; # FreeBSD 2.2.[012] allows us to include c++rt0.o to get C++ constructor # support. Future versions do this automatically, but an explicit c++rt0.o # does not break anything, and helps significantly (at the cost of a little # extra space). freebsd2.2*) _LT_TAGVAR(archive_cmds, $1)='$LD -Bshareable -o $lib $libobjs $deplibs $linker_flags /usr/lib/c++rt0.o' _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='-R$libdir' _LT_TAGVAR(hardcode_direct, $1)=yes _LT_TAGVAR(hardcode_shlibpath_var, $1)=no ;; # Unfortunately, older versions of FreeBSD 2 do not have this feature. freebsd2.*) _LT_TAGVAR(archive_cmds, $1)='$LD -Bshareable -o $lib $libobjs $deplibs $linker_flags' _LT_TAGVAR(hardcode_direct, $1)=yes _LT_TAGVAR(hardcode_minus_L, $1)=yes _LT_TAGVAR(hardcode_shlibpath_var, $1)=no ;; # FreeBSD 3 and greater uses gcc -shared to do shared libraries. freebsd* | dragonfly*) _LT_TAGVAR(archive_cmds, $1)='$CC -shared $pic_flag -o $lib $libobjs $deplibs $compiler_flags' _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='-R$libdir' _LT_TAGVAR(hardcode_direct, $1)=yes _LT_TAGVAR(hardcode_shlibpath_var, $1)=no ;; hpux9*) if test "$GCC" = yes; then _LT_TAGVAR(archive_cmds, $1)='$RM $output_objdir/$soname~$CC -shared $pic_flag ${wl}+b ${wl}$install_libdir -o $output_objdir/$soname $libobjs $deplibs $compiler_flags~test $output_objdir/$soname = $lib || mv $output_objdir/$soname $lib' else _LT_TAGVAR(archive_cmds, $1)='$RM $output_objdir/$soname~$LD -b +b $install_libdir -o $output_objdir/$soname $libobjs $deplibs $linker_flags~test $output_objdir/$soname = $lib || mv $output_objdir/$soname $lib' fi _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}+b ${wl}$libdir' _LT_TAGVAR(hardcode_libdir_separator, $1)=: _LT_TAGVAR(hardcode_direct, $1)=yes # hardcode_minus_L: Not really in the search PATH, # but as the default location of the library. _LT_TAGVAR(hardcode_minus_L, $1)=yes _LT_TAGVAR(export_dynamic_flag_spec, $1)='${wl}-E' ;; hpux10*) if test "$GCC" = yes && test "$with_gnu_ld" = no; then _LT_TAGVAR(archive_cmds, $1)='$CC -shared $pic_flag ${wl}+h ${wl}$soname ${wl}+b ${wl}$install_libdir -o $lib $libobjs $deplibs $compiler_flags' else _LT_TAGVAR(archive_cmds, $1)='$LD -b +h $soname +b $install_libdir -o $lib $libobjs $deplibs $linker_flags' fi if test "$with_gnu_ld" = no; then _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}+b ${wl}$libdir' _LT_TAGVAR(hardcode_libdir_separator, $1)=: _LT_TAGVAR(hardcode_direct, $1)=yes _LT_TAGVAR(hardcode_direct_absolute, $1)=yes _LT_TAGVAR(export_dynamic_flag_spec, $1)='${wl}-E' # hardcode_minus_L: Not really in the search PATH, # but as the default location of the library. _LT_TAGVAR(hardcode_minus_L, $1)=yes fi ;; hpux11*) if test "$GCC" = yes && test "$with_gnu_ld" = no; then case $host_cpu in hppa*64*) _LT_TAGVAR(archive_cmds, $1)='$CC -shared ${wl}+h ${wl}$soname -o $lib $libobjs $deplibs $compiler_flags' ;; ia64*) _LT_TAGVAR(archive_cmds, $1)='$CC -shared $pic_flag ${wl}+h ${wl}$soname ${wl}+nodefaultrpath -o $lib $libobjs $deplibs $compiler_flags' ;; *) _LT_TAGVAR(archive_cmds, $1)='$CC -shared $pic_flag ${wl}+h ${wl}$soname ${wl}+b ${wl}$install_libdir -o $lib $libobjs $deplibs $compiler_flags' ;; esac else case $host_cpu in hppa*64*) _LT_TAGVAR(archive_cmds, $1)='$CC -b ${wl}+h ${wl}$soname -o $lib $libobjs $deplibs $compiler_flags' ;; ia64*) _LT_TAGVAR(archive_cmds, $1)='$CC -b ${wl}+h ${wl}$soname ${wl}+nodefaultrpath -o $lib $libobjs $deplibs $compiler_flags' ;; *) m4_if($1, [], [ # Older versions of the 11.00 compiler do not understand -b yet # (HP92453-01 A.11.01.20 doesn't, HP92453-01 B.11.X.35175-35176.GP does) _LT_LINKER_OPTION([if $CC understands -b], _LT_TAGVAR(lt_cv_prog_compiler__b, $1), [-b], [_LT_TAGVAR(archive_cmds, $1)='$CC -b ${wl}+h ${wl}$soname ${wl}+b ${wl}$install_libdir -o $lib $libobjs $deplibs $compiler_flags'], [_LT_TAGVAR(archive_cmds, $1)='$LD -b +h $soname +b $install_libdir -o $lib $libobjs $deplibs $linker_flags'])], [_LT_TAGVAR(archive_cmds, $1)='$CC -b ${wl}+h ${wl}$soname ${wl}+b ${wl}$install_libdir -o $lib $libobjs $deplibs $compiler_flags']) ;; esac fi if test "$with_gnu_ld" = no; then _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}+b ${wl}$libdir' _LT_TAGVAR(hardcode_libdir_separator, $1)=: case $host_cpu in hppa*64*|ia64*) _LT_TAGVAR(hardcode_direct, $1)=no _LT_TAGVAR(hardcode_shlibpath_var, $1)=no ;; *) _LT_TAGVAR(hardcode_direct, $1)=yes _LT_TAGVAR(hardcode_direct_absolute, $1)=yes _LT_TAGVAR(export_dynamic_flag_spec, $1)='${wl}-E' # hardcode_minus_L: Not really in the search PATH, # but as the default location of the library. _LT_TAGVAR(hardcode_minus_L, $1)=yes ;; esac fi ;; irix5* | irix6* | nonstopux*) if test "$GCC" = yes; then _LT_TAGVAR(archive_cmds, $1)='$CC -shared $pic_flag $libobjs $deplibs $compiler_flags ${wl}-soname ${wl}$soname `test -n "$verstring" && func_echo_all "${wl}-set_version ${wl}$verstring"` ${wl}-update_registry ${wl}${output_objdir}/so_locations -o $lib' # Try to use the -exported_symbol ld option, if it does not # work, assume that -exports_file does not work either and # implicitly export all symbols. # This should be the same for all languages, so no per-tag cache variable. AC_CACHE_CHECK([whether the $host_os linker accepts -exported_symbol], [lt_cv_irix_exported_symbol], [save_LDFLAGS="$LDFLAGS" LDFLAGS="$LDFLAGS -shared ${wl}-exported_symbol ${wl}foo ${wl}-update_registry ${wl}/dev/null" AC_LINK_IFELSE( [AC_LANG_SOURCE( [AC_LANG_CASE([C], [[int foo (void) { return 0; }]], [C++], [[int foo (void) { return 0; }]], [Fortran 77], [[ subroutine foo end]], [Fortran], [[ subroutine foo end]])])], [lt_cv_irix_exported_symbol=yes], [lt_cv_irix_exported_symbol=no]) LDFLAGS="$save_LDFLAGS"]) if test "$lt_cv_irix_exported_symbol" = yes; then _LT_TAGVAR(archive_expsym_cmds, $1)='$CC -shared $pic_flag $libobjs $deplibs $compiler_flags ${wl}-soname ${wl}$soname `test -n "$verstring" && func_echo_all "${wl}-set_version ${wl}$verstring"` ${wl}-update_registry ${wl}${output_objdir}/so_locations ${wl}-exports_file ${wl}$export_symbols -o $lib' fi else _LT_TAGVAR(archive_cmds, $1)='$CC -shared $libobjs $deplibs $compiler_flags -soname $soname `test -n "$verstring" && func_echo_all "-set_version $verstring"` -update_registry ${output_objdir}/so_locations -o $lib' _LT_TAGVAR(archive_expsym_cmds, $1)='$CC -shared $libobjs $deplibs $compiler_flags -soname $soname `test -n "$verstring" && func_echo_all "-set_version $verstring"` -update_registry ${output_objdir}/so_locations -exports_file $export_symbols -o $lib' fi _LT_TAGVAR(archive_cmds_need_lc, $1)='no' _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}-rpath ${wl}$libdir' _LT_TAGVAR(hardcode_libdir_separator, $1)=: _LT_TAGVAR(inherit_rpath, $1)=yes _LT_TAGVAR(link_all_deplibs, $1)=yes ;; netbsd*) if echo __ELF__ | $CC -E - | $GREP __ELF__ >/dev/null; then _LT_TAGVAR(archive_cmds, $1)='$LD -Bshareable -o $lib $libobjs $deplibs $linker_flags' # a.out else _LT_TAGVAR(archive_cmds, $1)='$LD -shared -o $lib $libobjs $deplibs $linker_flags' # ELF fi _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='-R$libdir' _LT_TAGVAR(hardcode_direct, $1)=yes _LT_TAGVAR(hardcode_shlibpath_var, $1)=no ;; newsos6) _LT_TAGVAR(archive_cmds, $1)='$LD -G -h $soname -o $lib $libobjs $deplibs $linker_flags' _LT_TAGVAR(hardcode_direct, $1)=yes _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}-rpath ${wl}$libdir' _LT_TAGVAR(hardcode_libdir_separator, $1)=: _LT_TAGVAR(hardcode_shlibpath_var, $1)=no ;; *nto* | *qnx*) ;; openbsd*) if test -f /usr/libexec/ld.so; then _LT_TAGVAR(hardcode_direct, $1)=yes _LT_TAGVAR(hardcode_shlibpath_var, $1)=no _LT_TAGVAR(hardcode_direct_absolute, $1)=yes if test -z "`echo __ELF__ | $CC -E - | $GREP __ELF__`" || test "$host_os-$host_cpu" = "openbsd2.8-powerpc"; then _LT_TAGVAR(archive_cmds, $1)='$CC -shared $pic_flag -o $lib $libobjs $deplibs $compiler_flags' _LT_TAGVAR(archive_expsym_cmds, $1)='$CC -shared $pic_flag -o $lib $libobjs $deplibs $compiler_flags ${wl}-retain-symbols-file,$export_symbols' _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}-rpath,$libdir' _LT_TAGVAR(export_dynamic_flag_spec, $1)='${wl}-E' else case $host_os in openbsd[[01]].* | openbsd2.[[0-7]] | openbsd2.[[0-7]].*) _LT_TAGVAR(archive_cmds, $1)='$LD -Bshareable -o $lib $libobjs $deplibs $linker_flags' _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='-R$libdir' ;; *) _LT_TAGVAR(archive_cmds, $1)='$CC -shared $pic_flag -o $lib $libobjs $deplibs $compiler_flags' _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}-rpath,$libdir' ;; esac fi else _LT_TAGVAR(ld_shlibs, $1)=no fi ;; os2*) _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='-L$libdir' _LT_TAGVAR(hardcode_minus_L, $1)=yes _LT_TAGVAR(allow_undefined_flag, $1)=unsupported _LT_TAGVAR(archive_cmds, $1)='$ECHO "LIBRARY $libname INITINSTANCE" > $output_objdir/$libname.def~$ECHO "DESCRIPTION \"$libname\"" >> $output_objdir/$libname.def~echo DATA >> $output_objdir/$libname.def~echo " SINGLE NONSHARED" >> $output_objdir/$libname.def~echo EXPORTS >> $output_objdir/$libname.def~emxexp $libobjs >> $output_objdir/$libname.def~$CC -Zdll -Zcrtdll -o $lib $libobjs $deplibs $compiler_flags $output_objdir/$libname.def' _LT_TAGVAR(old_archive_from_new_cmds, $1)='emximp -o $output_objdir/$libname.a $output_objdir/$libname.def' ;; osf3*) if test "$GCC" = yes; then _LT_TAGVAR(allow_undefined_flag, $1)=' ${wl}-expect_unresolved ${wl}\*' _LT_TAGVAR(archive_cmds, $1)='$CC -shared${allow_undefined_flag} $libobjs $deplibs $compiler_flags ${wl}-soname ${wl}$soname `test -n "$verstring" && func_echo_all "${wl}-set_version ${wl}$verstring"` ${wl}-update_registry ${wl}${output_objdir}/so_locations -o $lib' else _LT_TAGVAR(allow_undefined_flag, $1)=' -expect_unresolved \*' _LT_TAGVAR(archive_cmds, $1)='$CC -shared${allow_undefined_flag} $libobjs $deplibs $compiler_flags -soname $soname `test -n "$verstring" && func_echo_all "-set_version $verstring"` -update_registry ${output_objdir}/so_locations -o $lib' fi _LT_TAGVAR(archive_cmds_need_lc, $1)='no' _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}-rpath ${wl}$libdir' _LT_TAGVAR(hardcode_libdir_separator, $1)=: ;; osf4* | osf5*) # as osf3* with the addition of -msym flag if test "$GCC" = yes; then _LT_TAGVAR(allow_undefined_flag, $1)=' ${wl}-expect_unresolved ${wl}\*' _LT_TAGVAR(archive_cmds, $1)='$CC -shared${allow_undefined_flag} $pic_flag $libobjs $deplibs $compiler_flags ${wl}-msym ${wl}-soname ${wl}$soname `test -n "$verstring" && func_echo_all "${wl}-set_version ${wl}$verstring"` ${wl}-update_registry ${wl}${output_objdir}/so_locations -o $lib' _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}-rpath ${wl}$libdir' else _LT_TAGVAR(allow_undefined_flag, $1)=' -expect_unresolved \*' _LT_TAGVAR(archive_cmds, $1)='$CC -shared${allow_undefined_flag} $libobjs $deplibs $compiler_flags -msym -soname $soname `test -n "$verstring" && func_echo_all "-set_version $verstring"` -update_registry ${output_objdir}/so_locations -o $lib' _LT_TAGVAR(archive_expsym_cmds, $1)='for i in `cat $export_symbols`; do printf "%s %s\\n" -exported_symbol "\$i" >> $lib.exp; done; printf "%s\\n" "-hidden">> $lib.exp~ $CC -shared${allow_undefined_flag} ${wl}-input ${wl}$lib.exp $compiler_flags $libobjs $deplibs -soname $soname `test -n "$verstring" && $ECHO "-set_version $verstring"` -update_registry ${output_objdir}/so_locations -o $lib~$RM $lib.exp' # Both c and cxx compiler support -rpath directly _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='-rpath $libdir' fi _LT_TAGVAR(archive_cmds_need_lc, $1)='no' _LT_TAGVAR(hardcode_libdir_separator, $1)=: ;; solaris*) _LT_TAGVAR(no_undefined_flag, $1)=' -z defs' if test "$GCC" = yes; then wlarc='${wl}' _LT_TAGVAR(archive_cmds, $1)='$CC -shared $pic_flag ${wl}-z ${wl}text ${wl}-h ${wl}$soname -o $lib $libobjs $deplibs $compiler_flags' _LT_TAGVAR(archive_expsym_cmds, $1)='echo "{ global:" > $lib.exp~cat $export_symbols | $SED -e "s/\(.*\)/\1;/" >> $lib.exp~echo "local: *; };" >> $lib.exp~ $CC -shared $pic_flag ${wl}-z ${wl}text ${wl}-M ${wl}$lib.exp ${wl}-h ${wl}$soname -o $lib $libobjs $deplibs $compiler_flags~$RM $lib.exp' else case `$CC -V 2>&1` in *"Compilers 5.0"*) wlarc='' _LT_TAGVAR(archive_cmds, $1)='$LD -G${allow_undefined_flag} -h $soname -o $lib $libobjs $deplibs $linker_flags' _LT_TAGVAR(archive_expsym_cmds, $1)='echo "{ global:" > $lib.exp~cat $export_symbols | $SED -e "s/\(.*\)/\1;/" >> $lib.exp~echo "local: *; };" >> $lib.exp~ $LD -G${allow_undefined_flag} -M $lib.exp -h $soname -o $lib $libobjs $deplibs $linker_flags~$RM $lib.exp' ;; *) wlarc='${wl}' _LT_TAGVAR(archive_cmds, $1)='$CC -G${allow_undefined_flag} -h $soname -o $lib $libobjs $deplibs $compiler_flags' _LT_TAGVAR(archive_expsym_cmds, $1)='echo "{ global:" > $lib.exp~cat $export_symbols | $SED -e "s/\(.*\)/\1;/" >> $lib.exp~echo "local: *; };" >> $lib.exp~ $CC -G${allow_undefined_flag} -M $lib.exp -h $soname -o $lib $libobjs $deplibs $compiler_flags~$RM $lib.exp' ;; esac fi _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='-R$libdir' _LT_TAGVAR(hardcode_shlibpath_var, $1)=no case $host_os in solaris2.[[0-5]] | solaris2.[[0-5]].*) ;; *) # The compiler driver will combine and reorder linker options, # but understands `-z linker_flag'. GCC discards it without `$wl', # but is careful enough not to reorder. # Supported since Solaris 2.6 (maybe 2.5.1?) if test "$GCC" = yes; then _LT_TAGVAR(whole_archive_flag_spec, $1)='${wl}-z ${wl}allextract$convenience ${wl}-z ${wl}defaultextract' else _LT_TAGVAR(whole_archive_flag_spec, $1)='-z allextract$convenience -z defaultextract' fi ;; esac _LT_TAGVAR(link_all_deplibs, $1)=yes ;; sunos4*) if test "x$host_vendor" = xsequent; then # Use $CC to link under sequent, because it throws in some extra .o # files that make .init and .fini sections work. _LT_TAGVAR(archive_cmds, $1)='$CC -G ${wl}-h $soname -o $lib $libobjs $deplibs $compiler_flags' else _LT_TAGVAR(archive_cmds, $1)='$LD -assert pure-text -Bstatic -o $lib $libobjs $deplibs $linker_flags' fi _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='-L$libdir' _LT_TAGVAR(hardcode_direct, $1)=yes _LT_TAGVAR(hardcode_minus_L, $1)=yes _LT_TAGVAR(hardcode_shlibpath_var, $1)=no ;; sysv4) case $host_vendor in sni) _LT_TAGVAR(archive_cmds, $1)='$LD -G -h $soname -o $lib $libobjs $deplibs $linker_flags' _LT_TAGVAR(hardcode_direct, $1)=yes # is this really true??? ;; siemens) ## LD is ld it makes a PLAMLIB ## CC just makes a GrossModule. _LT_TAGVAR(archive_cmds, $1)='$LD -G -o $lib $libobjs $deplibs $linker_flags' _LT_TAGVAR(reload_cmds, $1)='$CC -r -o $output$reload_objs' _LT_TAGVAR(hardcode_direct, $1)=no ;; motorola) _LT_TAGVAR(archive_cmds, $1)='$LD -G -h $soname -o $lib $libobjs $deplibs $linker_flags' _LT_TAGVAR(hardcode_direct, $1)=no #Motorola manual says yes, but my tests say they lie ;; esac runpath_var='LD_RUN_PATH' _LT_TAGVAR(hardcode_shlibpath_var, $1)=no ;; sysv4.3*) _LT_TAGVAR(archive_cmds, $1)='$LD -G -h $soname -o $lib $libobjs $deplibs $linker_flags' _LT_TAGVAR(hardcode_shlibpath_var, $1)=no _LT_TAGVAR(export_dynamic_flag_spec, $1)='-Bexport' ;; sysv4*MP*) if test -d /usr/nec; then _LT_TAGVAR(archive_cmds, $1)='$LD -G -h $soname -o $lib $libobjs $deplibs $linker_flags' _LT_TAGVAR(hardcode_shlibpath_var, $1)=no runpath_var=LD_RUN_PATH hardcode_runpath_var=yes _LT_TAGVAR(ld_shlibs, $1)=yes fi ;; sysv4*uw2* | sysv5OpenUNIX* | sysv5UnixWare7.[[01]].[[10]]* | unixware7* | sco3.2v5.0.[[024]]*) _LT_TAGVAR(no_undefined_flag, $1)='${wl}-z,text' _LT_TAGVAR(archive_cmds_need_lc, $1)=no _LT_TAGVAR(hardcode_shlibpath_var, $1)=no runpath_var='LD_RUN_PATH' if test "$GCC" = yes; then _LT_TAGVAR(archive_cmds, $1)='$CC -shared ${wl}-h,$soname -o $lib $libobjs $deplibs $compiler_flags' _LT_TAGVAR(archive_expsym_cmds, $1)='$CC -shared ${wl}-Bexport:$export_symbols ${wl}-h,$soname -o $lib $libobjs $deplibs $compiler_flags' else _LT_TAGVAR(archive_cmds, $1)='$CC -G ${wl}-h,$soname -o $lib $libobjs $deplibs $compiler_flags' _LT_TAGVAR(archive_expsym_cmds, $1)='$CC -G ${wl}-Bexport:$export_symbols ${wl}-h,$soname -o $lib $libobjs $deplibs $compiler_flags' fi ;; sysv5* | sco3.2v5* | sco5v6*) # Note: We can NOT use -z defs as we might desire, because we do not # link with -lc, and that would cause any symbols used from libc to # always be unresolved, which means just about no library would # ever link correctly. If we're not using GNU ld we use -z text # though, which does catch some bad symbols but isn't as heavy-handed # as -z defs. _LT_TAGVAR(no_undefined_flag, $1)='${wl}-z,text' _LT_TAGVAR(allow_undefined_flag, $1)='${wl}-z,nodefs' _LT_TAGVAR(archive_cmds_need_lc, $1)=no _LT_TAGVAR(hardcode_shlibpath_var, $1)=no _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}-R,$libdir' _LT_TAGVAR(hardcode_libdir_separator, $1)=':' _LT_TAGVAR(link_all_deplibs, $1)=yes _LT_TAGVAR(export_dynamic_flag_spec, $1)='${wl}-Bexport' runpath_var='LD_RUN_PATH' if test "$GCC" = yes; then _LT_TAGVAR(archive_cmds, $1)='$CC -shared ${wl}-h,$soname -o $lib $libobjs $deplibs $compiler_flags' _LT_TAGVAR(archive_expsym_cmds, $1)='$CC -shared ${wl}-Bexport:$export_symbols ${wl}-h,$soname -o $lib $libobjs $deplibs $compiler_flags' else _LT_TAGVAR(archive_cmds, $1)='$CC -G ${wl}-h,$soname -o $lib $libobjs $deplibs $compiler_flags' _LT_TAGVAR(archive_expsym_cmds, $1)='$CC -G ${wl}-Bexport:$export_symbols ${wl}-h,$soname -o $lib $libobjs $deplibs $compiler_flags' fi ;; uts4*) _LT_TAGVAR(archive_cmds, $1)='$LD -G -h $soname -o $lib $libobjs $deplibs $linker_flags' _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='-L$libdir' _LT_TAGVAR(hardcode_shlibpath_var, $1)=no ;; *) _LT_TAGVAR(ld_shlibs, $1)=no ;; esac if test x$host_vendor = xsni; then case $host in sysv4 | sysv4.2uw2* | sysv4.3* | sysv5*) _LT_TAGVAR(export_dynamic_flag_spec, $1)='${wl}-Blargedynsym' ;; esac fi fi ]) AC_MSG_RESULT([$_LT_TAGVAR(ld_shlibs, $1)]) test "$_LT_TAGVAR(ld_shlibs, $1)" = no && can_build_shared=no _LT_TAGVAR(with_gnu_ld, $1)=$with_gnu_ld _LT_DECL([], [libext], [0], [Old archive suffix (normally "a")])dnl _LT_DECL([], [shrext_cmds], [1], [Shared library suffix (normally ".so")])dnl _LT_DECL([], [extract_expsyms_cmds], [2], [The commands to extract the exported symbol list from a shared archive]) # # Do we need to explicitly link libc? # case "x$_LT_TAGVAR(archive_cmds_need_lc, $1)" in x|xyes) # Assume -lc should be added _LT_TAGVAR(archive_cmds_need_lc, $1)=yes if test "$enable_shared" = yes && test "$GCC" = yes; then case $_LT_TAGVAR(archive_cmds, $1) in *'~'*) # FIXME: we may have to deal with multi-command sequences. ;; '$CC '*) # Test whether the compiler implicitly links with -lc since on some # systems, -lgcc has to come before -lc. If gcc already passes -lc # to ld, don't add -lc before -lgcc. AC_CACHE_CHECK([whether -lc should be explicitly linked in], [lt_cv_]_LT_TAGVAR(archive_cmds_need_lc, $1), [$RM conftest* echo "$lt_simple_compile_test_code" > conftest.$ac_ext if AC_TRY_EVAL(ac_compile) 2>conftest.err; then soname=conftest lib=conftest libobjs=conftest.$ac_objext deplibs= wl=$_LT_TAGVAR(lt_prog_compiler_wl, $1) pic_flag=$_LT_TAGVAR(lt_prog_compiler_pic, $1) compiler_flags=-v linker_flags=-v verstring= output_objdir=. libname=conftest lt_save_allow_undefined_flag=$_LT_TAGVAR(allow_undefined_flag, $1) _LT_TAGVAR(allow_undefined_flag, $1)= if AC_TRY_EVAL(_LT_TAGVAR(archive_cmds, $1) 2\>\&1 \| $GREP \" -lc \" \>/dev/null 2\>\&1) then lt_cv_[]_LT_TAGVAR(archive_cmds_need_lc, $1)=no else lt_cv_[]_LT_TAGVAR(archive_cmds_need_lc, $1)=yes fi _LT_TAGVAR(allow_undefined_flag, $1)=$lt_save_allow_undefined_flag else cat conftest.err 1>&5 fi $RM conftest* ]) _LT_TAGVAR(archive_cmds_need_lc, $1)=$lt_cv_[]_LT_TAGVAR(archive_cmds_need_lc, $1) ;; esac fi ;; esac _LT_TAGDECL([build_libtool_need_lc], [archive_cmds_need_lc], [0], [Whether or not to add -lc for building shared libraries]) _LT_TAGDECL([allow_libtool_libs_with_static_runtimes], [enable_shared_with_static_runtimes], [0], [Whether or not to disallow shared libs when runtime libs are static]) _LT_TAGDECL([], [export_dynamic_flag_spec], [1], [Compiler flag to allow reflexive dlopens]) _LT_TAGDECL([], [whole_archive_flag_spec], [1], [Compiler flag to generate shared objects directly from archives]) _LT_TAGDECL([], [compiler_needs_object], [1], [Whether the compiler copes with passing no objects directly]) _LT_TAGDECL([], [old_archive_from_new_cmds], [2], [Create an old-style archive from a shared archive]) _LT_TAGDECL([], [old_archive_from_expsyms_cmds], [2], [Create a temporary old-style archive to link instead of a shared archive]) _LT_TAGDECL([], [archive_cmds], [2], [Commands used to build a shared archive]) _LT_TAGDECL([], [archive_expsym_cmds], [2]) _LT_TAGDECL([], [module_cmds], [2], [Commands used to build a loadable module if different from building a shared archive.]) _LT_TAGDECL([], [module_expsym_cmds], [2]) _LT_TAGDECL([], [with_gnu_ld], [1], [Whether we are building with GNU ld or not]) _LT_TAGDECL([], [allow_undefined_flag], [1], [Flag that allows shared libraries with undefined symbols to be built]) _LT_TAGDECL([], [no_undefined_flag], [1], [Flag that enforces no undefined symbols]) _LT_TAGDECL([], [hardcode_libdir_flag_spec], [1], [Flag to hardcode $libdir into a binary during linking. This must work even if $libdir does not exist]) _LT_TAGDECL([], [hardcode_libdir_separator], [1], [Whether we need a single "-rpath" flag with a separated argument]) _LT_TAGDECL([], [hardcode_direct], [0], [Set to "yes" if using DIR/libNAME${shared_ext} during linking hardcodes DIR into the resulting binary]) _LT_TAGDECL([], [hardcode_direct_absolute], [0], [Set to "yes" if using DIR/libNAME${shared_ext} during linking hardcodes DIR into the resulting binary and the resulting library dependency is "absolute", i.e impossible to change by setting ${shlibpath_var} if the library is relocated]) _LT_TAGDECL([], [hardcode_minus_L], [0], [Set to "yes" if using the -LDIR flag during linking hardcodes DIR into the resulting binary]) _LT_TAGDECL([], [hardcode_shlibpath_var], [0], [Set to "yes" if using SHLIBPATH_VAR=DIR during linking hardcodes DIR into the resulting binary]) _LT_TAGDECL([], [hardcode_automatic], [0], [Set to "yes" if building a shared library automatically hardcodes DIR into the library and all subsequent libraries and executables linked against it]) _LT_TAGDECL([], [inherit_rpath], [0], [Set to yes if linker adds runtime paths of dependent libraries to runtime path list]) _LT_TAGDECL([], [link_all_deplibs], [0], [Whether libtool must link a program against all its dependency libraries]) _LT_TAGDECL([], [always_export_symbols], [0], [Set to "yes" if exported symbols are required]) _LT_TAGDECL([], [export_symbols_cmds], [2], [The commands to list exported symbols]) _LT_TAGDECL([], [exclude_expsyms], [1], [Symbols that should not be listed in the preloaded symbols]) _LT_TAGDECL([], [include_expsyms], [1], [Symbols that must always be exported]) _LT_TAGDECL([], [prelink_cmds], [2], [Commands necessary for linking programs (against libraries) with templates]) _LT_TAGDECL([], [postlink_cmds], [2], [Commands necessary for finishing linking programs]) _LT_TAGDECL([], [file_list_spec], [1], [Specify filename containing input files]) dnl FIXME: Not yet implemented dnl _LT_TAGDECL([], [thread_safe_flag_spec], [1], dnl [Compiler flag to generate thread safe objects]) ])# _LT_LINKER_SHLIBS # _LT_LANG_C_CONFIG([TAG]) # ------------------------ # Ensure that the configuration variables for a C compiler are suitably # defined. These variables are subsequently used by _LT_CONFIG to write # the compiler configuration to `libtool'. m4_defun([_LT_LANG_C_CONFIG], [m4_require([_LT_DECL_EGREP])dnl lt_save_CC="$CC" AC_LANG_PUSH(C) # Source file extension for C test sources. ac_ext=c # Object file extension for compiled C test sources. objext=o _LT_TAGVAR(objext, $1)=$objext # Code to be used in simple compile tests lt_simple_compile_test_code="int some_variable = 0;" # Code to be used in simple link tests lt_simple_link_test_code='int main(){return(0);}' _LT_TAG_COMPILER # Save the default compiler, since it gets overwritten when the other # tags are being tested, and _LT_TAGVAR(compiler, []) is a NOP. compiler_DEFAULT=$CC # save warnings/boilerplate of simple test code _LT_COMPILER_BOILERPLATE _LT_LINKER_BOILERPLATE ## CAVEAT EMPTOR: ## There is no encapsulation within the following macros, do not change ## the running order or otherwise move them around unless you know exactly ## what you are doing... if test -n "$compiler"; then _LT_COMPILER_NO_RTTI($1) _LT_COMPILER_PIC($1) _LT_COMPILER_C_O($1) _LT_COMPILER_FILE_LOCKS($1) _LT_LINKER_SHLIBS($1) _LT_SYS_DYNAMIC_LINKER($1) _LT_LINKER_HARDCODE_LIBPATH($1) LT_SYS_DLOPEN_SELF _LT_CMD_STRIPLIB # Report which library types will actually be built AC_MSG_CHECKING([if libtool supports shared libraries]) AC_MSG_RESULT([$can_build_shared]) AC_MSG_CHECKING([whether to build shared libraries]) test "$can_build_shared" = "no" && enable_shared=no # On AIX, shared libraries and static libraries use the same namespace, and # are all built from PIC. case $host_os in aix3*) test "$enable_shared" = yes && enable_static=no if test -n "$RANLIB"; then archive_cmds="$archive_cmds~\$RANLIB \$lib" postinstall_cmds='$RANLIB $lib' fi ;; aix[[4-9]]*) if test "$host_cpu" != ia64 && test "$aix_use_runtimelinking" = no ; then test "$enable_shared" = yes && enable_static=no fi ;; esac AC_MSG_RESULT([$enable_shared]) AC_MSG_CHECKING([whether to build static libraries]) # Make sure either enable_shared or enable_static is yes. test "$enable_shared" = yes || enable_static=yes AC_MSG_RESULT([$enable_static]) _LT_CONFIG($1) fi AC_LANG_POP CC="$lt_save_CC" ])# _LT_LANG_C_CONFIG # _LT_LANG_CXX_CONFIG([TAG]) # -------------------------- # Ensure that the configuration variables for a C++ compiler are suitably # defined. These variables are subsequently used by _LT_CONFIG to write # the compiler configuration to `libtool'. m4_defun([_LT_LANG_CXX_CONFIG], [m4_require([_LT_FILEUTILS_DEFAULTS])dnl m4_require([_LT_DECL_EGREP])dnl m4_require([_LT_PATH_MANIFEST_TOOL])dnl if test -n "$CXX" && ( test "X$CXX" != "Xno" && ( (test "X$CXX" = "Xg++" && `g++ -v >/dev/null 2>&1` ) || (test "X$CXX" != "Xg++"))) ; then AC_PROG_CXXCPP else _lt_caught_CXX_error=yes fi AC_LANG_PUSH(C++) _LT_TAGVAR(archive_cmds_need_lc, $1)=no _LT_TAGVAR(allow_undefined_flag, $1)= _LT_TAGVAR(always_export_symbols, $1)=no _LT_TAGVAR(archive_expsym_cmds, $1)= _LT_TAGVAR(compiler_needs_object, $1)=no _LT_TAGVAR(export_dynamic_flag_spec, $1)= _LT_TAGVAR(hardcode_direct, $1)=no _LT_TAGVAR(hardcode_direct_absolute, $1)=no _LT_TAGVAR(hardcode_libdir_flag_spec, $1)= _LT_TAGVAR(hardcode_libdir_separator, $1)= _LT_TAGVAR(hardcode_minus_L, $1)=no _LT_TAGVAR(hardcode_shlibpath_var, $1)=unsupported _LT_TAGVAR(hardcode_automatic, $1)=no _LT_TAGVAR(inherit_rpath, $1)=no _LT_TAGVAR(module_cmds, $1)= _LT_TAGVAR(module_expsym_cmds, $1)= _LT_TAGVAR(link_all_deplibs, $1)=unknown _LT_TAGVAR(old_archive_cmds, $1)=$old_archive_cmds _LT_TAGVAR(reload_flag, $1)=$reload_flag _LT_TAGVAR(reload_cmds, $1)=$reload_cmds _LT_TAGVAR(no_undefined_flag, $1)= _LT_TAGVAR(whole_archive_flag_spec, $1)= _LT_TAGVAR(enable_shared_with_static_runtimes, $1)=no # Source file extension for C++ test sources. ac_ext=cpp # Object file extension for compiled C++ test sources. objext=o _LT_TAGVAR(objext, $1)=$objext # No sense in running all these tests if we already determined that # the CXX compiler isn't working. Some variables (like enable_shared) # are currently assumed to apply to all compilers on this platform, # and will be corrupted by setting them based on a non-working compiler. if test "$_lt_caught_CXX_error" != yes; then # Code to be used in simple compile tests lt_simple_compile_test_code="int some_variable = 0;" # Code to be used in simple link tests lt_simple_link_test_code='int main(int, char *[[]]) { return(0); }' # ltmain only uses $CC for tagged configurations so make sure $CC is set. _LT_TAG_COMPILER # save warnings/boilerplate of simple test code _LT_COMPILER_BOILERPLATE _LT_LINKER_BOILERPLATE # Allow CC to be a program name with arguments. lt_save_CC=$CC lt_save_CFLAGS=$CFLAGS lt_save_LD=$LD lt_save_GCC=$GCC GCC=$GXX lt_save_with_gnu_ld=$with_gnu_ld lt_save_path_LD=$lt_cv_path_LD if test -n "${lt_cv_prog_gnu_ldcxx+set}"; then lt_cv_prog_gnu_ld=$lt_cv_prog_gnu_ldcxx else $as_unset lt_cv_prog_gnu_ld fi if test -n "${lt_cv_path_LDCXX+set}"; then lt_cv_path_LD=$lt_cv_path_LDCXX else $as_unset lt_cv_path_LD fi test -z "${LDCXX+set}" || LD=$LDCXX CC=${CXX-"c++"} CFLAGS=$CXXFLAGS compiler=$CC _LT_TAGVAR(compiler, $1)=$CC _LT_CC_BASENAME([$compiler]) if test -n "$compiler"; then # We don't want -fno-exception when compiling C++ code, so set the # no_builtin_flag separately if test "$GXX" = yes; then _LT_TAGVAR(lt_prog_compiler_no_builtin_flag, $1)=' -fno-builtin' else _LT_TAGVAR(lt_prog_compiler_no_builtin_flag, $1)= fi if test "$GXX" = yes; then # Set up default GNU C++ configuration LT_PATH_LD # Check if GNU C++ uses GNU ld as the underlying linker, since the # archiving commands below assume that GNU ld is being used. if test "$with_gnu_ld" = yes; then _LT_TAGVAR(archive_cmds, $1)='$CC $pic_flag -shared -nostdlib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags ${wl}-soname $wl$soname -o $lib' _LT_TAGVAR(archive_expsym_cmds, $1)='$CC $pic_flag -shared -nostdlib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags ${wl}-soname $wl$soname ${wl}-retain-symbols-file $wl$export_symbols -o $lib' _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}-rpath ${wl}$libdir' _LT_TAGVAR(export_dynamic_flag_spec, $1)='${wl}--export-dynamic' # If archive_cmds runs LD, not CC, wlarc should be empty # XXX I think wlarc can be eliminated in ltcf-cxx, but I need to # investigate it a little bit more. (MM) wlarc='${wl}' # ancient GNU ld didn't support --whole-archive et. al. if eval "`$CC -print-prog-name=ld` --help 2>&1" | $GREP 'no-whole-archive' > /dev/null; then _LT_TAGVAR(whole_archive_flag_spec, $1)="$wlarc"'--whole-archive$convenience '"$wlarc"'--no-whole-archive' else _LT_TAGVAR(whole_archive_flag_spec, $1)= fi else with_gnu_ld=no wlarc= # A generic and very simple default shared library creation # command for GNU C++ for the case where it uses the native # linker, instead of GNU ld. If possible, this setting should # overridden to take advantage of the native linker features on # the platform it is being used on. _LT_TAGVAR(archive_cmds, $1)='$CC -shared -nostdlib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags -o $lib' fi # Commands to make compiler produce verbose output that lists # what "hidden" libraries, object files and flags are used when # linking a shared library. output_verbose_link_cmd='$CC -shared $CFLAGS -v conftest.$objext 2>&1 | $GREP -v "^Configured with:" | $GREP "\-L"' else GXX=no with_gnu_ld=no wlarc= fi # PORTME: fill in a description of your system's C++ link characteristics AC_MSG_CHECKING([whether the $compiler linker ($LD) supports shared libraries]) _LT_TAGVAR(ld_shlibs, $1)=yes case $host_os in aix3*) # FIXME: insert proper C++ library support _LT_TAGVAR(ld_shlibs, $1)=no ;; aix[[4-9]]*) if test "$host_cpu" = ia64; then # On IA64, the linker does run time linking by default, so we don't # have to do anything special. aix_use_runtimelinking=no exp_sym_flag='-Bexport' no_entry_flag="" else aix_use_runtimelinking=no # Test if we are trying to use run time linking or normal # AIX style linking. If -brtl is somewhere in LDFLAGS, we # need to do runtime linking. case $host_os in aix4.[[23]]|aix4.[[23]].*|aix[[5-9]]*) for ld_flag in $LDFLAGS; do case $ld_flag in *-brtl*) aix_use_runtimelinking=yes break ;; esac done ;; esac exp_sym_flag='-bexport' no_entry_flag='-bnoentry' fi # When large executables or shared objects are built, AIX ld can # have problems creating the table of contents. If linking a library # or program results in "error TOC overflow" add -mminimal-toc to # CXXFLAGS/CFLAGS for g++/gcc. In the cases where that is not # enough to fix the problem, add -Wl,-bbigtoc to LDFLAGS. _LT_TAGVAR(archive_cmds, $1)='' _LT_TAGVAR(hardcode_direct, $1)=yes _LT_TAGVAR(hardcode_direct_absolute, $1)=yes _LT_TAGVAR(hardcode_libdir_separator, $1)=':' _LT_TAGVAR(link_all_deplibs, $1)=yes _LT_TAGVAR(file_list_spec, $1)='${wl}-f,' if test "$GXX" = yes; then case $host_os in aix4.[[012]]|aix4.[[012]].*) # We only want to do this on AIX 4.2 and lower, the check # below for broken collect2 doesn't work under 4.3+ collect2name=`${CC} -print-prog-name=collect2` if test -f "$collect2name" && strings "$collect2name" | $GREP resolve_lib_name >/dev/null then # We have reworked collect2 : else # We have old collect2 _LT_TAGVAR(hardcode_direct, $1)=unsupported # It fails to find uninstalled libraries when the uninstalled # path is not listed in the libpath. Setting hardcode_minus_L # to unsupported forces relinking _LT_TAGVAR(hardcode_minus_L, $1)=yes _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='-L$libdir' _LT_TAGVAR(hardcode_libdir_separator, $1)= fi esac shared_flag='-shared' if test "$aix_use_runtimelinking" = yes; then shared_flag="$shared_flag "'${wl}-G' fi else # not using gcc if test "$host_cpu" = ia64; then # VisualAge C++, Version 5.5 for AIX 5L for IA-64, Beta 3 Release # chokes on -Wl,-G. The following line is correct: shared_flag='-G' else if test "$aix_use_runtimelinking" = yes; then shared_flag='${wl}-G' else shared_flag='${wl}-bM:SRE' fi fi fi _LT_TAGVAR(export_dynamic_flag_spec, $1)='${wl}-bexpall' # It seems that -bexpall does not export symbols beginning with # underscore (_), so it is better to generate a list of symbols to # export. _LT_TAGVAR(always_export_symbols, $1)=yes if test "$aix_use_runtimelinking" = yes; then # Warning - without using the other runtime loading flags (-brtl), # -berok will link without error, but may produce a broken library. _LT_TAGVAR(allow_undefined_flag, $1)='-berok' # Determine the default libpath from the value encoded in an empty # executable. _LT_SYS_MODULE_PATH_AIX([$1]) _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}-blibpath:$libdir:'"$aix_libpath" _LT_TAGVAR(archive_expsym_cmds, $1)='$CC -o $output_objdir/$soname $libobjs $deplibs '"\${wl}$no_entry_flag"' $compiler_flags `if test "x${allow_undefined_flag}" != "x"; then func_echo_all "${wl}${allow_undefined_flag}"; else :; fi` '"\${wl}$exp_sym_flag:\$export_symbols $shared_flag" else if test "$host_cpu" = ia64; then _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}-R $libdir:/usr/lib:/lib' _LT_TAGVAR(allow_undefined_flag, $1)="-z nodefs" _LT_TAGVAR(archive_expsym_cmds, $1)="\$CC $shared_flag"' -o $output_objdir/$soname $libobjs $deplibs '"\${wl}$no_entry_flag"' $compiler_flags ${wl}${allow_undefined_flag} '"\${wl}$exp_sym_flag:\$export_symbols" else # Determine the default libpath from the value encoded in an # empty executable. _LT_SYS_MODULE_PATH_AIX([$1]) _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}-blibpath:$libdir:'"$aix_libpath" # Warning - without using the other run time loading flags, # -berok will link without error, but may produce a broken library. _LT_TAGVAR(no_undefined_flag, $1)=' ${wl}-bernotok' _LT_TAGVAR(allow_undefined_flag, $1)=' ${wl}-berok' if test "$with_gnu_ld" = yes; then # We only use this code for GNU lds that support --whole-archive. _LT_TAGVAR(whole_archive_flag_spec, $1)='${wl}--whole-archive$convenience ${wl}--no-whole-archive' else # Exported symbols can be pulled into shared objects from archives _LT_TAGVAR(whole_archive_flag_spec, $1)='$convenience' fi _LT_TAGVAR(archive_cmds_need_lc, $1)=yes # This is similar to how AIX traditionally builds its shared # libraries. _LT_TAGVAR(archive_expsym_cmds, $1)="\$CC $shared_flag"' -o $output_objdir/$soname $libobjs $deplibs ${wl}-bnoentry $compiler_flags ${wl}-bE:$export_symbols${allow_undefined_flag}~$AR $AR_FLAGS $output_objdir/$libname$release.a $output_objdir/$soname' fi fi ;; beos*) if $LD --help 2>&1 | $GREP ': supported targets:.* elf' > /dev/null; then _LT_TAGVAR(allow_undefined_flag, $1)=unsupported # Joseph Beckenbach says some releases of gcc # support --undefined. This deserves some investigation. FIXME _LT_TAGVAR(archive_cmds, $1)='$CC -nostart $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname -o $lib' else _LT_TAGVAR(ld_shlibs, $1)=no fi ;; chorus*) case $cc_basename in *) # FIXME: insert proper C++ library support _LT_TAGVAR(ld_shlibs, $1)=no ;; esac ;; cygwin* | mingw* | pw32* | cegcc*) case $GXX,$cc_basename in ,cl* | no,cl*) # Native MSVC # hardcode_libdir_flag_spec is actually meaningless, as there is # no search path for DLLs. _LT_TAGVAR(hardcode_libdir_flag_spec, $1)=' ' _LT_TAGVAR(allow_undefined_flag, $1)=unsupported _LT_TAGVAR(always_export_symbols, $1)=yes _LT_TAGVAR(file_list_spec, $1)='@' # Tell ltmain to make .lib files, not .a files. libext=lib # Tell ltmain to make .dll files, not .so files. shrext_cmds=".dll" # FIXME: Setting linknames here is a bad hack. _LT_TAGVAR(archive_cmds, $1)='$CC -o $output_objdir/$soname $libobjs $compiler_flags $deplibs -Wl,-dll~linknames=' _LT_TAGVAR(archive_expsym_cmds, $1)='if test "x`$SED 1q $export_symbols`" = xEXPORTS; then $SED -n -e 's/\\\\\\\(.*\\\\\\\)/-link\\\ -EXPORT:\\\\\\\1/' -e '1\\\!p' < $export_symbols > $output_objdir/$soname.exp; else $SED -e 's/\\\\\\\(.*\\\\\\\)/-link\\\ -EXPORT:\\\\\\\1/' < $export_symbols > $output_objdir/$soname.exp; fi~ $CC -o $tool_output_objdir$soname $libobjs $compiler_flags $deplibs "@$tool_output_objdir$soname.exp" -Wl,-DLL,-IMPLIB:"$tool_output_objdir$libname.dll.lib"~ linknames=' # The linker will not automatically build a static lib if we build a DLL. # _LT_TAGVAR(old_archive_from_new_cmds, $1)='true' _LT_TAGVAR(enable_shared_with_static_runtimes, $1)=yes # Don't use ranlib _LT_TAGVAR(old_postinstall_cmds, $1)='chmod 644 $oldlib' _LT_TAGVAR(postlink_cmds, $1)='lt_outputfile="@OUTPUT@"~ lt_tool_outputfile="@TOOL_OUTPUT@"~ case $lt_outputfile in *.exe|*.EXE) ;; *) lt_outputfile="$lt_outputfile.exe" lt_tool_outputfile="$lt_tool_outputfile.exe" ;; esac~ func_to_tool_file "$lt_outputfile"~ if test "$MANIFEST_TOOL" != ":" && test -f "$lt_outputfile.manifest"; then $MANIFEST_TOOL -manifest "$lt_tool_outputfile.manifest" -outputresource:"$lt_tool_outputfile" || exit 1; $RM "$lt_outputfile.manifest"; fi' ;; *) # g++ # _LT_TAGVAR(hardcode_libdir_flag_spec, $1) is actually meaningless, # as there is no search path for DLLs. _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='-L$libdir' _LT_TAGVAR(export_dynamic_flag_spec, $1)='${wl}--export-all-symbols' _LT_TAGVAR(allow_undefined_flag, $1)=unsupported _LT_TAGVAR(always_export_symbols, $1)=no _LT_TAGVAR(enable_shared_with_static_runtimes, $1)=yes if $LD --help 2>&1 | $GREP 'auto-import' > /dev/null; then _LT_TAGVAR(archive_cmds, $1)='$CC -shared -nostdlib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags -o $output_objdir/$soname ${wl}--enable-auto-image-base -Xlinker --out-implib -Xlinker $lib' # If the export-symbols file already is a .def file (1st line # is EXPORTS), use it as is; otherwise, prepend... _LT_TAGVAR(archive_expsym_cmds, $1)='if test "x`$SED 1q $export_symbols`" = xEXPORTS; then cp $export_symbols $output_objdir/$soname.def; else echo EXPORTS > $output_objdir/$soname.def; cat $export_symbols >> $output_objdir/$soname.def; fi~ $CC -shared -nostdlib $output_objdir/$soname.def $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags -o $output_objdir/$soname ${wl}--enable-auto-image-base -Xlinker --out-implib -Xlinker $lib' else _LT_TAGVAR(ld_shlibs, $1)=no fi ;; esac ;; darwin* | rhapsody*) _LT_DARWIN_LINKER_FEATURES($1) ;; dgux*) case $cc_basename in ec++*) # FIXME: insert proper C++ library support _LT_TAGVAR(ld_shlibs, $1)=no ;; ghcx*) # Green Hills C++ Compiler # FIXME: insert proper C++ library support _LT_TAGVAR(ld_shlibs, $1)=no ;; *) # FIXME: insert proper C++ library support _LT_TAGVAR(ld_shlibs, $1)=no ;; esac ;; freebsd2.*) # C++ shared libraries reported to be fairly broken before # switch to ELF _LT_TAGVAR(ld_shlibs, $1)=no ;; freebsd-elf*) _LT_TAGVAR(archive_cmds_need_lc, $1)=no ;; freebsd* | dragonfly*) # FreeBSD 3 and later use GNU C++ and GNU ld with standard ELF # conventions _LT_TAGVAR(ld_shlibs, $1)=yes ;; gnu*) ;; haiku*) _LT_TAGVAR(archive_cmds, $1)='$CC -shared $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname -o $lib' _LT_TAGVAR(link_all_deplibs, $1)=yes ;; hpux9*) _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}+b ${wl}$libdir' _LT_TAGVAR(hardcode_libdir_separator, $1)=: _LT_TAGVAR(export_dynamic_flag_spec, $1)='${wl}-E' _LT_TAGVAR(hardcode_direct, $1)=yes _LT_TAGVAR(hardcode_minus_L, $1)=yes # Not in the search PATH, # but as the default # location of the library. case $cc_basename in CC*) # FIXME: insert proper C++ library support _LT_TAGVAR(ld_shlibs, $1)=no ;; aCC*) _LT_TAGVAR(archive_cmds, $1)='$RM $output_objdir/$soname~$CC -b ${wl}+b ${wl}$install_libdir -o $output_objdir/$soname $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags~test $output_objdir/$soname = $lib || mv $output_objdir/$soname $lib' # Commands to make compiler produce verbose output that lists # what "hidden" libraries, object files and flags are used when # linking a shared library. # # There doesn't appear to be a way to prevent this compiler from # explicitly linking system object files so we need to strip them # from the output so that they don't get included in the library # dependencies. output_verbose_link_cmd='templist=`($CC -b $CFLAGS -v conftest.$objext 2>&1) | $EGREP "\-L"`; list=""; for z in $templist; do case $z in conftest.$objext) list="$list $z";; *.$objext);; *) list="$list $z";;esac; done; func_echo_all "$list"' ;; *) if test "$GXX" = yes; then _LT_TAGVAR(archive_cmds, $1)='$RM $output_objdir/$soname~$CC -shared -nostdlib $pic_flag ${wl}+b ${wl}$install_libdir -o $output_objdir/$soname $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags~test $output_objdir/$soname = $lib || mv $output_objdir/$soname $lib' else # FIXME: insert proper C++ library support _LT_TAGVAR(ld_shlibs, $1)=no fi ;; esac ;; hpux10*|hpux11*) if test $with_gnu_ld = no; then _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}+b ${wl}$libdir' _LT_TAGVAR(hardcode_libdir_separator, $1)=: case $host_cpu in hppa*64*|ia64*) ;; *) _LT_TAGVAR(export_dynamic_flag_spec, $1)='${wl}-E' ;; esac fi case $host_cpu in hppa*64*|ia64*) _LT_TAGVAR(hardcode_direct, $1)=no _LT_TAGVAR(hardcode_shlibpath_var, $1)=no ;; *) _LT_TAGVAR(hardcode_direct, $1)=yes _LT_TAGVAR(hardcode_direct_absolute, $1)=yes _LT_TAGVAR(hardcode_minus_L, $1)=yes # Not in the search PATH, # but as the default # location of the library. ;; esac case $cc_basename in CC*) # FIXME: insert proper C++ library support _LT_TAGVAR(ld_shlibs, $1)=no ;; aCC*) case $host_cpu in hppa*64*) _LT_TAGVAR(archive_cmds, $1)='$CC -b ${wl}+h ${wl}$soname -o $lib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags' ;; ia64*) _LT_TAGVAR(archive_cmds, $1)='$CC -b ${wl}+h ${wl}$soname ${wl}+nodefaultrpath -o $lib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags' ;; *) _LT_TAGVAR(archive_cmds, $1)='$CC -b ${wl}+h ${wl}$soname ${wl}+b ${wl}$install_libdir -o $lib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags' ;; esac # Commands to make compiler produce verbose output that lists # what "hidden" libraries, object files and flags are used when # linking a shared library. # # There doesn't appear to be a way to prevent this compiler from # explicitly linking system object files so we need to strip them # from the output so that they don't get included in the library # dependencies. output_verbose_link_cmd='templist=`($CC -b $CFLAGS -v conftest.$objext 2>&1) | $GREP "\-L"`; list=""; for z in $templist; do case $z in conftest.$objext) list="$list $z";; *.$objext);; *) list="$list $z";;esac; done; func_echo_all "$list"' ;; *) if test "$GXX" = yes; then if test $with_gnu_ld = no; then case $host_cpu in hppa*64*) _LT_TAGVAR(archive_cmds, $1)='$CC -shared -nostdlib -fPIC ${wl}+h ${wl}$soname -o $lib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags' ;; ia64*) _LT_TAGVAR(archive_cmds, $1)='$CC -shared -nostdlib $pic_flag ${wl}+h ${wl}$soname ${wl}+nodefaultrpath -o $lib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags' ;; *) _LT_TAGVAR(archive_cmds, $1)='$CC -shared -nostdlib $pic_flag ${wl}+h ${wl}$soname ${wl}+b ${wl}$install_libdir -o $lib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags' ;; esac fi else # FIXME: insert proper C++ library support _LT_TAGVAR(ld_shlibs, $1)=no fi ;; esac ;; interix[[3-9]]*) _LT_TAGVAR(hardcode_direct, $1)=no _LT_TAGVAR(hardcode_shlibpath_var, $1)=no _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}-rpath,$libdir' _LT_TAGVAR(export_dynamic_flag_spec, $1)='${wl}-E' # Hack: On Interix 3.x, we cannot compile PIC because of a broken gcc. # Instead, shared libraries are loaded at an image base (0x10000000 by # default) and relocated if they conflict, which is a slow very memory # consuming and fragmenting process. To avoid this, we pick a random, # 256 KiB-aligned image base between 0x50000000 and 0x6FFC0000 at link # time. Moving up from 0x10000000 also allows more sbrk(2) space. _LT_TAGVAR(archive_cmds, $1)='$CC -shared $pic_flag $libobjs $deplibs $compiler_flags ${wl}-h,$soname ${wl}--image-base,`expr ${RANDOM-$$} % 4096 / 2 \* 262144 + 1342177280` -o $lib' _LT_TAGVAR(archive_expsym_cmds, $1)='sed "s,^,_," $export_symbols >$output_objdir/$soname.expsym~$CC -shared $pic_flag $libobjs $deplibs $compiler_flags ${wl}-h,$soname ${wl}--retain-symbols-file,$output_objdir/$soname.expsym ${wl}--image-base,`expr ${RANDOM-$$} % 4096 / 2 \* 262144 + 1342177280` -o $lib' ;; irix5* | irix6*) case $cc_basename in CC*) # SGI C++ _LT_TAGVAR(archive_cmds, $1)='$CC -shared -all -multigot $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags -soname $soname `test -n "$verstring" && func_echo_all "-set_version $verstring"` -update_registry ${output_objdir}/so_locations -o $lib' # Archives containing C++ object files must be created using # "CC -ar", where "CC" is the IRIX C++ compiler. This is # necessary to make sure instantiated templates are included # in the archive. _LT_TAGVAR(old_archive_cmds, $1)='$CC -ar -WR,-u -o $oldlib $oldobjs' ;; *) if test "$GXX" = yes; then if test "$with_gnu_ld" = no; then _LT_TAGVAR(archive_cmds, $1)='$CC -shared $pic_flag -nostdlib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags ${wl}-soname ${wl}$soname `test -n "$verstring" && func_echo_all "${wl}-set_version ${wl}$verstring"` ${wl}-update_registry ${wl}${output_objdir}/so_locations -o $lib' else _LT_TAGVAR(archive_cmds, $1)='$CC -shared $pic_flag -nostdlib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags ${wl}-soname ${wl}$soname `test -n "$verstring" && func_echo_all "${wl}-set_version ${wl}$verstring"` -o $lib' fi fi _LT_TAGVAR(link_all_deplibs, $1)=yes ;; esac _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}-rpath ${wl}$libdir' _LT_TAGVAR(hardcode_libdir_separator, $1)=: _LT_TAGVAR(inherit_rpath, $1)=yes ;; linux* | k*bsd*-gnu | kopensolaris*-gnu) case $cc_basename in KCC*) # Kuck and Associates, Inc. (KAI) C++ Compiler # KCC will only create a shared library if the output file # ends with ".so" (or ".sl" for HP-UX), so rename the library # to its proper name (with version) after linking. _LT_TAGVAR(archive_cmds, $1)='tempext=`echo $shared_ext | $SED -e '\''s/\([[^()0-9A-Za-z{}]]\)/\\\\\1/g'\''`; templib=`echo $lib | $SED -e "s/\${tempext}\..*/.so/"`; $CC $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags --soname $soname -o \$templib; mv \$templib $lib' _LT_TAGVAR(archive_expsym_cmds, $1)='tempext=`echo $shared_ext | $SED -e '\''s/\([[^()0-9A-Za-z{}]]\)/\\\\\1/g'\''`; templib=`echo $lib | $SED -e "s/\${tempext}\..*/.so/"`; $CC $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags --soname $soname -o \$templib ${wl}-retain-symbols-file,$export_symbols; mv \$templib $lib' # Commands to make compiler produce verbose output that lists # what "hidden" libraries, object files and flags are used when # linking a shared library. # # There doesn't appear to be a way to prevent this compiler from # explicitly linking system object files so we need to strip them # from the output so that they don't get included in the library # dependencies. output_verbose_link_cmd='templist=`$CC $CFLAGS -v conftest.$objext -o libconftest$shared_ext 2>&1 | $GREP "ld"`; rm -f libconftest$shared_ext; list=""; for z in $templist; do case $z in conftest.$objext) list="$list $z";; *.$objext);; *) list="$list $z";;esac; done; func_echo_all "$list"' _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}-rpath,$libdir' _LT_TAGVAR(export_dynamic_flag_spec, $1)='${wl}--export-dynamic' # Archives containing C++ object files must be created using # "CC -Bstatic", where "CC" is the KAI C++ compiler. _LT_TAGVAR(old_archive_cmds, $1)='$CC -Bstatic -o $oldlib $oldobjs' ;; icpc* | ecpc* ) # Intel C++ with_gnu_ld=yes # version 8.0 and above of icpc choke on multiply defined symbols # if we add $predep_objects and $postdep_objects, however 7.1 and # earlier do not add the objects themselves. case `$CC -V 2>&1` in *"Version 7."*) _LT_TAGVAR(archive_cmds, $1)='$CC -shared $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags ${wl}-soname $wl$soname -o $lib' _LT_TAGVAR(archive_expsym_cmds, $1)='$CC -shared $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags ${wl}-soname $wl$soname ${wl}-retain-symbols-file $wl$export_symbols -o $lib' ;; *) # Version 8.0 or newer tmp_idyn= case $host_cpu in ia64*) tmp_idyn=' -i_dynamic';; esac _LT_TAGVAR(archive_cmds, $1)='$CC -shared'"$tmp_idyn"' $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname -o $lib' _LT_TAGVAR(archive_expsym_cmds, $1)='$CC -shared'"$tmp_idyn"' $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname ${wl}-retain-symbols-file $wl$export_symbols -o $lib' ;; esac _LT_TAGVAR(archive_cmds_need_lc, $1)=no _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}-rpath,$libdir' _LT_TAGVAR(export_dynamic_flag_spec, $1)='${wl}--export-dynamic' _LT_TAGVAR(whole_archive_flag_spec, $1)='${wl}--whole-archive$convenience ${wl}--no-whole-archive' ;; pgCC* | pgcpp*) # Portland Group C++ compiler case `$CC -V` in *pgCC\ [[1-5]].* | *pgcpp\ [[1-5]].*) _LT_TAGVAR(prelink_cmds, $1)='tpldir=Template.dir~ rm -rf $tpldir~ $CC --prelink_objects --instantiation_dir $tpldir $objs $libobjs $compile_deplibs~ compile_command="$compile_command `find $tpldir -name \*.o | sort | $NL2SP`"' _LT_TAGVAR(old_archive_cmds, $1)='tpldir=Template.dir~ rm -rf $tpldir~ $CC --prelink_objects --instantiation_dir $tpldir $oldobjs$old_deplibs~ $AR $AR_FLAGS $oldlib$oldobjs$old_deplibs `find $tpldir -name \*.o | sort | $NL2SP`~ $RANLIB $oldlib' _LT_TAGVAR(archive_cmds, $1)='tpldir=Template.dir~ rm -rf $tpldir~ $CC --prelink_objects --instantiation_dir $tpldir $predep_objects $libobjs $deplibs $convenience $postdep_objects~ $CC -shared $pic_flag $predep_objects $libobjs $deplibs `find $tpldir -name \*.o | sort | $NL2SP` $postdep_objects $compiler_flags ${wl}-soname ${wl}$soname -o $lib' _LT_TAGVAR(archive_expsym_cmds, $1)='tpldir=Template.dir~ rm -rf $tpldir~ $CC --prelink_objects --instantiation_dir $tpldir $predep_objects $libobjs $deplibs $convenience $postdep_objects~ $CC -shared $pic_flag $predep_objects $libobjs $deplibs `find $tpldir -name \*.o | sort | $NL2SP` $postdep_objects $compiler_flags ${wl}-soname ${wl}$soname ${wl}-retain-symbols-file ${wl}$export_symbols -o $lib' ;; *) # Version 6 and above use weak symbols _LT_TAGVAR(archive_cmds, $1)='$CC -shared $pic_flag $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags ${wl}-soname ${wl}$soname -o $lib' _LT_TAGVAR(archive_expsym_cmds, $1)='$CC -shared $pic_flag $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags ${wl}-soname ${wl}$soname ${wl}-retain-symbols-file ${wl}$export_symbols -o $lib' ;; esac _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}--rpath ${wl}$libdir' _LT_TAGVAR(export_dynamic_flag_spec, $1)='${wl}--export-dynamic' _LT_TAGVAR(whole_archive_flag_spec, $1)='${wl}--whole-archive`for conv in $convenience\"\"; do test -n \"$conv\" && new_convenience=\"$new_convenience,$conv\"; done; func_echo_all \"$new_convenience\"` ${wl}--no-whole-archive' ;; cxx*) # Compaq C++ _LT_TAGVAR(archive_cmds, $1)='$CC -shared $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags ${wl}-soname $wl$soname -o $lib' _LT_TAGVAR(archive_expsym_cmds, $1)='$CC -shared $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags ${wl}-soname $wl$soname -o $lib ${wl}-retain-symbols-file $wl$export_symbols' runpath_var=LD_RUN_PATH _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='-rpath $libdir' _LT_TAGVAR(hardcode_libdir_separator, $1)=: # Commands to make compiler produce verbose output that lists # what "hidden" libraries, object files and flags are used when # linking a shared library. # # There doesn't appear to be a way to prevent this compiler from # explicitly linking system object files so we need to strip them # from the output so that they don't get included in the library # dependencies. output_verbose_link_cmd='templist=`$CC -shared $CFLAGS -v conftest.$objext 2>&1 | $GREP "ld"`; templist=`func_echo_all "$templist" | $SED "s/\(^.*ld.*\)\( .*ld .*$\)/\1/"`; list=""; for z in $templist; do case $z in conftest.$objext) list="$list $z";; *.$objext);; *) list="$list $z";;esac; done; func_echo_all "X$list" | $Xsed' ;; xl* | mpixl* | bgxl*) # IBM XL 8.0 on PPC, with GNU ld _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}-rpath ${wl}$libdir' _LT_TAGVAR(export_dynamic_flag_spec, $1)='${wl}--export-dynamic' _LT_TAGVAR(archive_cmds, $1)='$CC -qmkshrobj $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname -o $lib' if test "x$supports_anon_versioning" = xyes; then _LT_TAGVAR(archive_expsym_cmds, $1)='echo "{ global:" > $output_objdir/$libname.ver~ cat $export_symbols | sed -e "s/\(.*\)/\1;/" >> $output_objdir/$libname.ver~ echo "local: *; };" >> $output_objdir/$libname.ver~ $CC -qmkshrobj $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname ${wl}-version-script ${wl}$output_objdir/$libname.ver -o $lib' fi ;; *) case `$CC -V 2>&1 | sed 5q` in *Sun\ C*) # Sun C++ 5.9 _LT_TAGVAR(no_undefined_flag, $1)=' -zdefs' _LT_TAGVAR(archive_cmds, $1)='$CC -G${allow_undefined_flag} -h$soname -o $lib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags' _LT_TAGVAR(archive_expsym_cmds, $1)='$CC -G${allow_undefined_flag} -h$soname -o $lib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags ${wl}-retain-symbols-file ${wl}$export_symbols' _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='-R$libdir' _LT_TAGVAR(whole_archive_flag_spec, $1)='${wl}--whole-archive`new_convenience=; for conv in $convenience\"\"; do test -z \"$conv\" || new_convenience=\"$new_convenience,$conv\"; done; func_echo_all \"$new_convenience\"` ${wl}--no-whole-archive' _LT_TAGVAR(compiler_needs_object, $1)=yes # Not sure whether something based on # $CC $CFLAGS -v conftest.$objext -o libconftest$shared_ext 2>&1 # would be better. output_verbose_link_cmd='func_echo_all' # Archives containing C++ object files must be created using # "CC -xar", where "CC" is the Sun C++ compiler. This is # necessary to make sure instantiated templates are included # in the archive. _LT_TAGVAR(old_archive_cmds, $1)='$CC -xar -o $oldlib $oldobjs' ;; esac ;; esac ;; lynxos*) # FIXME: insert proper C++ library support _LT_TAGVAR(ld_shlibs, $1)=no ;; m88k*) # FIXME: insert proper C++ library support _LT_TAGVAR(ld_shlibs, $1)=no ;; mvs*) case $cc_basename in cxx*) # FIXME: insert proper C++ library support _LT_TAGVAR(ld_shlibs, $1)=no ;; *) # FIXME: insert proper C++ library support _LT_TAGVAR(ld_shlibs, $1)=no ;; esac ;; netbsd*) if echo __ELF__ | $CC -E - | $GREP __ELF__ >/dev/null; then _LT_TAGVAR(archive_cmds, $1)='$LD -Bshareable -o $lib $predep_objects $libobjs $deplibs $postdep_objects $linker_flags' wlarc= _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='-R$libdir' _LT_TAGVAR(hardcode_direct, $1)=yes _LT_TAGVAR(hardcode_shlibpath_var, $1)=no fi # Workaround some broken pre-1.5 toolchains output_verbose_link_cmd='$CC -shared $CFLAGS -v conftest.$objext 2>&1 | $GREP conftest.$objext | $SED -e "s:-lgcc -lc -lgcc::"' ;; *nto* | *qnx*) _LT_TAGVAR(ld_shlibs, $1)=yes ;; openbsd2*) # C++ shared libraries are fairly broken _LT_TAGVAR(ld_shlibs, $1)=no ;; openbsd*) if test -f /usr/libexec/ld.so; then _LT_TAGVAR(hardcode_direct, $1)=yes _LT_TAGVAR(hardcode_shlibpath_var, $1)=no _LT_TAGVAR(hardcode_direct_absolute, $1)=yes _LT_TAGVAR(archive_cmds, $1)='$CC -shared $pic_flag $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags -o $lib' _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}-rpath,$libdir' if test -z "`echo __ELF__ | $CC -E - | grep __ELF__`" || test "$host_os-$host_cpu" = "openbsd2.8-powerpc"; then _LT_TAGVAR(archive_expsym_cmds, $1)='$CC -shared $pic_flag $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags ${wl}-retain-symbols-file,$export_symbols -o $lib' _LT_TAGVAR(export_dynamic_flag_spec, $1)='${wl}-E' _LT_TAGVAR(whole_archive_flag_spec, $1)="$wlarc"'--whole-archive$convenience '"$wlarc"'--no-whole-archive' fi output_verbose_link_cmd=func_echo_all else _LT_TAGVAR(ld_shlibs, $1)=no fi ;; osf3* | osf4* | osf5*) case $cc_basename in KCC*) # Kuck and Associates, Inc. (KAI) C++ Compiler # KCC will only create a shared library if the output file # ends with ".so" (or ".sl" for HP-UX), so rename the library # to its proper name (with version) after linking. _LT_TAGVAR(archive_cmds, $1)='tempext=`echo $shared_ext | $SED -e '\''s/\([[^()0-9A-Za-z{}]]\)/\\\\\1/g'\''`; templib=`echo "$lib" | $SED -e "s/\${tempext}\..*/.so/"`; $CC $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags --soname $soname -o \$templib; mv \$templib $lib' _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}-rpath,$libdir' _LT_TAGVAR(hardcode_libdir_separator, $1)=: # Archives containing C++ object files must be created using # the KAI C++ compiler. case $host in osf3*) _LT_TAGVAR(old_archive_cmds, $1)='$CC -Bstatic -o $oldlib $oldobjs' ;; *) _LT_TAGVAR(old_archive_cmds, $1)='$CC -o $oldlib $oldobjs' ;; esac ;; RCC*) # Rational C++ 2.4.1 # FIXME: insert proper C++ library support _LT_TAGVAR(ld_shlibs, $1)=no ;; cxx*) case $host in osf3*) _LT_TAGVAR(allow_undefined_flag, $1)=' ${wl}-expect_unresolved ${wl}\*' _LT_TAGVAR(archive_cmds, $1)='$CC -shared${allow_undefined_flag} $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags ${wl}-soname $soname `test -n "$verstring" && func_echo_all "${wl}-set_version $verstring"` -update_registry ${output_objdir}/so_locations -o $lib' _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}-rpath ${wl}$libdir' ;; *) _LT_TAGVAR(allow_undefined_flag, $1)=' -expect_unresolved \*' _LT_TAGVAR(archive_cmds, $1)='$CC -shared${allow_undefined_flag} $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags -msym -soname $soname `test -n "$verstring" && func_echo_all "-set_version $verstring"` -update_registry ${output_objdir}/so_locations -o $lib' _LT_TAGVAR(archive_expsym_cmds, $1)='for i in `cat $export_symbols`; do printf "%s %s\\n" -exported_symbol "\$i" >> $lib.exp; done~ echo "-hidden">> $lib.exp~ $CC -shared$allow_undefined_flag $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags -msym -soname $soname ${wl}-input ${wl}$lib.exp `test -n "$verstring" && $ECHO "-set_version $verstring"` -update_registry ${output_objdir}/so_locations -o $lib~ $RM $lib.exp' _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='-rpath $libdir' ;; esac _LT_TAGVAR(hardcode_libdir_separator, $1)=: # Commands to make compiler produce verbose output that lists # what "hidden" libraries, object files and flags are used when # linking a shared library. # # There doesn't appear to be a way to prevent this compiler from # explicitly linking system object files so we need to strip them # from the output so that they don't get included in the library # dependencies. output_verbose_link_cmd='templist=`$CC -shared $CFLAGS -v conftest.$objext 2>&1 | $GREP "ld" | $GREP -v "ld:"`; templist=`func_echo_all "$templist" | $SED "s/\(^.*ld.*\)\( .*ld.*$\)/\1/"`; list=""; for z in $templist; do case $z in conftest.$objext) list="$list $z";; *.$objext);; *) list="$list $z";;esac; done; func_echo_all "$list"' ;; *) if test "$GXX" = yes && test "$with_gnu_ld" = no; then _LT_TAGVAR(allow_undefined_flag, $1)=' ${wl}-expect_unresolved ${wl}\*' case $host in osf3*) _LT_TAGVAR(archive_cmds, $1)='$CC -shared -nostdlib ${allow_undefined_flag} $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags ${wl}-soname ${wl}$soname `test -n "$verstring" && func_echo_all "${wl}-set_version ${wl}$verstring"` ${wl}-update_registry ${wl}${output_objdir}/so_locations -o $lib' ;; *) _LT_TAGVAR(archive_cmds, $1)='$CC -shared $pic_flag -nostdlib ${allow_undefined_flag} $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags ${wl}-msym ${wl}-soname ${wl}$soname `test -n "$verstring" && func_echo_all "${wl}-set_version ${wl}$verstring"` ${wl}-update_registry ${wl}${output_objdir}/so_locations -o $lib' ;; esac _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}-rpath ${wl}$libdir' _LT_TAGVAR(hardcode_libdir_separator, $1)=: # Commands to make compiler produce verbose output that lists # what "hidden" libraries, object files and flags are used when # linking a shared library. output_verbose_link_cmd='$CC -shared $CFLAGS -v conftest.$objext 2>&1 | $GREP -v "^Configured with:" | $GREP "\-L"' else # FIXME: insert proper C++ library support _LT_TAGVAR(ld_shlibs, $1)=no fi ;; esac ;; psos*) # FIXME: insert proper C++ library support _LT_TAGVAR(ld_shlibs, $1)=no ;; sunos4*) case $cc_basename in CC*) # Sun C++ 4.x # FIXME: insert proper C++ library support _LT_TAGVAR(ld_shlibs, $1)=no ;; lcc*) # Lucid # FIXME: insert proper C++ library support _LT_TAGVAR(ld_shlibs, $1)=no ;; *) # FIXME: insert proper C++ library support _LT_TAGVAR(ld_shlibs, $1)=no ;; esac ;; solaris*) case $cc_basename in CC* | sunCC*) # Sun C++ 4.2, 5.x and Centerline C++ _LT_TAGVAR(archive_cmds_need_lc,$1)=yes _LT_TAGVAR(no_undefined_flag, $1)=' -zdefs' _LT_TAGVAR(archive_cmds, $1)='$CC -G${allow_undefined_flag} -h$soname -o $lib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags' _LT_TAGVAR(archive_expsym_cmds, $1)='echo "{ global:" > $lib.exp~cat $export_symbols | $SED -e "s/\(.*\)/\1;/" >> $lib.exp~echo "local: *; };" >> $lib.exp~ $CC -G${allow_undefined_flag} ${wl}-M ${wl}$lib.exp -h$soname -o $lib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags~$RM $lib.exp' _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='-R$libdir' _LT_TAGVAR(hardcode_shlibpath_var, $1)=no case $host_os in solaris2.[[0-5]] | solaris2.[[0-5]].*) ;; *) # The compiler driver will combine and reorder linker options, # but understands `-z linker_flag'. # Supported since Solaris 2.6 (maybe 2.5.1?) _LT_TAGVAR(whole_archive_flag_spec, $1)='-z allextract$convenience -z defaultextract' ;; esac _LT_TAGVAR(link_all_deplibs, $1)=yes output_verbose_link_cmd='func_echo_all' # Archives containing C++ object files must be created using # "CC -xar", where "CC" is the Sun C++ compiler. This is # necessary to make sure instantiated templates are included # in the archive. _LT_TAGVAR(old_archive_cmds, $1)='$CC -xar -o $oldlib $oldobjs' ;; gcx*) # Green Hills C++ Compiler _LT_TAGVAR(archive_cmds, $1)='$CC -shared $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags ${wl}-h $wl$soname -o $lib' # The C++ compiler must be used to create the archive. _LT_TAGVAR(old_archive_cmds, $1)='$CC $LDFLAGS -archive -o $oldlib $oldobjs' ;; *) # GNU C++ compiler with Solaris linker if test "$GXX" = yes && test "$with_gnu_ld" = no; then _LT_TAGVAR(no_undefined_flag, $1)=' ${wl}-z ${wl}defs' if $CC --version | $GREP -v '^2\.7' > /dev/null; then _LT_TAGVAR(archive_cmds, $1)='$CC -shared $pic_flag -nostdlib $LDFLAGS $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags ${wl}-h $wl$soname -o $lib' _LT_TAGVAR(archive_expsym_cmds, $1)='echo "{ global:" > $lib.exp~cat $export_symbols | $SED -e "s/\(.*\)/\1;/" >> $lib.exp~echo "local: *; };" >> $lib.exp~ $CC -shared $pic_flag -nostdlib ${wl}-M $wl$lib.exp -o $lib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags~$RM $lib.exp' # Commands to make compiler produce verbose output that lists # what "hidden" libraries, object files and flags are used when # linking a shared library. output_verbose_link_cmd='$CC -shared $CFLAGS -v conftest.$objext 2>&1 | $GREP -v "^Configured with:" | $GREP "\-L"' else # g++ 2.7 appears to require `-G' NOT `-shared' on this # platform. _LT_TAGVAR(archive_cmds, $1)='$CC -G -nostdlib $LDFLAGS $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags ${wl}-h $wl$soname -o $lib' _LT_TAGVAR(archive_expsym_cmds, $1)='echo "{ global:" > $lib.exp~cat $export_symbols | $SED -e "s/\(.*\)/\1;/" >> $lib.exp~echo "local: *; };" >> $lib.exp~ $CC -G -nostdlib ${wl}-M $wl$lib.exp -o $lib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags~$RM $lib.exp' # Commands to make compiler produce verbose output that lists # what "hidden" libraries, object files and flags are used when # linking a shared library. output_verbose_link_cmd='$CC -G $CFLAGS -v conftest.$objext 2>&1 | $GREP -v "^Configured with:" | $GREP "\-L"' fi _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}-R $wl$libdir' case $host_os in solaris2.[[0-5]] | solaris2.[[0-5]].*) ;; *) _LT_TAGVAR(whole_archive_flag_spec, $1)='${wl}-z ${wl}allextract$convenience ${wl}-z ${wl}defaultextract' ;; esac fi ;; esac ;; sysv4*uw2* | sysv5OpenUNIX* | sysv5UnixWare7.[[01]].[[10]]* | unixware7* | sco3.2v5.0.[[024]]*) _LT_TAGVAR(no_undefined_flag, $1)='${wl}-z,text' _LT_TAGVAR(archive_cmds_need_lc, $1)=no _LT_TAGVAR(hardcode_shlibpath_var, $1)=no runpath_var='LD_RUN_PATH' case $cc_basename in CC*) _LT_TAGVAR(archive_cmds, $1)='$CC -G ${wl}-h,$soname -o $lib $libobjs $deplibs $compiler_flags' _LT_TAGVAR(archive_expsym_cmds, $1)='$CC -G ${wl}-Bexport:$export_symbols ${wl}-h,$soname -o $lib $libobjs $deplibs $compiler_flags' ;; *) _LT_TAGVAR(archive_cmds, $1)='$CC -shared ${wl}-h,$soname -o $lib $libobjs $deplibs $compiler_flags' _LT_TAGVAR(archive_expsym_cmds, $1)='$CC -shared ${wl}-Bexport:$export_symbols ${wl}-h,$soname -o $lib $libobjs $deplibs $compiler_flags' ;; esac ;; sysv5* | sco3.2v5* | sco5v6*) # Note: We can NOT use -z defs as we might desire, because we do not # link with -lc, and that would cause any symbols used from libc to # always be unresolved, which means just about no library would # ever link correctly. If we're not using GNU ld we use -z text # though, which does catch some bad symbols but isn't as heavy-handed # as -z defs. _LT_TAGVAR(no_undefined_flag, $1)='${wl}-z,text' _LT_TAGVAR(allow_undefined_flag, $1)='${wl}-z,nodefs' _LT_TAGVAR(archive_cmds_need_lc, $1)=no _LT_TAGVAR(hardcode_shlibpath_var, $1)=no _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}-R,$libdir' _LT_TAGVAR(hardcode_libdir_separator, $1)=':' _LT_TAGVAR(link_all_deplibs, $1)=yes _LT_TAGVAR(export_dynamic_flag_spec, $1)='${wl}-Bexport' runpath_var='LD_RUN_PATH' case $cc_basename in CC*) _LT_TAGVAR(archive_cmds, $1)='$CC -G ${wl}-h,$soname -o $lib $libobjs $deplibs $compiler_flags' _LT_TAGVAR(archive_expsym_cmds, $1)='$CC -G ${wl}-Bexport:$export_symbols ${wl}-h,$soname -o $lib $libobjs $deplibs $compiler_flags' _LT_TAGVAR(old_archive_cmds, $1)='$CC -Tprelink_objects $oldobjs~ '"$_LT_TAGVAR(old_archive_cmds, $1)" _LT_TAGVAR(reload_cmds, $1)='$CC -Tprelink_objects $reload_objs~ '"$_LT_TAGVAR(reload_cmds, $1)" ;; *) _LT_TAGVAR(archive_cmds, $1)='$CC -shared ${wl}-h,$soname -o $lib $libobjs $deplibs $compiler_flags' _LT_TAGVAR(archive_expsym_cmds, $1)='$CC -shared ${wl}-Bexport:$export_symbols ${wl}-h,$soname -o $lib $libobjs $deplibs $compiler_flags' ;; esac ;; tandem*) case $cc_basename in NCC*) # NonStop-UX NCC 3.20 # FIXME: insert proper C++ library support _LT_TAGVAR(ld_shlibs, $1)=no ;; *) # FIXME: insert proper C++ library support _LT_TAGVAR(ld_shlibs, $1)=no ;; esac ;; vxworks*) # FIXME: insert proper C++ library support _LT_TAGVAR(ld_shlibs, $1)=no ;; *) # FIXME: insert proper C++ library support _LT_TAGVAR(ld_shlibs, $1)=no ;; esac AC_MSG_RESULT([$_LT_TAGVAR(ld_shlibs, $1)]) test "$_LT_TAGVAR(ld_shlibs, $1)" = no && can_build_shared=no _LT_TAGVAR(GCC, $1)="$GXX" _LT_TAGVAR(LD, $1)="$LD" ## CAVEAT EMPTOR: ## There is no encapsulation within the following macros, do not change ## the running order or otherwise move them around unless you know exactly ## what you are doing... _LT_SYS_HIDDEN_LIBDEPS($1) _LT_COMPILER_PIC($1) _LT_COMPILER_C_O($1) _LT_COMPILER_FILE_LOCKS($1) _LT_LINKER_SHLIBS($1) _LT_SYS_DYNAMIC_LINKER($1) _LT_LINKER_HARDCODE_LIBPATH($1) _LT_CONFIG($1) fi # test -n "$compiler" CC=$lt_save_CC CFLAGS=$lt_save_CFLAGS LDCXX=$LD LD=$lt_save_LD GCC=$lt_save_GCC with_gnu_ld=$lt_save_with_gnu_ld lt_cv_path_LDCXX=$lt_cv_path_LD lt_cv_path_LD=$lt_save_path_LD lt_cv_prog_gnu_ldcxx=$lt_cv_prog_gnu_ld lt_cv_prog_gnu_ld=$lt_save_with_gnu_ld fi # test "$_lt_caught_CXX_error" != yes AC_LANG_POP ])# _LT_LANG_CXX_CONFIG # _LT_FUNC_STRIPNAME_CNF # ---------------------- # func_stripname_cnf prefix suffix name # strip PREFIX and SUFFIX off of NAME. # PREFIX and SUFFIX must not contain globbing or regex special # characters, hashes, percent signs, but SUFFIX may contain a leading # dot (in which case that matches only a dot). # # This function is identical to the (non-XSI) version of func_stripname, # except this one can be used by m4 code that may be executed by configure, # rather than the libtool script. m4_defun([_LT_FUNC_STRIPNAME_CNF],[dnl AC_REQUIRE([_LT_DECL_SED]) AC_REQUIRE([_LT_PROG_ECHO_BACKSLASH]) func_stripname_cnf () { case ${2} in .*) func_stripname_result=`$ECHO "${3}" | $SED "s%^${1}%%; s%\\\\${2}\$%%"`;; *) func_stripname_result=`$ECHO "${3}" | $SED "s%^${1}%%; s%${2}\$%%"`;; esac } # func_stripname_cnf ])# _LT_FUNC_STRIPNAME_CNF # _LT_SYS_HIDDEN_LIBDEPS([TAGNAME]) # --------------------------------- # Figure out "hidden" library dependencies from verbose # compiler output when linking a shared library. # Parse the compiler output and extract the necessary # objects, libraries and library flags. m4_defun([_LT_SYS_HIDDEN_LIBDEPS], [m4_require([_LT_FILEUTILS_DEFAULTS])dnl AC_REQUIRE([_LT_FUNC_STRIPNAME_CNF])dnl # Dependencies to place before and after the object being linked: _LT_TAGVAR(predep_objects, $1)= _LT_TAGVAR(postdep_objects, $1)= _LT_TAGVAR(predeps, $1)= _LT_TAGVAR(postdeps, $1)= _LT_TAGVAR(compiler_lib_search_path, $1)= dnl we can't use the lt_simple_compile_test_code here, dnl because it contains code intended for an executable, dnl not a library. It's possible we should let each dnl tag define a new lt_????_link_test_code variable, dnl but it's only used here... m4_if([$1], [], [cat > conftest.$ac_ext <<_LT_EOF int a; void foo (void) { a = 0; } _LT_EOF ], [$1], [CXX], [cat > conftest.$ac_ext <<_LT_EOF class Foo { public: Foo (void) { a = 0; } private: int a; }; _LT_EOF ], [$1], [F77], [cat > conftest.$ac_ext <<_LT_EOF subroutine foo implicit none integer*4 a a=0 return end _LT_EOF ], [$1], [FC], [cat > conftest.$ac_ext <<_LT_EOF subroutine foo implicit none integer a a=0 return end _LT_EOF ], [$1], [GCJ], [cat > conftest.$ac_ext <<_LT_EOF public class foo { private int a; public void bar (void) { a = 0; } }; _LT_EOF ], [$1], [GO], [cat > conftest.$ac_ext <<_LT_EOF package foo func foo() { } _LT_EOF ]) _lt_libdeps_save_CFLAGS=$CFLAGS case "$CC $CFLAGS " in #( *\ -flto*\ *) CFLAGS="$CFLAGS -fno-lto" ;; *\ -fwhopr*\ *) CFLAGS="$CFLAGS -fno-whopr" ;; *\ -fuse-linker-plugin*\ *) CFLAGS="$CFLAGS -fno-use-linker-plugin" ;; esac dnl Parse the compiler output and extract the necessary dnl objects, libraries and library flags. if AC_TRY_EVAL(ac_compile); then # Parse the compiler output and extract the necessary # objects, libraries and library flags. # Sentinel used to keep track of whether or not we are before # the conftest object file. pre_test_object_deps_done=no for p in `eval "$output_verbose_link_cmd"`; do case ${prev}${p} in -L* | -R* | -l*) # Some compilers place space between "-{L,R}" and the path. # Remove the space. if test $p = "-L" || test $p = "-R"; then prev=$p continue fi # Expand the sysroot to ease extracting the directories later. if test -z "$prev"; then case $p in -L*) func_stripname_cnf '-L' '' "$p"; prev=-L; p=$func_stripname_result ;; -R*) func_stripname_cnf '-R' '' "$p"; prev=-R; p=$func_stripname_result ;; -l*) func_stripname_cnf '-l' '' "$p"; prev=-l; p=$func_stripname_result ;; esac fi case $p in =*) func_stripname_cnf '=' '' "$p"; p=$lt_sysroot$func_stripname_result ;; esac if test "$pre_test_object_deps_done" = no; then case ${prev} in -L | -R) # Internal compiler library paths should come after those # provided the user. The postdeps already come after the # user supplied libs so there is no need to process them. if test -z "$_LT_TAGVAR(compiler_lib_search_path, $1)"; then _LT_TAGVAR(compiler_lib_search_path, $1)="${prev}${p}" else _LT_TAGVAR(compiler_lib_search_path, $1)="${_LT_TAGVAR(compiler_lib_search_path, $1)} ${prev}${p}" fi ;; # The "-l" case would never come before the object being # linked, so don't bother handling this case. esac else if test -z "$_LT_TAGVAR(postdeps, $1)"; then _LT_TAGVAR(postdeps, $1)="${prev}${p}" else _LT_TAGVAR(postdeps, $1)="${_LT_TAGVAR(postdeps, $1)} ${prev}${p}" fi fi prev= ;; *.lto.$objext) ;; # Ignore GCC LTO objects *.$objext) # This assumes that the test object file only shows up # once in the compiler output. if test "$p" = "conftest.$objext"; then pre_test_object_deps_done=yes continue fi if test "$pre_test_object_deps_done" = no; then if test -z "$_LT_TAGVAR(predep_objects, $1)"; then _LT_TAGVAR(predep_objects, $1)="$p" else _LT_TAGVAR(predep_objects, $1)="$_LT_TAGVAR(predep_objects, $1) $p" fi else if test -z "$_LT_TAGVAR(postdep_objects, $1)"; then _LT_TAGVAR(postdep_objects, $1)="$p" else _LT_TAGVAR(postdep_objects, $1)="$_LT_TAGVAR(postdep_objects, $1) $p" fi fi ;; *) ;; # Ignore the rest. esac done # Clean up. rm -f a.out a.exe else echo "libtool.m4: error: problem compiling $1 test program" fi $RM -f confest.$objext CFLAGS=$_lt_libdeps_save_CFLAGS # PORTME: override above test on systems where it is broken m4_if([$1], [CXX], [case $host_os in interix[[3-9]]*) # Interix 3.5 installs completely hosed .la files for C++, so rather than # hack all around it, let's just trust "g++" to DTRT. _LT_TAGVAR(predep_objects,$1)= _LT_TAGVAR(postdep_objects,$1)= _LT_TAGVAR(postdeps,$1)= ;; linux*) case `$CC -V 2>&1 | sed 5q` in *Sun\ C*) # Sun C++ 5.9 # The more standards-conforming stlport4 library is # incompatible with the Cstd library. Avoid specifying # it if it's in CXXFLAGS. Ignore libCrun as # -library=stlport4 depends on it. case " $CXX $CXXFLAGS " in *" -library=stlport4 "*) solaris_use_stlport4=yes ;; esac if test "$solaris_use_stlport4" != yes; then _LT_TAGVAR(postdeps,$1)='-library=Cstd -library=Crun' fi ;; esac ;; solaris*) case $cc_basename in CC* | sunCC*) # The more standards-conforming stlport4 library is # incompatible with the Cstd library. Avoid specifying # it if it's in CXXFLAGS. Ignore libCrun as # -library=stlport4 depends on it. case " $CXX $CXXFLAGS " in *" -library=stlport4 "*) solaris_use_stlport4=yes ;; esac # Adding this requires a known-good setup of shared libraries for # Sun compiler versions before 5.6, else PIC objects from an old # archive will be linked into the output, leading to subtle bugs. if test "$solaris_use_stlport4" != yes; then _LT_TAGVAR(postdeps,$1)='-library=Cstd -library=Crun' fi ;; esac ;; esac ]) case " $_LT_TAGVAR(postdeps, $1) " in *" -lc "*) _LT_TAGVAR(archive_cmds_need_lc, $1)=no ;; esac _LT_TAGVAR(compiler_lib_search_dirs, $1)= if test -n "${_LT_TAGVAR(compiler_lib_search_path, $1)}"; then _LT_TAGVAR(compiler_lib_search_dirs, $1)=`echo " ${_LT_TAGVAR(compiler_lib_search_path, $1)}" | ${SED} -e 's! -L! !g' -e 's!^ !!'` fi _LT_TAGDECL([], [compiler_lib_search_dirs], [1], [The directories searched by this compiler when creating a shared library]) _LT_TAGDECL([], [predep_objects], [1], [Dependencies to place before and after the objects being linked to create a shared library]) _LT_TAGDECL([], [postdep_objects], [1]) _LT_TAGDECL([], [predeps], [1]) _LT_TAGDECL([], [postdeps], [1]) _LT_TAGDECL([], [compiler_lib_search_path], [1], [The library search path used internally by the compiler when linking a shared library]) ])# _LT_SYS_HIDDEN_LIBDEPS # _LT_LANG_F77_CONFIG([TAG]) # -------------------------- # Ensure that the configuration variables for a Fortran 77 compiler are # suitably defined. These variables are subsequently used by _LT_CONFIG # to write the compiler configuration to `libtool'. m4_defun([_LT_LANG_F77_CONFIG], [AC_LANG_PUSH(Fortran 77) if test -z "$F77" || test "X$F77" = "Xno"; then _lt_disable_F77=yes fi _LT_TAGVAR(archive_cmds_need_lc, $1)=no _LT_TAGVAR(allow_undefined_flag, $1)= _LT_TAGVAR(always_export_symbols, $1)=no _LT_TAGVAR(archive_expsym_cmds, $1)= _LT_TAGVAR(export_dynamic_flag_spec, $1)= _LT_TAGVAR(hardcode_direct, $1)=no _LT_TAGVAR(hardcode_direct_absolute, $1)=no _LT_TAGVAR(hardcode_libdir_flag_spec, $1)= _LT_TAGVAR(hardcode_libdir_separator, $1)= _LT_TAGVAR(hardcode_minus_L, $1)=no _LT_TAGVAR(hardcode_automatic, $1)=no _LT_TAGVAR(inherit_rpath, $1)=no _LT_TAGVAR(module_cmds, $1)= _LT_TAGVAR(module_expsym_cmds, $1)= _LT_TAGVAR(link_all_deplibs, $1)=unknown _LT_TAGVAR(old_archive_cmds, $1)=$old_archive_cmds _LT_TAGVAR(reload_flag, $1)=$reload_flag _LT_TAGVAR(reload_cmds, $1)=$reload_cmds _LT_TAGVAR(no_undefined_flag, $1)= _LT_TAGVAR(whole_archive_flag_spec, $1)= _LT_TAGVAR(enable_shared_with_static_runtimes, $1)=no # Source file extension for f77 test sources. ac_ext=f # Object file extension for compiled f77 test sources. objext=o _LT_TAGVAR(objext, $1)=$objext # No sense in running all these tests if we already determined that # the F77 compiler isn't working. Some variables (like enable_shared) # are currently assumed to apply to all compilers on this platform, # and will be corrupted by setting them based on a non-working compiler. if test "$_lt_disable_F77" != yes; then # Code to be used in simple compile tests lt_simple_compile_test_code="\ subroutine t return end " # Code to be used in simple link tests lt_simple_link_test_code="\ program t end " # ltmain only uses $CC for tagged configurations so make sure $CC is set. _LT_TAG_COMPILER # save warnings/boilerplate of simple test code _LT_COMPILER_BOILERPLATE _LT_LINKER_BOILERPLATE # Allow CC to be a program name with arguments. lt_save_CC="$CC" lt_save_GCC=$GCC lt_save_CFLAGS=$CFLAGS CC=${F77-"f77"} CFLAGS=$FFLAGS compiler=$CC _LT_TAGVAR(compiler, $1)=$CC _LT_CC_BASENAME([$compiler]) GCC=$G77 if test -n "$compiler"; then AC_MSG_CHECKING([if libtool supports shared libraries]) AC_MSG_RESULT([$can_build_shared]) AC_MSG_CHECKING([whether to build shared libraries]) test "$can_build_shared" = "no" && enable_shared=no # On AIX, shared libraries and static libraries use the same namespace, and # are all built from PIC. case $host_os in aix3*) test "$enable_shared" = yes && enable_static=no if test -n "$RANLIB"; then archive_cmds="$archive_cmds~\$RANLIB \$lib" postinstall_cmds='$RANLIB $lib' fi ;; aix[[4-9]]*) if test "$host_cpu" != ia64 && test "$aix_use_runtimelinking" = no ; then test "$enable_shared" = yes && enable_static=no fi ;; esac AC_MSG_RESULT([$enable_shared]) AC_MSG_CHECKING([whether to build static libraries]) # Make sure either enable_shared or enable_static is yes. test "$enable_shared" = yes || enable_static=yes AC_MSG_RESULT([$enable_static]) _LT_TAGVAR(GCC, $1)="$G77" _LT_TAGVAR(LD, $1)="$LD" ## CAVEAT EMPTOR: ## There is no encapsulation within the following macros, do not change ## the running order or otherwise move them around unless you know exactly ## what you are doing... _LT_COMPILER_PIC($1) _LT_COMPILER_C_O($1) _LT_COMPILER_FILE_LOCKS($1) _LT_LINKER_SHLIBS($1) _LT_SYS_DYNAMIC_LINKER($1) _LT_LINKER_HARDCODE_LIBPATH($1) _LT_CONFIG($1) fi # test -n "$compiler" GCC=$lt_save_GCC CC="$lt_save_CC" CFLAGS="$lt_save_CFLAGS" fi # test "$_lt_disable_F77" != yes AC_LANG_POP ])# _LT_LANG_F77_CONFIG # _LT_LANG_FC_CONFIG([TAG]) # ------------------------- # Ensure that the configuration variables for a Fortran compiler are # suitably defined. These variables are subsequently used by _LT_CONFIG # to write the compiler configuration to `libtool'. m4_defun([_LT_LANG_FC_CONFIG], [AC_LANG_PUSH(Fortran) if test -z "$FC" || test "X$FC" = "Xno"; then _lt_disable_FC=yes fi _LT_TAGVAR(archive_cmds_need_lc, $1)=no _LT_TAGVAR(allow_undefined_flag, $1)= _LT_TAGVAR(always_export_symbols, $1)=no _LT_TAGVAR(archive_expsym_cmds, $1)= _LT_TAGVAR(export_dynamic_flag_spec, $1)= _LT_TAGVAR(hardcode_direct, $1)=no _LT_TAGVAR(hardcode_direct_absolute, $1)=no _LT_TAGVAR(hardcode_libdir_flag_spec, $1)= _LT_TAGVAR(hardcode_libdir_separator, $1)= _LT_TAGVAR(hardcode_minus_L, $1)=no _LT_TAGVAR(hardcode_automatic, $1)=no _LT_TAGVAR(inherit_rpath, $1)=no _LT_TAGVAR(module_cmds, $1)= _LT_TAGVAR(module_expsym_cmds, $1)= _LT_TAGVAR(link_all_deplibs, $1)=unknown _LT_TAGVAR(old_archive_cmds, $1)=$old_archive_cmds _LT_TAGVAR(reload_flag, $1)=$reload_flag _LT_TAGVAR(reload_cmds, $1)=$reload_cmds _LT_TAGVAR(no_undefined_flag, $1)= _LT_TAGVAR(whole_archive_flag_spec, $1)= _LT_TAGVAR(enable_shared_with_static_runtimes, $1)=no # Source file extension for fc test sources. ac_ext=${ac_fc_srcext-f} # Object file extension for compiled fc test sources. objext=o _LT_TAGVAR(objext, $1)=$objext # No sense in running all these tests if we already determined that # the FC compiler isn't working. Some variables (like enable_shared) # are currently assumed to apply to all compilers on this platform, # and will be corrupted by setting them based on a non-working compiler. if test "$_lt_disable_FC" != yes; then # Code to be used in simple compile tests lt_simple_compile_test_code="\ subroutine t return end " # Code to be used in simple link tests lt_simple_link_test_code="\ program t end " # ltmain only uses $CC for tagged configurations so make sure $CC is set. _LT_TAG_COMPILER # save warnings/boilerplate of simple test code _LT_COMPILER_BOILERPLATE _LT_LINKER_BOILERPLATE # Allow CC to be a program name with arguments. lt_save_CC="$CC" lt_save_GCC=$GCC lt_save_CFLAGS=$CFLAGS CC=${FC-"f95"} CFLAGS=$FCFLAGS compiler=$CC GCC=$ac_cv_fc_compiler_gnu _LT_TAGVAR(compiler, $1)=$CC _LT_CC_BASENAME([$compiler]) if test -n "$compiler"; then AC_MSG_CHECKING([if libtool supports shared libraries]) AC_MSG_RESULT([$can_build_shared]) AC_MSG_CHECKING([whether to build shared libraries]) test "$can_build_shared" = "no" && enable_shared=no # On AIX, shared libraries and static libraries use the same namespace, and # are all built from PIC. case $host_os in aix3*) test "$enable_shared" = yes && enable_static=no if test -n "$RANLIB"; then archive_cmds="$archive_cmds~\$RANLIB \$lib" postinstall_cmds='$RANLIB $lib' fi ;; aix[[4-9]]*) if test "$host_cpu" != ia64 && test "$aix_use_runtimelinking" = no ; then test "$enable_shared" = yes && enable_static=no fi ;; esac AC_MSG_RESULT([$enable_shared]) AC_MSG_CHECKING([whether to build static libraries]) # Make sure either enable_shared or enable_static is yes. test "$enable_shared" = yes || enable_static=yes AC_MSG_RESULT([$enable_static]) _LT_TAGVAR(GCC, $1)="$ac_cv_fc_compiler_gnu" _LT_TAGVAR(LD, $1)="$LD" ## CAVEAT EMPTOR: ## There is no encapsulation within the following macros, do not change ## the running order or otherwise move them around unless you know exactly ## what you are doing... _LT_SYS_HIDDEN_LIBDEPS($1) _LT_COMPILER_PIC($1) _LT_COMPILER_C_O($1) _LT_COMPILER_FILE_LOCKS($1) _LT_LINKER_SHLIBS($1) _LT_SYS_DYNAMIC_LINKER($1) _LT_LINKER_HARDCODE_LIBPATH($1) _LT_CONFIG($1) fi # test -n "$compiler" GCC=$lt_save_GCC CC=$lt_save_CC CFLAGS=$lt_save_CFLAGS fi # test "$_lt_disable_FC" != yes AC_LANG_POP ])# _LT_LANG_FC_CONFIG # _LT_LANG_GCJ_CONFIG([TAG]) # -------------------------- # Ensure that the configuration variables for the GNU Java Compiler compiler # are suitably defined. These variables are subsequently used by _LT_CONFIG # to write the compiler configuration to `libtool'. m4_defun([_LT_LANG_GCJ_CONFIG], [AC_REQUIRE([LT_PROG_GCJ])dnl AC_LANG_SAVE # Source file extension for Java test sources. ac_ext=java # Object file extension for compiled Java test sources. objext=o _LT_TAGVAR(objext, $1)=$objext # Code to be used in simple compile tests lt_simple_compile_test_code="class foo {}" # Code to be used in simple link tests lt_simple_link_test_code='public class conftest { public static void main(String[[]] argv) {}; }' # ltmain only uses $CC for tagged configurations so make sure $CC is set. _LT_TAG_COMPILER # save warnings/boilerplate of simple test code _LT_COMPILER_BOILERPLATE _LT_LINKER_BOILERPLATE # Allow CC to be a program name with arguments. lt_save_CC=$CC lt_save_CFLAGS=$CFLAGS lt_save_GCC=$GCC GCC=yes CC=${GCJ-"gcj"} CFLAGS=$GCJFLAGS compiler=$CC _LT_TAGVAR(compiler, $1)=$CC _LT_TAGVAR(LD, $1)="$LD" _LT_CC_BASENAME([$compiler]) # GCJ did not exist at the time GCC didn't implicitly link libc in. _LT_TAGVAR(archive_cmds_need_lc, $1)=no _LT_TAGVAR(old_archive_cmds, $1)=$old_archive_cmds _LT_TAGVAR(reload_flag, $1)=$reload_flag _LT_TAGVAR(reload_cmds, $1)=$reload_cmds ## CAVEAT EMPTOR: ## There is no encapsulation within the following macros, do not change ## the running order or otherwise move them around unless you know exactly ## what you are doing... if test -n "$compiler"; then _LT_COMPILER_NO_RTTI($1) _LT_COMPILER_PIC($1) _LT_COMPILER_C_O($1) _LT_COMPILER_FILE_LOCKS($1) _LT_LINKER_SHLIBS($1) _LT_LINKER_HARDCODE_LIBPATH($1) _LT_CONFIG($1) fi AC_LANG_RESTORE GCC=$lt_save_GCC CC=$lt_save_CC CFLAGS=$lt_save_CFLAGS ])# _LT_LANG_GCJ_CONFIG # _LT_LANG_GO_CONFIG([TAG]) # -------------------------- # Ensure that the configuration variables for the GNU Go compiler # are suitably defined. These variables are subsequently used by _LT_CONFIG # to write the compiler configuration to `libtool'. m4_defun([_LT_LANG_GO_CONFIG], [AC_REQUIRE([LT_PROG_GO])dnl AC_LANG_SAVE # Source file extension for Go test sources. ac_ext=go # Object file extension for compiled Go test sources. objext=o _LT_TAGVAR(objext, $1)=$objext # Code to be used in simple compile tests lt_simple_compile_test_code="package main; func main() { }" # Code to be used in simple link tests lt_simple_link_test_code='package main; func main() { }' # ltmain only uses $CC for tagged configurations so make sure $CC is set. _LT_TAG_COMPILER # save warnings/boilerplate of simple test code _LT_COMPILER_BOILERPLATE _LT_LINKER_BOILERPLATE # Allow CC to be a program name with arguments. lt_save_CC=$CC lt_save_CFLAGS=$CFLAGS lt_save_GCC=$GCC GCC=yes CC=${GOC-"gccgo"} CFLAGS=$GOFLAGS compiler=$CC _LT_TAGVAR(compiler, $1)=$CC _LT_TAGVAR(LD, $1)="$LD" _LT_CC_BASENAME([$compiler]) # Go did not exist at the time GCC didn't implicitly link libc in. _LT_TAGVAR(archive_cmds_need_lc, $1)=no _LT_TAGVAR(old_archive_cmds, $1)=$old_archive_cmds _LT_TAGVAR(reload_flag, $1)=$reload_flag _LT_TAGVAR(reload_cmds, $1)=$reload_cmds ## CAVEAT EMPTOR: ## There is no encapsulation within the following macros, do not change ## the running order or otherwise move them around unless you know exactly ## what you are doing... if test -n "$compiler"; then _LT_COMPILER_NO_RTTI($1) _LT_COMPILER_PIC($1) _LT_COMPILER_C_O($1) _LT_COMPILER_FILE_LOCKS($1) _LT_LINKER_SHLIBS($1) _LT_LINKER_HARDCODE_LIBPATH($1) _LT_CONFIG($1) fi AC_LANG_RESTORE GCC=$lt_save_GCC CC=$lt_save_CC CFLAGS=$lt_save_CFLAGS ])# _LT_LANG_GO_CONFIG # _LT_LANG_RC_CONFIG([TAG]) # ------------------------- # Ensure that the configuration variables for the Windows resource compiler # are suitably defined. These variables are subsequently used by _LT_CONFIG # to write the compiler configuration to `libtool'. m4_defun([_LT_LANG_RC_CONFIG], [AC_REQUIRE([LT_PROG_RC])dnl AC_LANG_SAVE # Source file extension for RC test sources. ac_ext=rc # Object file extension for compiled RC test sources. objext=o _LT_TAGVAR(objext, $1)=$objext # Code to be used in simple compile tests lt_simple_compile_test_code='sample MENU { MENUITEM "&Soup", 100, CHECKED }' # Code to be used in simple link tests lt_simple_link_test_code="$lt_simple_compile_test_code" # ltmain only uses $CC for tagged configurations so make sure $CC is set. _LT_TAG_COMPILER # save warnings/boilerplate of simple test code _LT_COMPILER_BOILERPLATE _LT_LINKER_BOILERPLATE # Allow CC to be a program name with arguments. lt_save_CC="$CC" lt_save_CFLAGS=$CFLAGS lt_save_GCC=$GCC GCC= CC=${RC-"windres"} CFLAGS= compiler=$CC _LT_TAGVAR(compiler, $1)=$CC _LT_CC_BASENAME([$compiler]) _LT_TAGVAR(lt_cv_prog_compiler_c_o, $1)=yes if test -n "$compiler"; then : _LT_CONFIG($1) fi GCC=$lt_save_GCC AC_LANG_RESTORE CC=$lt_save_CC CFLAGS=$lt_save_CFLAGS ])# _LT_LANG_RC_CONFIG # LT_PROG_GCJ # ----------- AC_DEFUN([LT_PROG_GCJ], [m4_ifdef([AC_PROG_GCJ], [AC_PROG_GCJ], [m4_ifdef([A][M_PROG_GCJ], [A][M_PROG_GCJ], [AC_CHECK_TOOL(GCJ, gcj,) test "x${GCJFLAGS+set}" = xset || GCJFLAGS="-g -O2" AC_SUBST(GCJFLAGS)])])[]dnl ]) # Old name: AU_ALIAS([LT_AC_PROG_GCJ], [LT_PROG_GCJ]) dnl aclocal-1.4 backwards compatibility: dnl AC_DEFUN([LT_AC_PROG_GCJ], []) # LT_PROG_GO # ---------- AC_DEFUN([LT_PROG_GO], [AC_CHECK_TOOL(GOC, gccgo,) ]) # LT_PROG_RC # ---------- AC_DEFUN([LT_PROG_RC], [AC_CHECK_TOOL(RC, windres,) ]) # Old name: AU_ALIAS([LT_AC_PROG_RC], [LT_PROG_RC]) dnl aclocal-1.4 backwards compatibility: dnl AC_DEFUN([LT_AC_PROG_RC], []) # _LT_DECL_EGREP # -------------- # If we don't have a new enough Autoconf to choose the best grep # available, choose the one first in the user's PATH. m4_defun([_LT_DECL_EGREP], [AC_REQUIRE([AC_PROG_EGREP])dnl AC_REQUIRE([AC_PROG_FGREP])dnl test -z "$GREP" && GREP=grep _LT_DECL([], [GREP], [1], [A grep program that handles long lines]) _LT_DECL([], [EGREP], [1], [An ERE matcher]) _LT_DECL([], [FGREP], [1], [A literal string matcher]) dnl Non-bleeding-edge autoconf doesn't subst GREP, so do it here too AC_SUBST([GREP]) ]) # _LT_DECL_OBJDUMP # -------------- # If we don't have a new enough Autoconf to choose the best objdump # available, choose the one first in the user's PATH. m4_defun([_LT_DECL_OBJDUMP], [AC_CHECK_TOOL(OBJDUMP, objdump, false) test -z "$OBJDUMP" && OBJDUMP=objdump _LT_DECL([], [OBJDUMP], [1], [An object symbol dumper]) AC_SUBST([OBJDUMP]) ]) # _LT_DECL_DLLTOOL # ---------------- # Ensure DLLTOOL variable is set. m4_defun([_LT_DECL_DLLTOOL], [AC_CHECK_TOOL(DLLTOOL, dlltool, false) test -z "$DLLTOOL" && DLLTOOL=dlltool _LT_DECL([], [DLLTOOL], [1], [DLL creation program]) AC_SUBST([DLLTOOL]) ]) # _LT_DECL_SED # ------------ # Check for a fully-functional sed program, that truncates # as few characters as possible. Prefer GNU sed if found. m4_defun([_LT_DECL_SED], [AC_PROG_SED test -z "$SED" && SED=sed Xsed="$SED -e 1s/^X//" _LT_DECL([], [SED], [1], [A sed program that does not truncate output]) _LT_DECL([], [Xsed], ["\$SED -e 1s/^X//"], [Sed that helps us avoid accidentally triggering echo(1) options like -n]) ])# _LT_DECL_SED m4_ifndef([AC_PROG_SED], [ ############################################################ # NOTE: This macro has been submitted for inclusion into # # GNU Autoconf as AC_PROG_SED. When it is available in # # a released version of Autoconf we should remove this # # macro and use it instead. # ############################################################ m4_defun([AC_PROG_SED], [AC_MSG_CHECKING([for a sed that does not truncate output]) AC_CACHE_VAL(lt_cv_path_SED, [# Loop through the user's path and test for sed and gsed. # Then use that list of sed's as ones to test for truncation. as_save_IFS=$IFS; IFS=$PATH_SEPARATOR for as_dir in $PATH do IFS=$as_save_IFS test -z "$as_dir" && as_dir=. for lt_ac_prog in sed gsed; do for ac_exec_ext in '' $ac_executable_extensions; do if $as_executable_p "$as_dir/$lt_ac_prog$ac_exec_ext"; then lt_ac_sed_list="$lt_ac_sed_list $as_dir/$lt_ac_prog$ac_exec_ext" fi done done done IFS=$as_save_IFS lt_ac_max=0 lt_ac_count=0 # Add /usr/xpg4/bin/sed as it is typically found on Solaris # along with /bin/sed that truncates output. for lt_ac_sed in $lt_ac_sed_list /usr/xpg4/bin/sed; do test ! -f $lt_ac_sed && continue cat /dev/null > conftest.in lt_ac_count=0 echo $ECHO_N "0123456789$ECHO_C" >conftest.in # Check for GNU sed and select it if it is found. if "$lt_ac_sed" --version 2>&1 < /dev/null | grep 'GNU' > /dev/null; then lt_cv_path_SED=$lt_ac_sed break fi while true; do cat conftest.in conftest.in >conftest.tmp mv conftest.tmp conftest.in cp conftest.in conftest.nl echo >>conftest.nl $lt_ac_sed -e 's/a$//' < conftest.nl >conftest.out || break cmp -s conftest.out conftest.nl || break # 10000 chars as input seems more than enough test $lt_ac_count -gt 10 && break lt_ac_count=`expr $lt_ac_count + 1` if test $lt_ac_count -gt $lt_ac_max; then lt_ac_max=$lt_ac_count lt_cv_path_SED=$lt_ac_sed fi done done ]) SED=$lt_cv_path_SED AC_SUBST([SED]) AC_MSG_RESULT([$SED]) ])#AC_PROG_SED ])#m4_ifndef # Old name: AU_ALIAS([LT_AC_PROG_SED], [AC_PROG_SED]) dnl aclocal-1.4 backwards compatibility: dnl AC_DEFUN([LT_AC_PROG_SED], []) # _LT_CHECK_SHELL_FEATURES # ------------------------ # Find out whether the shell is Bourne or XSI compatible, # or has some other useful features. m4_defun([_LT_CHECK_SHELL_FEATURES], [AC_MSG_CHECKING([whether the shell understands some XSI constructs]) # Try some XSI features xsi_shell=no ( _lt_dummy="a/b/c" test "${_lt_dummy##*/},${_lt_dummy%/*},${_lt_dummy#??}"${_lt_dummy%"$_lt_dummy"}, \ = c,a/b,b/c, \ && eval 'test $(( 1 + 1 )) -eq 2 \ && test "${#_lt_dummy}" -eq 5' ) >/dev/null 2>&1 \ && xsi_shell=yes AC_MSG_RESULT([$xsi_shell]) _LT_CONFIG_LIBTOOL_INIT([xsi_shell='$xsi_shell']) AC_MSG_CHECKING([whether the shell understands "+="]) lt_shell_append=no ( foo=bar; set foo baz; eval "$[1]+=\$[2]" && test "$foo" = barbaz ) \ >/dev/null 2>&1 \ && lt_shell_append=yes AC_MSG_RESULT([$lt_shell_append]) _LT_CONFIG_LIBTOOL_INIT([lt_shell_append='$lt_shell_append']) if ( (MAIL=60; unset MAIL) || exit) >/dev/null 2>&1; then lt_unset=unset else lt_unset=false fi _LT_DECL([], [lt_unset], [0], [whether the shell understands "unset"])dnl # test EBCDIC or ASCII case `echo X|tr X '\101'` in A) # ASCII based system # \n is not interpreted correctly by Solaris 8 /usr/ucb/tr lt_SP2NL='tr \040 \012' lt_NL2SP='tr \015\012 \040\040' ;; *) # EBCDIC based system lt_SP2NL='tr \100 \n' lt_NL2SP='tr \r\n \100\100' ;; esac _LT_DECL([SP2NL], [lt_SP2NL], [1], [turn spaces into newlines])dnl _LT_DECL([NL2SP], [lt_NL2SP], [1], [turn newlines into spaces])dnl ])# _LT_CHECK_SHELL_FEATURES # _LT_PROG_FUNCTION_REPLACE (FUNCNAME, REPLACEMENT-BODY) # ------------------------------------------------------ # In `$cfgfile', look for function FUNCNAME delimited by `^FUNCNAME ()$' and # '^} FUNCNAME ', and replace its body with REPLACEMENT-BODY. m4_defun([_LT_PROG_FUNCTION_REPLACE], [dnl { sed -e '/^$1 ()$/,/^} # $1 /c\ $1 ()\ {\ m4_bpatsubsts([$2], [$], [\\], [^\([ ]\)], [\\\1]) } # Extended-shell $1 implementation' "$cfgfile" > $cfgfile.tmp \ && mv -f "$cfgfile.tmp" "$cfgfile" \ || (rm -f "$cfgfile" && cp "$cfgfile.tmp" "$cfgfile" && rm -f "$cfgfile.tmp") test 0 -eq $? || _lt_function_replace_fail=: ]) # _LT_PROG_REPLACE_SHELLFNS # ------------------------- # Replace existing portable implementations of several shell functions with # equivalent extended shell implementations where those features are available.. m4_defun([_LT_PROG_REPLACE_SHELLFNS], [if test x"$xsi_shell" = xyes; then _LT_PROG_FUNCTION_REPLACE([func_dirname], [dnl case ${1} in */*) func_dirname_result="${1%/*}${2}" ;; * ) func_dirname_result="${3}" ;; esac]) _LT_PROG_FUNCTION_REPLACE([func_basename], [dnl func_basename_result="${1##*/}"]) _LT_PROG_FUNCTION_REPLACE([func_dirname_and_basename], [dnl case ${1} in */*) func_dirname_result="${1%/*}${2}" ;; * ) func_dirname_result="${3}" ;; esac func_basename_result="${1##*/}"]) _LT_PROG_FUNCTION_REPLACE([func_stripname], [dnl # pdksh 5.2.14 does not do ${X%$Y} correctly if both X and Y are # positional parameters, so assign one to ordinary parameter first. func_stripname_result=${3} func_stripname_result=${func_stripname_result#"${1}"} func_stripname_result=${func_stripname_result%"${2}"}]) _LT_PROG_FUNCTION_REPLACE([func_split_long_opt], [dnl func_split_long_opt_name=${1%%=*} func_split_long_opt_arg=${1#*=}]) _LT_PROG_FUNCTION_REPLACE([func_split_short_opt], [dnl func_split_short_opt_arg=${1#??} func_split_short_opt_name=${1%"$func_split_short_opt_arg"}]) _LT_PROG_FUNCTION_REPLACE([func_lo2o], [dnl case ${1} in *.lo) func_lo2o_result=${1%.lo}.${objext} ;; *) func_lo2o_result=${1} ;; esac]) _LT_PROG_FUNCTION_REPLACE([func_xform], [ func_xform_result=${1%.*}.lo]) _LT_PROG_FUNCTION_REPLACE([func_arith], [ func_arith_result=$(( $[*] ))]) _LT_PROG_FUNCTION_REPLACE([func_len], [ func_len_result=${#1}]) fi if test x"$lt_shell_append" = xyes; then _LT_PROG_FUNCTION_REPLACE([func_append], [ eval "${1}+=\\${2}"]) _LT_PROG_FUNCTION_REPLACE([func_append_quoted], [dnl func_quote_for_eval "${2}" dnl m4 expansion turns \\\\ into \\, and then the shell eval turns that into \ eval "${1}+=\\\\ \\$func_quote_for_eval_result"]) # Save a `func_append' function call where possible by direct use of '+=' sed -e 's%func_append \([[a-zA-Z_]]\{1,\}\) "%\1+="%g' $cfgfile > $cfgfile.tmp \ && mv -f "$cfgfile.tmp" "$cfgfile" \ || (rm -f "$cfgfile" && cp "$cfgfile.tmp" "$cfgfile" && rm -f "$cfgfile.tmp") test 0 -eq $? || _lt_function_replace_fail=: else # Save a `func_append' function call even when '+=' is not available sed -e 's%func_append \([[a-zA-Z_]]\{1,\}\) "%\1="$\1%g' $cfgfile > $cfgfile.tmp \ && mv -f "$cfgfile.tmp" "$cfgfile" \ || (rm -f "$cfgfile" && cp "$cfgfile.tmp" "$cfgfile" && rm -f "$cfgfile.tmp") test 0 -eq $? || _lt_function_replace_fail=: fi if test x"$_lt_function_replace_fail" = x":"; then AC_MSG_WARN([Unable to substitute extended shell functions in $ofile]) fi ]) # _LT_PATH_CONVERSION_FUNCTIONS # ----------------------------- # Determine which file name conversion functions should be used by # func_to_host_file (and, implicitly, by func_to_host_path). These are needed # for certain cross-compile configurations and native mingw. m4_defun([_LT_PATH_CONVERSION_FUNCTIONS], [AC_REQUIRE([AC_CANONICAL_HOST])dnl AC_REQUIRE([AC_CANONICAL_BUILD])dnl AC_MSG_CHECKING([how to convert $build file names to $host format]) AC_CACHE_VAL(lt_cv_to_host_file_cmd, [case $host in *-*-mingw* ) case $build in *-*-mingw* ) # actually msys lt_cv_to_host_file_cmd=func_convert_file_msys_to_w32 ;; *-*-cygwin* ) lt_cv_to_host_file_cmd=func_convert_file_cygwin_to_w32 ;; * ) # otherwise, assume *nix lt_cv_to_host_file_cmd=func_convert_file_nix_to_w32 ;; esac ;; *-*-cygwin* ) case $build in *-*-mingw* ) # actually msys lt_cv_to_host_file_cmd=func_convert_file_msys_to_cygwin ;; *-*-cygwin* ) lt_cv_to_host_file_cmd=func_convert_file_noop ;; * ) # otherwise, assume *nix lt_cv_to_host_file_cmd=func_convert_file_nix_to_cygwin ;; esac ;; * ) # unhandled hosts (and "normal" native builds) lt_cv_to_host_file_cmd=func_convert_file_noop ;; esac ]) to_host_file_cmd=$lt_cv_to_host_file_cmd AC_MSG_RESULT([$lt_cv_to_host_file_cmd]) _LT_DECL([to_host_file_cmd], [lt_cv_to_host_file_cmd], [0], [convert $build file names to $host format])dnl AC_MSG_CHECKING([how to convert $build file names to toolchain format]) AC_CACHE_VAL(lt_cv_to_tool_file_cmd, [#assume ordinary cross tools, or native build. lt_cv_to_tool_file_cmd=func_convert_file_noop case $host in *-*-mingw* ) case $build in *-*-mingw* ) # actually msys lt_cv_to_tool_file_cmd=func_convert_file_msys_to_w32 ;; esac ;; esac ]) to_tool_file_cmd=$lt_cv_to_tool_file_cmd AC_MSG_RESULT([$lt_cv_to_tool_file_cmd]) _LT_DECL([to_tool_file_cmd], [lt_cv_to_tool_file_cmd], [0], [convert $build files to toolchain format])dnl ])# _LT_PATH_CONVERSION_FUNCTIONS apache-couchdb-1.5.0/m4/ltversion.m40000644000175000001440000000126212230722216014065 00000000000000# ltversion.m4 -- version numbers -*- Autoconf -*- # # Copyright (C) 2004 Free Software Foundation, Inc. # Written by Scott James Remnant, 2004 # # This file is free software; the Free Software Foundation gives # unlimited permission to copy and/or distribute it, with or without # modifications, as long as this notice is preserved. # @configure_input@ # serial 3337 ltversion.m4 # This file is part of GNU Libtool m4_define([LT_PACKAGE_VERSION], [2.4.2]) m4_define([LT_PACKAGE_REVISION], [1.3337]) AC_DEFUN([LTVERSION_VERSION], [macro_version='2.4.2' macro_revision='1.3337' _LT_DECL(, macro_version, 0, [Which release of libtool.m4 was used?]) _LT_DECL(, macro_revision, 0) ]) apache-couchdb-1.5.0/m4/lt~obsolete.m40000644000175000001440000001375612230722216014425 00000000000000# lt~obsolete.m4 -- aclocal satisfying obsolete definitions. -*-Autoconf-*- # # Copyright (C) 2004, 2005, 2007, 2009 Free Software Foundation, Inc. # Written by Scott James Remnant, 2004. # # This file is free software; the Free Software Foundation gives # unlimited permission to copy and/or distribute it, with or without # modifications, as long as this notice is preserved. # serial 5 lt~obsolete.m4 # These exist entirely to fool aclocal when bootstrapping libtool. # # In the past libtool.m4 has provided macros via AC_DEFUN (or AU_DEFUN) # which have later been changed to m4_define as they aren't part of the # exported API, or moved to Autoconf or Automake where they belong. # # The trouble is, aclocal is a bit thick. It'll see the old AC_DEFUN # in /usr/share/aclocal/libtool.m4 and remember it, then when it sees us # using a macro with the same name in our local m4/libtool.m4 it'll # pull the old libtool.m4 in (it doesn't see our shiny new m4_define # and doesn't know about Autoconf macros at all.) # # So we provide this file, which has a silly filename so it's always # included after everything else. This provides aclocal with the # AC_DEFUNs it wants, but when m4 processes it, it doesn't do anything # because those macros already exist, or will be overwritten later. # We use AC_DEFUN over AU_DEFUN for compatibility with aclocal-1.6. # # Anytime we withdraw an AC_DEFUN or AU_DEFUN, remember to add it here. # Yes, that means every name once taken will need to remain here until # we give up compatibility with versions before 1.7, at which point # we need to keep only those names which we still refer to. # This is to help aclocal find these macros, as it can't see m4_define. AC_DEFUN([LTOBSOLETE_VERSION], [m4_if([1])]) m4_ifndef([AC_LIBTOOL_LINKER_OPTION], [AC_DEFUN([AC_LIBTOOL_LINKER_OPTION])]) m4_ifndef([AC_PROG_EGREP], [AC_DEFUN([AC_PROG_EGREP])]) m4_ifndef([_LT_AC_PROG_ECHO_BACKSLASH], [AC_DEFUN([_LT_AC_PROG_ECHO_BACKSLASH])]) m4_ifndef([_LT_AC_SHELL_INIT], [AC_DEFUN([_LT_AC_SHELL_INIT])]) m4_ifndef([_LT_AC_SYS_LIBPATH_AIX], [AC_DEFUN([_LT_AC_SYS_LIBPATH_AIX])]) m4_ifndef([_LT_PROG_LTMAIN], [AC_DEFUN([_LT_PROG_LTMAIN])]) m4_ifndef([_LT_AC_TAGVAR], [AC_DEFUN([_LT_AC_TAGVAR])]) m4_ifndef([AC_LTDL_ENABLE_INSTALL], [AC_DEFUN([AC_LTDL_ENABLE_INSTALL])]) m4_ifndef([AC_LTDL_PREOPEN], [AC_DEFUN([AC_LTDL_PREOPEN])]) m4_ifndef([_LT_AC_SYS_COMPILER], [AC_DEFUN([_LT_AC_SYS_COMPILER])]) m4_ifndef([_LT_AC_LOCK], [AC_DEFUN([_LT_AC_LOCK])]) m4_ifndef([AC_LIBTOOL_SYS_OLD_ARCHIVE], [AC_DEFUN([AC_LIBTOOL_SYS_OLD_ARCHIVE])]) m4_ifndef([_LT_AC_TRY_DLOPEN_SELF], [AC_DEFUN([_LT_AC_TRY_DLOPEN_SELF])]) m4_ifndef([AC_LIBTOOL_PROG_CC_C_O], [AC_DEFUN([AC_LIBTOOL_PROG_CC_C_O])]) m4_ifndef([AC_LIBTOOL_SYS_HARD_LINK_LOCKS], [AC_DEFUN([AC_LIBTOOL_SYS_HARD_LINK_LOCKS])]) m4_ifndef([AC_LIBTOOL_OBJDIR], [AC_DEFUN([AC_LIBTOOL_OBJDIR])]) m4_ifndef([AC_LTDL_OBJDIR], [AC_DEFUN([AC_LTDL_OBJDIR])]) m4_ifndef([AC_LIBTOOL_PROG_LD_HARDCODE_LIBPATH], [AC_DEFUN([AC_LIBTOOL_PROG_LD_HARDCODE_LIBPATH])]) m4_ifndef([AC_LIBTOOL_SYS_LIB_STRIP], [AC_DEFUN([AC_LIBTOOL_SYS_LIB_STRIP])]) m4_ifndef([AC_PATH_MAGIC], [AC_DEFUN([AC_PATH_MAGIC])]) m4_ifndef([AC_PROG_LD_GNU], [AC_DEFUN([AC_PROG_LD_GNU])]) m4_ifndef([AC_PROG_LD_RELOAD_FLAG], [AC_DEFUN([AC_PROG_LD_RELOAD_FLAG])]) m4_ifndef([AC_DEPLIBS_CHECK_METHOD], [AC_DEFUN([AC_DEPLIBS_CHECK_METHOD])]) m4_ifndef([AC_LIBTOOL_PROG_COMPILER_NO_RTTI], [AC_DEFUN([AC_LIBTOOL_PROG_COMPILER_NO_RTTI])]) m4_ifndef([AC_LIBTOOL_SYS_GLOBAL_SYMBOL_PIPE], [AC_DEFUN([AC_LIBTOOL_SYS_GLOBAL_SYMBOL_PIPE])]) m4_ifndef([AC_LIBTOOL_PROG_COMPILER_PIC], [AC_DEFUN([AC_LIBTOOL_PROG_COMPILER_PIC])]) m4_ifndef([AC_LIBTOOL_PROG_LD_SHLIBS], [AC_DEFUN([AC_LIBTOOL_PROG_LD_SHLIBS])]) m4_ifndef([AC_LIBTOOL_POSTDEP_PREDEP], [AC_DEFUN([AC_LIBTOOL_POSTDEP_PREDEP])]) m4_ifndef([LT_AC_PROG_EGREP], [AC_DEFUN([LT_AC_PROG_EGREP])]) m4_ifndef([LT_AC_PROG_SED], [AC_DEFUN([LT_AC_PROG_SED])]) m4_ifndef([_LT_CC_BASENAME], [AC_DEFUN([_LT_CC_BASENAME])]) m4_ifndef([_LT_COMPILER_BOILERPLATE], [AC_DEFUN([_LT_COMPILER_BOILERPLATE])]) m4_ifndef([_LT_LINKER_BOILERPLATE], [AC_DEFUN([_LT_LINKER_BOILERPLATE])]) m4_ifndef([_AC_PROG_LIBTOOL], [AC_DEFUN([_AC_PROG_LIBTOOL])]) m4_ifndef([AC_LIBTOOL_SETUP], [AC_DEFUN([AC_LIBTOOL_SETUP])]) m4_ifndef([_LT_AC_CHECK_DLFCN], [AC_DEFUN([_LT_AC_CHECK_DLFCN])]) m4_ifndef([AC_LIBTOOL_SYS_DYNAMIC_LINKER], [AC_DEFUN([AC_LIBTOOL_SYS_DYNAMIC_LINKER])]) m4_ifndef([_LT_AC_TAGCONFIG], [AC_DEFUN([_LT_AC_TAGCONFIG])]) m4_ifndef([AC_DISABLE_FAST_INSTALL], [AC_DEFUN([AC_DISABLE_FAST_INSTALL])]) m4_ifndef([_LT_AC_LANG_CXX], [AC_DEFUN([_LT_AC_LANG_CXX])]) m4_ifndef([_LT_AC_LANG_F77], [AC_DEFUN([_LT_AC_LANG_F77])]) m4_ifndef([_LT_AC_LANG_GCJ], [AC_DEFUN([_LT_AC_LANG_GCJ])]) m4_ifndef([AC_LIBTOOL_LANG_C_CONFIG], [AC_DEFUN([AC_LIBTOOL_LANG_C_CONFIG])]) m4_ifndef([_LT_AC_LANG_C_CONFIG], [AC_DEFUN([_LT_AC_LANG_C_CONFIG])]) m4_ifndef([AC_LIBTOOL_LANG_CXX_CONFIG], [AC_DEFUN([AC_LIBTOOL_LANG_CXX_CONFIG])]) m4_ifndef([_LT_AC_LANG_CXX_CONFIG], [AC_DEFUN([_LT_AC_LANG_CXX_CONFIG])]) m4_ifndef([AC_LIBTOOL_LANG_F77_CONFIG], [AC_DEFUN([AC_LIBTOOL_LANG_F77_CONFIG])]) m4_ifndef([_LT_AC_LANG_F77_CONFIG], [AC_DEFUN([_LT_AC_LANG_F77_CONFIG])]) m4_ifndef([AC_LIBTOOL_LANG_GCJ_CONFIG], [AC_DEFUN([AC_LIBTOOL_LANG_GCJ_CONFIG])]) m4_ifndef([_LT_AC_LANG_GCJ_CONFIG], [AC_DEFUN([_LT_AC_LANG_GCJ_CONFIG])]) m4_ifndef([AC_LIBTOOL_LANG_RC_CONFIG], [AC_DEFUN([AC_LIBTOOL_LANG_RC_CONFIG])]) m4_ifndef([_LT_AC_LANG_RC_CONFIG], [AC_DEFUN([_LT_AC_LANG_RC_CONFIG])]) m4_ifndef([AC_LIBTOOL_CONFIG], [AC_DEFUN([AC_LIBTOOL_CONFIG])]) m4_ifndef([_LT_AC_FILE_LTDLL_C], [AC_DEFUN([_LT_AC_FILE_LTDLL_C])]) m4_ifndef([_LT_REQUIRED_DARWIN_CHECKS], [AC_DEFUN([_LT_REQUIRED_DARWIN_CHECKS])]) m4_ifndef([_LT_AC_PROG_CXXCPP], [AC_DEFUN([_LT_AC_PROG_CXXCPP])]) m4_ifndef([_LT_PREPARE_SED_QUOTE_VARS], [AC_DEFUN([_LT_PREPARE_SED_QUOTE_VARS])]) m4_ifndef([_LT_PROG_ECHO_BACKSLASH], [AC_DEFUN([_LT_PROG_ECHO_BACKSLASH])]) m4_ifndef([_LT_PROG_F77], [AC_DEFUN([_LT_PROG_F77])]) m4_ifndef([_LT_PROG_FC], [AC_DEFUN([_LT_PROG_FC])]) m4_ifndef([_LT_PROG_CXX], [AC_DEFUN([_LT_PROG_CXX])]) apache-couchdb-1.5.0/m4/ltoptions.m40000644000175000001440000003007312230722216014075 00000000000000# Helper functions for option handling. -*- Autoconf -*- # # Copyright (C) 2004, 2005, 2007, 2008, 2009 Free Software Foundation, # Inc. # Written by Gary V. Vaughan, 2004 # # This file is free software; the Free Software Foundation gives # unlimited permission to copy and/or distribute it, with or without # modifications, as long as this notice is preserved. # serial 7 ltoptions.m4 # This is to help aclocal find these macros, as it can't see m4_define. AC_DEFUN([LTOPTIONS_VERSION], [m4_if([1])]) # _LT_MANGLE_OPTION(MACRO-NAME, OPTION-NAME) # ------------------------------------------ m4_define([_LT_MANGLE_OPTION], [[_LT_OPTION_]m4_bpatsubst($1__$2, [[^a-zA-Z0-9_]], [_])]) # _LT_SET_OPTION(MACRO-NAME, OPTION-NAME) # --------------------------------------- # Set option OPTION-NAME for macro MACRO-NAME, and if there is a # matching handler defined, dispatch to it. Other OPTION-NAMEs are # saved as a flag. m4_define([_LT_SET_OPTION], [m4_define(_LT_MANGLE_OPTION([$1], [$2]))dnl m4_ifdef(_LT_MANGLE_DEFUN([$1], [$2]), _LT_MANGLE_DEFUN([$1], [$2]), [m4_warning([Unknown $1 option `$2'])])[]dnl ]) # _LT_IF_OPTION(MACRO-NAME, OPTION-NAME, IF-SET, [IF-NOT-SET]) # ------------------------------------------------------------ # Execute IF-SET if OPTION is set, IF-NOT-SET otherwise. m4_define([_LT_IF_OPTION], [m4_ifdef(_LT_MANGLE_OPTION([$1], [$2]), [$3], [$4])]) # _LT_UNLESS_OPTIONS(MACRO-NAME, OPTION-LIST, IF-NOT-SET) # ------------------------------------------------------- # Execute IF-NOT-SET unless all options in OPTION-LIST for MACRO-NAME # are set. m4_define([_LT_UNLESS_OPTIONS], [m4_foreach([_LT_Option], m4_split(m4_normalize([$2])), [m4_ifdef(_LT_MANGLE_OPTION([$1], _LT_Option), [m4_define([$0_found])])])[]dnl m4_ifdef([$0_found], [m4_undefine([$0_found])], [$3 ])[]dnl ]) # _LT_SET_OPTIONS(MACRO-NAME, OPTION-LIST) # ---------------------------------------- # OPTION-LIST is a space-separated list of Libtool options associated # with MACRO-NAME. If any OPTION has a matching handler declared with # LT_OPTION_DEFINE, dispatch to that macro; otherwise complain about # the unknown option and exit. m4_defun([_LT_SET_OPTIONS], [# Set options m4_foreach([_LT_Option], m4_split(m4_normalize([$2])), [_LT_SET_OPTION([$1], _LT_Option)]) m4_if([$1],[LT_INIT],[ dnl dnl Simply set some default values (i.e off) if boolean options were not dnl specified: _LT_UNLESS_OPTIONS([LT_INIT], [dlopen], [enable_dlopen=no ]) _LT_UNLESS_OPTIONS([LT_INIT], [win32-dll], [enable_win32_dll=no ]) dnl dnl If no reference was made to various pairs of opposing options, then dnl we run the default mode handler for the pair. For example, if neither dnl `shared' nor `disable-shared' was passed, we enable building of shared dnl archives by default: _LT_UNLESS_OPTIONS([LT_INIT], [shared disable-shared], [_LT_ENABLE_SHARED]) _LT_UNLESS_OPTIONS([LT_INIT], [static disable-static], [_LT_ENABLE_STATIC]) _LT_UNLESS_OPTIONS([LT_INIT], [pic-only no-pic], [_LT_WITH_PIC]) _LT_UNLESS_OPTIONS([LT_INIT], [fast-install disable-fast-install], [_LT_ENABLE_FAST_INSTALL]) ]) ])# _LT_SET_OPTIONS ## --------------------------------- ## ## Macros to handle LT_INIT options. ## ## --------------------------------- ## # _LT_MANGLE_DEFUN(MACRO-NAME, OPTION-NAME) # ----------------------------------------- m4_define([_LT_MANGLE_DEFUN], [[_LT_OPTION_DEFUN_]m4_bpatsubst(m4_toupper([$1__$2]), [[^A-Z0-9_]], [_])]) # LT_OPTION_DEFINE(MACRO-NAME, OPTION-NAME, CODE) # ----------------------------------------------- m4_define([LT_OPTION_DEFINE], [m4_define(_LT_MANGLE_DEFUN([$1], [$2]), [$3])[]dnl ])# LT_OPTION_DEFINE # dlopen # ------ LT_OPTION_DEFINE([LT_INIT], [dlopen], [enable_dlopen=yes ]) AU_DEFUN([AC_LIBTOOL_DLOPEN], [_LT_SET_OPTION([LT_INIT], [dlopen]) AC_DIAGNOSE([obsolete], [$0: Remove this warning and the call to _LT_SET_OPTION when you put the `dlopen' option into LT_INIT's first parameter.]) ]) dnl aclocal-1.4 backwards compatibility: dnl AC_DEFUN([AC_LIBTOOL_DLOPEN], []) # win32-dll # --------- # Declare package support for building win32 dll's. LT_OPTION_DEFINE([LT_INIT], [win32-dll], [enable_win32_dll=yes case $host in *-*-cygwin* | *-*-mingw* | *-*-pw32* | *-*-cegcc*) AC_CHECK_TOOL(AS, as, false) AC_CHECK_TOOL(DLLTOOL, dlltool, false) AC_CHECK_TOOL(OBJDUMP, objdump, false) ;; esac test -z "$AS" && AS=as _LT_DECL([], [AS], [1], [Assembler program])dnl test -z "$DLLTOOL" && DLLTOOL=dlltool _LT_DECL([], [DLLTOOL], [1], [DLL creation program])dnl test -z "$OBJDUMP" && OBJDUMP=objdump _LT_DECL([], [OBJDUMP], [1], [Object dumper program])dnl ])# win32-dll AU_DEFUN([AC_LIBTOOL_WIN32_DLL], [AC_REQUIRE([AC_CANONICAL_HOST])dnl _LT_SET_OPTION([LT_INIT], [win32-dll]) AC_DIAGNOSE([obsolete], [$0: Remove this warning and the call to _LT_SET_OPTION when you put the `win32-dll' option into LT_INIT's first parameter.]) ]) dnl aclocal-1.4 backwards compatibility: dnl AC_DEFUN([AC_LIBTOOL_WIN32_DLL], []) # _LT_ENABLE_SHARED([DEFAULT]) # ---------------------------- # implement the --enable-shared flag, and supports the `shared' and # `disable-shared' LT_INIT options. # DEFAULT is either `yes' or `no'. If omitted, it defaults to `yes'. m4_define([_LT_ENABLE_SHARED], [m4_define([_LT_ENABLE_SHARED_DEFAULT], [m4_if($1, no, no, yes)])dnl AC_ARG_ENABLE([shared], [AS_HELP_STRING([--enable-shared@<:@=PKGS@:>@], [build shared libraries @<:@default=]_LT_ENABLE_SHARED_DEFAULT[@:>@])], [p=${PACKAGE-default} case $enableval in yes) enable_shared=yes ;; no) enable_shared=no ;; *) enable_shared=no # Look at the argument we got. We use all the common list separators. lt_save_ifs="$IFS"; IFS="${IFS}$PATH_SEPARATOR," for pkg in $enableval; do IFS="$lt_save_ifs" if test "X$pkg" = "X$p"; then enable_shared=yes fi done IFS="$lt_save_ifs" ;; esac], [enable_shared=]_LT_ENABLE_SHARED_DEFAULT) _LT_DECL([build_libtool_libs], [enable_shared], [0], [Whether or not to build shared libraries]) ])# _LT_ENABLE_SHARED LT_OPTION_DEFINE([LT_INIT], [shared], [_LT_ENABLE_SHARED([yes])]) LT_OPTION_DEFINE([LT_INIT], [disable-shared], [_LT_ENABLE_SHARED([no])]) # Old names: AC_DEFUN([AC_ENABLE_SHARED], [_LT_SET_OPTION([LT_INIT], m4_if([$1], [no], [disable-])[shared]) ]) AC_DEFUN([AC_DISABLE_SHARED], [_LT_SET_OPTION([LT_INIT], [disable-shared]) ]) AU_DEFUN([AM_ENABLE_SHARED], [AC_ENABLE_SHARED($@)]) AU_DEFUN([AM_DISABLE_SHARED], [AC_DISABLE_SHARED($@)]) dnl aclocal-1.4 backwards compatibility: dnl AC_DEFUN([AM_ENABLE_SHARED], []) dnl AC_DEFUN([AM_DISABLE_SHARED], []) # _LT_ENABLE_STATIC([DEFAULT]) # ---------------------------- # implement the --enable-static flag, and support the `static' and # `disable-static' LT_INIT options. # DEFAULT is either `yes' or `no'. If omitted, it defaults to `yes'. m4_define([_LT_ENABLE_STATIC], [m4_define([_LT_ENABLE_STATIC_DEFAULT], [m4_if($1, no, no, yes)])dnl AC_ARG_ENABLE([static], [AS_HELP_STRING([--enable-static@<:@=PKGS@:>@], [build static libraries @<:@default=]_LT_ENABLE_STATIC_DEFAULT[@:>@])], [p=${PACKAGE-default} case $enableval in yes) enable_static=yes ;; no) enable_static=no ;; *) enable_static=no # Look at the argument we got. We use all the common list separators. lt_save_ifs="$IFS"; IFS="${IFS}$PATH_SEPARATOR," for pkg in $enableval; do IFS="$lt_save_ifs" if test "X$pkg" = "X$p"; then enable_static=yes fi done IFS="$lt_save_ifs" ;; esac], [enable_static=]_LT_ENABLE_STATIC_DEFAULT) _LT_DECL([build_old_libs], [enable_static], [0], [Whether or not to build static libraries]) ])# _LT_ENABLE_STATIC LT_OPTION_DEFINE([LT_INIT], [static], [_LT_ENABLE_STATIC([yes])]) LT_OPTION_DEFINE([LT_INIT], [disable-static], [_LT_ENABLE_STATIC([no])]) # Old names: AC_DEFUN([AC_ENABLE_STATIC], [_LT_SET_OPTION([LT_INIT], m4_if([$1], [no], [disable-])[static]) ]) AC_DEFUN([AC_DISABLE_STATIC], [_LT_SET_OPTION([LT_INIT], [disable-static]) ]) AU_DEFUN([AM_ENABLE_STATIC], [AC_ENABLE_STATIC($@)]) AU_DEFUN([AM_DISABLE_STATIC], [AC_DISABLE_STATIC($@)]) dnl aclocal-1.4 backwards compatibility: dnl AC_DEFUN([AM_ENABLE_STATIC], []) dnl AC_DEFUN([AM_DISABLE_STATIC], []) # _LT_ENABLE_FAST_INSTALL([DEFAULT]) # ---------------------------------- # implement the --enable-fast-install flag, and support the `fast-install' # and `disable-fast-install' LT_INIT options. # DEFAULT is either `yes' or `no'. If omitted, it defaults to `yes'. m4_define([_LT_ENABLE_FAST_INSTALL], [m4_define([_LT_ENABLE_FAST_INSTALL_DEFAULT], [m4_if($1, no, no, yes)])dnl AC_ARG_ENABLE([fast-install], [AS_HELP_STRING([--enable-fast-install@<:@=PKGS@:>@], [optimize for fast installation @<:@default=]_LT_ENABLE_FAST_INSTALL_DEFAULT[@:>@])], [p=${PACKAGE-default} case $enableval in yes) enable_fast_install=yes ;; no) enable_fast_install=no ;; *) enable_fast_install=no # Look at the argument we got. We use all the common list separators. lt_save_ifs="$IFS"; IFS="${IFS}$PATH_SEPARATOR," for pkg in $enableval; do IFS="$lt_save_ifs" if test "X$pkg" = "X$p"; then enable_fast_install=yes fi done IFS="$lt_save_ifs" ;; esac], [enable_fast_install=]_LT_ENABLE_FAST_INSTALL_DEFAULT) _LT_DECL([fast_install], [enable_fast_install], [0], [Whether or not to optimize for fast installation])dnl ])# _LT_ENABLE_FAST_INSTALL LT_OPTION_DEFINE([LT_INIT], [fast-install], [_LT_ENABLE_FAST_INSTALL([yes])]) LT_OPTION_DEFINE([LT_INIT], [disable-fast-install], [_LT_ENABLE_FAST_INSTALL([no])]) # Old names: AU_DEFUN([AC_ENABLE_FAST_INSTALL], [_LT_SET_OPTION([LT_INIT], m4_if([$1], [no], [disable-])[fast-install]) AC_DIAGNOSE([obsolete], [$0: Remove this warning and the call to _LT_SET_OPTION when you put the `fast-install' option into LT_INIT's first parameter.]) ]) AU_DEFUN([AC_DISABLE_FAST_INSTALL], [_LT_SET_OPTION([LT_INIT], [disable-fast-install]) AC_DIAGNOSE([obsolete], [$0: Remove this warning and the call to _LT_SET_OPTION when you put the `disable-fast-install' option into LT_INIT's first parameter.]) ]) dnl aclocal-1.4 backwards compatibility: dnl AC_DEFUN([AC_ENABLE_FAST_INSTALL], []) dnl AC_DEFUN([AM_DISABLE_FAST_INSTALL], []) # _LT_WITH_PIC([MODE]) # -------------------- # implement the --with-pic flag, and support the `pic-only' and `no-pic' # LT_INIT options. # MODE is either `yes' or `no'. If omitted, it defaults to `both'. m4_define([_LT_WITH_PIC], [AC_ARG_WITH([pic], [AS_HELP_STRING([--with-pic@<:@=PKGS@:>@], [try to use only PIC/non-PIC objects @<:@default=use both@:>@])], [lt_p=${PACKAGE-default} case $withval in yes|no) pic_mode=$withval ;; *) pic_mode=default # Look at the argument we got. We use all the common list separators. lt_save_ifs="$IFS"; IFS="${IFS}$PATH_SEPARATOR," for lt_pkg in $withval; do IFS="$lt_save_ifs" if test "X$lt_pkg" = "X$lt_p"; then pic_mode=yes fi done IFS="$lt_save_ifs" ;; esac], [pic_mode=default]) test -z "$pic_mode" && pic_mode=m4_default([$1], [default]) _LT_DECL([], [pic_mode], [0], [What type of objects to build])dnl ])# _LT_WITH_PIC LT_OPTION_DEFINE([LT_INIT], [pic-only], [_LT_WITH_PIC([yes])]) LT_OPTION_DEFINE([LT_INIT], [no-pic], [_LT_WITH_PIC([no])]) # Old name: AU_DEFUN([AC_LIBTOOL_PICMODE], [_LT_SET_OPTION([LT_INIT], [pic-only]) AC_DIAGNOSE([obsolete], [$0: Remove this warning and the call to _LT_SET_OPTION when you put the `pic-only' option into LT_INIT's first parameter.]) ]) dnl aclocal-1.4 backwards compatibility: dnl AC_DEFUN([AC_LIBTOOL_PICMODE], []) ## ----------------- ## ## LTDL_INIT Options ## ## ----------------- ## m4_define([_LTDL_MODE], []) LT_OPTION_DEFINE([LTDL_INIT], [nonrecursive], [m4_define([_LTDL_MODE], [nonrecursive])]) LT_OPTION_DEFINE([LTDL_INIT], [recursive], [m4_define([_LTDL_MODE], [recursive])]) LT_OPTION_DEFINE([LTDL_INIT], [subproject], [m4_define([_LTDL_MODE], [subproject])]) m4_define([_LTDL_TYPE], []) LT_OPTION_DEFINE([LTDL_INIT], [installable], [m4_define([_LTDL_TYPE], [installable])]) LT_OPTION_DEFINE([LTDL_INIT], [convenience], [m4_define([_LTDL_TYPE], [convenience])]) apache-couchdb-1.5.0/m4/ltsugar.m40000644000175000001440000001042412230722216013521 00000000000000# ltsugar.m4 -- libtool m4 base layer. -*-Autoconf-*- # # Copyright (C) 2004, 2005, 2007, 2008 Free Software Foundation, Inc. # Written by Gary V. Vaughan, 2004 # # This file is free software; the Free Software Foundation gives # unlimited permission to copy and/or distribute it, with or without # modifications, as long as this notice is preserved. # serial 6 ltsugar.m4 # This is to help aclocal find these macros, as it can't see m4_define. AC_DEFUN([LTSUGAR_VERSION], [m4_if([0.1])]) # lt_join(SEP, ARG1, [ARG2...]) # ----------------------------- # Produce ARG1SEPARG2...SEPARGn, omitting [] arguments and their # associated separator. # Needed until we can rely on m4_join from Autoconf 2.62, since all earlier # versions in m4sugar had bugs. m4_define([lt_join], [m4_if([$#], [1], [], [$#], [2], [[$2]], [m4_if([$2], [], [], [[$2]_])$0([$1], m4_shift(m4_shift($@)))])]) m4_define([_lt_join], [m4_if([$#$2], [2], [], [m4_if([$2], [], [], [[$1$2]])$0([$1], m4_shift(m4_shift($@)))])]) # lt_car(LIST) # lt_cdr(LIST) # ------------ # Manipulate m4 lists. # These macros are necessary as long as will still need to support # Autoconf-2.59 which quotes differently. m4_define([lt_car], [[$1]]) m4_define([lt_cdr], [m4_if([$#], 0, [m4_fatal([$0: cannot be called without arguments])], [$#], 1, [], [m4_dquote(m4_shift($@))])]) m4_define([lt_unquote], $1) # lt_append(MACRO-NAME, STRING, [SEPARATOR]) # ------------------------------------------ # Redefine MACRO-NAME to hold its former content plus `SEPARATOR'`STRING'. # Note that neither SEPARATOR nor STRING are expanded; they are appended # to MACRO-NAME as is (leaving the expansion for when MACRO-NAME is invoked). # No SEPARATOR is output if MACRO-NAME was previously undefined (different # than defined and empty). # # This macro is needed until we can rely on Autoconf 2.62, since earlier # versions of m4sugar mistakenly expanded SEPARATOR but not STRING. m4_define([lt_append], [m4_define([$1], m4_ifdef([$1], [m4_defn([$1])[$3]])[$2])]) # lt_combine(SEP, PREFIX-LIST, INFIX, SUFFIX1, [SUFFIX2...]) # ---------------------------------------------------------- # Produce a SEP delimited list of all paired combinations of elements of # PREFIX-LIST with SUFFIX1 through SUFFIXn. Each element of the list # has the form PREFIXmINFIXSUFFIXn. # Needed until we can rely on m4_combine added in Autoconf 2.62. m4_define([lt_combine], [m4_if(m4_eval([$# > 3]), [1], [m4_pushdef([_Lt_sep], [m4_define([_Lt_sep], m4_defn([lt_car]))])]]dnl [[m4_foreach([_Lt_prefix], [$2], [m4_foreach([_Lt_suffix], ]m4_dquote(m4_dquote(m4_shift(m4_shift(m4_shift($@)))))[, [_Lt_sep([$1])[]m4_defn([_Lt_prefix])[$3]m4_defn([_Lt_suffix])])])])]) # lt_if_append_uniq(MACRO-NAME, VARNAME, [SEPARATOR], [UNIQ], [NOT-UNIQ]) # ----------------------------------------------------------------------- # Iff MACRO-NAME does not yet contain VARNAME, then append it (delimited # by SEPARATOR if supplied) and expand UNIQ, else NOT-UNIQ. m4_define([lt_if_append_uniq], [m4_ifdef([$1], [m4_if(m4_index([$3]m4_defn([$1])[$3], [$3$2$3]), [-1], [lt_append([$1], [$2], [$3])$4], [$5])], [lt_append([$1], [$2], [$3])$4])]) # lt_dict_add(DICT, KEY, VALUE) # ----------------------------- m4_define([lt_dict_add], [m4_define([$1($2)], [$3])]) # lt_dict_add_subkey(DICT, KEY, SUBKEY, VALUE) # -------------------------------------------- m4_define([lt_dict_add_subkey], [m4_define([$1($2:$3)], [$4])]) # lt_dict_fetch(DICT, KEY, [SUBKEY]) # ---------------------------------- m4_define([lt_dict_fetch], [m4_ifval([$3], m4_ifdef([$1($2:$3)], [m4_defn([$1($2:$3)])]), m4_ifdef([$1($2)], [m4_defn([$1($2)])]))]) # lt_if_dict_fetch(DICT, KEY, [SUBKEY], VALUE, IF-TRUE, [IF-FALSE]) # ----------------------------------------------------------------- m4_define([lt_if_dict_fetch], [m4_if(lt_dict_fetch([$1], [$2], [$3]), [$4], [$5], [$6])]) # lt_dict_filter(DICT, [SUBKEY], VALUE, [SEPARATOR], KEY, [...]) # -------------------------------------------------------------- m4_define([lt_dict_filter], [m4_if([$5], [], [], [lt_join(m4_quote(m4_default([$4], [[, ]])), lt_unquote(m4_split(m4_normalize(m4_foreach(_Lt_key, lt_car([m4_shiftn(4, $@)]), [lt_if_dict_fetch([$1], _Lt_key, [$2], [$3], [_Lt_key ])])))))])[]dnl ]) apache-couchdb-1.5.0/bin/0000755000175000001440000000000012230722302012101 500000000000000apache-couchdb-1.5.0/bin/couchdb.tpl.in0000644000175000001440000002616412230722213014570 00000000000000#! /bin/sh -e # 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. BACKGROUND=false DEFAULT_CONFIG_DIR=%localconfdir%/default.d DEFAULT_CONFIG_FILE=%localconfdir%/%defaultini% ERL_OS_MON_OPTIONS="-os_mon \ start_memsup false \ start_cpu_sup false \ disk_space_check_interval 1 \ disk_almost_full_threshold 1" ERL_START_OPTIONS="$ERL_OS_MON_OPTIONS -sasl errlog_type error +K true +A 4" HEART_BEAT_TIMEOUT=11 HEART_COMMAND="%bindir%/%couchdb_command_name% -k" INTERACTIVE=false KILL=false PLUGINS_DIR=%locallibdir%/plugins LOCAL_CONFIG_DIR=%localconfdir%/local.d LOCAL_CONFIG_FILE=%localconfdir%/%localini% PID_FILE=%localstatedir%/run/couchdb/couchdb.pid RECURSED=false RESET_CONFIG=true RESPAWN_TIMEOUT=0 SCRIPT_ERROR=1 SCRIPT_OK=0 SHUTDOWN=false STDERR_FILE=couchdb.stderr STDOUT_FILE=couchdb.stdout print_arguments="" start_arguments="" background_start_arguments="" basename=`basename $0` display_version () { cat << EOF $basename - %package_name% %version% 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. EOF } display_help () { cat << EOF Usage: $basename [OPTION] The $basename command runs the %package_name% server. Erlang is called with: $ERL_START_OPTIONS Erlang inherits the environment of this command. You can override these options using the environment: ERL_AFLAGS, ERL_FLAGS, ERL_ZFLAGS See erl(1) for more information about the environment variables. The exit status is 0 for success or 1 for failure. Options: -h display a short help message and exit -V display version information and exit -a FILE add configuration FILE to chain -A DIR add configuration DIR to chain -n reset configuration file chain (including system default) -c print configuration file chain and exit -i use the interactive Erlang shell -b spawn as a background process -p FILE set the background PID FILE (overrides system default) -r SECONDS respawn background process after SECONDS (defaults to no respawn) -o FILE redirect background stdout to FILE (defaults to $STDOUT_FILE) -e FILE redirect background stderr to FILE (defaults to $STDERR_FILE) -s display the status of the background process -k kill the background process, will respawn if needed -d shutdown the background process Report bugs at <%bug_uri%>. EOF } display_error () { if test -n "$1"; then echo $1 >&2 fi echo >&2 echo "Try \`"$basename" -h' for more information." >&2 false } _get_pid () { if test -f $PID_FILE; then PID=`cat $PID_FILE` fi echo $PID } _add_config_file () { if test -z "$print_arguments"; then print_arguments="$1" else print_arguments="`cat < /dev/null; then echo "Apache CouchDB is running as process $PID, time to relax." return $SCRIPT_OK else echo >&2 << EOF Apache CouchDB is not running but a stale PID file exists: $PID_FILE EOF fi else echo "Apache CouchDB is not running." >&2 fi return $SCRIPT_ERROR } check_environment () { if test "$BACKGROUND" != "true"; then return fi touch $PID_FILE 2> /dev/null || true touch $STDOUT_FILE 2> /dev/null || true touch $STDERR_FILE 2> /dev/null || true message_prefix="Apache CouchDB needs write permission on the" if test ! -w $PID_FILE; then echo "$message_prefix PID file: $PID_FILE" >&2 false fi if test ! -w $STDOUT_FILE; then echo "$message_prefix STDOUT file: $STDOUT_FILE" >&2 false fi if test ! -w $STDERR_FILE; then echo "$message_prefix STDERR file: $STDERR_FILE" >&2 false fi message_prefix="Apache CouchDB needs a regular" if test `echo 2> /dev/null >> $PID_FILE; echo $?` -gt 0; then echo "$message_prefix PID file: $PID_FILE" >&2 false fi if test `echo 2> /dev/null >> $STDOUT_FILE; echo $?` -gt 0; then echo "$message_prefix STDOUT file: $STDOUT_FILE" >&2 false fi if test `echo 2> /dev/null >> $STDERR_FILE; echo $?` -gt 0; then echo "$message_prefix STDERR file: $STDERR_FILE" >&2 false fi } _find_plugins () { # Find plugins and add them to the Erlang path and load their default # configurations. This should be called from _load_config. if test -d "$PLUGINS_DIR"; then for plugin in "$PLUGINS_DIR"/*; do if echo "$COUCH_PLUGIN_BLACKLIST" | grep "$plugin" > /dev/null 2> /dev/null; then : # Do not use this plugin. else if echo "$ERL_ZFLAGS" | grep "$plugin/ebin" > /dev/null 2> /dev/null; then : # It's already loaded. else ERL_ZFLAGS="$ERL_ZFLAGS -pz '$plugin/ebin'" fi _add_config_dir "$plugin/priv/default.d" _add_erlang_config "$plugin/priv/couch_plugin.config" fi done export ERL_ZFLAGS fi } start_couchdb () { if test ! "$RECURSED" = "true"; then if check_status 2> /dev/null; then exit fi check_environment fi interactive_option="+Bd -noinput" if test "$INTERACTIVE" = "true"; then interactive_option="" fi if test "$BACKGROUND" = "true"; then touch $PID_FILE interactive_option="+Bd -noinput" fi command="%ERL% $interactive_option $ERL_START_OPTIONS \ -env ERL_LIBS $ERL_LIBS:%localerlanglibdir% -couch_ini $start_arguments -s couch" if test "$BACKGROUND" = "true" -a "$RECURSED" = "false"; then $0 $background_start_arguments -b -r $RESPAWN_TIMEOUT -p $PID_FILE \ -o $STDOUT_FILE -e $STDERR_FILE -R & echo "Apache CouchDB has started, time to relax." else if test "$RECURSED" = "true"; then while true; do export HEART_COMMAND export HEART_BEAT_TIMEOUT `eval $command -pidfile $PID_FILE -heart \ >> $STDOUT_FILE 2>> $STDERR_FILE` || true PID=`_get_pid` if test -n "$PID"; then if kill -0 $PID 2> /dev/null; then return $SCRIPT_ERROR fi else return $SCRIPT_OK fi if test "$RESPAWN_TIMEOUT" = "0"; then return $SCRIPT_OK fi if test "$RESPAWN_TIMEOUT" != "1"; then plural_ending="s" fi cat << EOF Apache CouchDB crashed, restarting in $RESPAWN_TIMEOUT second$plural_ending. EOF sleep $RESPAWN_TIMEOUT done else eval exec $command fi fi } stop_couchdb () { PID=`_get_pid` STOP_TIMEOUT=60 if test -n "$PID"; then if kill -0 $PID 2> /dev/null; then if kill -TERM $PID 2> /dev/null; then count=0 while kill -0 $PID 2> /dev/null; do if [ $count -ge $STOP_TIMEOUT ]; then echo "Apache CouchDB failed to shutdown." return $SCRIPT_ERROR else count=$[count+1] sleep 1 fi done if test "$1" = "false"; then echo "Apache CouchDB has been shutdown." else echo "Apache CouchDB has been killed." fi return $SCRIPT_OK else echo "Apache CouchDB could not be killed." >&2 return $SCRIPT_ERROR fi if test "$1" = "false"; then echo "Stale PID file exists but Apache CouchDB is not running." else echo "Stale PID file existed but Apache CouchDB is not running." fi fi else echo "Apache CouchDB is not running." fi } parse_script_option_list () { _load_config set +e options=`getopt hVa:A:ncibp:r:Ro:e:skd $@` if test ! $? -eq 0; then display_error fi set -e eval set -- $options while [ $# -gt 0 ]; do case "$1" in -h) shift; display_help; exit;; -V) shift; display_version; exit;; -a) shift; _add_config_file "$1"; shift;; -A) shift; _add_config_dir "$1"; shift;; -n) shift; _reset_config;; -c) shift; _print_config; exit;; -i) shift; INTERACTIVE=true;; -b) shift; BACKGROUND=true;; -r) shift; RESPAWN_TIMEOUT=$1; shift;; -R) shift; RECURSED=true;; -p) shift; PID_FILE=$1; shift;; -o) shift; STDOUT_FILE=$1; shift;; -e) shift; STDERR_FILE=$1; shift;; -s) shift; check_status; exit;; -k) shift; KILL=true;; -d) shift; SHUTDOWN=true;; --) shift; break;; *) display_error "Unknown option: $1" >&2;; esac done if test "$KILL" = "true" -o "$SHUTDOWN" = "true"; then stop_couchdb $KILL else start_couchdb fi } parse_script_option_list $@ apache-couchdb-1.5.0/bin/couchdb.10000644000175000001440000000444512230722302013521 00000000000000.\" DO NOT MODIFY THIS FILE! It was generated by help2man 1.40.11. .TH COUCHDB "1" "October 2013" "couchdb - Apache CouchDB 1.5.0" "User Commands" .SH NAME couchdb \- Apache CouchDB database server .SH SYNOPSIS .B couchdb [\fIOPTION\fR] .SH DESCRIPTION The couchdb command runs the Apache CouchDB server. .PP Erlang is called with: .TP \fB\-os_mon\fR start_memsup false start_cpu_sup false disk_space_check_interval 1 disk_almost_full_threshold 1 \fB\-sasl\fR errlog_type error +K true +A 4 .PP Erlang inherits the environment of this command. .PP You can override these options using the environment: .IP ERL_AFLAGS, ERL_FLAGS, ERL_ZFLAGS .PP See erl(1) for more information about the environment variables. .PP The exit status is 0 for success or 1 for failure. .SH OPTIONS .TP \fB\-h\fR display a short help message and exit .TP \fB\-V\fR display version information and exit .TP \fB\-a\fR FILE add configuration FILE to chain .TP \fB\-A\fR DIR add configuration DIR to chain .TP \fB\-n\fR reset configuration file chain (including system default) .TP \fB\-c\fR print configuration file chain and exit .TP \fB\-i\fR use the interactive Erlang shell .TP \fB\-b\fR spawn as a background process .TP \fB\-p\fR FILE set the background PID FILE (overrides system default) .TP \fB\-r\fR SECONDS respawn background process after SECONDS (defaults to no respawn) .TP \fB\-o\fR FILE redirect background stdout to FILE (defaults to couchdb.stdout) .TP \fB\-e\fR FILE redirect background stderr to FILE (defaults to couchdb.stderr) .TP \fB\-s\fR display the status of the background process .TP \fB\-k\fR kill the background process, will respawn if needed .TP \fB\-d\fR shutdown the background process .SH "REPORTING BUGS" Report bugs at . .PP .br 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 .br License at .IP http://www.apache.org/licenses/LICENSE\-2.0 .PP .br 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 .br CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. apache-couchdb-1.5.0/bin/couchdb.bat.tpl.in0000644000175000001440000000202312230722213015321 00000000000000@echo off rem Licensed under the Apache License, Version 2.0 (the "License"); you may not rem use this file except in compliance with the License. You may obtain a copy rem of the License at rem rem http://www.apache.org/licenses/LICENSE-2.0 rem rem Unless required by applicable law or agreed to in writing, software rem distributed under the License is distributed on an "AS IS" BASIS, WITHOUT rem WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the rem License for the specific language governing permissions and limitations rem under the License. setlocal rem First change to the drive with the erlang bin directory %~d0 rem then change to the erlang bin directory cd %~dp0 rem Allow a different erlang executable (eg, erl) to be used. rem When using erl instead of werl, server restarts during test runs can fail rem intermittently. But using erl should be fine for production use. if "%ERL%x" == "x" set ERL=werl.exe echo CouchDB %version% - prepare to relax... %ERL% -sasl errlog_type error -s couch +A 4 +W w apache-couchdb-1.5.0/bin/couch-config.tpl.in0000644000175000001440000000667112230722213015526 00000000000000#! /bin/sh -e # 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. basename=`basename "$0"` staticdir="%localbuilddatadir%" erlanglibdir="%localerlanglibdir%" couchversion="%version%" dbdir="%localstatelibdir%" viewdir="%localstatelibdir%" confdir="%localconfdir%" urifile="%localstaterundir%/couch.uri" logdir="%localstatelogdir%" erlangversion="%erlangversion%" erlangbin="%erlangbin%" version () { cat << EOF $basename - %package_name% configuration helper %version% 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. EOF } usage() { cat << EOF Usage: $basename [OPTION] The $basename command runs the %package_name% configuration helper script. Options: --erl-libs-dir Erlang library directory --erl-bin Erlang binary --config-dir configuration directory --db-dir database directory --view-dir view index directory --static-dir static asset directory --doc-dir documentation directory --log-dir log directory --uri-file daemon sockets file --couch-version version of Apache CouchDB --erlang-version version of Erlang that CouchDB was built with --version version of $basename --help Print usage If you want to add an option in couch-config or report bugs please do it at <%bug_uri%>. EOF } if [ $# -lt 1 ]; then usage exit 1 fi while [ $# -gt 0 ]; do arg="$1" var=`echo $arg | sed -e 's/^[^=]*=//'` case "$arg" in --erl-libs-dir) echo $erlanglibdir ;; --erl-bin) echo $erlangbin ;; --config-dir) echo $confdir ;; --db-dir) echo $dbdir ;; --view-dir) echo $viewdir ;; --static-dir) echo $staticdir ;; --doc-dir) echo $staticdir ;; --log-dir) echo $logdir ;; --uri-file) echo $urifile ;; --couch-version) echo $couchversion ;; --erlang-version) echo $erlangversion ;; --version) version exit 0 ;; --help) usage exit 0 ;; *|-*) echo $basename: ERROR Unknown Option $arg 1>&2 echo 1>&2 usage 1>&2 echo "### $basename: Exitting." 1>&2 exit 1; ;; esac shift done exit 0 apache-couchdb-1.5.0/bin/erlang-version.escript0000644000175000001440000000010412230722213016343 00000000000000 main(_) -> io:format("~s~n", [erlang:system_info(otp_release)]). apache-couchdb-1.5.0/bin/Makefile.am0000644000175000001440000001302212230722213014054 00000000000000## 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. MAKE_SAFE = $(MAKE) if WINDOWS bin_SCRIPTS = couchdb.bat else bin_SCRIPTS = couchdb couch-config endif man1dir = $(mandir)/man1 noinst_SCRIPTS = couchjs_dev couch-config_dev man_file = couchdb.1 if BUILD_MAN man_file_build = $(man_file) else man_file_build = endif BUILT_SOURCES = $(man_file_build) EXTRA_DIST = $(man_file_build) erlang-version.escript CLEANFILES = $(bin_SCRIPTS) $(man_file_build) $(noinst_SCRIPTS) transform = @program_transform_name@ couchdb_command_name = `echo couchdb | sed '$(transform)'` couchjs_command_name = `echo couchjs | sed '$(transform)'` couchdb: couchdb.tpl sed -e "s|%ERL%|$(ERL)|g" \ -e "s|%ICU_CONFIG%|$(ICU_CONFIG)|g" \ -e "s|%bindir%|@bindir@|g" \ -e "s|%localerlanglibdir%|@localerlanglibdir@|g" \ -e "s|%defaultini%|default.ini|g" \ -e "s|%localini%|local.ini|g" \ -e "s|%localconfdir%|@localconfdir@|g" \ -e "s|%localstatelogdir%|@localstatelogdir@|g" \ -e "s|%localstatelibdir%|@localstatelibdir@|g" \ -e "s|%localstatedir%|@localstatedir@|g" \ -e "s|%locallibdir%|@locallibdir@|g" \ -e "s|%bug_uri%|@bug_uri@|g" \ -e "s|%package_author_address%|@package_author_address@|g" \ -e "s|%package_author_name%|@package_author_name@|g" \ -e "s|%package_name%|@package_name@|g" \ -e "s|%version%|@version@|g" \ -e "s|%couchdb_command_name%|$(couchdb_command_name)|g" > \ $@ < $< chmod +x $@ if !WINDOWS install-exec-hook: $(LN_S) -f "$(locallibbindir)/$(couchjs_command_name)" \ "$(DESTDIR)$(bindir)/$(couchjs_command_name)" endif couchjs_dev: $(LN_S) -f "$(abs_top_builddir)/src/couchdb/priv/couchjs" "$@" couchdb.bat: couchdb.bat.tpl sed -e "s|%ICU_CONFIG%|$(ICU_CONFIG)|g" \ -e "s|%version%|@version@|g" \ $< > $@ couch-config: couch-config.tpl sed -e "s|%ERL%|$(ERL)|g" \ -e "s|%bindir%|@bindir@|g" \ -e "s|%localerlanglibdir%|@localerlanglibdir@|g" \ -e "s|%localconfdir%|@localconfdir@|g" \ -e "s|%localdatadir%|$(localdatadir)|g" \ -e "s|%localbuilddatadir%|$(localdatadir)|g" \ -e "s|%localstatelogdir%|@localstatelogdir@|g" \ -e "s|%localstatelibdir%|@localstatelibdir@|g" \ -e "s|%localstatedir%|@localstatedir@|g" \ -e "s|%localstaterundir%|@localstaterundir@|g" \ -e "s|%couchlibdir%|@localerlanglibdir@/couch-%version%|g"\ -e "s|%couchincludedir%|@localerlanglibdir@/include|g"\ -e "s|%couchebindir%|@localerlanglibdir@/ebin|g"\ -e "s|%couchprivlibdir%|@localerlanglibdir@/couch-%version%/priv/lib|g"\ -e "s|%bug_uri%|@bug_uri@|g" \ -e "s|%package_author_address%|@package_author_address@|g" \ -e "s|%package_author_name%|@package_author_name@|g" \ -e "s|%package_name%|@package_name@|g" \ -e "s|%version%|@version@|g" \ -e "s|%erlangversion%|@erlangversion@|g" \ -e "s|%erlangbin%|@erlangbin@|g" \ -e "s|%couchdb_command_name%|$(couchdb_command_name)|g" > \ $@ < $< chmod +x $@ couch-config_dev: couch-config.tpl sed -e "s|%ERL%|$(ERL)|g" \ -e "s|%bindir%|$(abs_top_builddir)/bin|g" \ -e "s|%localerlanglibdir%|$(abs_top_builddir)\/src\/couchdb|g" \ -e "s|%couchlibdir%|$(abs_top_builddir)\/src\/couchdb|g"\ -e "s|%couchincludedir%|$(abs_top_builddir)\/src\/couchdb|g"\ -e "s|%couchebindir%|$(abs_top_builddir)\/src\/couchdb|g"\ -e "s|%couchprivlibdir%|$(abs_top_builddir)/src/couchdb/priv/.libs|g"\ -e "s|%localdatadir%|$(abs_top_srcdir)/share|g" \ -e "s|%localbuilddatadir%|$(abs_top_builddir)/share|g" \ -e "s|%localstatelibdir%|$(abs_top_builddir)/tmp/lib|g" \ -e "s|%localstatelogdir%|$(abs_top_builddir)/tmp/log|g" \ -e "s|%localstatedir%|$(abs_top_builddir)/tmp|g" \ -e "s|%localstaterundir%|$(abs_top_builddir)/tmp/run|g" \ -e "s|%bug_uri%|@bug_uri@|g" \ -e "s|%package_author_address%|@package_author_address@|g" \ -e "s|%package_author_name%|@package_author_name@|g" \ -e "s|%package_name%|@package_name@|g" \ -e "s|%version%|@version@|g" \ -e "s|%erlangversion%|@erlangversion@|g" \ -e "s|%erlangbin%|@erlangbin@|g" \ -e "s|%couchdb_command_name%|$(abs_top_builddir)/utils/run|g" > \ $@ < $< chmod +x $@ # Depend on source files so distributed man pages are not rebuilt for end user. $(man_file): couchdb.tpl.in $(MAKE_SAFE) -f Makefile couchdb; \ $(top_srcdir)/build-aux/missing --run \ help2man \ --no-info \ --help-option="-h" \ --version-option="-V" \ --name="$(package_name) database server" \ ./couchdb --output $@ install-data-local: if test -s $(man_file); then \ if test `cat $(man_file) | wc -l` -gt 1; then \ $(INSTALL) -d $(DESTDIR)$(man1dir); \ $(INSTALL_DATA) $(man_file) $(DESTDIR)$(man1dir)/$(man_file); \ fi \ fi uninstall-local: rm -f $(DESTDIR)$(man1dir)/$(man_file) distcheck-hook: if test ! -s $(man_file); then \ $(top_srcdir)/build-aux/dist-error $(man_file); \ else \ if test ! `cat $(man_file) | wc -l` -gt 1; then \ $(top_srcdir)/build-aux/dist-error $(man_file); \ fi \ fi apache-couchdb-1.5.0/bin/Makefile.in0000644000175000001440000005147712230722241014106 00000000000000# Makefile.in generated by automake 1.11.6 from Makefile.am. # @configure_input@ # Copyright (C) 1994, 1995, 1996, 1997, 1998, 1999, 2000, 2001, 2002, # 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011 Free Software # Foundation, Inc. # This Makefile.in is free software; the Free Software Foundation # gives unlimited permission to copy and/or distribute it, # with or without modifications, as long as this notice is preserved. # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY, to the extent permitted by law; without # even the implied warranty of MERCHANTABILITY or FITNESS FOR A # PARTICULAR PURPOSE. @SET_MAKE@ VPATH = @srcdir@ am__make_dryrun = \ { \ am__dry=no; \ case $$MAKEFLAGS in \ *\\[\ \ ]*) \ echo 'am--echo: ; @echo "AM" OK' | $(MAKE) -f - 2>/dev/null \ | grep '^AM OK$$' >/dev/null || am__dry=yes;; \ *) \ for am__flg in $$MAKEFLAGS; do \ case $$am__flg in \ *=*|--*) ;; \ *n*) am__dry=yes; break;; \ esac; \ done;; \ esac; \ test $$am__dry = yes; \ } pkgdatadir = $(datadir)/@PACKAGE@ pkgincludedir = $(includedir)/@PACKAGE@ pkglibdir = $(libdir)/@PACKAGE@ pkglibexecdir = $(libexecdir)/@PACKAGE@ am__cd = CDPATH="$${ZSH_VERSION+.}$(PATH_SEPARATOR)" && cd install_sh_DATA = $(install_sh) -c -m 644 install_sh_PROGRAM = $(install_sh) -c install_sh_SCRIPT = $(install_sh) -c INSTALL_HEADER = $(INSTALL_DATA) NORMAL_INSTALL = : PRE_INSTALL = : POST_INSTALL = : NORMAL_UNINSTALL = : PRE_UNINSTALL = : POST_UNINSTALL = : build_triplet = @build@ host_triplet = @host@ subdir = bin DIST_COMMON = $(srcdir)/Makefile.am $(srcdir)/Makefile.in \ $(srcdir)/couch-config.tpl.in $(srcdir)/couchdb.bat.tpl.in \ $(srcdir)/couchdb.tpl.in ACLOCAL_M4 = $(top_srcdir)/aclocal.m4 am__aclocal_m4_deps = $(top_srcdir)/m4/libtool.m4 \ $(top_srcdir)/m4/ltoptions.m4 $(top_srcdir)/m4/ltsugar.m4 \ $(top_srcdir)/m4/ltversion.m4 $(top_srcdir)/m4/lt~obsolete.m4 \ $(top_srcdir)/acinclude.m4 $(top_srcdir)/configure.ac am__configure_deps = $(am__aclocal_m4_deps) $(CONFIGURE_DEPENDENCIES) \ $(ACLOCAL_M4) mkinstalldirs = $(install_sh) -d CONFIG_HEADER = $(top_builddir)/config.h \ $(top_builddir)/src/snappy/google-snappy/config.h CONFIG_CLEAN_FILES = couch-config.tpl couchdb.tpl couchdb.bat.tpl CONFIG_CLEAN_VPATH_FILES = am__vpath_adj_setup = srcdirstrip=`echo "$(srcdir)" | sed 's|.|.|g'`; am__vpath_adj = case $$p in \ $(srcdir)/*) f=`echo "$$p" | sed "s|^$$srcdirstrip/||"`;; \ *) f=$$p;; \ esac; am__strip_dir = f=`echo $$p | sed -e 's|^.*/||'`; am__install_max = 40 am__nobase_strip_setup = \ srcdirstrip=`echo "$(srcdir)" | sed 's/[].[^$$\\*|]/\\\\&/g'` am__nobase_strip = \ for p in $$list; do echo "$$p"; done | sed -e "s|$$srcdirstrip/||" am__nobase_list = $(am__nobase_strip_setup); \ for p in $$list; do echo "$$p $$p"; done | \ sed "s| $$srcdirstrip/| |;"' / .*\//!s/ .*/ ./; s,\( .*\)/[^/]*$$,\1,' | \ $(AWK) 'BEGIN { files["."] = "" } { files[$$2] = files[$$2] " " $$1; \ if (++n[$$2] == $(am__install_max)) \ { print $$2, files[$$2]; n[$$2] = 0; files[$$2] = "" } } \ END { for (dir in files) print dir, files[dir] }' am__base_list = \ sed '$$!N;$$!N;$$!N;$$!N;$$!N;$$!N;$$!N;s/\n/ /g' | \ sed '$$!N;$$!N;$$!N;$$!N;s/\n/ /g' am__uninstall_files_from_dir = { \ test -z "$$files" \ || { test ! -d "$$dir" && test ! -f "$$dir" && test ! -r "$$dir"; } \ || { echo " ( cd '$$dir' && rm -f" $$files ")"; \ $(am__cd) "$$dir" && rm -f $$files; }; \ } am__installdirs = "$(DESTDIR)$(bindir)" SCRIPTS = $(bin_SCRIPTS) $(noinst_SCRIPTS) SOURCES = DIST_SOURCES = am__can_run_installinfo = \ case $$AM_UPDATE_INFO_DIR in \ n|no|NO) false;; \ *) (install-info --version) >/dev/null 2>&1;; \ esac DISTFILES = $(DIST_COMMON) $(DIST_SOURCES) $(TEXINFOS) $(EXTRA_DIST) transform = @program_transform_name@ ACLOCAL = @ACLOCAL@ AMTAR = @AMTAR@ AR = @AR@ AS = @AS@ AUTOCONF = @AUTOCONF@ AUTOHEADER = @AUTOHEADER@ AUTOMAKE = @AUTOMAKE@ AWK = @AWK@ CC = @CC@ CCDEPMODE = @CCDEPMODE@ CFLAGS = @CFLAGS@ CPP = @CPP@ CPPFLAGS = @CPPFLAGS@ CURL_CFLAGS = @CURL_CFLAGS@ CURL_CONFIG = @CURL_CONFIG@ CURL_LIBS = @CURL_LIBS@ CXX = @CXX@ CXXCPP = @CXXCPP@ CXXDEPMODE = @CXXDEPMODE@ CXXFLAGS = @CXXFLAGS@ CYGPATH_W = @CYGPATH_W@ DEFS = @DEFS@ DEPDIR = @DEPDIR@ DLLTOOL = @DLLTOOL@ DSYMUTIL = @DSYMUTIL@ DUMPBIN = @DUMPBIN@ ECHO_C = @ECHO_C@ ECHO_N = @ECHO_N@ ECHO_T = @ECHO_T@ EGREP = @EGREP@ ERL = @ERL@ ERLANG_FLAGS = @ERLANG_FLAGS@ ERLC = @ERLC@ ERLC_FLAGS = @ERLC_FLAGS@ ESCRIPT = @ESCRIPT@ EXEEXT = @EXEEXT@ FGREP = @FGREP@ FLAGS = @FLAGS@ GREP = @GREP@ HAS_HELP2MAN = @HAS_HELP2MAN@ HAS_INSTALLINFO = @HAS_INSTALLINFO@ HAS_MAKEINFO = @HAS_MAKEINFO@ HAS_PDFLATEX = @HAS_PDFLATEX@ HAS_SPHINX_BUILD = @HAS_SPHINX_BUILD@ ICU_BIN = @ICU_BIN@ ICU_CFLAGS = @ICU_CFLAGS@ ICU_CONFIG = @ICU_CONFIG@ ICU_CPPFLAGS = @ICU_CPPFLAGS@ ICU_CXXFLAGS = @ICU_CXXFLAGS@ ICU_LIBS = @ICU_LIBS@ INNO_COMPILER_EXECUTABLE = @INNO_COMPILER_EXECUTABLE@ INSTALL = @INSTALL@ INSTALL_DATA = @INSTALL_DATA@ INSTALL_PROGRAM = @INSTALL_PROGRAM@ INSTALL_SCRIPT = @INSTALL_SCRIPT@ INSTALL_STRIP_PROGRAM = @INSTALL_STRIP_PROGRAM@ JS_CFLAGS = @JS_CFLAGS@ JS_LIBS = @JS_LIBS@ JS_LIB_BINARY = @JS_LIB_BINARY@ LD = @LD@ LDFLAGS = @LDFLAGS@ LIBOBJS = @LIBOBJS@ LIBS = @LIBS@ LIBTOOL = @LIBTOOL@ LIPO = @LIPO@ LN_S = @LN_S@ LTLIBOBJS = @LTLIBOBJS@ MAKEINFO = @MAKEINFO@ MANIFEST_TOOL = @MANIFEST_TOOL@ MKDIR_P = @MKDIR_P@ NM = @NM@ NMEDIT = @NMEDIT@ OBJDUMP = @OBJDUMP@ OBJEXT = @OBJEXT@ OTOOL = @OTOOL@ OTOOL64 = @OTOOL64@ PACKAGE = @PACKAGE@ PACKAGE_BUGREPORT = @PACKAGE_BUGREPORT@ PACKAGE_NAME = @PACKAGE_NAME@ PACKAGE_STRING = @PACKAGE_STRING@ PACKAGE_TARNAME = @PACKAGE_TARNAME@ PACKAGE_URL = @PACKAGE_URL@ PACKAGE_VERSION = @PACKAGE_VERSION@ PATH_SEPARATOR = @PATH_SEPARATOR@ PKG_CONFIG = @PKG_CONFIG@ PKG_CONFIG_LIBDIR = @PKG_CONFIG_LIBDIR@ PKG_CONFIG_PATH = @PKG_CONFIG_PATH@ RANLIB = @RANLIB@ SED = @SED@ SET_MAKE = @SET_MAKE@ SHELL = @SHELL@ SNAPPY_MAJOR = @SNAPPY_MAJOR@ SNAPPY_MINOR = @SNAPPY_MINOR@ SNAPPY_PATCHLEVEL = @SNAPPY_PATCHLEVEL@ STRIP = @STRIP@ VERSION = @VERSION@ abs_builddir = @abs_builddir@ abs_srcdir = @abs_srcdir@ abs_top_builddir = @abs_top_builddir@ abs_top_srcdir = @abs_top_srcdir@ ac_ct_AR = @ac_ct_AR@ ac_ct_CC = @ac_ct_CC@ ac_ct_CXX = @ac_ct_CXX@ ac_ct_DUMPBIN = @ac_ct_DUMPBIN@ ac_cv_have_stddef_h = @ac_cv_have_stddef_h@ ac_cv_have_stdint_h = @ac_cv_have_stdint_h@ am__include = @am__include@ am__leading_dot = @am__leading_dot@ am__quote = @am__quote@ am__tar = @am__tar@ am__untar = @am__untar@ bindir = @bindir@ bug_uri = @bug_uri@ build = @build@ build_alias = @build_alias@ build_cpu = @build_cpu@ build_os = @build_os@ build_vendor = @build_vendor@ builddir = @builddir@ datadir = @datadir@ datarootdir = @datarootdir@ docdir = @docdir@ dvidir = @dvidir@ erlangbin = @erlangbin@ erlangversion = @erlangversion@ exec_prefix = @exec_prefix@ host = @host@ host_alias = @host_alias@ host_cpu = @host_cpu@ host_os = @host_os@ host_vendor = @host_vendor@ htmldir = @htmldir@ includedir = @includedir@ infodir = @infodir@ initdir = @initdir@ install_sh = @install_sh@ launchddir = @launchddir@ libdir = @libdir@ libexecdir = @libexecdir@ localconfdir = @localconfdir@ localdatadir = @localdatadir@ localdocdir = @localdocdir@ localedir = @localedir@ localerlanglibdir = @localerlanglibdir@ locallibbindir = @locallibbindir@ locallibdir = @locallibdir@ localstatedir = @localstatedir@ localstatelibdir = @localstatelibdir@ localstatelogdir = @localstatelogdir@ localstaterundir = @localstaterundir@ mandir = @mandir@ mkdir_p = @mkdir_p@ msvc_redist_dir = @msvc_redist_dir@ msvc_redist_name = @msvc_redist_name@ oldincludedir = @oldincludedir@ openssl_bin_dir = @openssl_bin_dir@ otp_release = @otp_release@ package_author_address = @package_author_address@ package_author_name = @package_author_name@ package_identifier = @package_identifier@ package_name = @package_name@ package_tarname = @package_tarname@ pdfdir = @pdfdir@ prefix = @prefix@ program_transform_name = @program_transform_name@ psdir = @psdir@ sbindir = @sbindir@ sharedstatedir = @sharedstatedir@ srcdir = @srcdir@ sysconfdir = @sysconfdir@ target_alias = @target_alias@ top_build_prefix = @top_build_prefix@ top_builddir = @top_builddir@ top_srcdir = @top_srcdir@ version = @version@ version_major = @version_major@ version_minor = @version_minor@ version_release = @version_release@ version_revision = @version_revision@ version_stage = @version_stage@ MAKE_SAFE = $(MAKE) @WINDOWS_FALSE@bin_SCRIPTS = couchdb couch-config @WINDOWS_TRUE@bin_SCRIPTS = couchdb.bat man1dir = $(mandir)/man1 noinst_SCRIPTS = couchjs_dev couch-config_dev man_file = couchdb.1 @BUILD_MAN_FALSE@man_file_build = @BUILD_MAN_TRUE@man_file_build = $(man_file) BUILT_SOURCES = $(man_file_build) EXTRA_DIST = $(man_file_build) erlang-version.escript CLEANFILES = $(bin_SCRIPTS) $(man_file_build) $(noinst_SCRIPTS) couchdb_command_name = `echo couchdb | sed '$(transform)'` couchjs_command_name = `echo couchjs | sed '$(transform)'` all: $(BUILT_SOURCES) $(MAKE) $(AM_MAKEFLAGS) all-am .SUFFIXES: $(srcdir)/Makefile.in: $(srcdir)/Makefile.am $(am__configure_deps) @for dep in $?; do \ case '$(am__configure_deps)' in \ *$$dep*) \ ( cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh ) \ && { if test -f $@; then exit 0; else break; fi; }; \ exit 1;; \ esac; \ done; \ echo ' cd $(top_srcdir) && $(AUTOMAKE) --foreign bin/Makefile'; \ $(am__cd) $(top_srcdir) && \ $(AUTOMAKE) --foreign bin/Makefile .PRECIOUS: Makefile Makefile: $(srcdir)/Makefile.in $(top_builddir)/config.status @case '$?' in \ *config.status*) \ cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh;; \ *) \ echo ' cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ $(am__depfiles_maybe)'; \ cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ $(am__depfiles_maybe);; \ esac; $(top_builddir)/config.status: $(top_srcdir)/configure $(CONFIG_STATUS_DEPENDENCIES) cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh $(top_srcdir)/configure: $(am__configure_deps) cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh $(ACLOCAL_M4): $(am__aclocal_m4_deps) cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh $(am__aclocal_m4_deps): couch-config.tpl: $(top_builddir)/config.status $(srcdir)/couch-config.tpl.in cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ couchdb.tpl: $(top_builddir)/config.status $(srcdir)/couchdb.tpl.in cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ couchdb.bat.tpl: $(top_builddir)/config.status $(srcdir)/couchdb.bat.tpl.in cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ install-binSCRIPTS: $(bin_SCRIPTS) @$(NORMAL_INSTALL) @list='$(bin_SCRIPTS)'; test -n "$(bindir)" || list=; \ if test -n "$$list"; then \ echo " $(MKDIR_P) '$(DESTDIR)$(bindir)'"; \ $(MKDIR_P) "$(DESTDIR)$(bindir)" || exit 1; \ fi; \ for p in $$list; do \ if test -f "$$p"; then d=; else d="$(srcdir)/"; fi; \ if test -f "$$d$$p"; then echo "$$d$$p"; echo "$$p"; else :; fi; \ done | \ sed -e 'p;s,.*/,,;n' \ -e 'h;s|.*|.|' \ -e 'p;x;s,.*/,,;$(transform)' | sed 'N;N;N;s,\n, ,g' | \ $(AWK) 'BEGIN { files["."] = ""; dirs["."] = 1; } \ { d=$$3; if (dirs[d] != 1) { print "d", d; dirs[d] = 1 } \ if ($$2 == $$4) { files[d] = files[d] " " $$1; \ if (++n[d] == $(am__install_max)) { \ print "f", d, files[d]; n[d] = 0; files[d] = "" } } \ else { print "f", d "/" $$4, $$1 } } \ END { for (d in files) print "f", d, files[d] }' | \ while read type dir files; do \ if test "$$dir" = .; then dir=; else dir=/$$dir; fi; \ test -z "$$files" || { \ echo " $(INSTALL_SCRIPT) $$files '$(DESTDIR)$(bindir)$$dir'"; \ $(INSTALL_SCRIPT) $$files "$(DESTDIR)$(bindir)$$dir" || exit $$?; \ } \ ; done uninstall-binSCRIPTS: @$(NORMAL_UNINSTALL) @list='$(bin_SCRIPTS)'; test -n "$(bindir)" || exit 0; \ files=`for p in $$list; do echo "$$p"; done | \ sed -e 's,.*/,,;$(transform)'`; \ dir='$(DESTDIR)$(bindir)'; $(am__uninstall_files_from_dir) mostlyclean-libtool: -rm -f *.lo clean-libtool: -rm -rf .libs _libs tags: TAGS TAGS: ctags: CTAGS CTAGS: distdir: $(DISTFILES) @srcdirstrip=`echo "$(srcdir)" | sed 's/[].[^$$\\*]/\\\\&/g'`; \ topsrcdirstrip=`echo "$(top_srcdir)" | sed 's/[].[^$$\\*]/\\\\&/g'`; \ list='$(DISTFILES)'; \ dist_files=`for file in $$list; do echo $$file; done | \ sed -e "s|^$$srcdirstrip/||;t" \ -e "s|^$$topsrcdirstrip/|$(top_builddir)/|;t"`; \ case $$dist_files in \ */*) $(MKDIR_P) `echo "$$dist_files" | \ sed '/\//!d;s|^|$(distdir)/|;s,/[^/]*$$,,' | \ sort -u` ;; \ esac; \ for file in $$dist_files; do \ if test -f $$file || test -d $$file; then d=.; else d=$(srcdir); fi; \ if test -d $$d/$$file; then \ dir=`echo "/$$file" | sed -e 's,/[^/]*$$,,'`; \ if test -d "$(distdir)/$$file"; then \ find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} \;; \ fi; \ if test -d $(srcdir)/$$file && test $$d != $(srcdir); then \ cp -fpR $(srcdir)/$$file "$(distdir)$$dir" || exit 1; \ find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} \;; \ fi; \ cp -fpR $$d/$$file "$(distdir)$$dir" || exit 1; \ else \ test -f "$(distdir)/$$file" \ || cp -p $$d/$$file "$(distdir)/$$file" \ || exit 1; \ fi; \ done check-am: all-am check: $(BUILT_SOURCES) $(MAKE) $(AM_MAKEFLAGS) check-am all-am: Makefile $(SCRIPTS) installdirs: for dir in "$(DESTDIR)$(bindir)"; do \ test -z "$$dir" || $(MKDIR_P) "$$dir"; \ done install: $(BUILT_SOURCES) $(MAKE) $(AM_MAKEFLAGS) install-am install-exec: install-exec-am install-data: install-data-am uninstall: uninstall-am install-am: all-am @$(MAKE) $(AM_MAKEFLAGS) install-exec-am install-data-am installcheck: installcheck-am install-strip: if test -z '$(STRIP)'; then \ $(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(INSTALL_STRIP_PROGRAM)" \ install_sh_PROGRAM="$(INSTALL_STRIP_PROGRAM)" INSTALL_STRIP_FLAG=-s \ install; \ else \ $(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(INSTALL_STRIP_PROGRAM)" \ install_sh_PROGRAM="$(INSTALL_STRIP_PROGRAM)" INSTALL_STRIP_FLAG=-s \ "INSTALL_PROGRAM_ENV=STRIPPROG='$(STRIP)'" install; \ fi mostlyclean-generic: clean-generic: -test -z "$(CLEANFILES)" || rm -f $(CLEANFILES) distclean-generic: -test -z "$(CONFIG_CLEAN_FILES)" || rm -f $(CONFIG_CLEAN_FILES) -test . = "$(srcdir)" || test -z "$(CONFIG_CLEAN_VPATH_FILES)" || rm -f $(CONFIG_CLEAN_VPATH_FILES) maintainer-clean-generic: @echo "This command is intended for maintainers to use" @echo "it deletes files that may require special tools to rebuild." -test -z "$(BUILT_SOURCES)" || rm -f $(BUILT_SOURCES) @WINDOWS_TRUE@install-exec-hook: clean: clean-am clean-am: clean-generic clean-libtool mostlyclean-am distclean: distclean-am -rm -f Makefile distclean-am: clean-am distclean-generic dvi: dvi-am dvi-am: html: html-am html-am: info: info-am info-am: install-data-am: install-data-local install-dvi: install-dvi-am install-dvi-am: install-exec-am: install-binSCRIPTS @$(NORMAL_INSTALL) $(MAKE) $(AM_MAKEFLAGS) install-exec-hook install-html: install-html-am install-html-am: install-info: install-info-am install-info-am: install-man: install-pdf: install-pdf-am install-pdf-am: install-ps: install-ps-am install-ps-am: installcheck-am: maintainer-clean: maintainer-clean-am -rm -f Makefile maintainer-clean-am: distclean-am maintainer-clean-generic mostlyclean: mostlyclean-am mostlyclean-am: mostlyclean-generic mostlyclean-libtool pdf: pdf-am pdf-am: ps: ps-am ps-am: uninstall-am: uninstall-binSCRIPTS uninstall-local .MAKE: all check install install-am install-exec-am install-strip .PHONY: all all-am check check-am clean clean-generic clean-libtool \ distclean distclean-generic distclean-libtool distdir dvi \ dvi-am html html-am info info-am install install-am \ install-binSCRIPTS install-data install-data-am \ install-data-local install-dvi install-dvi-am install-exec \ install-exec-am install-exec-hook install-html install-html-am \ install-info install-info-am install-man install-pdf \ install-pdf-am install-ps install-ps-am install-strip \ installcheck installcheck-am installdirs maintainer-clean \ maintainer-clean-generic mostlyclean mostlyclean-generic \ mostlyclean-libtool pdf pdf-am ps ps-am uninstall uninstall-am \ uninstall-binSCRIPTS uninstall-local couchdb: couchdb.tpl sed -e "s|%ERL%|$(ERL)|g" \ -e "s|%ICU_CONFIG%|$(ICU_CONFIG)|g" \ -e "s|%bindir%|@bindir@|g" \ -e "s|%localerlanglibdir%|@localerlanglibdir@|g" \ -e "s|%defaultini%|default.ini|g" \ -e "s|%localini%|local.ini|g" \ -e "s|%localconfdir%|@localconfdir@|g" \ -e "s|%localstatelogdir%|@localstatelogdir@|g" \ -e "s|%localstatelibdir%|@localstatelibdir@|g" \ -e "s|%localstatedir%|@localstatedir@|g" \ -e "s|%locallibdir%|@locallibdir@|g" \ -e "s|%bug_uri%|@bug_uri@|g" \ -e "s|%package_author_address%|@package_author_address@|g" \ -e "s|%package_author_name%|@package_author_name@|g" \ -e "s|%package_name%|@package_name@|g" \ -e "s|%version%|@version@|g" \ -e "s|%couchdb_command_name%|$(couchdb_command_name)|g" > \ $@ < $< chmod +x $@ @WINDOWS_FALSE@install-exec-hook: @WINDOWS_FALSE@ $(LN_S) -f "$(locallibbindir)/$(couchjs_command_name)" \ @WINDOWS_FALSE@ "$(DESTDIR)$(bindir)/$(couchjs_command_name)" couchjs_dev: $(LN_S) -f "$(abs_top_builddir)/src/couchdb/priv/couchjs" "$@" couchdb.bat: couchdb.bat.tpl sed -e "s|%ICU_CONFIG%|$(ICU_CONFIG)|g" \ -e "s|%version%|@version@|g" \ $< > $@ couch-config: couch-config.tpl sed -e "s|%ERL%|$(ERL)|g" \ -e "s|%bindir%|@bindir@|g" \ -e "s|%localerlanglibdir%|@localerlanglibdir@|g" \ -e "s|%localconfdir%|@localconfdir@|g" \ -e "s|%localdatadir%|$(localdatadir)|g" \ -e "s|%localbuilddatadir%|$(localdatadir)|g" \ -e "s|%localstatelogdir%|@localstatelogdir@|g" \ -e "s|%localstatelibdir%|@localstatelibdir@|g" \ -e "s|%localstatedir%|@localstatedir@|g" \ -e "s|%localstaterundir%|@localstaterundir@|g" \ -e "s|%couchlibdir%|@localerlanglibdir@/couch-%version%|g"\ -e "s|%couchincludedir%|@localerlanglibdir@/include|g"\ -e "s|%couchebindir%|@localerlanglibdir@/ebin|g"\ -e "s|%couchprivlibdir%|@localerlanglibdir@/couch-%version%/priv/lib|g"\ -e "s|%bug_uri%|@bug_uri@|g" \ -e "s|%package_author_address%|@package_author_address@|g" \ -e "s|%package_author_name%|@package_author_name@|g" \ -e "s|%package_name%|@package_name@|g" \ -e "s|%version%|@version@|g" \ -e "s|%erlangversion%|@erlangversion@|g" \ -e "s|%erlangbin%|@erlangbin@|g" \ -e "s|%couchdb_command_name%|$(couchdb_command_name)|g" > \ $@ < $< chmod +x $@ couch-config_dev: couch-config.tpl sed -e "s|%ERL%|$(ERL)|g" \ -e "s|%bindir%|$(abs_top_builddir)/bin|g" \ -e "s|%localerlanglibdir%|$(abs_top_builddir)\/src\/couchdb|g" \ -e "s|%couchlibdir%|$(abs_top_builddir)\/src\/couchdb|g"\ -e "s|%couchincludedir%|$(abs_top_builddir)\/src\/couchdb|g"\ -e "s|%couchebindir%|$(abs_top_builddir)\/src\/couchdb|g"\ -e "s|%couchprivlibdir%|$(abs_top_builddir)/src/couchdb/priv/.libs|g"\ -e "s|%localdatadir%|$(abs_top_srcdir)/share|g" \ -e "s|%localbuilddatadir%|$(abs_top_builddir)/share|g" \ -e "s|%localstatelibdir%|$(abs_top_builddir)/tmp/lib|g" \ -e "s|%localstatelogdir%|$(abs_top_builddir)/tmp/log|g" \ -e "s|%localstatedir%|$(abs_top_builddir)/tmp|g" \ -e "s|%localstaterundir%|$(abs_top_builddir)/tmp/run|g" \ -e "s|%bug_uri%|@bug_uri@|g" \ -e "s|%package_author_address%|@package_author_address@|g" \ -e "s|%package_author_name%|@package_author_name@|g" \ -e "s|%package_name%|@package_name@|g" \ -e "s|%version%|@version@|g" \ -e "s|%erlangversion%|@erlangversion@|g" \ -e "s|%erlangbin%|@erlangbin@|g" \ -e "s|%couchdb_command_name%|$(abs_top_builddir)/utils/run|g" > \ $@ < $< chmod +x $@ # Depend on source files so distributed man pages are not rebuilt for end user. $(man_file): couchdb.tpl.in $(MAKE_SAFE) -f Makefile couchdb; \ $(top_srcdir)/build-aux/missing --run \ help2man \ --no-info \ --help-option="-h" \ --version-option="-V" \ --name="$(package_name) database server" \ ./couchdb --output $@ install-data-local: if test -s $(man_file); then \ if test `cat $(man_file) | wc -l` -gt 1; then \ $(INSTALL) -d $(DESTDIR)$(man1dir); \ $(INSTALL_DATA) $(man_file) $(DESTDIR)$(man1dir)/$(man_file); \ fi \ fi uninstall-local: rm -f $(DESTDIR)$(man1dir)/$(man_file) distcheck-hook: if test ! -s $(man_file); then \ $(top_srcdir)/build-aux/dist-error $(man_file); \ else \ if test ! `cat $(man_file) | wc -l` -gt 1; then \ $(top_srcdir)/build-aux/dist-error $(man_file); \ fi \ fi # Tell versions [3.59,3.63) of GNU make to not export all variables. # Otherwise a system limit (for SysV at least) may be exceeded. .NOEXPORT: apache-couchdb-1.5.0/etc/0000755000175000001440000000000012230722302012104 500000000000000apache-couchdb-1.5.0/etc/init/0000755000175000001440000000000012230722302013047 500000000000000apache-couchdb-1.5.0/etc/init/couchdb.tpl.in0000644000175000001440000000760612230722213015536 00000000000000#!/bin/sh -e # 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. ### BEGIN INIT INFO # Provides: couchdb # Required-Start: $local_fs $remote_fs # Required-Stop: $local_fs $remote_fs # Default-Start: 2 3 4 5 # Default-Stop: 0 1 6 # Short-Description: Apache CouchDB init script # Description: Apache CouchDB init script for the database server. ### END INIT INFO SCRIPT_OK=0 SCRIPT_ERROR=1 DESCRIPTION="database server" NAME=couchdb SCRIPT_NAME=`basename $0` COUCHDB=%bindir%/%couchdb_command_name% CONFIGURATION_FILE=%sysconfdir%/default/couchdb RUN_DIR=%localstaterundir% LSB_LIBRARY=/lib/lsb/init-functions if test ! -x $COUCHDB; then exit $SCRIPT_ERROR fi if test -r $CONFIGURATION_FILE; then . $CONFIGURATION_FILE fi log_daemon_msg () { # Dummy function to be replaced by LSB library. echo $@ } log_end_msg () { # Dummy function to be replaced by LSB library. if test "$1" != "0"; then echo "Error with $DESCRIPTION: $NAME" fi return $1 } if test -r $LSB_LIBRARY; then . $LSB_LIBRARY fi run_command () { command="$1" if test -n "$COUCHDB_OPTIONS"; then command="$command $COUCHDB_OPTIONS" fi if test -n "$COUCHDB_USER"; then if su $COUCHDB_USER -c "$command"; then return $SCRIPT_OK else return $SCRIPT_ERROR fi else if $command; then return $SCRIPT_OK else return $SCRIPT_ERROR fi fi } start_couchdb () { # Start Apache CouchDB as a background process. mkdir -p "$RUN_DIR" if test -n "$COUCHDB_USER"; then chown $COUCHDB_USER "$RUN_DIR" fi command="$COUCHDB -b" if test -n "$COUCHDB_STDOUT_FILE"; then command="$command -o $COUCHDB_STDOUT_FILE" fi if test -n "$COUCHDB_STDERR_FILE"; then command="$command -e $COUCHDB_STDERR_FILE" fi if test -n "$COUCHDB_RESPAWN_TIMEOUT"; then command="$command -r $COUCHDB_RESPAWN_TIMEOUT" fi run_command "$command" > /dev/null } stop_couchdb () { # Stop the running Apache CouchDB process. run_command "$COUCHDB -d" > /dev/null } display_status () { # Display the status of the running Apache CouchDB process. run_command "$COUCHDB -s" } parse_script_option_list () { # Parse arguments passed to the script and take appropriate action. case "$1" in start) log_daemon_msg "Starting $DESCRIPTION" $NAME if start_couchdb; then log_end_msg $SCRIPT_OK else log_end_msg $SCRIPT_ERROR fi ;; stop) log_daemon_msg "Stopping $DESCRIPTION" $NAME if stop_couchdb; then log_end_msg $SCRIPT_OK else log_end_msg $SCRIPT_ERROR fi ;; restart) log_daemon_msg "Restarting $DESCRIPTION" $NAME if stop_couchdb; then if start_couchdb; then log_end_msg $SCRIPT_OK else log_end_msg $SCRIPT_ERROR fi else log_end_msg $SCRIPT_ERROR fi ;; status) display_status ;; *) cat << EOF >&2 Usage: $SCRIPT_NAME {start|stop|restart|status} EOF exit $SCRIPT_ERROR ;; esac } parse_script_option_list $@ apache-couchdb-1.5.0/etc/init/Makefile.am0000644000175000001440000000112112230722213015017 00000000000000## 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. ## This file intentionally left blank. apache-couchdb-1.5.0/etc/init/Makefile.in0000644000175000001440000003035112230722242015041 00000000000000# Makefile.in generated by automake 1.11.6 from Makefile.am. # @configure_input@ # Copyright (C) 1994, 1995, 1996, 1997, 1998, 1999, 2000, 2001, 2002, # 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011 Free Software # Foundation, Inc. # This Makefile.in is free software; the Free Software Foundation # gives unlimited permission to copy and/or distribute it, # with or without modifications, as long as this notice is preserved. # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY, to the extent permitted by law; without # even the implied warranty of MERCHANTABILITY or FITNESS FOR A # PARTICULAR PURPOSE. @SET_MAKE@ VPATH = @srcdir@ am__make_dryrun = \ { \ am__dry=no; \ case $$MAKEFLAGS in \ *\\[\ \ ]*) \ echo 'am--echo: ; @echo "AM" OK' | $(MAKE) -f - 2>/dev/null \ | grep '^AM OK$$' >/dev/null || am__dry=yes;; \ *) \ for am__flg in $$MAKEFLAGS; do \ case $$am__flg in \ *=*|--*) ;; \ *n*) am__dry=yes; break;; \ esac; \ done;; \ esac; \ test $$am__dry = yes; \ } pkgdatadir = $(datadir)/@PACKAGE@ pkgincludedir = $(includedir)/@PACKAGE@ pkglibdir = $(libdir)/@PACKAGE@ pkglibexecdir = $(libexecdir)/@PACKAGE@ am__cd = CDPATH="$${ZSH_VERSION+.}$(PATH_SEPARATOR)" && cd install_sh_DATA = $(install_sh) -c -m 644 install_sh_PROGRAM = $(install_sh) -c install_sh_SCRIPT = $(install_sh) -c INSTALL_HEADER = $(INSTALL_DATA) transform = $(program_transform_name) NORMAL_INSTALL = : PRE_INSTALL = : POST_INSTALL = : NORMAL_UNINSTALL = : PRE_UNINSTALL = : POST_UNINSTALL = : build_triplet = @build@ host_triplet = @host@ subdir = etc/init DIST_COMMON = $(srcdir)/Makefile.am $(srcdir)/Makefile.in \ $(srcdir)/couchdb.tpl.in ACLOCAL_M4 = $(top_srcdir)/aclocal.m4 am__aclocal_m4_deps = $(top_srcdir)/m4/libtool.m4 \ $(top_srcdir)/m4/ltoptions.m4 $(top_srcdir)/m4/ltsugar.m4 \ $(top_srcdir)/m4/ltversion.m4 $(top_srcdir)/m4/lt~obsolete.m4 \ $(top_srcdir)/acinclude.m4 $(top_srcdir)/configure.ac am__configure_deps = $(am__aclocal_m4_deps) $(CONFIGURE_DEPENDENCIES) \ $(ACLOCAL_M4) mkinstalldirs = $(install_sh) -d CONFIG_HEADER = $(top_builddir)/config.h \ $(top_builddir)/src/snappy/google-snappy/config.h CONFIG_CLEAN_FILES = couchdb.tpl CONFIG_CLEAN_VPATH_FILES = SOURCES = DIST_SOURCES = am__can_run_installinfo = \ case $$AM_UPDATE_INFO_DIR in \ n|no|NO) false;; \ *) (install-info --version) >/dev/null 2>&1;; \ esac DISTFILES = $(DIST_COMMON) $(DIST_SOURCES) $(TEXINFOS) $(EXTRA_DIST) ACLOCAL = @ACLOCAL@ AMTAR = @AMTAR@ AR = @AR@ AS = @AS@ AUTOCONF = @AUTOCONF@ AUTOHEADER = @AUTOHEADER@ AUTOMAKE = @AUTOMAKE@ AWK = @AWK@ CC = @CC@ CCDEPMODE = @CCDEPMODE@ CFLAGS = @CFLAGS@ CPP = @CPP@ CPPFLAGS = @CPPFLAGS@ CURL_CFLAGS = @CURL_CFLAGS@ CURL_CONFIG = @CURL_CONFIG@ CURL_LIBS = @CURL_LIBS@ CXX = @CXX@ CXXCPP = @CXXCPP@ CXXDEPMODE = @CXXDEPMODE@ CXXFLAGS = @CXXFLAGS@ CYGPATH_W = @CYGPATH_W@ DEFS = @DEFS@ DEPDIR = @DEPDIR@ DLLTOOL = @DLLTOOL@ DSYMUTIL = @DSYMUTIL@ DUMPBIN = @DUMPBIN@ ECHO_C = @ECHO_C@ ECHO_N = @ECHO_N@ ECHO_T = @ECHO_T@ EGREP = @EGREP@ ERL = @ERL@ ERLANG_FLAGS = @ERLANG_FLAGS@ ERLC = @ERLC@ ERLC_FLAGS = @ERLC_FLAGS@ ESCRIPT = @ESCRIPT@ EXEEXT = @EXEEXT@ FGREP = @FGREP@ FLAGS = @FLAGS@ GREP = @GREP@ HAS_HELP2MAN = @HAS_HELP2MAN@ HAS_INSTALLINFO = @HAS_INSTALLINFO@ HAS_MAKEINFO = @HAS_MAKEINFO@ HAS_PDFLATEX = @HAS_PDFLATEX@ HAS_SPHINX_BUILD = @HAS_SPHINX_BUILD@ ICU_BIN = @ICU_BIN@ ICU_CFLAGS = @ICU_CFLAGS@ ICU_CONFIG = @ICU_CONFIG@ ICU_CPPFLAGS = @ICU_CPPFLAGS@ ICU_CXXFLAGS = @ICU_CXXFLAGS@ ICU_LIBS = @ICU_LIBS@ INNO_COMPILER_EXECUTABLE = @INNO_COMPILER_EXECUTABLE@ INSTALL = @INSTALL@ INSTALL_DATA = @INSTALL_DATA@ INSTALL_PROGRAM = @INSTALL_PROGRAM@ INSTALL_SCRIPT = @INSTALL_SCRIPT@ INSTALL_STRIP_PROGRAM = @INSTALL_STRIP_PROGRAM@ JS_CFLAGS = @JS_CFLAGS@ JS_LIBS = @JS_LIBS@ JS_LIB_BINARY = @JS_LIB_BINARY@ LD = @LD@ LDFLAGS = @LDFLAGS@ LIBOBJS = @LIBOBJS@ LIBS = @LIBS@ LIBTOOL = @LIBTOOL@ LIPO = @LIPO@ LN_S = @LN_S@ LTLIBOBJS = @LTLIBOBJS@ MAKEINFO = @MAKEINFO@ MANIFEST_TOOL = @MANIFEST_TOOL@ MKDIR_P = @MKDIR_P@ NM = @NM@ NMEDIT = @NMEDIT@ OBJDUMP = @OBJDUMP@ OBJEXT = @OBJEXT@ OTOOL = @OTOOL@ OTOOL64 = @OTOOL64@ PACKAGE = @PACKAGE@ PACKAGE_BUGREPORT = @PACKAGE_BUGREPORT@ PACKAGE_NAME = @PACKAGE_NAME@ PACKAGE_STRING = @PACKAGE_STRING@ PACKAGE_TARNAME = @PACKAGE_TARNAME@ PACKAGE_URL = @PACKAGE_URL@ PACKAGE_VERSION = @PACKAGE_VERSION@ PATH_SEPARATOR = @PATH_SEPARATOR@ PKG_CONFIG = @PKG_CONFIG@ PKG_CONFIG_LIBDIR = @PKG_CONFIG_LIBDIR@ PKG_CONFIG_PATH = @PKG_CONFIG_PATH@ RANLIB = @RANLIB@ SED = @SED@ SET_MAKE = @SET_MAKE@ SHELL = @SHELL@ SNAPPY_MAJOR = @SNAPPY_MAJOR@ SNAPPY_MINOR = @SNAPPY_MINOR@ SNAPPY_PATCHLEVEL = @SNAPPY_PATCHLEVEL@ STRIP = @STRIP@ VERSION = @VERSION@ abs_builddir = @abs_builddir@ abs_srcdir = @abs_srcdir@ abs_top_builddir = @abs_top_builddir@ abs_top_srcdir = @abs_top_srcdir@ ac_ct_AR = @ac_ct_AR@ ac_ct_CC = @ac_ct_CC@ ac_ct_CXX = @ac_ct_CXX@ ac_ct_DUMPBIN = @ac_ct_DUMPBIN@ ac_cv_have_stddef_h = @ac_cv_have_stddef_h@ ac_cv_have_stdint_h = @ac_cv_have_stdint_h@ am__include = @am__include@ am__leading_dot = @am__leading_dot@ am__quote = @am__quote@ am__tar = @am__tar@ am__untar = @am__untar@ bindir = @bindir@ bug_uri = @bug_uri@ build = @build@ build_alias = @build_alias@ build_cpu = @build_cpu@ build_os = @build_os@ build_vendor = @build_vendor@ builddir = @builddir@ datadir = @datadir@ datarootdir = @datarootdir@ docdir = @docdir@ dvidir = @dvidir@ erlangbin = @erlangbin@ erlangversion = @erlangversion@ exec_prefix = @exec_prefix@ host = @host@ host_alias = @host_alias@ host_cpu = @host_cpu@ host_os = @host_os@ host_vendor = @host_vendor@ htmldir = @htmldir@ includedir = @includedir@ infodir = @infodir@ initdir = @initdir@ install_sh = @install_sh@ launchddir = @launchddir@ libdir = @libdir@ libexecdir = @libexecdir@ localconfdir = @localconfdir@ localdatadir = @localdatadir@ localdocdir = @localdocdir@ localedir = @localedir@ localerlanglibdir = @localerlanglibdir@ locallibbindir = @locallibbindir@ locallibdir = @locallibdir@ localstatedir = @localstatedir@ localstatelibdir = @localstatelibdir@ localstatelogdir = @localstatelogdir@ localstaterundir = @localstaterundir@ mandir = @mandir@ mkdir_p = @mkdir_p@ msvc_redist_dir = @msvc_redist_dir@ msvc_redist_name = @msvc_redist_name@ oldincludedir = @oldincludedir@ openssl_bin_dir = @openssl_bin_dir@ otp_release = @otp_release@ package_author_address = @package_author_address@ package_author_name = @package_author_name@ package_identifier = @package_identifier@ package_name = @package_name@ package_tarname = @package_tarname@ pdfdir = @pdfdir@ prefix = @prefix@ program_transform_name = @program_transform_name@ psdir = @psdir@ sbindir = @sbindir@ sharedstatedir = @sharedstatedir@ srcdir = @srcdir@ sysconfdir = @sysconfdir@ target_alias = @target_alias@ top_build_prefix = @top_build_prefix@ top_builddir = @top_builddir@ top_srcdir = @top_srcdir@ version = @version@ version_major = @version_major@ version_minor = @version_minor@ version_release = @version_release@ version_revision = @version_revision@ version_stage = @version_stage@ all: all-am .SUFFIXES: $(srcdir)/Makefile.in: $(srcdir)/Makefile.am $(am__configure_deps) @for dep in $?; do \ case '$(am__configure_deps)' in \ *$$dep*) \ ( cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh ) \ && { if test -f $@; then exit 0; else break; fi; }; \ exit 1;; \ esac; \ done; \ echo ' cd $(top_srcdir) && $(AUTOMAKE) --foreign etc/init/Makefile'; \ $(am__cd) $(top_srcdir) && \ $(AUTOMAKE) --foreign etc/init/Makefile .PRECIOUS: Makefile Makefile: $(srcdir)/Makefile.in $(top_builddir)/config.status @case '$?' in \ *config.status*) \ cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh;; \ *) \ echo ' cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ $(am__depfiles_maybe)'; \ cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ $(am__depfiles_maybe);; \ esac; $(top_builddir)/config.status: $(top_srcdir)/configure $(CONFIG_STATUS_DEPENDENCIES) cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh $(top_srcdir)/configure: $(am__configure_deps) cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh $(ACLOCAL_M4): $(am__aclocal_m4_deps) cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh $(am__aclocal_m4_deps): couchdb.tpl: $(top_builddir)/config.status $(srcdir)/couchdb.tpl.in cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ mostlyclean-libtool: -rm -f *.lo clean-libtool: -rm -rf .libs _libs tags: TAGS TAGS: ctags: CTAGS CTAGS: distdir: $(DISTFILES) @srcdirstrip=`echo "$(srcdir)" | sed 's/[].[^$$\\*]/\\\\&/g'`; \ topsrcdirstrip=`echo "$(top_srcdir)" | sed 's/[].[^$$\\*]/\\\\&/g'`; \ list='$(DISTFILES)'; \ dist_files=`for file in $$list; do echo $$file; done | \ sed -e "s|^$$srcdirstrip/||;t" \ -e "s|^$$topsrcdirstrip/|$(top_builddir)/|;t"`; \ case $$dist_files in \ */*) $(MKDIR_P) `echo "$$dist_files" | \ sed '/\//!d;s|^|$(distdir)/|;s,/[^/]*$$,,' | \ sort -u` ;; \ esac; \ for file in $$dist_files; do \ if test -f $$file || test -d $$file; then d=.; else d=$(srcdir); fi; \ if test -d $$d/$$file; then \ dir=`echo "/$$file" | sed -e 's,/[^/]*$$,,'`; \ if test -d "$(distdir)/$$file"; then \ find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} \;; \ fi; \ if test -d $(srcdir)/$$file && test $$d != $(srcdir); then \ cp -fpR $(srcdir)/$$file "$(distdir)$$dir" || exit 1; \ find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} \;; \ fi; \ cp -fpR $$d/$$file "$(distdir)$$dir" || exit 1; \ else \ test -f "$(distdir)/$$file" \ || cp -p $$d/$$file "$(distdir)/$$file" \ || exit 1; \ fi; \ done check-am: all-am check: check-am all-am: Makefile installdirs: install: install-am install-exec: install-exec-am install-data: install-data-am uninstall: uninstall-am install-am: all-am @$(MAKE) $(AM_MAKEFLAGS) install-exec-am install-data-am installcheck: installcheck-am install-strip: if test -z '$(STRIP)'; then \ $(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(INSTALL_STRIP_PROGRAM)" \ install_sh_PROGRAM="$(INSTALL_STRIP_PROGRAM)" INSTALL_STRIP_FLAG=-s \ install; \ else \ $(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(INSTALL_STRIP_PROGRAM)" \ install_sh_PROGRAM="$(INSTALL_STRIP_PROGRAM)" INSTALL_STRIP_FLAG=-s \ "INSTALL_PROGRAM_ENV=STRIPPROG='$(STRIP)'" install; \ fi mostlyclean-generic: clean-generic: distclean-generic: -test -z "$(CONFIG_CLEAN_FILES)" || rm -f $(CONFIG_CLEAN_FILES) -test . = "$(srcdir)" || test -z "$(CONFIG_CLEAN_VPATH_FILES)" || rm -f $(CONFIG_CLEAN_VPATH_FILES) maintainer-clean-generic: @echo "This command is intended for maintainers to use" @echo "it deletes files that may require special tools to rebuild." clean: clean-am clean-am: clean-generic clean-libtool mostlyclean-am distclean: distclean-am -rm -f Makefile distclean-am: clean-am distclean-generic dvi: dvi-am dvi-am: html: html-am html-am: info: info-am info-am: install-data-am: install-dvi: install-dvi-am install-dvi-am: install-exec-am: install-html: install-html-am install-html-am: install-info: install-info-am install-info-am: install-man: install-pdf: install-pdf-am install-pdf-am: install-ps: install-ps-am install-ps-am: installcheck-am: maintainer-clean: maintainer-clean-am -rm -f Makefile maintainer-clean-am: distclean-am maintainer-clean-generic mostlyclean: mostlyclean-am mostlyclean-am: mostlyclean-generic mostlyclean-libtool pdf: pdf-am pdf-am: ps: ps-am ps-am: uninstall-am: .MAKE: install-am install-strip .PHONY: all all-am check check-am clean clean-generic clean-libtool \ distclean distclean-generic distclean-libtool distdir dvi \ dvi-am html html-am info info-am install install-am \ install-data install-data-am install-dvi install-dvi-am \ install-exec install-exec-am install-html install-html-am \ install-info install-info-am install-man install-pdf \ install-pdf-am install-ps install-ps-am install-strip \ installcheck installcheck-am installdirs maintainer-clean \ maintainer-clean-generic mostlyclean mostlyclean-generic \ mostlyclean-libtool pdf pdf-am ps ps-am uninstall uninstall-am # Tell versions [3.59,3.63) of GNU make to not export all variables. # Otherwise a system limit (for SysV at least) may be exceeded. .NOEXPORT: apache-couchdb-1.5.0/etc/default/0000755000175000001440000000000012230722302013530 500000000000000apache-couchdb-1.5.0/etc/default/couchdb0000644000175000001440000000025112230722213015001 00000000000000# Sourced by init script for configuration. COUCHDB_USER=couchdb COUCHDB_STDOUT_FILE=/dev/null COUCHDB_STDERR_FILE=/dev/null COUCHDB_RESPAWN_TIMEOUT=5 COUCHDB_OPTIONS= apache-couchdb-1.5.0/etc/default/Makefile.am0000644000175000001440000000112112230722213015500 00000000000000## 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. ## This file intentionally left blank. apache-couchdb-1.5.0/etc/default/Makefile.in0000644000175000001440000003011112230722241015513 00000000000000# Makefile.in generated by automake 1.11.6 from Makefile.am. # @configure_input@ # Copyright (C) 1994, 1995, 1996, 1997, 1998, 1999, 2000, 2001, 2002, # 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011 Free Software # Foundation, Inc. # This Makefile.in is free software; the Free Software Foundation # gives unlimited permission to copy and/or distribute it, # with or without modifications, as long as this notice is preserved. # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY, to the extent permitted by law; without # even the implied warranty of MERCHANTABILITY or FITNESS FOR A # PARTICULAR PURPOSE. @SET_MAKE@ VPATH = @srcdir@ am__make_dryrun = \ { \ am__dry=no; \ case $$MAKEFLAGS in \ *\\[\ \ ]*) \ echo 'am--echo: ; @echo "AM" OK' | $(MAKE) -f - 2>/dev/null \ | grep '^AM OK$$' >/dev/null || am__dry=yes;; \ *) \ for am__flg in $$MAKEFLAGS; do \ case $$am__flg in \ *=*|--*) ;; \ *n*) am__dry=yes; break;; \ esac; \ done;; \ esac; \ test $$am__dry = yes; \ } pkgdatadir = $(datadir)/@PACKAGE@ pkgincludedir = $(includedir)/@PACKAGE@ pkglibdir = $(libdir)/@PACKAGE@ pkglibexecdir = $(libexecdir)/@PACKAGE@ am__cd = CDPATH="$${ZSH_VERSION+.}$(PATH_SEPARATOR)" && cd install_sh_DATA = $(install_sh) -c -m 644 install_sh_PROGRAM = $(install_sh) -c install_sh_SCRIPT = $(install_sh) -c INSTALL_HEADER = $(INSTALL_DATA) transform = $(program_transform_name) NORMAL_INSTALL = : PRE_INSTALL = : POST_INSTALL = : NORMAL_UNINSTALL = : PRE_UNINSTALL = : POST_UNINSTALL = : build_triplet = @build@ host_triplet = @host@ subdir = etc/default DIST_COMMON = $(srcdir)/Makefile.am $(srcdir)/Makefile.in ACLOCAL_M4 = $(top_srcdir)/aclocal.m4 am__aclocal_m4_deps = $(top_srcdir)/m4/libtool.m4 \ $(top_srcdir)/m4/ltoptions.m4 $(top_srcdir)/m4/ltsugar.m4 \ $(top_srcdir)/m4/ltversion.m4 $(top_srcdir)/m4/lt~obsolete.m4 \ $(top_srcdir)/acinclude.m4 $(top_srcdir)/configure.ac am__configure_deps = $(am__aclocal_m4_deps) $(CONFIGURE_DEPENDENCIES) \ $(ACLOCAL_M4) mkinstalldirs = $(install_sh) -d CONFIG_HEADER = $(top_builddir)/config.h \ $(top_builddir)/src/snappy/google-snappy/config.h CONFIG_CLEAN_FILES = CONFIG_CLEAN_VPATH_FILES = SOURCES = DIST_SOURCES = am__can_run_installinfo = \ case $$AM_UPDATE_INFO_DIR in \ n|no|NO) false;; \ *) (install-info --version) >/dev/null 2>&1;; \ esac DISTFILES = $(DIST_COMMON) $(DIST_SOURCES) $(TEXINFOS) $(EXTRA_DIST) ACLOCAL = @ACLOCAL@ AMTAR = @AMTAR@ AR = @AR@ AS = @AS@ AUTOCONF = @AUTOCONF@ AUTOHEADER = @AUTOHEADER@ AUTOMAKE = @AUTOMAKE@ AWK = @AWK@ CC = @CC@ CCDEPMODE = @CCDEPMODE@ CFLAGS = @CFLAGS@ CPP = @CPP@ CPPFLAGS = @CPPFLAGS@ CURL_CFLAGS = @CURL_CFLAGS@ CURL_CONFIG = @CURL_CONFIG@ CURL_LIBS = @CURL_LIBS@ CXX = @CXX@ CXXCPP = @CXXCPP@ CXXDEPMODE = @CXXDEPMODE@ CXXFLAGS = @CXXFLAGS@ CYGPATH_W = @CYGPATH_W@ DEFS = @DEFS@ DEPDIR = @DEPDIR@ DLLTOOL = @DLLTOOL@ DSYMUTIL = @DSYMUTIL@ DUMPBIN = @DUMPBIN@ ECHO_C = @ECHO_C@ ECHO_N = @ECHO_N@ ECHO_T = @ECHO_T@ EGREP = @EGREP@ ERL = @ERL@ ERLANG_FLAGS = @ERLANG_FLAGS@ ERLC = @ERLC@ ERLC_FLAGS = @ERLC_FLAGS@ ESCRIPT = @ESCRIPT@ EXEEXT = @EXEEXT@ FGREP = @FGREP@ FLAGS = @FLAGS@ GREP = @GREP@ HAS_HELP2MAN = @HAS_HELP2MAN@ HAS_INSTALLINFO = @HAS_INSTALLINFO@ HAS_MAKEINFO = @HAS_MAKEINFO@ HAS_PDFLATEX = @HAS_PDFLATEX@ HAS_SPHINX_BUILD = @HAS_SPHINX_BUILD@ ICU_BIN = @ICU_BIN@ ICU_CFLAGS = @ICU_CFLAGS@ ICU_CONFIG = @ICU_CONFIG@ ICU_CPPFLAGS = @ICU_CPPFLAGS@ ICU_CXXFLAGS = @ICU_CXXFLAGS@ ICU_LIBS = @ICU_LIBS@ INNO_COMPILER_EXECUTABLE = @INNO_COMPILER_EXECUTABLE@ INSTALL = @INSTALL@ INSTALL_DATA = @INSTALL_DATA@ INSTALL_PROGRAM = @INSTALL_PROGRAM@ INSTALL_SCRIPT = @INSTALL_SCRIPT@ INSTALL_STRIP_PROGRAM = @INSTALL_STRIP_PROGRAM@ JS_CFLAGS = @JS_CFLAGS@ JS_LIBS = @JS_LIBS@ JS_LIB_BINARY = @JS_LIB_BINARY@ LD = @LD@ LDFLAGS = @LDFLAGS@ LIBOBJS = @LIBOBJS@ LIBS = @LIBS@ LIBTOOL = @LIBTOOL@ LIPO = @LIPO@ LN_S = @LN_S@ LTLIBOBJS = @LTLIBOBJS@ MAKEINFO = @MAKEINFO@ MANIFEST_TOOL = @MANIFEST_TOOL@ MKDIR_P = @MKDIR_P@ NM = @NM@ NMEDIT = @NMEDIT@ OBJDUMP = @OBJDUMP@ OBJEXT = @OBJEXT@ OTOOL = @OTOOL@ OTOOL64 = @OTOOL64@ PACKAGE = @PACKAGE@ PACKAGE_BUGREPORT = @PACKAGE_BUGREPORT@ PACKAGE_NAME = @PACKAGE_NAME@ PACKAGE_STRING = @PACKAGE_STRING@ PACKAGE_TARNAME = @PACKAGE_TARNAME@ PACKAGE_URL = @PACKAGE_URL@ PACKAGE_VERSION = @PACKAGE_VERSION@ PATH_SEPARATOR = @PATH_SEPARATOR@ PKG_CONFIG = @PKG_CONFIG@ PKG_CONFIG_LIBDIR = @PKG_CONFIG_LIBDIR@ PKG_CONFIG_PATH = @PKG_CONFIG_PATH@ RANLIB = @RANLIB@ SED = @SED@ SET_MAKE = @SET_MAKE@ SHELL = @SHELL@ SNAPPY_MAJOR = @SNAPPY_MAJOR@ SNAPPY_MINOR = @SNAPPY_MINOR@ SNAPPY_PATCHLEVEL = @SNAPPY_PATCHLEVEL@ STRIP = @STRIP@ VERSION = @VERSION@ abs_builddir = @abs_builddir@ abs_srcdir = @abs_srcdir@ abs_top_builddir = @abs_top_builddir@ abs_top_srcdir = @abs_top_srcdir@ ac_ct_AR = @ac_ct_AR@ ac_ct_CC = @ac_ct_CC@ ac_ct_CXX = @ac_ct_CXX@ ac_ct_DUMPBIN = @ac_ct_DUMPBIN@ ac_cv_have_stddef_h = @ac_cv_have_stddef_h@ ac_cv_have_stdint_h = @ac_cv_have_stdint_h@ am__include = @am__include@ am__leading_dot = @am__leading_dot@ am__quote = @am__quote@ am__tar = @am__tar@ am__untar = @am__untar@ bindir = @bindir@ bug_uri = @bug_uri@ build = @build@ build_alias = @build_alias@ build_cpu = @build_cpu@ build_os = @build_os@ build_vendor = @build_vendor@ builddir = @builddir@ datadir = @datadir@ datarootdir = @datarootdir@ docdir = @docdir@ dvidir = @dvidir@ erlangbin = @erlangbin@ erlangversion = @erlangversion@ exec_prefix = @exec_prefix@ host = @host@ host_alias = @host_alias@ host_cpu = @host_cpu@ host_os = @host_os@ host_vendor = @host_vendor@ htmldir = @htmldir@ includedir = @includedir@ infodir = @infodir@ initdir = @initdir@ install_sh = @install_sh@ launchddir = @launchddir@ libdir = @libdir@ libexecdir = @libexecdir@ localconfdir = @localconfdir@ localdatadir = @localdatadir@ localdocdir = @localdocdir@ localedir = @localedir@ localerlanglibdir = @localerlanglibdir@ locallibbindir = @locallibbindir@ locallibdir = @locallibdir@ localstatedir = @localstatedir@ localstatelibdir = @localstatelibdir@ localstatelogdir = @localstatelogdir@ localstaterundir = @localstaterundir@ mandir = @mandir@ mkdir_p = @mkdir_p@ msvc_redist_dir = @msvc_redist_dir@ msvc_redist_name = @msvc_redist_name@ oldincludedir = @oldincludedir@ openssl_bin_dir = @openssl_bin_dir@ otp_release = @otp_release@ package_author_address = @package_author_address@ package_author_name = @package_author_name@ package_identifier = @package_identifier@ package_name = @package_name@ package_tarname = @package_tarname@ pdfdir = @pdfdir@ prefix = @prefix@ program_transform_name = @program_transform_name@ psdir = @psdir@ sbindir = @sbindir@ sharedstatedir = @sharedstatedir@ srcdir = @srcdir@ sysconfdir = @sysconfdir@ target_alias = @target_alias@ top_build_prefix = @top_build_prefix@ top_builddir = @top_builddir@ top_srcdir = @top_srcdir@ version = @version@ version_major = @version_major@ version_minor = @version_minor@ version_release = @version_release@ version_revision = @version_revision@ version_stage = @version_stage@ all: all-am .SUFFIXES: $(srcdir)/Makefile.in: $(srcdir)/Makefile.am $(am__configure_deps) @for dep in $?; do \ case '$(am__configure_deps)' in \ *$$dep*) \ ( cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh ) \ && { if test -f $@; then exit 0; else break; fi; }; \ exit 1;; \ esac; \ done; \ echo ' cd $(top_srcdir) && $(AUTOMAKE) --foreign etc/default/Makefile'; \ $(am__cd) $(top_srcdir) && \ $(AUTOMAKE) --foreign etc/default/Makefile .PRECIOUS: Makefile Makefile: $(srcdir)/Makefile.in $(top_builddir)/config.status @case '$?' in \ *config.status*) \ cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh;; \ *) \ echo ' cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ $(am__depfiles_maybe)'; \ cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ $(am__depfiles_maybe);; \ esac; $(top_builddir)/config.status: $(top_srcdir)/configure $(CONFIG_STATUS_DEPENDENCIES) cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh $(top_srcdir)/configure: $(am__configure_deps) cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh $(ACLOCAL_M4): $(am__aclocal_m4_deps) cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh $(am__aclocal_m4_deps): mostlyclean-libtool: -rm -f *.lo clean-libtool: -rm -rf .libs _libs tags: TAGS TAGS: ctags: CTAGS CTAGS: distdir: $(DISTFILES) @srcdirstrip=`echo "$(srcdir)" | sed 's/[].[^$$\\*]/\\\\&/g'`; \ topsrcdirstrip=`echo "$(top_srcdir)" | sed 's/[].[^$$\\*]/\\\\&/g'`; \ list='$(DISTFILES)'; \ dist_files=`for file in $$list; do echo $$file; done | \ sed -e "s|^$$srcdirstrip/||;t" \ -e "s|^$$topsrcdirstrip/|$(top_builddir)/|;t"`; \ case $$dist_files in \ */*) $(MKDIR_P) `echo "$$dist_files" | \ sed '/\//!d;s|^|$(distdir)/|;s,/[^/]*$$,,' | \ sort -u` ;; \ esac; \ for file in $$dist_files; do \ if test -f $$file || test -d $$file; then d=.; else d=$(srcdir); fi; \ if test -d $$d/$$file; then \ dir=`echo "/$$file" | sed -e 's,/[^/]*$$,,'`; \ if test -d "$(distdir)/$$file"; then \ find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} \;; \ fi; \ if test -d $(srcdir)/$$file && test $$d != $(srcdir); then \ cp -fpR $(srcdir)/$$file "$(distdir)$$dir" || exit 1; \ find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} \;; \ fi; \ cp -fpR $$d/$$file "$(distdir)$$dir" || exit 1; \ else \ test -f "$(distdir)/$$file" \ || cp -p $$d/$$file "$(distdir)/$$file" \ || exit 1; \ fi; \ done check-am: all-am check: check-am all-am: Makefile installdirs: install: install-am install-exec: install-exec-am install-data: install-data-am uninstall: uninstall-am install-am: all-am @$(MAKE) $(AM_MAKEFLAGS) install-exec-am install-data-am installcheck: installcheck-am install-strip: if test -z '$(STRIP)'; then \ $(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(INSTALL_STRIP_PROGRAM)" \ install_sh_PROGRAM="$(INSTALL_STRIP_PROGRAM)" INSTALL_STRIP_FLAG=-s \ install; \ else \ $(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(INSTALL_STRIP_PROGRAM)" \ install_sh_PROGRAM="$(INSTALL_STRIP_PROGRAM)" INSTALL_STRIP_FLAG=-s \ "INSTALL_PROGRAM_ENV=STRIPPROG='$(STRIP)'" install; \ fi mostlyclean-generic: clean-generic: distclean-generic: -test -z "$(CONFIG_CLEAN_FILES)" || rm -f $(CONFIG_CLEAN_FILES) -test . = "$(srcdir)" || test -z "$(CONFIG_CLEAN_VPATH_FILES)" || rm -f $(CONFIG_CLEAN_VPATH_FILES) maintainer-clean-generic: @echo "This command is intended for maintainers to use" @echo "it deletes files that may require special tools to rebuild." clean: clean-am clean-am: clean-generic clean-libtool mostlyclean-am distclean: distclean-am -rm -f Makefile distclean-am: clean-am distclean-generic dvi: dvi-am dvi-am: html: html-am html-am: info: info-am info-am: install-data-am: install-dvi: install-dvi-am install-dvi-am: install-exec-am: install-html: install-html-am install-html-am: install-info: install-info-am install-info-am: install-man: install-pdf: install-pdf-am install-pdf-am: install-ps: install-ps-am install-ps-am: installcheck-am: maintainer-clean: maintainer-clean-am -rm -f Makefile maintainer-clean-am: distclean-am maintainer-clean-generic mostlyclean: mostlyclean-am mostlyclean-am: mostlyclean-generic mostlyclean-libtool pdf: pdf-am pdf-am: ps: ps-am ps-am: uninstall-am: .MAKE: install-am install-strip .PHONY: all all-am check check-am clean clean-generic clean-libtool \ distclean distclean-generic distclean-libtool distdir dvi \ dvi-am html html-am info info-am install install-am \ install-data install-data-am install-dvi install-dvi-am \ install-exec install-exec-am install-html install-html-am \ install-info install-info-am install-man install-pdf \ install-pdf-am install-ps install-ps-am install-strip \ installcheck installcheck-am installdirs maintainer-clean \ maintainer-clean-generic mostlyclean mostlyclean-generic \ mostlyclean-libtool pdf pdf-am ps ps-am uninstall uninstall-am # Tell versions [3.59,3.63) of GNU make to not export all variables. # Otherwise a system limit (for SysV at least) may be exceeded. .NOEXPORT: apache-couchdb-1.5.0/etc/couchdb/0000755000175000001440000000000012230722302013513 500000000000000apache-couchdb-1.5.0/etc/couchdb/Makefile.am0000644000175000001440000000723012230722213015472 00000000000000## 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. couchprivlibdir = $(localerlanglibdir)/couch-$(version)/priv/lib devcouchprivlibdir = $(abs_top_builddir)/src/couchdb/priv/.libs localconf_DATA = default.ini noinst_DATA = default_dev.ini local_dev.ini EXTRA_DIST = local.ini CLEANFILES = $(localconf_DATA) $(noinst_DATA) transform = @program_transform_name@ couchjs_command_name = `echo couchjs | sed '$(transform)'` couchjs_dev_command_name = `echo couchjs_dev | sed '$(transform)'` if WINDOWS default.ini: default.ini.tpl sed -e "s|%bindir%|.|g" \ -e "s|%localconfdir%|$(localconfdir)|g" \ -e "s|%localdatadir%|../share/couchdb|g" \ -e "s|%localbuilddatadir%|../share/couchdb|g" \ -e "s|%localstatelibdir%|../var/lib/couchdb|g" \ -e "s|%localstatelogdir%|../var/log/couchdb|g" \ -e "s|%localstaterundir%|../var/run/couchdb|g" \ -e "s|%couchprivlibdir%|../lib/couch-$(version)/priv/lib|g" \ -e "s|%couchjs_command_name%|couchjs.exe|g" \ -e "s|%package_author_name%|$(package_author_name)|g" \ -e "s|%version%|$(version)|g" \ < $< > $@ else default.ini: default.ini.tpl sed -e "s|%bindir%|$(bindir)|g" \ -e "s|%localconfdir%|$(localconfdir)|g" \ -e "s|%localdatadir%|$(localdatadir)|g" \ -e "s|%localbuilddatadir%|$(localdatadir)|g" \ -e "s|%locallibdir%|$(locallibdir)|g" \ -e "s|%localstatelibdir%|$(localstatelibdir)|g" \ -e "s|%localstatelogdir%|$(localstatelogdir)|g" \ -e "s|%localstaterundir%|$(localstaterundir)|g" \ -e "s|%couchprivlibdir%|$(couchprivlibdir)|g" \ -e "s|%couchjs_command_name%|$(couchjs_command_name)|g" \ -e "s|%package_author_name%|$(package_author_name)|g" \ -e "s|%version%|$(version)|g" \ < $< > $@ endif default_dev.ini: default.ini.tpl sed -e "s|%bindir%|$(abs_top_builddir)/bin|g" \ -e "s|%localconfdir%|$(abs_top_builddir)/etc/couchdb|g" \ -e "s|%localdatadir%|$(abs_top_srcdir)/share|g" \ -e "s|%locallibdir%|$(abs_top_builddir)/tmp|g" \ -e "s|%localbuilddatadir%|$(abs_top_builddir)/share|g" \ -e "s|%localstatelibdir%|$(abs_top_builddir)/tmp/lib|g" \ -e "s|%localstatelogdir%|$(abs_top_builddir)/tmp/log|g" \ -e "s|%localstaterundir%|$(abs_top_builddir)/tmp/run|g" \ -e "s|%couchprivlibdir%|$(devcouchprivlibdir)|g" \ -e "s|%couchjs_command_name%|$(couchjs_dev_command_name)|g" \ -e "s|%package_author_name%|$(package_author_name)|g" \ -e "s|%version%|$(version)|g" \ < $< > $@ # Noah said to not specify local.ini but it borks # VPATH builds that make distcheck uses. local_dev.ini: local.ini if test ! -f "$@"; then \ cp $< $@; \ chmod +w $@; \ fi install-data-hook: if test ! -f "$(DESTDIR)$(localconfdir)/local.ini"; then \ cp $(srcdir)/local.ini "$(DESTDIR)$(localconfdir)/local.ini"; \ fi if test ! "$(mkdir_p)" = ""; then \ $(mkdir_p) "$(DESTDIR)$(localconfdir)/default.d"; \ $(mkdir_p) "$(DESTDIR)$(localconfdir)/local.d"; \ else \ echo "WARNING: You may have to create these directories by hand."; \ mkdir -p "$(DESTDIR)$(localconfdir)/default.d"; \ mkdir -p "$(DESTDIR)$(localconfdir)/local.d"; \ fi uninstall-local: rm -f "$(DESTDIR)/$(localconfdir)/local.ini" apache-couchdb-1.5.0/etc/couchdb/Makefile.in0000644000175000001440000004414312230722241015510 00000000000000# Makefile.in generated by automake 1.11.6 from Makefile.am. # @configure_input@ # Copyright (C) 1994, 1995, 1996, 1997, 1998, 1999, 2000, 2001, 2002, # 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011 Free Software # Foundation, Inc. # This Makefile.in is free software; the Free Software Foundation # gives unlimited permission to copy and/or distribute it, # with or without modifications, as long as this notice is preserved. # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY, to the extent permitted by law; without # even the implied warranty of MERCHANTABILITY or FITNESS FOR A # PARTICULAR PURPOSE. @SET_MAKE@ VPATH = @srcdir@ am__make_dryrun = \ { \ am__dry=no; \ case $$MAKEFLAGS in \ *\\[\ \ ]*) \ echo 'am--echo: ; @echo "AM" OK' | $(MAKE) -f - 2>/dev/null \ | grep '^AM OK$$' >/dev/null || am__dry=yes;; \ *) \ for am__flg in $$MAKEFLAGS; do \ case $$am__flg in \ *=*|--*) ;; \ *n*) am__dry=yes; break;; \ esac; \ done;; \ esac; \ test $$am__dry = yes; \ } pkgdatadir = $(datadir)/@PACKAGE@ pkgincludedir = $(includedir)/@PACKAGE@ pkglibdir = $(libdir)/@PACKAGE@ pkglibexecdir = $(libexecdir)/@PACKAGE@ am__cd = CDPATH="$${ZSH_VERSION+.}$(PATH_SEPARATOR)" && cd install_sh_DATA = $(install_sh) -c -m 644 install_sh_PROGRAM = $(install_sh) -c install_sh_SCRIPT = $(install_sh) -c INSTALL_HEADER = $(INSTALL_DATA) NORMAL_INSTALL = : PRE_INSTALL = : POST_INSTALL = : NORMAL_UNINSTALL = : PRE_UNINSTALL = : POST_UNINSTALL = : build_triplet = @build@ host_triplet = @host@ subdir = etc/couchdb DIST_COMMON = $(srcdir)/Makefile.am $(srcdir)/Makefile.in \ $(srcdir)/default.ini.tpl.in ACLOCAL_M4 = $(top_srcdir)/aclocal.m4 am__aclocal_m4_deps = $(top_srcdir)/m4/libtool.m4 \ $(top_srcdir)/m4/ltoptions.m4 $(top_srcdir)/m4/ltsugar.m4 \ $(top_srcdir)/m4/ltversion.m4 $(top_srcdir)/m4/lt~obsolete.m4 \ $(top_srcdir)/acinclude.m4 $(top_srcdir)/configure.ac am__configure_deps = $(am__aclocal_m4_deps) $(CONFIGURE_DEPENDENCIES) \ $(ACLOCAL_M4) mkinstalldirs = $(install_sh) -d CONFIG_HEADER = $(top_builddir)/config.h \ $(top_builddir)/src/snappy/google-snappy/config.h CONFIG_CLEAN_FILES = default.ini.tpl CONFIG_CLEAN_VPATH_FILES = SOURCES = DIST_SOURCES = am__can_run_installinfo = \ case $$AM_UPDATE_INFO_DIR in \ n|no|NO) false;; \ *) (install-info --version) >/dev/null 2>&1;; \ esac am__vpath_adj_setup = srcdirstrip=`echo "$(srcdir)" | sed 's|.|.|g'`; am__vpath_adj = case $$p in \ $(srcdir)/*) f=`echo "$$p" | sed "s|^$$srcdirstrip/||"`;; \ *) f=$$p;; \ esac; am__strip_dir = f=`echo $$p | sed -e 's|^.*/||'`; am__install_max = 40 am__nobase_strip_setup = \ srcdirstrip=`echo "$(srcdir)" | sed 's/[].[^$$\\*|]/\\\\&/g'` am__nobase_strip = \ for p in $$list; do echo "$$p"; done | sed -e "s|$$srcdirstrip/||" am__nobase_list = $(am__nobase_strip_setup); \ for p in $$list; do echo "$$p $$p"; done | \ sed "s| $$srcdirstrip/| |;"' / .*\//!s/ .*/ ./; s,\( .*\)/[^/]*$$,\1,' | \ $(AWK) 'BEGIN { files["."] = "" } { files[$$2] = files[$$2] " " $$1; \ if (++n[$$2] == $(am__install_max)) \ { print $$2, files[$$2]; n[$$2] = 0; files[$$2] = "" } } \ END { for (dir in files) print dir, files[dir] }' am__base_list = \ sed '$$!N;$$!N;$$!N;$$!N;$$!N;$$!N;$$!N;s/\n/ /g' | \ sed '$$!N;$$!N;$$!N;$$!N;s/\n/ /g' am__uninstall_files_from_dir = { \ test -z "$$files" \ || { test ! -d "$$dir" && test ! -f "$$dir" && test ! -r "$$dir"; } \ || { echo " ( cd '$$dir' && rm -f" $$files ")"; \ $(am__cd) "$$dir" && rm -f $$files; }; \ } am__installdirs = "$(DESTDIR)$(localconfdir)" DATA = $(localconf_DATA) $(noinst_DATA) DISTFILES = $(DIST_COMMON) $(DIST_SOURCES) $(TEXINFOS) $(EXTRA_DIST) transform = @program_transform_name@ ACLOCAL = @ACLOCAL@ AMTAR = @AMTAR@ AR = @AR@ AS = @AS@ AUTOCONF = @AUTOCONF@ AUTOHEADER = @AUTOHEADER@ AUTOMAKE = @AUTOMAKE@ AWK = @AWK@ CC = @CC@ CCDEPMODE = @CCDEPMODE@ CFLAGS = @CFLAGS@ CPP = @CPP@ CPPFLAGS = @CPPFLAGS@ CURL_CFLAGS = @CURL_CFLAGS@ CURL_CONFIG = @CURL_CONFIG@ CURL_LIBS = @CURL_LIBS@ CXX = @CXX@ CXXCPP = @CXXCPP@ CXXDEPMODE = @CXXDEPMODE@ CXXFLAGS = @CXXFLAGS@ CYGPATH_W = @CYGPATH_W@ DEFS = @DEFS@ DEPDIR = @DEPDIR@ DLLTOOL = @DLLTOOL@ DSYMUTIL = @DSYMUTIL@ DUMPBIN = @DUMPBIN@ ECHO_C = @ECHO_C@ ECHO_N = @ECHO_N@ ECHO_T = @ECHO_T@ EGREP = @EGREP@ ERL = @ERL@ ERLANG_FLAGS = @ERLANG_FLAGS@ ERLC = @ERLC@ ERLC_FLAGS = @ERLC_FLAGS@ ESCRIPT = @ESCRIPT@ EXEEXT = @EXEEXT@ FGREP = @FGREP@ FLAGS = @FLAGS@ GREP = @GREP@ HAS_HELP2MAN = @HAS_HELP2MAN@ HAS_INSTALLINFO = @HAS_INSTALLINFO@ HAS_MAKEINFO = @HAS_MAKEINFO@ HAS_PDFLATEX = @HAS_PDFLATEX@ HAS_SPHINX_BUILD = @HAS_SPHINX_BUILD@ ICU_BIN = @ICU_BIN@ ICU_CFLAGS = @ICU_CFLAGS@ ICU_CONFIG = @ICU_CONFIG@ ICU_CPPFLAGS = @ICU_CPPFLAGS@ ICU_CXXFLAGS = @ICU_CXXFLAGS@ ICU_LIBS = @ICU_LIBS@ INNO_COMPILER_EXECUTABLE = @INNO_COMPILER_EXECUTABLE@ INSTALL = @INSTALL@ INSTALL_DATA = @INSTALL_DATA@ INSTALL_PROGRAM = @INSTALL_PROGRAM@ INSTALL_SCRIPT = @INSTALL_SCRIPT@ INSTALL_STRIP_PROGRAM = @INSTALL_STRIP_PROGRAM@ JS_CFLAGS = @JS_CFLAGS@ JS_LIBS = @JS_LIBS@ JS_LIB_BINARY = @JS_LIB_BINARY@ LD = @LD@ LDFLAGS = @LDFLAGS@ LIBOBJS = @LIBOBJS@ LIBS = @LIBS@ LIBTOOL = @LIBTOOL@ LIPO = @LIPO@ LN_S = @LN_S@ LTLIBOBJS = @LTLIBOBJS@ MAKEINFO = @MAKEINFO@ MANIFEST_TOOL = @MANIFEST_TOOL@ MKDIR_P = @MKDIR_P@ NM = @NM@ NMEDIT = @NMEDIT@ OBJDUMP = @OBJDUMP@ OBJEXT = @OBJEXT@ OTOOL = @OTOOL@ OTOOL64 = @OTOOL64@ PACKAGE = @PACKAGE@ PACKAGE_BUGREPORT = @PACKAGE_BUGREPORT@ PACKAGE_NAME = @PACKAGE_NAME@ PACKAGE_STRING = @PACKAGE_STRING@ PACKAGE_TARNAME = @PACKAGE_TARNAME@ PACKAGE_URL = @PACKAGE_URL@ PACKAGE_VERSION = @PACKAGE_VERSION@ PATH_SEPARATOR = @PATH_SEPARATOR@ PKG_CONFIG = @PKG_CONFIG@ PKG_CONFIG_LIBDIR = @PKG_CONFIG_LIBDIR@ PKG_CONFIG_PATH = @PKG_CONFIG_PATH@ RANLIB = @RANLIB@ SED = @SED@ SET_MAKE = @SET_MAKE@ SHELL = @SHELL@ SNAPPY_MAJOR = @SNAPPY_MAJOR@ SNAPPY_MINOR = @SNAPPY_MINOR@ SNAPPY_PATCHLEVEL = @SNAPPY_PATCHLEVEL@ STRIP = @STRIP@ VERSION = @VERSION@ abs_builddir = @abs_builddir@ abs_srcdir = @abs_srcdir@ abs_top_builddir = @abs_top_builddir@ abs_top_srcdir = @abs_top_srcdir@ ac_ct_AR = @ac_ct_AR@ ac_ct_CC = @ac_ct_CC@ ac_ct_CXX = @ac_ct_CXX@ ac_ct_DUMPBIN = @ac_ct_DUMPBIN@ ac_cv_have_stddef_h = @ac_cv_have_stddef_h@ ac_cv_have_stdint_h = @ac_cv_have_stdint_h@ am__include = @am__include@ am__leading_dot = @am__leading_dot@ am__quote = @am__quote@ am__tar = @am__tar@ am__untar = @am__untar@ bindir = @bindir@ bug_uri = @bug_uri@ build = @build@ build_alias = @build_alias@ build_cpu = @build_cpu@ build_os = @build_os@ build_vendor = @build_vendor@ builddir = @builddir@ datadir = @datadir@ datarootdir = @datarootdir@ docdir = @docdir@ dvidir = @dvidir@ erlangbin = @erlangbin@ erlangversion = @erlangversion@ exec_prefix = @exec_prefix@ host = @host@ host_alias = @host_alias@ host_cpu = @host_cpu@ host_os = @host_os@ host_vendor = @host_vendor@ htmldir = @htmldir@ includedir = @includedir@ infodir = @infodir@ initdir = @initdir@ install_sh = @install_sh@ launchddir = @launchddir@ libdir = @libdir@ libexecdir = @libexecdir@ localconfdir = @localconfdir@ localdatadir = @localdatadir@ localdocdir = @localdocdir@ localedir = @localedir@ localerlanglibdir = @localerlanglibdir@ locallibbindir = @locallibbindir@ locallibdir = @locallibdir@ localstatedir = @localstatedir@ localstatelibdir = @localstatelibdir@ localstatelogdir = @localstatelogdir@ localstaterundir = @localstaterundir@ mandir = @mandir@ mkdir_p = @mkdir_p@ msvc_redist_dir = @msvc_redist_dir@ msvc_redist_name = @msvc_redist_name@ oldincludedir = @oldincludedir@ openssl_bin_dir = @openssl_bin_dir@ otp_release = @otp_release@ package_author_address = @package_author_address@ package_author_name = @package_author_name@ package_identifier = @package_identifier@ package_name = @package_name@ package_tarname = @package_tarname@ pdfdir = @pdfdir@ prefix = @prefix@ program_transform_name = @program_transform_name@ psdir = @psdir@ sbindir = @sbindir@ sharedstatedir = @sharedstatedir@ srcdir = @srcdir@ sysconfdir = @sysconfdir@ target_alias = @target_alias@ top_build_prefix = @top_build_prefix@ top_builddir = @top_builddir@ top_srcdir = @top_srcdir@ version = @version@ version_major = @version_major@ version_minor = @version_minor@ version_release = @version_release@ version_revision = @version_revision@ version_stage = @version_stage@ couchprivlibdir = $(localerlanglibdir)/couch-$(version)/priv/lib devcouchprivlibdir = $(abs_top_builddir)/src/couchdb/priv/.libs localconf_DATA = default.ini noinst_DATA = default_dev.ini local_dev.ini EXTRA_DIST = local.ini CLEANFILES = $(localconf_DATA) $(noinst_DATA) couchjs_command_name = `echo couchjs | sed '$(transform)'` couchjs_dev_command_name = `echo couchjs_dev | sed '$(transform)'` all: all-am .SUFFIXES: $(srcdir)/Makefile.in: $(srcdir)/Makefile.am $(am__configure_deps) @for dep in $?; do \ case '$(am__configure_deps)' in \ *$$dep*) \ ( cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh ) \ && { if test -f $@; then exit 0; else break; fi; }; \ exit 1;; \ esac; \ done; \ echo ' cd $(top_srcdir) && $(AUTOMAKE) --foreign etc/couchdb/Makefile'; \ $(am__cd) $(top_srcdir) && \ $(AUTOMAKE) --foreign etc/couchdb/Makefile .PRECIOUS: Makefile Makefile: $(srcdir)/Makefile.in $(top_builddir)/config.status @case '$?' in \ *config.status*) \ cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh;; \ *) \ echo ' cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ $(am__depfiles_maybe)'; \ cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ $(am__depfiles_maybe);; \ esac; $(top_builddir)/config.status: $(top_srcdir)/configure $(CONFIG_STATUS_DEPENDENCIES) cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh $(top_srcdir)/configure: $(am__configure_deps) cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh $(ACLOCAL_M4): $(am__aclocal_m4_deps) cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh $(am__aclocal_m4_deps): default.ini.tpl: $(top_builddir)/config.status $(srcdir)/default.ini.tpl.in cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ mostlyclean-libtool: -rm -f *.lo clean-libtool: -rm -rf .libs _libs install-localconfDATA: $(localconf_DATA) @$(NORMAL_INSTALL) @list='$(localconf_DATA)'; test -n "$(localconfdir)" || list=; \ if test -n "$$list"; then \ echo " $(MKDIR_P) '$(DESTDIR)$(localconfdir)'"; \ $(MKDIR_P) "$(DESTDIR)$(localconfdir)" || exit 1; \ fi; \ for p in $$list; do \ if test -f "$$p"; then d=; else d="$(srcdir)/"; fi; \ echo "$$d$$p"; \ done | $(am__base_list) | \ while read files; do \ echo " $(INSTALL_DATA) $$files '$(DESTDIR)$(localconfdir)'"; \ $(INSTALL_DATA) $$files "$(DESTDIR)$(localconfdir)" || exit $$?; \ done uninstall-localconfDATA: @$(NORMAL_UNINSTALL) @list='$(localconf_DATA)'; test -n "$(localconfdir)" || list=; \ files=`for p in $$list; do echo $$p; done | sed -e 's|^.*/||'`; \ dir='$(DESTDIR)$(localconfdir)'; $(am__uninstall_files_from_dir) tags: TAGS TAGS: ctags: CTAGS CTAGS: distdir: $(DISTFILES) @srcdirstrip=`echo "$(srcdir)" | sed 's/[].[^$$\\*]/\\\\&/g'`; \ topsrcdirstrip=`echo "$(top_srcdir)" | sed 's/[].[^$$\\*]/\\\\&/g'`; \ list='$(DISTFILES)'; \ dist_files=`for file in $$list; do echo $$file; done | \ sed -e "s|^$$srcdirstrip/||;t" \ -e "s|^$$topsrcdirstrip/|$(top_builddir)/|;t"`; \ case $$dist_files in \ */*) $(MKDIR_P) `echo "$$dist_files" | \ sed '/\//!d;s|^|$(distdir)/|;s,/[^/]*$$,,' | \ sort -u` ;; \ esac; \ for file in $$dist_files; do \ if test -f $$file || test -d $$file; then d=.; else d=$(srcdir); fi; \ if test -d $$d/$$file; then \ dir=`echo "/$$file" | sed -e 's,/[^/]*$$,,'`; \ if test -d "$(distdir)/$$file"; then \ find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} \;; \ fi; \ if test -d $(srcdir)/$$file && test $$d != $(srcdir); then \ cp -fpR $(srcdir)/$$file "$(distdir)$$dir" || exit 1; \ find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} \;; \ fi; \ cp -fpR $$d/$$file "$(distdir)$$dir" || exit 1; \ else \ test -f "$(distdir)/$$file" \ || cp -p $$d/$$file "$(distdir)/$$file" \ || exit 1; \ fi; \ done check-am: all-am check: check-am all-am: Makefile $(DATA) installdirs: for dir in "$(DESTDIR)$(localconfdir)"; do \ test -z "$$dir" || $(MKDIR_P) "$$dir"; \ done install: install-am install-exec: install-exec-am install-data: install-data-am uninstall: uninstall-am install-am: all-am @$(MAKE) $(AM_MAKEFLAGS) install-exec-am install-data-am installcheck: installcheck-am install-strip: if test -z '$(STRIP)'; then \ $(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(INSTALL_STRIP_PROGRAM)" \ install_sh_PROGRAM="$(INSTALL_STRIP_PROGRAM)" INSTALL_STRIP_FLAG=-s \ install; \ else \ $(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(INSTALL_STRIP_PROGRAM)" \ install_sh_PROGRAM="$(INSTALL_STRIP_PROGRAM)" INSTALL_STRIP_FLAG=-s \ "INSTALL_PROGRAM_ENV=STRIPPROG='$(STRIP)'" install; \ fi mostlyclean-generic: clean-generic: -test -z "$(CLEANFILES)" || rm -f $(CLEANFILES) distclean-generic: -test -z "$(CONFIG_CLEAN_FILES)" || rm -f $(CONFIG_CLEAN_FILES) -test . = "$(srcdir)" || test -z "$(CONFIG_CLEAN_VPATH_FILES)" || rm -f $(CONFIG_CLEAN_VPATH_FILES) maintainer-clean-generic: @echo "This command is intended for maintainers to use" @echo "it deletes files that may require special tools to rebuild." clean: clean-am clean-am: clean-generic clean-libtool mostlyclean-am distclean: distclean-am -rm -f Makefile distclean-am: clean-am distclean-generic dvi: dvi-am dvi-am: html: html-am html-am: info: info-am info-am: install-data-am: install-localconfDATA @$(NORMAL_INSTALL) $(MAKE) $(AM_MAKEFLAGS) install-data-hook install-dvi: install-dvi-am install-dvi-am: install-exec-am: install-html: install-html-am install-html-am: install-info: install-info-am install-info-am: install-man: install-pdf: install-pdf-am install-pdf-am: install-ps: install-ps-am install-ps-am: installcheck-am: maintainer-clean: maintainer-clean-am -rm -f Makefile maintainer-clean-am: distclean-am maintainer-clean-generic mostlyclean: mostlyclean-am mostlyclean-am: mostlyclean-generic mostlyclean-libtool pdf: pdf-am pdf-am: ps: ps-am ps-am: uninstall-am: uninstall-local uninstall-localconfDATA .MAKE: install-am install-data-am install-strip .PHONY: all all-am check check-am clean clean-generic clean-libtool \ distclean distclean-generic distclean-libtool distdir dvi \ dvi-am html html-am info info-am install install-am \ install-data install-data-am install-data-hook install-dvi \ install-dvi-am install-exec install-exec-am install-html \ install-html-am install-info install-info-am \ install-localconfDATA install-man install-pdf install-pdf-am \ install-ps install-ps-am install-strip installcheck \ installcheck-am installdirs maintainer-clean \ maintainer-clean-generic mostlyclean mostlyclean-generic \ mostlyclean-libtool pdf pdf-am ps ps-am uninstall uninstall-am \ uninstall-local uninstall-localconfDATA @WINDOWS_TRUE@default.ini: default.ini.tpl @WINDOWS_TRUE@ sed -e "s|%bindir%|.|g" \ @WINDOWS_TRUE@ -e "s|%localconfdir%|$(localconfdir)|g" \ @WINDOWS_TRUE@ -e "s|%localdatadir%|../share/couchdb|g" \ @WINDOWS_TRUE@ -e "s|%localbuilddatadir%|../share/couchdb|g" \ @WINDOWS_TRUE@ -e "s|%localstatelibdir%|../var/lib/couchdb|g" \ @WINDOWS_TRUE@ -e "s|%localstatelogdir%|../var/log/couchdb|g" \ @WINDOWS_TRUE@ -e "s|%localstaterundir%|../var/run/couchdb|g" \ @WINDOWS_TRUE@ -e "s|%couchprivlibdir%|../lib/couch-$(version)/priv/lib|g" \ @WINDOWS_TRUE@ -e "s|%couchjs_command_name%|couchjs.exe|g" \ @WINDOWS_TRUE@ -e "s|%package_author_name%|$(package_author_name)|g" \ @WINDOWS_TRUE@ -e "s|%version%|$(version)|g" \ @WINDOWS_TRUE@ < $< > $@ @WINDOWS_FALSE@default.ini: default.ini.tpl @WINDOWS_FALSE@ sed -e "s|%bindir%|$(bindir)|g" \ @WINDOWS_FALSE@ -e "s|%localconfdir%|$(localconfdir)|g" \ @WINDOWS_FALSE@ -e "s|%localdatadir%|$(localdatadir)|g" \ @WINDOWS_FALSE@ -e "s|%localbuilddatadir%|$(localdatadir)|g" \ @WINDOWS_FALSE@ -e "s|%locallibdir%|$(locallibdir)|g" \ @WINDOWS_FALSE@ -e "s|%localstatelibdir%|$(localstatelibdir)|g" \ @WINDOWS_FALSE@ -e "s|%localstatelogdir%|$(localstatelogdir)|g" \ @WINDOWS_FALSE@ -e "s|%localstaterundir%|$(localstaterundir)|g" \ @WINDOWS_FALSE@ -e "s|%couchprivlibdir%|$(couchprivlibdir)|g" \ @WINDOWS_FALSE@ -e "s|%couchjs_command_name%|$(couchjs_command_name)|g" \ @WINDOWS_FALSE@ -e "s|%package_author_name%|$(package_author_name)|g" \ @WINDOWS_FALSE@ -e "s|%version%|$(version)|g" \ @WINDOWS_FALSE@ < $< > $@ default_dev.ini: default.ini.tpl sed -e "s|%bindir%|$(abs_top_builddir)/bin|g" \ -e "s|%localconfdir%|$(abs_top_builddir)/etc/couchdb|g" \ -e "s|%localdatadir%|$(abs_top_srcdir)/share|g" \ -e "s|%locallibdir%|$(abs_top_builddir)/tmp|g" \ -e "s|%localbuilddatadir%|$(abs_top_builddir)/share|g" \ -e "s|%localstatelibdir%|$(abs_top_builddir)/tmp/lib|g" \ -e "s|%localstatelogdir%|$(abs_top_builddir)/tmp/log|g" \ -e "s|%localstaterundir%|$(abs_top_builddir)/tmp/run|g" \ -e "s|%couchprivlibdir%|$(devcouchprivlibdir)|g" \ -e "s|%couchjs_command_name%|$(couchjs_dev_command_name)|g" \ -e "s|%package_author_name%|$(package_author_name)|g" \ -e "s|%version%|$(version)|g" \ < $< > $@ # Noah said to not specify local.ini but it borks # VPATH builds that make distcheck uses. local_dev.ini: local.ini if test ! -f "$@"; then \ cp $< $@; \ chmod +w $@; \ fi install-data-hook: if test ! -f "$(DESTDIR)$(localconfdir)/local.ini"; then \ cp $(srcdir)/local.ini "$(DESTDIR)$(localconfdir)/local.ini"; \ fi if test ! "$(mkdir_p)" = ""; then \ $(mkdir_p) "$(DESTDIR)$(localconfdir)/default.d"; \ $(mkdir_p) "$(DESTDIR)$(localconfdir)/local.d"; \ else \ echo "WARNING: You may have to create these directories by hand."; \ mkdir -p "$(DESTDIR)$(localconfdir)/default.d"; \ mkdir -p "$(DESTDIR)$(localconfdir)/local.d"; \ fi uninstall-local: rm -f "$(DESTDIR)/$(localconfdir)/local.ini" # Tell versions [3.59,3.63) of GNU make to not export all variables. # Otherwise a system limit (for SysV at least) may be exceeded. .NOEXPORT: apache-couchdb-1.5.0/etc/couchdb/local.ini0000644000175000001440000000721712230722213015236 00000000000000; CouchDB Configuration Settings ; Custom settings should be made in this file. They will override settings ; in default.ini, but unlike changes made to default.ini, this file won't be ; overwritten on server upgrade. [couchdb] ;max_document_size = 4294967296 ; bytes [httpd] ;port = 5984 ;bind_address = 127.0.0.1 ; Options for the MochiWeb HTTP server. ;server_options = [{backlog, 128}, {acceptor_pool_size, 16}] ; For more socket options, consult Erlang's module 'inet' man page. ;socket_options = [{recbuf, 262144}, {sndbuf, 262144}, {nodelay, true}] ; Uncomment next line to trigger basic-auth popup on unauthorized requests. ;WWW-Authenticate = Basic realm="administrator" ; Uncomment next line to set the configuration modification whitelist. Only ; whitelisted values may be changed via the /_config URLs. To allow the admin ; to change this value over HTTP, remember to include {httpd,config_whitelist} ; itself. Excluding it from the list would require editing this file to update ; the whitelist. ;config_whitelist = [{httpd,config_whitelist}, {log,level}, {etc,etc}] [query_servers] ;nodejs = /usr/local/bin/couchjs-node /path/to/couchdb/share/server/main.js [httpd_global_handlers] ;_google = {couch_httpd_proxy, handle_proxy_req, <<"http://www.google.com">>} [couch_httpd_auth] ; If you set this to true, you should also uncomment the WWW-Authenticate line ; above. If you don't configure a WWW-Authenticate header, CouchDB will send ; Basic realm="server" in order to prevent you getting logged out. ; require_valid_user = false [log] ;level = debug [log_level_by_module] ; In this section you can specify any of the four log levels 'none', 'info', ; 'error' or 'debug' on a per-module basis. See src/*/*.erl for various ; modules. ;couch_httpd = error [os_daemons] ; For any commands listed here, CouchDB will attempt to ensure that ; the process remains alive. Daemons should monitor their environment ; to know when to exit. This can most easily be accomplished by exiting ; when stdin is closed. ;foo = /path/to/command -with args [daemons] ; enable SSL support by uncommenting the following line and supply the PEM's below. ; the default ssl port CouchDB listens on is 6984 ; httpsd = {couch_httpd, start_link, [https]} [ssl] ;cert_file = /full/path/to/server_cert.pem ;key_file = /full/path/to/server_key.pem ;password = somepassword ; set to true to validate peer certificates verify_ssl_certificates = false ; Path to file containing PEM encoded CA certificates (trusted ; certificates used for verifying a peer certificate). May be omitted if ; you do not want to verify the peer. ;cacert_file = /full/path/to/cacertf ; The verification fun (optional) if not specified, the default ; verification fun will be used. ;verify_fun = {Module, VerifyFun} ; maximum peer certificate depth ssl_certificate_max_depth = 1 ; To enable Virtual Hosts in CouchDB, add a vhost = path directive. All requests to ; the Virual Host will be redirected to the path. In the example below all requests ; to http://example.com/ are redirected to /database. ; If you run CouchDB on a specific port, include the port number in the vhost: ; example.com:5984 = /database [vhosts] ;example.com = /database/ [update_notification] ;unique notifier name=/full/path/to/exe -with "cmd line arg" ; To create an admin account uncomment the '[admins]' section below and add a ; line in the format 'username = password'. When you next start CouchDB, it ; will change the password to a hash (so that your passwords don't linger ; around in plain-text files). You can add more admin accounts with more ; 'username = password' lines. Don't forget to restart CouchDB after ; changing this. [admins] ;admin = mysecretpassword apache-couchdb-1.5.0/etc/couchdb/default.ini.tpl.in0000644000175000001440000003542312230722213016773 00000000000000; @configure_input@ ; Upgrading CouchDB will overwrite this file. [vendor] name = %package_author_name% version = %version% [couchdb] database_dir = %localstatelibdir% view_index_dir = %localstatelibdir% util_driver_dir = %couchprivlibdir% max_document_size = 4294967296 ; 4 GB os_process_timeout = 5000 ; 5 seconds. for view and external servers. max_dbs_open = 100 delayed_commits = true ; set this to false to ensure an fsync before 201 Created is returned uri_file = %localstaterundir%/couch.uri ; Method used to compress everything that is appended to database and view index files, except ; for attachments (see the attachments section). Available methods are: ; ; none - no compression ; snappy - use google snappy, a very fast compressor/decompressor ; deflate_[N] - use zlib's deflate, N is the compression level which ranges from 1 (fastest, ; lowest compression ratio) to 9 (slowest, highest compression ratio) file_compression = snappy ; Higher values may give better read performance due to less read operations ; and/or more OS page cache hits, but they can also increase overall response ; time for writes when there are many attachment write requests in parallel. attachment_stream_buffer_size = 4096 plugin_dir = %locallibdir%/plugins [database_compaction] ; larger buffer sizes can originate smaller files doc_buffer_size = 524288 ; value in bytes checkpoint_after = 5242880 ; checkpoint after every N bytes were written [view_compaction] ; larger buffer sizes can originate smaller files keyvalue_buffer_size = 2097152 ; value in bytes [httpd] port = 5984 bind_address = 127.0.0.1 authentication_handlers = {couch_httpd_oauth, oauth_authentication_handler}, {couch_httpd_auth, cookie_authentication_handler}, {couch_httpd_auth, default_authentication_handler} default_handler = {couch_httpd_db, handle_request} secure_rewrites = true vhost_global_handlers = _utils, _uuids, _session, _oauth, _users allow_jsonp = false ; Options for the MochiWeb HTTP server. ;server_options = [{backlog, 128}, {acceptor_pool_size, 16}] ; For more socket options, consult Erlang's module 'inet' man page. ;socket_options = [{recbuf, 262144}, {sndbuf, 262144}, {nodelay, true}] log_max_chunk_size = 1000000 enable_cors = false [ssl] port = 6984 [log] file = %localstatelogdir%/couch.log level = info include_sasl = true [couch_httpd_auth] authentication_db = _users authentication_redirect = /_utils/session.html require_valid_user = false timeout = 600 ; number of seconds before automatic logout auth_cache_size = 50 ; size is number of cache entries allow_persistent_cookies = false ; set to true to allow persistent cookies iterations = 10 ; iterations for password hashing ; comma-separated list of public fields, 404 if empty ; public_fields = [cors] credentials = false ; List of origins separated by a comma, * means accept all ; Origins must include the scheme: http://example.com ; You can’t set origins: * and credentials = true at the same time. ;origins = * ; List of accepted headers separated by a comma ; headers = ; List of accepted methods ; methods = ; Configuration for a vhost ;[cors:http://example.com] ; credentials = false ; List of origins separated by a comma ; Origins must include the scheme: http://example.com ; You can’t set origins: * and credentials = true at the same time. ;origins = ; List of accepted headers separated by a comma ; headers = ; List of accepted methods ; methods = [couch_httpd_oauth] ; If set to 'true', oauth token and consumer secrets will be looked up ; in the authentication database (_users). These secrets are stored in ; a top level property named "oauth" in user documents. Example: ; { ; "_id": "org.couchdb.user:joe", ; "type": "user", ; "name": "joe", ; "password_sha": "fe95df1ca59a9b567bdca5cbaf8412abd6e06121", ; "salt": "4e170ffeb6f34daecfd814dfb4001a73" ; "roles": ["foo", "bar"], ; "oauth": { ; "consumer_keys": { ; "consumerKey1": "key1Secret", ; "consumerKey2": "key2Secret" ; }, ; "tokens": { ; "token1": "token1Secret", ; "token2": "token2Secret" ; } ; } ; } use_users_db = false [query_servers] javascript = %bindir%/%couchjs_command_name% %localbuilddatadir%/server/main.js coffeescript = %bindir%/%couchjs_command_name% %localbuilddatadir%/server/main-coffee.js ; Changing reduce_limit to false will disable reduce_limit. ; If you think you're hitting reduce_limit with a "good" reduce function, ; please let us know on the mailing list so we can fine tune the heuristic. [query_server_config] reduce_limit = true os_process_limit = 25 [daemons] index_server={couch_index_server, start_link, []} external_manager={couch_external_manager, start_link, []} query_servers={couch_query_servers, start_link, []} vhosts={couch_httpd_vhost, start_link, []} httpd={couch_httpd, start_link, []} stats_aggregator={couch_stats_aggregator, start, []} stats_collector={couch_stats_collector, start, []} uuids={couch_uuids, start, []} auth_cache={couch_auth_cache, start_link, []} replicator_manager={couch_replicator_manager, start_link, []} os_daemons={couch_os_daemons, start_link, []} compaction_daemon={couch_compaction_daemon, start_link, []} [httpd_global_handlers] / = {couch_httpd_misc_handlers, handle_welcome_req, <<"Welcome">>} favicon.ico = {couch_httpd_misc_handlers, handle_favicon_req, "%localdatadir%/www"} _utils = {couch_httpd_misc_handlers, handle_utils_dir_req, "%localdatadir%/www"} _all_dbs = {couch_httpd_misc_handlers, handle_all_dbs_req} _active_tasks = {couch_httpd_misc_handlers, handle_task_status_req} _config = {couch_httpd_misc_handlers, handle_config_req} _replicate = {couch_replicator_httpd, handle_req} _uuids = {couch_httpd_misc_handlers, handle_uuids_req} _restart = {couch_httpd_misc_handlers, handle_restart_req} _stats = {couch_httpd_stats_handlers, handle_stats_req} _log = {couch_httpd_misc_handlers, handle_log_req} _session = {couch_httpd_auth, handle_session_req} _oauth = {couch_httpd_oauth, handle_oauth_req} _db_updates = {couch_dbupdates_httpd, handle_req} _plugins = {couch_plugins_httpd, handle_req} [httpd_db_handlers] _all_docs = {couch_mrview_http, handle_all_docs_req} _changes = {couch_httpd_db, handle_changes_req} _compact = {couch_httpd_db, handle_compact_req} _design = {couch_httpd_db, handle_design_req} _temp_view = {couch_mrview_http, handle_temp_view_req} _view_cleanup = {couch_mrview_http, handle_cleanup_req} ; The external module takes an optional argument allowing you to narrow it to a ; single script. Otherwise the script name is inferred from the first path section ; after _external's own path. ; _mypath = {couch_httpd_external, handle_external_req, <<"mykey">>} ; _external = {couch_httpd_external, handle_external_req} [httpd_design_handlers] _compact = {couch_mrview_http, handle_compact_req} _info = {couch_mrview_http, handle_info_req} _list = {couch_mrview_show, handle_view_list_req} _rewrite = {couch_httpd_rewrite, handle_rewrite_req} _show = {couch_mrview_show, handle_doc_show_req} _update = {couch_mrview_show, handle_doc_update_req} _view = {couch_mrview_http, handle_view_req} ; enable external as an httpd handler, then link it with commands here. ; note, this api is still under consideration. ; [external] ; mykey = /path/to/mycommand ; Here you can setup commands for CouchDB to manage ; while it is alive. It will attempt to keep each command ; alive if it exits. ; [os_daemons] ; some_daemon_name = /path/to/script -with args [uuids] ; Known algorithms: ; random - 128 bits of random awesome ; All awesome, all the time. ; sequential - monotonically increasing ids with random increments ; First 26 hex characters are random. Last 6 increment in ; random amounts until an overflow occurs. On overflow, the ; random prefix is regenerated and the process starts over. ; utc_random - Time since Jan 1, 1970 UTC with microseconds ; First 14 characters are the time in hex. Last 18 are random. ; utc_id - Time since Jan 1, 1970 UTC with microseconds, plus utc_id_suffix string ; First 14 characters are the time in hex. uuids/utc_id_suffix string value is appended to these. algorithm = sequential ; The utc_id_suffix value will be appended to uuids generated by the utc_id algorithm. ; Replicating instances should have unique utc_id_suffix values to ensure uniqueness of utc_id ids. utc_id_suffix = [stats] ; rate is in milliseconds rate = 1000 ; sample intervals are in seconds samples = [0, 60, 300, 900] [attachments] compression_level = 8 ; from 1 (lowest, fastest) to 9 (highest, slowest), 0 to disable compression compressible_types = text/*, application/javascript, application/json, application/xml [replicator] db = _replicator ; Maximum replicaton retry count can be a non-negative integer or "infinity". max_replication_retry_count = 10 ; More worker processes can give higher network throughput but can also ; imply more disk and network IO. worker_processes = 4 ; With lower batch sizes checkpoints are done more frequently. Lower batch sizes ; also reduce the total amount of used RAM memory. worker_batch_size = 500 ; Maximum number of HTTP connections per replication. http_connections = 20 ; HTTP connection timeout per replication. ; Even for very fast/reliable networks it might need to be increased if a remote ; database is too busy. connection_timeout = 30000 ; If a request fails, the replicator will retry it up to N times. retries_per_request = 10 ; Some socket options that might boost performance in some scenarios: ; {nodelay, boolean()} ; {sndbuf, integer()} ; {recbuf, integer()} ; {priority, integer()} ; See the `inet` Erlang module's man page for the full list of options. socket_options = [{keepalive, true}, {nodelay, false}] ; Path to a file containing the user's certificate. ;cert_file = /full/path/to/server_cert.pem ; Path to file containing user's private PEM encoded key. ;key_file = /full/path/to/server_key.pem ; String containing the user's password. Only used if the private keyfile is password protected. ;password = somepassword ; Set to true to validate peer certificates. verify_ssl_certificates = false ; File containing a list of peer trusted certificates (in the PEM format). ;ssl_trusted_certificates_file = /etc/ssl/certs/ca-certificates.crt ; Maximum peer certificate depth (must be set even if certificate validation is off). ssl_certificate_max_depth = 3 [compaction_daemon] ; The delay, in seconds, between each check for which database and view indexes ; need to be compacted. check_interval = 300 ; If a database or view index file is smaller then this value (in bytes), ; compaction will not happen. Very small files always have a very high ; fragmentation therefore it's not worth to compact them. min_file_size = 131072 [compactions] ; List of compaction rules for the compaction daemon. ; The daemon compacts databases and their respective view groups when all the ; condition parameters are satisfied. Configuration can be per database or ; global, and it has the following format: ; ; database_name = [ {ParamName, ParamValue}, {ParamName, ParamValue}, ... ] ; _default = [ {ParamName, ParamValue}, {ParamName, ParamValue}, ... ] ; ; Possible parameters: ; ; * db_fragmentation - If the ratio (as an integer percentage), of the amount ; of old data (and its supporting metadata) over the database ; file size is equal to or greater then this value, this ; database compaction condition is satisfied. ; This value is computed as: ; ; (file_size - data_size) / file_size * 100 ; ; The data_size and file_size values can be obtained when ; querying a database's information URI (GET /dbname/). ; ; * view_fragmentation - If the ratio (as an integer percentage), of the amount ; of old data (and its supporting metadata) over the view ; index (view group) file size is equal to or greater then ; this value, then this view index compaction condition is ; satisfied. This value is computed as: ; ; (file_size - data_size) / file_size * 100 ; ; The data_size and file_size values can be obtained when ; querying a view group's information URI ; (GET /dbname/_design/groupname/_info). ; ; * from _and_ to - The period for which a database (and its view groups) compaction ; is allowed. The value for these parameters must obey the format: ; ; HH:MM - HH:MM (HH in [0..23], MM in [0..59]) ; ; * strict_window - If a compaction is still running after the end of the allowed ; period, it will be canceled if this parameter is set to 'true'. ; It defaults to 'false' and it's meaningful only if the *period* ; parameter is also specified. ; ; * parallel_view_compaction - If set to 'true', the database and its views are ; compacted in parallel. This is only useful on ; certain setups, like for example when the database ; and view index directories point to different ; disks. It defaults to 'false'. ; ; Before a compaction is triggered, an estimation of how much free disk space is ; needed is computed. This estimation corresponds to 2 times the data size of ; the database or view index. When there's not enough free disk space to compact ; a particular database or view index, a warning message is logged. ; ; Examples: ; ; 1) [{db_fragmentation, "70%"}, {view_fragmentation, "60%"}] ; The `foo` database is compacted if its fragmentation is 70% or more. ; Any view index of this database is compacted only if its fragmentation ; is 60% or more. ; ; 2) [{db_fragmentation, "70%"}, {view_fragmentation, "60%"}, {from, "00:00"}, {to, "04:00"}] ; Similar to the preceding example but a compaction (database or view index) ; is only triggered if the current time is between midnight and 4 AM. ; ; 3) [{db_fragmentation, "70%"}, {view_fragmentation, "60%"}, {from, "00:00"}, {to, "04:00"}, {strict_window, true}] ; Similar to the preceding example - a compaction (database or view index) ; is only triggered if the current time is between midnight and 4 AM. If at ; 4 AM the database or one of its views is still compacting, the compaction ; process will be canceled. ; ; 4) [{db_fragmentation, "70%"}, {view_fragmentation, "60%"}, {from, "00:00"}, {to, "04:00"}, {strict_window, true}, {parallel_view_compaction, true}] ; Similar to the preceding example, but a database and its views can be ; compacted in parallel. ; ;_default = [{db_fragmentation, "70%"}, {view_fragmentation, "60%"}, {from, "23:00"}, {to, "04:00"}] apache-couchdb-1.5.0/etc/launchd/0000755000175000001440000000000012230722302013522 500000000000000apache-couchdb-1.5.0/etc/launchd/org.apache.couchdb.plist.tpl.in0000644000175000001440000000147312230722213021345 00000000000000 Label org.apache.couchdb EnvironmentVariables HOME ~ DYLD_LIBRARY_PATH /opt/local/lib:$DYLD_LIBRARY_PATH ProgramArguments %bindir%/%couchdb_command_name% UserName couchdb StandardOutPath /dev/null StandardErrorPath /dev/null RunAtLoad KeepAlive apache-couchdb-1.5.0/etc/launchd/Makefile.am0000644000175000001440000000112112230722213015472 00000000000000## 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. ## This file intentionally left blank. apache-couchdb-1.5.0/etc/launchd/Makefile.in0000644000175000001440000003046612230722242015523 00000000000000# Makefile.in generated by automake 1.11.6 from Makefile.am. # @configure_input@ # Copyright (C) 1994, 1995, 1996, 1997, 1998, 1999, 2000, 2001, 2002, # 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011 Free Software # Foundation, Inc. # This Makefile.in is free software; the Free Software Foundation # gives unlimited permission to copy and/or distribute it, # with or without modifications, as long as this notice is preserved. # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY, to the extent permitted by law; without # even the implied warranty of MERCHANTABILITY or FITNESS FOR A # PARTICULAR PURPOSE. @SET_MAKE@ VPATH = @srcdir@ am__make_dryrun = \ { \ am__dry=no; \ case $$MAKEFLAGS in \ *\\[\ \ ]*) \ echo 'am--echo: ; @echo "AM" OK' | $(MAKE) -f - 2>/dev/null \ | grep '^AM OK$$' >/dev/null || am__dry=yes;; \ *) \ for am__flg in $$MAKEFLAGS; do \ case $$am__flg in \ *=*|--*) ;; \ *n*) am__dry=yes; break;; \ esac; \ done;; \ esac; \ test $$am__dry = yes; \ } pkgdatadir = $(datadir)/@PACKAGE@ pkgincludedir = $(includedir)/@PACKAGE@ pkglibdir = $(libdir)/@PACKAGE@ pkglibexecdir = $(libexecdir)/@PACKAGE@ am__cd = CDPATH="$${ZSH_VERSION+.}$(PATH_SEPARATOR)" && cd install_sh_DATA = $(install_sh) -c -m 644 install_sh_PROGRAM = $(install_sh) -c install_sh_SCRIPT = $(install_sh) -c INSTALL_HEADER = $(INSTALL_DATA) transform = $(program_transform_name) NORMAL_INSTALL = : PRE_INSTALL = : POST_INSTALL = : NORMAL_UNINSTALL = : PRE_UNINSTALL = : POST_UNINSTALL = : build_triplet = @build@ host_triplet = @host@ subdir = etc/launchd DIST_COMMON = $(srcdir)/Makefile.am $(srcdir)/Makefile.in \ $(srcdir)/org.apache.couchdb.plist.tpl.in ACLOCAL_M4 = $(top_srcdir)/aclocal.m4 am__aclocal_m4_deps = $(top_srcdir)/m4/libtool.m4 \ $(top_srcdir)/m4/ltoptions.m4 $(top_srcdir)/m4/ltsugar.m4 \ $(top_srcdir)/m4/ltversion.m4 $(top_srcdir)/m4/lt~obsolete.m4 \ $(top_srcdir)/acinclude.m4 $(top_srcdir)/configure.ac am__configure_deps = $(am__aclocal_m4_deps) $(CONFIGURE_DEPENDENCIES) \ $(ACLOCAL_M4) mkinstalldirs = $(install_sh) -d CONFIG_HEADER = $(top_builddir)/config.h \ $(top_builddir)/src/snappy/google-snappy/config.h CONFIG_CLEAN_FILES = org.apache.couchdb.plist.tpl CONFIG_CLEAN_VPATH_FILES = SOURCES = DIST_SOURCES = am__can_run_installinfo = \ case $$AM_UPDATE_INFO_DIR in \ n|no|NO) false;; \ *) (install-info --version) >/dev/null 2>&1;; \ esac DISTFILES = $(DIST_COMMON) $(DIST_SOURCES) $(TEXINFOS) $(EXTRA_DIST) ACLOCAL = @ACLOCAL@ AMTAR = @AMTAR@ AR = @AR@ AS = @AS@ AUTOCONF = @AUTOCONF@ AUTOHEADER = @AUTOHEADER@ AUTOMAKE = @AUTOMAKE@ AWK = @AWK@ CC = @CC@ CCDEPMODE = @CCDEPMODE@ CFLAGS = @CFLAGS@ CPP = @CPP@ CPPFLAGS = @CPPFLAGS@ CURL_CFLAGS = @CURL_CFLAGS@ CURL_CONFIG = @CURL_CONFIG@ CURL_LIBS = @CURL_LIBS@ CXX = @CXX@ CXXCPP = @CXXCPP@ CXXDEPMODE = @CXXDEPMODE@ CXXFLAGS = @CXXFLAGS@ CYGPATH_W = @CYGPATH_W@ DEFS = @DEFS@ DEPDIR = @DEPDIR@ DLLTOOL = @DLLTOOL@ DSYMUTIL = @DSYMUTIL@ DUMPBIN = @DUMPBIN@ ECHO_C = @ECHO_C@ ECHO_N = @ECHO_N@ ECHO_T = @ECHO_T@ EGREP = @EGREP@ ERL = @ERL@ ERLANG_FLAGS = @ERLANG_FLAGS@ ERLC = @ERLC@ ERLC_FLAGS = @ERLC_FLAGS@ ESCRIPT = @ESCRIPT@ EXEEXT = @EXEEXT@ FGREP = @FGREP@ FLAGS = @FLAGS@ GREP = @GREP@ HAS_HELP2MAN = @HAS_HELP2MAN@ HAS_INSTALLINFO = @HAS_INSTALLINFO@ HAS_MAKEINFO = @HAS_MAKEINFO@ HAS_PDFLATEX = @HAS_PDFLATEX@ HAS_SPHINX_BUILD = @HAS_SPHINX_BUILD@ ICU_BIN = @ICU_BIN@ ICU_CFLAGS = @ICU_CFLAGS@ ICU_CONFIG = @ICU_CONFIG@ ICU_CPPFLAGS = @ICU_CPPFLAGS@ ICU_CXXFLAGS = @ICU_CXXFLAGS@ ICU_LIBS = @ICU_LIBS@ INNO_COMPILER_EXECUTABLE = @INNO_COMPILER_EXECUTABLE@ INSTALL = @INSTALL@ INSTALL_DATA = @INSTALL_DATA@ INSTALL_PROGRAM = @INSTALL_PROGRAM@ INSTALL_SCRIPT = @INSTALL_SCRIPT@ INSTALL_STRIP_PROGRAM = @INSTALL_STRIP_PROGRAM@ JS_CFLAGS = @JS_CFLAGS@ JS_LIBS = @JS_LIBS@ JS_LIB_BINARY = @JS_LIB_BINARY@ LD = @LD@ LDFLAGS = @LDFLAGS@ LIBOBJS = @LIBOBJS@ LIBS = @LIBS@ LIBTOOL = @LIBTOOL@ LIPO = @LIPO@ LN_S = @LN_S@ LTLIBOBJS = @LTLIBOBJS@ MAKEINFO = @MAKEINFO@ MANIFEST_TOOL = @MANIFEST_TOOL@ MKDIR_P = @MKDIR_P@ NM = @NM@ NMEDIT = @NMEDIT@ OBJDUMP = @OBJDUMP@ OBJEXT = @OBJEXT@ OTOOL = @OTOOL@ OTOOL64 = @OTOOL64@ PACKAGE = @PACKAGE@ PACKAGE_BUGREPORT = @PACKAGE_BUGREPORT@ PACKAGE_NAME = @PACKAGE_NAME@ PACKAGE_STRING = @PACKAGE_STRING@ PACKAGE_TARNAME = @PACKAGE_TARNAME@ PACKAGE_URL = @PACKAGE_URL@ PACKAGE_VERSION = @PACKAGE_VERSION@ PATH_SEPARATOR = @PATH_SEPARATOR@ PKG_CONFIG = @PKG_CONFIG@ PKG_CONFIG_LIBDIR = @PKG_CONFIG_LIBDIR@ PKG_CONFIG_PATH = @PKG_CONFIG_PATH@ RANLIB = @RANLIB@ SED = @SED@ SET_MAKE = @SET_MAKE@ SHELL = @SHELL@ SNAPPY_MAJOR = @SNAPPY_MAJOR@ SNAPPY_MINOR = @SNAPPY_MINOR@ SNAPPY_PATCHLEVEL = @SNAPPY_PATCHLEVEL@ STRIP = @STRIP@ VERSION = @VERSION@ abs_builddir = @abs_builddir@ abs_srcdir = @abs_srcdir@ abs_top_builddir = @abs_top_builddir@ abs_top_srcdir = @abs_top_srcdir@ ac_ct_AR = @ac_ct_AR@ ac_ct_CC = @ac_ct_CC@ ac_ct_CXX = @ac_ct_CXX@ ac_ct_DUMPBIN = @ac_ct_DUMPBIN@ ac_cv_have_stddef_h = @ac_cv_have_stddef_h@ ac_cv_have_stdint_h = @ac_cv_have_stdint_h@ am__include = @am__include@ am__leading_dot = @am__leading_dot@ am__quote = @am__quote@ am__tar = @am__tar@ am__untar = @am__untar@ bindir = @bindir@ bug_uri = @bug_uri@ build = @build@ build_alias = @build_alias@ build_cpu = @build_cpu@ build_os = @build_os@ build_vendor = @build_vendor@ builddir = @builddir@ datadir = @datadir@ datarootdir = @datarootdir@ docdir = @docdir@ dvidir = @dvidir@ erlangbin = @erlangbin@ erlangversion = @erlangversion@ exec_prefix = @exec_prefix@ host = @host@ host_alias = @host_alias@ host_cpu = @host_cpu@ host_os = @host_os@ host_vendor = @host_vendor@ htmldir = @htmldir@ includedir = @includedir@ infodir = @infodir@ initdir = @initdir@ install_sh = @install_sh@ launchddir = @launchddir@ libdir = @libdir@ libexecdir = @libexecdir@ localconfdir = @localconfdir@ localdatadir = @localdatadir@ localdocdir = @localdocdir@ localedir = @localedir@ localerlanglibdir = @localerlanglibdir@ locallibbindir = @locallibbindir@ locallibdir = @locallibdir@ localstatedir = @localstatedir@ localstatelibdir = @localstatelibdir@ localstatelogdir = @localstatelogdir@ localstaterundir = @localstaterundir@ mandir = @mandir@ mkdir_p = @mkdir_p@ msvc_redist_dir = @msvc_redist_dir@ msvc_redist_name = @msvc_redist_name@ oldincludedir = @oldincludedir@ openssl_bin_dir = @openssl_bin_dir@ otp_release = @otp_release@ package_author_address = @package_author_address@ package_author_name = @package_author_name@ package_identifier = @package_identifier@ package_name = @package_name@ package_tarname = @package_tarname@ pdfdir = @pdfdir@ prefix = @prefix@ program_transform_name = @program_transform_name@ psdir = @psdir@ sbindir = @sbindir@ sharedstatedir = @sharedstatedir@ srcdir = @srcdir@ sysconfdir = @sysconfdir@ target_alias = @target_alias@ top_build_prefix = @top_build_prefix@ top_builddir = @top_builddir@ top_srcdir = @top_srcdir@ version = @version@ version_major = @version_major@ version_minor = @version_minor@ version_release = @version_release@ version_revision = @version_revision@ version_stage = @version_stage@ all: all-am .SUFFIXES: $(srcdir)/Makefile.in: $(srcdir)/Makefile.am $(am__configure_deps) @for dep in $?; do \ case '$(am__configure_deps)' in \ *$$dep*) \ ( cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh ) \ && { if test -f $@; then exit 0; else break; fi; }; \ exit 1;; \ esac; \ done; \ echo ' cd $(top_srcdir) && $(AUTOMAKE) --foreign etc/launchd/Makefile'; \ $(am__cd) $(top_srcdir) && \ $(AUTOMAKE) --foreign etc/launchd/Makefile .PRECIOUS: Makefile Makefile: $(srcdir)/Makefile.in $(top_builddir)/config.status @case '$?' in \ *config.status*) \ cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh;; \ *) \ echo ' cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ $(am__depfiles_maybe)'; \ cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ $(am__depfiles_maybe);; \ esac; $(top_builddir)/config.status: $(top_srcdir)/configure $(CONFIG_STATUS_DEPENDENCIES) cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh $(top_srcdir)/configure: $(am__configure_deps) cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh $(ACLOCAL_M4): $(am__aclocal_m4_deps) cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh $(am__aclocal_m4_deps): org.apache.couchdb.plist.tpl: $(top_builddir)/config.status $(srcdir)/org.apache.couchdb.plist.tpl.in cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ mostlyclean-libtool: -rm -f *.lo clean-libtool: -rm -rf .libs _libs tags: TAGS TAGS: ctags: CTAGS CTAGS: distdir: $(DISTFILES) @srcdirstrip=`echo "$(srcdir)" | sed 's/[].[^$$\\*]/\\\\&/g'`; \ topsrcdirstrip=`echo "$(top_srcdir)" | sed 's/[].[^$$\\*]/\\\\&/g'`; \ list='$(DISTFILES)'; \ dist_files=`for file in $$list; do echo $$file; done | \ sed -e "s|^$$srcdirstrip/||;t" \ -e "s|^$$topsrcdirstrip/|$(top_builddir)/|;t"`; \ case $$dist_files in \ */*) $(MKDIR_P) `echo "$$dist_files" | \ sed '/\//!d;s|^|$(distdir)/|;s,/[^/]*$$,,' | \ sort -u` ;; \ esac; \ for file in $$dist_files; do \ if test -f $$file || test -d $$file; then d=.; else d=$(srcdir); fi; \ if test -d $$d/$$file; then \ dir=`echo "/$$file" | sed -e 's,/[^/]*$$,,'`; \ if test -d "$(distdir)/$$file"; then \ find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} \;; \ fi; \ if test -d $(srcdir)/$$file && test $$d != $(srcdir); then \ cp -fpR $(srcdir)/$$file "$(distdir)$$dir" || exit 1; \ find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} \;; \ fi; \ cp -fpR $$d/$$file "$(distdir)$$dir" || exit 1; \ else \ test -f "$(distdir)/$$file" \ || cp -p $$d/$$file "$(distdir)/$$file" \ || exit 1; \ fi; \ done check-am: all-am check: check-am all-am: Makefile installdirs: install: install-am install-exec: install-exec-am install-data: install-data-am uninstall: uninstall-am install-am: all-am @$(MAKE) $(AM_MAKEFLAGS) install-exec-am install-data-am installcheck: installcheck-am install-strip: if test -z '$(STRIP)'; then \ $(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(INSTALL_STRIP_PROGRAM)" \ install_sh_PROGRAM="$(INSTALL_STRIP_PROGRAM)" INSTALL_STRIP_FLAG=-s \ install; \ else \ $(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(INSTALL_STRIP_PROGRAM)" \ install_sh_PROGRAM="$(INSTALL_STRIP_PROGRAM)" INSTALL_STRIP_FLAG=-s \ "INSTALL_PROGRAM_ENV=STRIPPROG='$(STRIP)'" install; \ fi mostlyclean-generic: clean-generic: distclean-generic: -test -z "$(CONFIG_CLEAN_FILES)" || rm -f $(CONFIG_CLEAN_FILES) -test . = "$(srcdir)" || test -z "$(CONFIG_CLEAN_VPATH_FILES)" || rm -f $(CONFIG_CLEAN_VPATH_FILES) maintainer-clean-generic: @echo "This command is intended for maintainers to use" @echo "it deletes files that may require special tools to rebuild." clean: clean-am clean-am: clean-generic clean-libtool mostlyclean-am distclean: distclean-am -rm -f Makefile distclean-am: clean-am distclean-generic dvi: dvi-am dvi-am: html: html-am html-am: info: info-am info-am: install-data-am: install-dvi: install-dvi-am install-dvi-am: install-exec-am: install-html: install-html-am install-html-am: install-info: install-info-am install-info-am: install-man: install-pdf: install-pdf-am install-pdf-am: install-ps: install-ps-am install-ps-am: installcheck-am: maintainer-clean: maintainer-clean-am -rm -f Makefile maintainer-clean-am: distclean-am maintainer-clean-generic mostlyclean: mostlyclean-am mostlyclean-am: mostlyclean-generic mostlyclean-libtool pdf: pdf-am pdf-am: ps: ps-am ps-am: uninstall-am: .MAKE: install-am install-strip .PHONY: all all-am check check-am clean clean-generic clean-libtool \ distclean distclean-generic distclean-libtool distdir dvi \ dvi-am html html-am info info-am install install-am \ install-data install-data-am install-dvi install-dvi-am \ install-exec install-exec-am install-html install-html-am \ install-info install-info-am install-man install-pdf \ install-pdf-am install-ps install-ps-am install-strip \ installcheck installcheck-am installdirs maintainer-clean \ maintainer-clean-generic mostlyclean mostlyclean-generic \ mostlyclean-libtool pdf pdf-am ps ps-am uninstall uninstall-am # Tell versions [3.59,3.63) of GNU make to not export all variables. # Otherwise a system limit (for SysV at least) may be exceeded. .NOEXPORT: apache-couchdb-1.5.0/etc/Makefile.am0000644000175000001440000000742412230722213014070 00000000000000## 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. SUBDIRS = couchdb default init launchd logrotate.d windows default_sysconf_data = logrotate.d/couchdb if INIT init_sysconf_data = default/couchdb init_DATA = init/couchdb endif if LAUNCHD launchd_DATA = launchd/org.apache.couchdb.plist endif nobase_sysconf_DATA = $(default_sysconf_data) $(init_sysconf_data) EXTRA_DIST = \ default/couchdb \ windows/couchdb.iss.tpl \ windows/README.txt.tpl if WINDOWS EXTRA_DIST += \ windows/setup-couchdb-@version@.exe.md5 \ windows/setup-couchdb-@version@.exe.sha endif CLEANFILES = $(init_DATA) $(default_sysconf_data) $(launchd_DATA) transform = @program_transform_name@ couchdb_command_name = `echo couchdb | sed '$(transform)'` init/couchdb: init/couchdb.tpl if test "$(mkdir_p)"; then \ $(mkdir_p) init; \ else \ if test ! -d init; then \ mkdir init; \ fi \ fi sed -e "s|%configure_input%|$@. Generated from $< by configure.|" \ -e "s|%bindir%|$(bindir)|" \ -e "s|%sysconfdir%|$(sysconfdir)|" \ -e "s|%localstaterundir%|$(localstaterundir)|" \ -e "s|%couchdb_command_name%|$(couchdb_command_name)|" \ < $< > $@ logrotate.d/couchdb: logrotate.d/couchdb.tpl sed -e "s|%localstatelogdir%|@localstatelogdir@|g" < $< > $@ launchd/org.apache.couchdb.plist: launchd/org.apache.couchdb.plist.tpl if test "$(mkdir_p)"; then \ $(mkdir_p) launchd; \ else \ if test ! -d launchd; then \ mkdir launchd; \ fi \ fi sed -e "s|%configure_input%|$@. Generated from $< by configure.|" \ -e "s|%bindir%|$(bindir)|" \ -e "s|%couchdb_command_name%|$(couchdb_command_name)|" \ < $< > $@ if WINDOWS # README.txt has \n line endings in the repo and must have \r\n # when installed as notepad is used to view it. # Also: the targets below don't seem to update after an svn-up (which # changes the version string in the generated files) so we trick make # into always building it with the FORCE pattern... windows/README.txt: windows/README.txt.tpl FORCE sed -e "s|%package_name%|@package_name@|g" \ -e "s|%version%|@version@|g" \ < $< | unix2dos > $@ windows/couchdb.iss: windows/couchdb.iss.tpl FORCE sed -e "s|%configure_input%|$@. Generated from $< by configure.|" \ -e "s|%package_name%|@package_name@|g" \ -e "s|%locallibbindir%|`cygpath -m @locallibbindir@`|g" \ -e "s|%version%|@version@|g" \ -e "s|%erts_version%|`$(ERL) -version 2>&1 | $(SED) 's/[^0-9\.]//g'`|g" \ -e "s|%openssl_bin_dir%|@openssl_bin_dir@|g" \ -e "s|%msvc_redist_dir%|@msvc_redist_dir@|g" \ -e "s|%msvc_redist_name%|@msvc_redist_name@|g" \ < $< > $@ # The installer depends on all files, not just the source .iss file, # so we trick make into always building it with the FORCE pattern... windows/setup-couchdb-@version@.exe: windows/couchdb.iss windows/README.txt FORCE "$(INNO_COMPILER_EXECUTABLE)" /q $< @echo Windows Installer is at: `cygpath -a -w windows/setup-couchdb-@version@.exe` windows/setup-couchdb-@version@.exe.md5: windows/setup-couchdb-@version@.exe cd windows && md5sum ./$( $(@F) windows/setup-couchdb-@version@.exe.sha: windows/setup-couchdb-@version@.exe cd windows && sha1sum ./$( $(@F) FORCE: endif install-data-hook: if test -n "$(init_DATA)"; then \ chmod +x "$(DESTDIR)$(initdir)/couchdb"; \ fi apache-couchdb-1.5.0/etc/Makefile.in0000644000175000001440000006575112230722241014111 00000000000000# Makefile.in generated by automake 1.11.6 from Makefile.am. # @configure_input@ # Copyright (C) 1994, 1995, 1996, 1997, 1998, 1999, 2000, 2001, 2002, # 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011 Free Software # Foundation, Inc. # This Makefile.in is free software; the Free Software Foundation # gives unlimited permission to copy and/or distribute it, # with or without modifications, as long as this notice is preserved. # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY, to the extent permitted by law; without # even the implied warranty of MERCHANTABILITY or FITNESS FOR A # PARTICULAR PURPOSE. @SET_MAKE@ VPATH = @srcdir@ am__make_dryrun = \ { \ am__dry=no; \ case $$MAKEFLAGS in \ *\\[\ \ ]*) \ echo 'am--echo: ; @echo "AM" OK' | $(MAKE) -f - 2>/dev/null \ | grep '^AM OK$$' >/dev/null || am__dry=yes;; \ *) \ for am__flg in $$MAKEFLAGS; do \ case $$am__flg in \ *=*|--*) ;; \ *n*) am__dry=yes; break;; \ esac; \ done;; \ esac; \ test $$am__dry = yes; \ } pkgdatadir = $(datadir)/@PACKAGE@ pkgincludedir = $(includedir)/@PACKAGE@ pkglibdir = $(libdir)/@PACKAGE@ pkglibexecdir = $(libexecdir)/@PACKAGE@ am__cd = CDPATH="$${ZSH_VERSION+.}$(PATH_SEPARATOR)" && cd install_sh_DATA = $(install_sh) -c -m 644 install_sh_PROGRAM = $(install_sh) -c install_sh_SCRIPT = $(install_sh) -c INSTALL_HEADER = $(INSTALL_DATA) NORMAL_INSTALL = : PRE_INSTALL = : POST_INSTALL = : NORMAL_UNINSTALL = : PRE_UNINSTALL = : POST_UNINSTALL = : build_triplet = @build@ host_triplet = @host@ @WINDOWS_TRUE@am__append_1 = \ @WINDOWS_TRUE@ windows/setup-couchdb-@version@.exe.md5 \ @WINDOWS_TRUE@ windows/setup-couchdb-@version@.exe.sha subdir = etc DIST_COMMON = $(srcdir)/Makefile.am $(srcdir)/Makefile.in ACLOCAL_M4 = $(top_srcdir)/aclocal.m4 am__aclocal_m4_deps = $(top_srcdir)/m4/libtool.m4 \ $(top_srcdir)/m4/ltoptions.m4 $(top_srcdir)/m4/ltsugar.m4 \ $(top_srcdir)/m4/ltversion.m4 $(top_srcdir)/m4/lt~obsolete.m4 \ $(top_srcdir)/acinclude.m4 $(top_srcdir)/configure.ac am__configure_deps = $(am__aclocal_m4_deps) $(CONFIGURE_DEPENDENCIES) \ $(ACLOCAL_M4) mkinstalldirs = $(install_sh) -d CONFIG_HEADER = $(top_builddir)/config.h \ $(top_builddir)/src/snappy/google-snappy/config.h CONFIG_CLEAN_FILES = CONFIG_CLEAN_VPATH_FILES = SOURCES = DIST_SOURCES = RECURSIVE_TARGETS = all-recursive check-recursive dvi-recursive \ html-recursive info-recursive install-data-recursive \ install-dvi-recursive install-exec-recursive \ install-html-recursive install-info-recursive \ install-pdf-recursive install-ps-recursive install-recursive \ installcheck-recursive installdirs-recursive pdf-recursive \ ps-recursive uninstall-recursive am__can_run_installinfo = \ case $$AM_UPDATE_INFO_DIR in \ n|no|NO) false;; \ *) (install-info --version) >/dev/null 2>&1;; \ esac am__vpath_adj_setup = srcdirstrip=`echo "$(srcdir)" | sed 's|.|.|g'`; am__vpath_adj = case $$p in \ $(srcdir)/*) f=`echo "$$p" | sed "s|^$$srcdirstrip/||"`;; \ *) f=$$p;; \ esac; am__strip_dir = f=`echo $$p | sed -e 's|^.*/||'`; am__install_max = 40 am__nobase_strip_setup = \ srcdirstrip=`echo "$(srcdir)" | sed 's/[].[^$$\\*|]/\\\\&/g'` am__nobase_strip = \ for p in $$list; do echo "$$p"; done | sed -e "s|$$srcdirstrip/||" am__nobase_list = $(am__nobase_strip_setup); \ for p in $$list; do echo "$$p $$p"; done | \ sed "s| $$srcdirstrip/| |;"' / .*\//!s/ .*/ ./; s,\( .*\)/[^/]*$$,\1,' | \ $(AWK) 'BEGIN { files["."] = "" } { files[$$2] = files[$$2] " " $$1; \ if (++n[$$2] == $(am__install_max)) \ { print $$2, files[$$2]; n[$$2] = 0; files[$$2] = "" } } \ END { for (dir in files) print dir, files[dir] }' am__base_list = \ sed '$$!N;$$!N;$$!N;$$!N;$$!N;$$!N;$$!N;s/\n/ /g' | \ sed '$$!N;$$!N;$$!N;$$!N;s/\n/ /g' am__uninstall_files_from_dir = { \ test -z "$$files" \ || { test ! -d "$$dir" && test ! -f "$$dir" && test ! -r "$$dir"; } \ || { echo " ( cd '$$dir' && rm -f" $$files ")"; \ $(am__cd) "$$dir" && rm -f $$files; }; \ } am__installdirs = "$(DESTDIR)$(initdir)" "$(DESTDIR)$(launchddir)" \ "$(DESTDIR)$(sysconfdir)" DATA = $(init_DATA) $(launchd_DATA) $(nobase_sysconf_DATA) RECURSIVE_CLEAN_TARGETS = mostlyclean-recursive clean-recursive \ distclean-recursive maintainer-clean-recursive AM_RECURSIVE_TARGETS = $(RECURSIVE_TARGETS:-recursive=) \ $(RECURSIVE_CLEAN_TARGETS:-recursive=) tags TAGS ctags CTAGS \ distdir ETAGS = etags CTAGS = ctags DIST_SUBDIRS = $(SUBDIRS) DISTFILES = $(DIST_COMMON) $(DIST_SOURCES) $(TEXINFOS) $(EXTRA_DIST) am__relativize = \ dir0=`pwd`; \ sed_first='s,^\([^/]*\)/.*$$,\1,'; \ sed_rest='s,^[^/]*/*,,'; \ sed_last='s,^.*/\([^/]*\)$$,\1,'; \ sed_butlast='s,/*[^/]*$$,,'; \ while test -n "$$dir1"; do \ first=`echo "$$dir1" | sed -e "$$sed_first"`; \ if test "$$first" != "."; then \ if test "$$first" = ".."; then \ dir2=`echo "$$dir0" | sed -e "$$sed_last"`/"$$dir2"; \ dir0=`echo "$$dir0" | sed -e "$$sed_butlast"`; \ else \ first2=`echo "$$dir2" | sed -e "$$sed_first"`; \ if test "$$first2" = "$$first"; then \ dir2=`echo "$$dir2" | sed -e "$$sed_rest"`; \ else \ dir2="../$$dir2"; \ fi; \ dir0="$$dir0"/"$$first"; \ fi; \ fi; \ dir1=`echo "$$dir1" | sed -e "$$sed_rest"`; \ done; \ reldir="$$dir2" transform = @program_transform_name@ ACLOCAL = @ACLOCAL@ AMTAR = @AMTAR@ AR = @AR@ AS = @AS@ AUTOCONF = @AUTOCONF@ AUTOHEADER = @AUTOHEADER@ AUTOMAKE = @AUTOMAKE@ AWK = @AWK@ CC = @CC@ CCDEPMODE = @CCDEPMODE@ CFLAGS = @CFLAGS@ CPP = @CPP@ CPPFLAGS = @CPPFLAGS@ CURL_CFLAGS = @CURL_CFLAGS@ CURL_CONFIG = @CURL_CONFIG@ CURL_LIBS = @CURL_LIBS@ CXX = @CXX@ CXXCPP = @CXXCPP@ CXXDEPMODE = @CXXDEPMODE@ CXXFLAGS = @CXXFLAGS@ CYGPATH_W = @CYGPATH_W@ DEFS = @DEFS@ DEPDIR = @DEPDIR@ DLLTOOL = @DLLTOOL@ DSYMUTIL = @DSYMUTIL@ DUMPBIN = @DUMPBIN@ ECHO_C = @ECHO_C@ ECHO_N = @ECHO_N@ ECHO_T = @ECHO_T@ EGREP = @EGREP@ ERL = @ERL@ ERLANG_FLAGS = @ERLANG_FLAGS@ ERLC = @ERLC@ ERLC_FLAGS = @ERLC_FLAGS@ ESCRIPT = @ESCRIPT@ EXEEXT = @EXEEXT@ FGREP = @FGREP@ FLAGS = @FLAGS@ GREP = @GREP@ HAS_HELP2MAN = @HAS_HELP2MAN@ HAS_INSTALLINFO = @HAS_INSTALLINFO@ HAS_MAKEINFO = @HAS_MAKEINFO@ HAS_PDFLATEX = @HAS_PDFLATEX@ HAS_SPHINX_BUILD = @HAS_SPHINX_BUILD@ ICU_BIN = @ICU_BIN@ ICU_CFLAGS = @ICU_CFLAGS@ ICU_CONFIG = @ICU_CONFIG@ ICU_CPPFLAGS = @ICU_CPPFLAGS@ ICU_CXXFLAGS = @ICU_CXXFLAGS@ ICU_LIBS = @ICU_LIBS@ INNO_COMPILER_EXECUTABLE = @INNO_COMPILER_EXECUTABLE@ INSTALL = @INSTALL@ INSTALL_DATA = @INSTALL_DATA@ INSTALL_PROGRAM = @INSTALL_PROGRAM@ INSTALL_SCRIPT = @INSTALL_SCRIPT@ INSTALL_STRIP_PROGRAM = @INSTALL_STRIP_PROGRAM@ JS_CFLAGS = @JS_CFLAGS@ JS_LIBS = @JS_LIBS@ JS_LIB_BINARY = @JS_LIB_BINARY@ LD = @LD@ LDFLAGS = @LDFLAGS@ LIBOBJS = @LIBOBJS@ LIBS = @LIBS@ LIBTOOL = @LIBTOOL@ LIPO = @LIPO@ LN_S = @LN_S@ LTLIBOBJS = @LTLIBOBJS@ MAKEINFO = @MAKEINFO@ MANIFEST_TOOL = @MANIFEST_TOOL@ MKDIR_P = @MKDIR_P@ NM = @NM@ NMEDIT = @NMEDIT@ OBJDUMP = @OBJDUMP@ OBJEXT = @OBJEXT@ OTOOL = @OTOOL@ OTOOL64 = @OTOOL64@ PACKAGE = @PACKAGE@ PACKAGE_BUGREPORT = @PACKAGE_BUGREPORT@ PACKAGE_NAME = @PACKAGE_NAME@ PACKAGE_STRING = @PACKAGE_STRING@ PACKAGE_TARNAME = @PACKAGE_TARNAME@ PACKAGE_URL = @PACKAGE_URL@ PACKAGE_VERSION = @PACKAGE_VERSION@ PATH_SEPARATOR = @PATH_SEPARATOR@ PKG_CONFIG = @PKG_CONFIG@ PKG_CONFIG_LIBDIR = @PKG_CONFIG_LIBDIR@ PKG_CONFIG_PATH = @PKG_CONFIG_PATH@ RANLIB = @RANLIB@ SED = @SED@ SET_MAKE = @SET_MAKE@ SHELL = @SHELL@ SNAPPY_MAJOR = @SNAPPY_MAJOR@ SNAPPY_MINOR = @SNAPPY_MINOR@ SNAPPY_PATCHLEVEL = @SNAPPY_PATCHLEVEL@ STRIP = @STRIP@ VERSION = @VERSION@ abs_builddir = @abs_builddir@ abs_srcdir = @abs_srcdir@ abs_top_builddir = @abs_top_builddir@ abs_top_srcdir = @abs_top_srcdir@ ac_ct_AR = @ac_ct_AR@ ac_ct_CC = @ac_ct_CC@ ac_ct_CXX = @ac_ct_CXX@ ac_ct_DUMPBIN = @ac_ct_DUMPBIN@ ac_cv_have_stddef_h = @ac_cv_have_stddef_h@ ac_cv_have_stdint_h = @ac_cv_have_stdint_h@ am__include = @am__include@ am__leading_dot = @am__leading_dot@ am__quote = @am__quote@ am__tar = @am__tar@ am__untar = @am__untar@ bindir = @bindir@ bug_uri = @bug_uri@ build = @build@ build_alias = @build_alias@ build_cpu = @build_cpu@ build_os = @build_os@ build_vendor = @build_vendor@ builddir = @builddir@ datadir = @datadir@ datarootdir = @datarootdir@ docdir = @docdir@ dvidir = @dvidir@ erlangbin = @erlangbin@ erlangversion = @erlangversion@ exec_prefix = @exec_prefix@ host = @host@ host_alias = @host_alias@ host_cpu = @host_cpu@ host_os = @host_os@ host_vendor = @host_vendor@ htmldir = @htmldir@ includedir = @includedir@ infodir = @infodir@ initdir = @initdir@ install_sh = @install_sh@ launchddir = @launchddir@ libdir = @libdir@ libexecdir = @libexecdir@ localconfdir = @localconfdir@ localdatadir = @localdatadir@ localdocdir = @localdocdir@ localedir = @localedir@ localerlanglibdir = @localerlanglibdir@ locallibbindir = @locallibbindir@ locallibdir = @locallibdir@ localstatedir = @localstatedir@ localstatelibdir = @localstatelibdir@ localstatelogdir = @localstatelogdir@ localstaterundir = @localstaterundir@ mandir = @mandir@ mkdir_p = @mkdir_p@ msvc_redist_dir = @msvc_redist_dir@ msvc_redist_name = @msvc_redist_name@ oldincludedir = @oldincludedir@ openssl_bin_dir = @openssl_bin_dir@ otp_release = @otp_release@ package_author_address = @package_author_address@ package_author_name = @package_author_name@ package_identifier = @package_identifier@ package_name = @package_name@ package_tarname = @package_tarname@ pdfdir = @pdfdir@ prefix = @prefix@ program_transform_name = @program_transform_name@ psdir = @psdir@ sbindir = @sbindir@ sharedstatedir = @sharedstatedir@ srcdir = @srcdir@ sysconfdir = @sysconfdir@ target_alias = @target_alias@ top_build_prefix = @top_build_prefix@ top_builddir = @top_builddir@ top_srcdir = @top_srcdir@ version = @version@ version_major = @version_major@ version_minor = @version_minor@ version_release = @version_release@ version_revision = @version_revision@ version_stage = @version_stage@ SUBDIRS = couchdb default init launchd logrotate.d windows default_sysconf_data = logrotate.d/couchdb @INIT_TRUE@init_sysconf_data = default/couchdb @INIT_TRUE@init_DATA = init/couchdb @LAUNCHD_TRUE@launchd_DATA = launchd/org.apache.couchdb.plist nobase_sysconf_DATA = $(default_sysconf_data) $(init_sysconf_data) EXTRA_DIST = default/couchdb windows/couchdb.iss.tpl \ windows/README.txt.tpl $(am__append_1) CLEANFILES = $(init_DATA) $(default_sysconf_data) $(launchd_DATA) couchdb_command_name = `echo couchdb | sed '$(transform)'` all: all-recursive .SUFFIXES: $(srcdir)/Makefile.in: $(srcdir)/Makefile.am $(am__configure_deps) @for dep in $?; do \ case '$(am__configure_deps)' in \ *$$dep*) \ ( cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh ) \ && { if test -f $@; then exit 0; else break; fi; }; \ exit 1;; \ esac; \ done; \ echo ' cd $(top_srcdir) && $(AUTOMAKE) --foreign etc/Makefile'; \ $(am__cd) $(top_srcdir) && \ $(AUTOMAKE) --foreign etc/Makefile .PRECIOUS: Makefile Makefile: $(srcdir)/Makefile.in $(top_builddir)/config.status @case '$?' in \ *config.status*) \ cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh;; \ *) \ echo ' cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ $(am__depfiles_maybe)'; \ cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ $(am__depfiles_maybe);; \ esac; $(top_builddir)/config.status: $(top_srcdir)/configure $(CONFIG_STATUS_DEPENDENCIES) cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh $(top_srcdir)/configure: $(am__configure_deps) cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh $(ACLOCAL_M4): $(am__aclocal_m4_deps) cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh $(am__aclocal_m4_deps): mostlyclean-libtool: -rm -f *.lo clean-libtool: -rm -rf .libs _libs install-initDATA: $(init_DATA) @$(NORMAL_INSTALL) @list='$(init_DATA)'; test -n "$(initdir)" || list=; \ if test -n "$$list"; then \ echo " $(MKDIR_P) '$(DESTDIR)$(initdir)'"; \ $(MKDIR_P) "$(DESTDIR)$(initdir)" || exit 1; \ fi; \ for p in $$list; do \ if test -f "$$p"; then d=; else d="$(srcdir)/"; fi; \ echo "$$d$$p"; \ done | $(am__base_list) | \ while read files; do \ echo " $(INSTALL_DATA) $$files '$(DESTDIR)$(initdir)'"; \ $(INSTALL_DATA) $$files "$(DESTDIR)$(initdir)" || exit $$?; \ done uninstall-initDATA: @$(NORMAL_UNINSTALL) @list='$(init_DATA)'; test -n "$(initdir)" || list=; \ files=`for p in $$list; do echo $$p; done | sed -e 's|^.*/||'`; \ dir='$(DESTDIR)$(initdir)'; $(am__uninstall_files_from_dir) install-launchdDATA: $(launchd_DATA) @$(NORMAL_INSTALL) @list='$(launchd_DATA)'; test -n "$(launchddir)" || list=; \ if test -n "$$list"; then \ echo " $(MKDIR_P) '$(DESTDIR)$(launchddir)'"; \ $(MKDIR_P) "$(DESTDIR)$(launchddir)" || exit 1; \ fi; \ for p in $$list; do \ if test -f "$$p"; then d=; else d="$(srcdir)/"; fi; \ echo "$$d$$p"; \ done | $(am__base_list) | \ while read files; do \ echo " $(INSTALL_DATA) $$files '$(DESTDIR)$(launchddir)'"; \ $(INSTALL_DATA) $$files "$(DESTDIR)$(launchddir)" || exit $$?; \ done uninstall-launchdDATA: @$(NORMAL_UNINSTALL) @list='$(launchd_DATA)'; test -n "$(launchddir)" || list=; \ files=`for p in $$list; do echo $$p; done | sed -e 's|^.*/||'`; \ dir='$(DESTDIR)$(launchddir)'; $(am__uninstall_files_from_dir) install-nobase_sysconfDATA: $(nobase_sysconf_DATA) @$(NORMAL_INSTALL) @list='$(nobase_sysconf_DATA)'; test -n "$(sysconfdir)" || list=; \ if test -n "$$list"; then \ echo " $(MKDIR_P) '$(DESTDIR)$(sysconfdir)'"; \ $(MKDIR_P) "$(DESTDIR)$(sysconfdir)" || exit 1; \ fi; \ $(am__nobase_list) | while read dir files; do \ xfiles=; for file in $$files; do \ if test -f "$$file"; then xfiles="$$xfiles $$file"; \ else xfiles="$$xfiles $(srcdir)/$$file"; fi; done; \ test -z "$$xfiles" || { \ test "x$$dir" = x. || { \ echo " $(MKDIR_P) '$(DESTDIR)$(sysconfdir)/$$dir'"; \ $(MKDIR_P) "$(DESTDIR)$(sysconfdir)/$$dir"; }; \ echo " $(INSTALL_DATA) $$xfiles '$(DESTDIR)$(sysconfdir)/$$dir'"; \ $(INSTALL_DATA) $$xfiles "$(DESTDIR)$(sysconfdir)/$$dir" || exit $$?; }; \ done uninstall-nobase_sysconfDATA: @$(NORMAL_UNINSTALL) @list='$(nobase_sysconf_DATA)'; test -n "$(sysconfdir)" || list=; \ $(am__nobase_strip_setup); files=`$(am__nobase_strip)`; \ dir='$(DESTDIR)$(sysconfdir)'; $(am__uninstall_files_from_dir) # This directory's subdirectories are mostly independent; you can cd # into them and run `make' without going through this Makefile. # To change the values of `make' variables: instead of editing Makefiles, # (1) if the variable is set in `config.status', edit `config.status' # (which will cause the Makefiles to be regenerated when you run `make'); # (2) otherwise, pass the desired values on the `make' command line. $(RECURSIVE_TARGETS): @fail= failcom='exit 1'; \ for f in x $$MAKEFLAGS; do \ case $$f in \ *=* | --[!k]*);; \ *k*) failcom='fail=yes';; \ esac; \ done; \ dot_seen=no; \ target=`echo $@ | sed s/-recursive//`; \ list='$(SUBDIRS)'; for subdir in $$list; do \ echo "Making $$target in $$subdir"; \ if test "$$subdir" = "."; then \ dot_seen=yes; \ local_target="$$target-am"; \ else \ local_target="$$target"; \ fi; \ ($(am__cd) $$subdir && $(MAKE) $(AM_MAKEFLAGS) $$local_target) \ || eval $$failcom; \ done; \ if test "$$dot_seen" = "no"; then \ $(MAKE) $(AM_MAKEFLAGS) "$$target-am" || exit 1; \ fi; test -z "$$fail" $(RECURSIVE_CLEAN_TARGETS): @fail= failcom='exit 1'; \ for f in x $$MAKEFLAGS; do \ case $$f in \ *=* | --[!k]*);; \ *k*) failcom='fail=yes';; \ esac; \ done; \ dot_seen=no; \ case "$@" in \ distclean-* | maintainer-clean-*) list='$(DIST_SUBDIRS)' ;; \ *) list='$(SUBDIRS)' ;; \ esac; \ rev=''; for subdir in $$list; do \ if test "$$subdir" = "."; then :; else \ rev="$$subdir $$rev"; \ fi; \ done; \ rev="$$rev ."; \ target=`echo $@ | sed s/-recursive//`; \ for subdir in $$rev; do \ echo "Making $$target in $$subdir"; \ if test "$$subdir" = "."; then \ local_target="$$target-am"; \ else \ local_target="$$target"; \ fi; \ ($(am__cd) $$subdir && $(MAKE) $(AM_MAKEFLAGS) $$local_target) \ || eval $$failcom; \ done && test -z "$$fail" tags-recursive: list='$(SUBDIRS)'; for subdir in $$list; do \ test "$$subdir" = . || ($(am__cd) $$subdir && $(MAKE) $(AM_MAKEFLAGS) tags); \ done ctags-recursive: list='$(SUBDIRS)'; for subdir in $$list; do \ test "$$subdir" = . || ($(am__cd) $$subdir && $(MAKE) $(AM_MAKEFLAGS) ctags); \ done ID: $(HEADERS) $(SOURCES) $(LISP) $(TAGS_FILES) list='$(SOURCES) $(HEADERS) $(LISP) $(TAGS_FILES)'; \ unique=`for i in $$list; do \ if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \ done | \ $(AWK) '{ files[$$0] = 1; nonempty = 1; } \ END { if (nonempty) { for (i in files) print i; }; }'`; \ mkid -fID $$unique tags: TAGS TAGS: tags-recursive $(HEADERS) $(SOURCES) $(TAGS_DEPENDENCIES) \ $(TAGS_FILES) $(LISP) set x; \ here=`pwd`; \ if ($(ETAGS) --etags-include --version) >/dev/null 2>&1; then \ include_option=--etags-include; \ empty_fix=.; \ else \ include_option=--include; \ empty_fix=; \ fi; \ list='$(SUBDIRS)'; for subdir in $$list; do \ if test "$$subdir" = .; then :; else \ test ! -f $$subdir/TAGS || \ set "$$@" "$$include_option=$$here/$$subdir/TAGS"; \ fi; \ done; \ list='$(SOURCES) $(HEADERS) $(LISP) $(TAGS_FILES)'; \ unique=`for i in $$list; do \ if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \ done | \ $(AWK) '{ files[$$0] = 1; nonempty = 1; } \ END { if (nonempty) { for (i in files) print i; }; }'`; \ shift; \ if test -z "$(ETAGS_ARGS)$$*$$unique"; then :; else \ test -n "$$unique" || unique=$$empty_fix; \ if test $$# -gt 0; then \ $(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \ "$$@" $$unique; \ else \ $(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \ $$unique; \ fi; \ fi ctags: CTAGS CTAGS: ctags-recursive $(HEADERS) $(SOURCES) $(TAGS_DEPENDENCIES) \ $(TAGS_FILES) $(LISP) list='$(SOURCES) $(HEADERS) $(LISP) $(TAGS_FILES)'; \ unique=`for i in $$list; do \ if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \ done | \ $(AWK) '{ files[$$0] = 1; nonempty = 1; } \ END { if (nonempty) { for (i in files) print i; }; }'`; \ test -z "$(CTAGS_ARGS)$$unique" \ || $(CTAGS) $(CTAGSFLAGS) $(AM_CTAGSFLAGS) $(CTAGS_ARGS) \ $$unique GTAGS: here=`$(am__cd) $(top_builddir) && pwd` \ && $(am__cd) $(top_srcdir) \ && gtags -i $(GTAGS_ARGS) "$$here" distclean-tags: -rm -f TAGS ID GTAGS GRTAGS GSYMS GPATH tags distdir: $(DISTFILES) @srcdirstrip=`echo "$(srcdir)" | sed 's/[].[^$$\\*]/\\\\&/g'`; \ topsrcdirstrip=`echo "$(top_srcdir)" | sed 's/[].[^$$\\*]/\\\\&/g'`; \ list='$(DISTFILES)'; \ dist_files=`for file in $$list; do echo $$file; done | \ sed -e "s|^$$srcdirstrip/||;t" \ -e "s|^$$topsrcdirstrip/|$(top_builddir)/|;t"`; \ case $$dist_files in \ */*) $(MKDIR_P) `echo "$$dist_files" | \ sed '/\//!d;s|^|$(distdir)/|;s,/[^/]*$$,,' | \ sort -u` ;; \ esac; \ for file in $$dist_files; do \ if test -f $$file || test -d $$file; then d=.; else d=$(srcdir); fi; \ if test -d $$d/$$file; then \ dir=`echo "/$$file" | sed -e 's,/[^/]*$$,,'`; \ if test -d "$(distdir)/$$file"; then \ find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} \;; \ fi; \ if test -d $(srcdir)/$$file && test $$d != $(srcdir); then \ cp -fpR $(srcdir)/$$file "$(distdir)$$dir" || exit 1; \ find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} \;; \ fi; \ cp -fpR $$d/$$file "$(distdir)$$dir" || exit 1; \ else \ test -f "$(distdir)/$$file" \ || cp -p $$d/$$file "$(distdir)/$$file" \ || exit 1; \ fi; \ done @list='$(DIST_SUBDIRS)'; for subdir in $$list; do \ if test "$$subdir" = .; then :; else \ $(am__make_dryrun) \ || test -d "$(distdir)/$$subdir" \ || $(MKDIR_P) "$(distdir)/$$subdir" \ || exit 1; \ dir1=$$subdir; dir2="$(distdir)/$$subdir"; \ $(am__relativize); \ new_distdir=$$reldir; \ dir1=$$subdir; dir2="$(top_distdir)"; \ $(am__relativize); \ new_top_distdir=$$reldir; \ echo " (cd $$subdir && $(MAKE) $(AM_MAKEFLAGS) top_distdir="$$new_top_distdir" distdir="$$new_distdir" \\"; \ echo " am__remove_distdir=: am__skip_length_check=: am__skip_mode_fix=: distdir)"; \ ($(am__cd) $$subdir && \ $(MAKE) $(AM_MAKEFLAGS) \ top_distdir="$$new_top_distdir" \ distdir="$$new_distdir" \ am__remove_distdir=: \ am__skip_length_check=: \ am__skip_mode_fix=: \ distdir) \ || exit 1; \ fi; \ done check-am: all-am check: check-recursive all-am: Makefile $(DATA) installdirs: installdirs-recursive installdirs-am: for dir in "$(DESTDIR)$(initdir)" "$(DESTDIR)$(launchddir)" "$(DESTDIR)$(sysconfdir)"; do \ test -z "$$dir" || $(MKDIR_P) "$$dir"; \ done install: install-recursive install-exec: install-exec-recursive install-data: install-data-recursive uninstall: uninstall-recursive install-am: all-am @$(MAKE) $(AM_MAKEFLAGS) install-exec-am install-data-am installcheck: installcheck-recursive install-strip: if test -z '$(STRIP)'; then \ $(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(INSTALL_STRIP_PROGRAM)" \ install_sh_PROGRAM="$(INSTALL_STRIP_PROGRAM)" INSTALL_STRIP_FLAG=-s \ install; \ else \ $(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(INSTALL_STRIP_PROGRAM)" \ install_sh_PROGRAM="$(INSTALL_STRIP_PROGRAM)" INSTALL_STRIP_FLAG=-s \ "INSTALL_PROGRAM_ENV=STRIPPROG='$(STRIP)'" install; \ fi mostlyclean-generic: clean-generic: -test -z "$(CLEANFILES)" || rm -f $(CLEANFILES) distclean-generic: -test -z "$(CONFIG_CLEAN_FILES)" || rm -f $(CONFIG_CLEAN_FILES) -test . = "$(srcdir)" || test -z "$(CONFIG_CLEAN_VPATH_FILES)" || rm -f $(CONFIG_CLEAN_VPATH_FILES) maintainer-clean-generic: @echo "This command is intended for maintainers to use" @echo "it deletes files that may require special tools to rebuild." clean: clean-recursive clean-am: clean-generic clean-libtool mostlyclean-am distclean: distclean-recursive -rm -f Makefile distclean-am: clean-am distclean-generic distclean-tags dvi: dvi-recursive dvi-am: html: html-recursive html-am: info: info-recursive info-am: install-data-am: install-initDATA install-launchdDATA @$(NORMAL_INSTALL) $(MAKE) $(AM_MAKEFLAGS) install-data-hook install-dvi: install-dvi-recursive install-dvi-am: install-exec-am: install-nobase_sysconfDATA install-html: install-html-recursive install-html-am: install-info: install-info-recursive install-info-am: install-man: install-pdf: install-pdf-recursive install-pdf-am: install-ps: install-ps-recursive install-ps-am: installcheck-am: maintainer-clean: maintainer-clean-recursive -rm -f Makefile maintainer-clean-am: distclean-am maintainer-clean-generic mostlyclean: mostlyclean-recursive mostlyclean-am: mostlyclean-generic mostlyclean-libtool pdf: pdf-recursive pdf-am: ps: ps-recursive ps-am: uninstall-am: uninstall-initDATA uninstall-launchdDATA \ uninstall-nobase_sysconfDATA .MAKE: $(RECURSIVE_CLEAN_TARGETS) $(RECURSIVE_TARGETS) ctags-recursive \ install-am install-data-am install-strip tags-recursive .PHONY: $(RECURSIVE_CLEAN_TARGETS) $(RECURSIVE_TARGETS) CTAGS GTAGS \ all all-am check check-am clean clean-generic clean-libtool \ ctags ctags-recursive distclean distclean-generic \ distclean-libtool distclean-tags distdir dvi dvi-am html \ html-am info info-am install install-am install-data \ install-data-am install-data-hook install-dvi install-dvi-am \ install-exec install-exec-am install-html install-html-am \ install-info install-info-am install-initDATA \ install-launchdDATA install-man install-nobase_sysconfDATA \ install-pdf install-pdf-am install-ps install-ps-am \ install-strip installcheck installcheck-am installdirs \ installdirs-am maintainer-clean maintainer-clean-generic \ mostlyclean mostlyclean-generic mostlyclean-libtool pdf pdf-am \ ps ps-am tags tags-recursive uninstall uninstall-am \ uninstall-initDATA uninstall-launchdDATA \ uninstall-nobase_sysconfDATA init/couchdb: init/couchdb.tpl if test "$(mkdir_p)"; then \ $(mkdir_p) init; \ else \ if test ! -d init; then \ mkdir init; \ fi \ fi sed -e "s|%configure_input%|$@. Generated from $< by configure.|" \ -e "s|%bindir%|$(bindir)|" \ -e "s|%sysconfdir%|$(sysconfdir)|" \ -e "s|%localstaterundir%|$(localstaterundir)|" \ -e "s|%couchdb_command_name%|$(couchdb_command_name)|" \ < $< > $@ logrotate.d/couchdb: logrotate.d/couchdb.tpl sed -e "s|%localstatelogdir%|@localstatelogdir@|g" < $< > $@ launchd/org.apache.couchdb.plist: launchd/org.apache.couchdb.plist.tpl if test "$(mkdir_p)"; then \ $(mkdir_p) launchd; \ else \ if test ! -d launchd; then \ mkdir launchd; \ fi \ fi sed -e "s|%configure_input%|$@. Generated from $< by configure.|" \ -e "s|%bindir%|$(bindir)|" \ -e "s|%couchdb_command_name%|$(couchdb_command_name)|" \ < $< > $@ # README.txt has \n line endings in the repo and must have \r\n # when installed as notepad is used to view it. # Also: the targets below don't seem to update after an svn-up (which # changes the version string in the generated files) so we trick make # into always building it with the FORCE pattern... @WINDOWS_TRUE@windows/README.txt: windows/README.txt.tpl FORCE @WINDOWS_TRUE@ sed -e "s|%package_name%|@package_name@|g" \ @WINDOWS_TRUE@ -e "s|%version%|@version@|g" \ @WINDOWS_TRUE@ < $< | unix2dos > $@ @WINDOWS_TRUE@windows/couchdb.iss: windows/couchdb.iss.tpl FORCE @WINDOWS_TRUE@ sed -e "s|%configure_input%|$@. Generated from $< by configure.|" \ @WINDOWS_TRUE@ -e "s|%package_name%|@package_name@|g" \ @WINDOWS_TRUE@ -e "s|%locallibbindir%|`cygpath -m @locallibbindir@`|g" \ @WINDOWS_TRUE@ -e "s|%version%|@version@|g" \ @WINDOWS_TRUE@ -e "s|%erts_version%|`$(ERL) -version 2>&1 | $(SED) 's/[^0-9\.]//g'`|g" \ @WINDOWS_TRUE@ -e "s|%openssl_bin_dir%|@openssl_bin_dir@|g" \ @WINDOWS_TRUE@ -e "s|%msvc_redist_dir%|@msvc_redist_dir@|g" \ @WINDOWS_TRUE@ -e "s|%msvc_redist_name%|@msvc_redist_name@|g" \ @WINDOWS_TRUE@ < $< > $@ # The installer depends on all files, not just the source .iss file, # so we trick make into always building it with the FORCE pattern... @WINDOWS_TRUE@windows/setup-couchdb-@version@.exe: windows/couchdb.iss windows/README.txt FORCE @WINDOWS_TRUE@ "$(INNO_COMPILER_EXECUTABLE)" /q $< @WINDOWS_TRUE@ @echo Windows Installer is at: `cygpath -a -w windows/setup-couchdb-@version@.exe` @WINDOWS_TRUE@windows/setup-couchdb-@version@.exe.md5: windows/setup-couchdb-@version@.exe @WINDOWS_TRUE@ cd windows && md5sum ./$( $(@F) @WINDOWS_TRUE@windows/setup-couchdb-@version@.exe.sha: windows/setup-couchdb-@version@.exe @WINDOWS_TRUE@ cd windows && sha1sum ./$( $(@F) @WINDOWS_TRUE@FORCE: install-data-hook: if test -n "$(init_DATA)"; then \ chmod +x "$(DESTDIR)$(initdir)/couchdb"; \ fi # Tell versions [3.59,3.63) of GNU make to not export all variables. # Otherwise a system limit (for SysV at least) may be exceeded. .NOEXPORT: apache-couchdb-1.5.0/etc/logrotate.d/0000755000175000001440000000000012230722302014326 500000000000000apache-couchdb-1.5.0/etc/logrotate.d/couchdb.tpl.in0000644000175000001440000000023012230722213016777 00000000000000%localstatelogdir%/*.log { weekly rotate 10 copytruncate delaycompress compress notifempty missingok } apache-couchdb-1.5.0/etc/logrotate.d/Makefile.am0000644000175000001440000000112112230722213016276 00000000000000## 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. ## This file intentionally left blank. apache-couchdb-1.5.0/etc/logrotate.d/Makefile.in0000644000175000001440000003037612230722242016327 00000000000000# Makefile.in generated by automake 1.11.6 from Makefile.am. # @configure_input@ # Copyright (C) 1994, 1995, 1996, 1997, 1998, 1999, 2000, 2001, 2002, # 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011 Free Software # Foundation, Inc. # This Makefile.in is free software; the Free Software Foundation # gives unlimited permission to copy and/or distribute it, # with or without modifications, as long as this notice is preserved. # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY, to the extent permitted by law; without # even the implied warranty of MERCHANTABILITY or FITNESS FOR A # PARTICULAR PURPOSE. @SET_MAKE@ VPATH = @srcdir@ am__make_dryrun = \ { \ am__dry=no; \ case $$MAKEFLAGS in \ *\\[\ \ ]*) \ echo 'am--echo: ; @echo "AM" OK' | $(MAKE) -f - 2>/dev/null \ | grep '^AM OK$$' >/dev/null || am__dry=yes;; \ *) \ for am__flg in $$MAKEFLAGS; do \ case $$am__flg in \ *=*|--*) ;; \ *n*) am__dry=yes; break;; \ esac; \ done;; \ esac; \ test $$am__dry = yes; \ } pkgdatadir = $(datadir)/@PACKAGE@ pkgincludedir = $(includedir)/@PACKAGE@ pkglibdir = $(libdir)/@PACKAGE@ pkglibexecdir = $(libexecdir)/@PACKAGE@ am__cd = CDPATH="$${ZSH_VERSION+.}$(PATH_SEPARATOR)" && cd install_sh_DATA = $(install_sh) -c -m 644 install_sh_PROGRAM = $(install_sh) -c install_sh_SCRIPT = $(install_sh) -c INSTALL_HEADER = $(INSTALL_DATA) transform = $(program_transform_name) NORMAL_INSTALL = : PRE_INSTALL = : POST_INSTALL = : NORMAL_UNINSTALL = : PRE_UNINSTALL = : POST_UNINSTALL = : build_triplet = @build@ host_triplet = @host@ subdir = etc/logrotate.d DIST_COMMON = $(srcdir)/Makefile.am $(srcdir)/Makefile.in \ $(srcdir)/couchdb.tpl.in ACLOCAL_M4 = $(top_srcdir)/aclocal.m4 am__aclocal_m4_deps = $(top_srcdir)/m4/libtool.m4 \ $(top_srcdir)/m4/ltoptions.m4 $(top_srcdir)/m4/ltsugar.m4 \ $(top_srcdir)/m4/ltversion.m4 $(top_srcdir)/m4/lt~obsolete.m4 \ $(top_srcdir)/acinclude.m4 $(top_srcdir)/configure.ac am__configure_deps = $(am__aclocal_m4_deps) $(CONFIGURE_DEPENDENCIES) \ $(ACLOCAL_M4) mkinstalldirs = $(install_sh) -d CONFIG_HEADER = $(top_builddir)/config.h \ $(top_builddir)/src/snappy/google-snappy/config.h CONFIG_CLEAN_FILES = couchdb.tpl CONFIG_CLEAN_VPATH_FILES = SOURCES = DIST_SOURCES = am__can_run_installinfo = \ case $$AM_UPDATE_INFO_DIR in \ n|no|NO) false;; \ *) (install-info --version) >/dev/null 2>&1;; \ esac DISTFILES = $(DIST_COMMON) $(DIST_SOURCES) $(TEXINFOS) $(EXTRA_DIST) ACLOCAL = @ACLOCAL@ AMTAR = @AMTAR@ AR = @AR@ AS = @AS@ AUTOCONF = @AUTOCONF@ AUTOHEADER = @AUTOHEADER@ AUTOMAKE = @AUTOMAKE@ AWK = @AWK@ CC = @CC@ CCDEPMODE = @CCDEPMODE@ CFLAGS = @CFLAGS@ CPP = @CPP@ CPPFLAGS = @CPPFLAGS@ CURL_CFLAGS = @CURL_CFLAGS@ CURL_CONFIG = @CURL_CONFIG@ CURL_LIBS = @CURL_LIBS@ CXX = @CXX@ CXXCPP = @CXXCPP@ CXXDEPMODE = @CXXDEPMODE@ CXXFLAGS = @CXXFLAGS@ CYGPATH_W = @CYGPATH_W@ DEFS = @DEFS@ DEPDIR = @DEPDIR@ DLLTOOL = @DLLTOOL@ DSYMUTIL = @DSYMUTIL@ DUMPBIN = @DUMPBIN@ ECHO_C = @ECHO_C@ ECHO_N = @ECHO_N@ ECHO_T = @ECHO_T@ EGREP = @EGREP@ ERL = @ERL@ ERLANG_FLAGS = @ERLANG_FLAGS@ ERLC = @ERLC@ ERLC_FLAGS = @ERLC_FLAGS@ ESCRIPT = @ESCRIPT@ EXEEXT = @EXEEXT@ FGREP = @FGREP@ FLAGS = @FLAGS@ GREP = @GREP@ HAS_HELP2MAN = @HAS_HELP2MAN@ HAS_INSTALLINFO = @HAS_INSTALLINFO@ HAS_MAKEINFO = @HAS_MAKEINFO@ HAS_PDFLATEX = @HAS_PDFLATEX@ HAS_SPHINX_BUILD = @HAS_SPHINX_BUILD@ ICU_BIN = @ICU_BIN@ ICU_CFLAGS = @ICU_CFLAGS@ ICU_CONFIG = @ICU_CONFIG@ ICU_CPPFLAGS = @ICU_CPPFLAGS@ ICU_CXXFLAGS = @ICU_CXXFLAGS@ ICU_LIBS = @ICU_LIBS@ INNO_COMPILER_EXECUTABLE = @INNO_COMPILER_EXECUTABLE@ INSTALL = @INSTALL@ INSTALL_DATA = @INSTALL_DATA@ INSTALL_PROGRAM = @INSTALL_PROGRAM@ INSTALL_SCRIPT = @INSTALL_SCRIPT@ INSTALL_STRIP_PROGRAM = @INSTALL_STRIP_PROGRAM@ JS_CFLAGS = @JS_CFLAGS@ JS_LIBS = @JS_LIBS@ JS_LIB_BINARY = @JS_LIB_BINARY@ LD = @LD@ LDFLAGS = @LDFLAGS@ LIBOBJS = @LIBOBJS@ LIBS = @LIBS@ LIBTOOL = @LIBTOOL@ LIPO = @LIPO@ LN_S = @LN_S@ LTLIBOBJS = @LTLIBOBJS@ MAKEINFO = @MAKEINFO@ MANIFEST_TOOL = @MANIFEST_TOOL@ MKDIR_P = @MKDIR_P@ NM = @NM@ NMEDIT = @NMEDIT@ OBJDUMP = @OBJDUMP@ OBJEXT = @OBJEXT@ OTOOL = @OTOOL@ OTOOL64 = @OTOOL64@ PACKAGE = @PACKAGE@ PACKAGE_BUGREPORT = @PACKAGE_BUGREPORT@ PACKAGE_NAME = @PACKAGE_NAME@ PACKAGE_STRING = @PACKAGE_STRING@ PACKAGE_TARNAME = @PACKAGE_TARNAME@ PACKAGE_URL = @PACKAGE_URL@ PACKAGE_VERSION = @PACKAGE_VERSION@ PATH_SEPARATOR = @PATH_SEPARATOR@ PKG_CONFIG = @PKG_CONFIG@ PKG_CONFIG_LIBDIR = @PKG_CONFIG_LIBDIR@ PKG_CONFIG_PATH = @PKG_CONFIG_PATH@ RANLIB = @RANLIB@ SED = @SED@ SET_MAKE = @SET_MAKE@ SHELL = @SHELL@ SNAPPY_MAJOR = @SNAPPY_MAJOR@ SNAPPY_MINOR = @SNAPPY_MINOR@ SNAPPY_PATCHLEVEL = @SNAPPY_PATCHLEVEL@ STRIP = @STRIP@ VERSION = @VERSION@ abs_builddir = @abs_builddir@ abs_srcdir = @abs_srcdir@ abs_top_builddir = @abs_top_builddir@ abs_top_srcdir = @abs_top_srcdir@ ac_ct_AR = @ac_ct_AR@ ac_ct_CC = @ac_ct_CC@ ac_ct_CXX = @ac_ct_CXX@ ac_ct_DUMPBIN = @ac_ct_DUMPBIN@ ac_cv_have_stddef_h = @ac_cv_have_stddef_h@ ac_cv_have_stdint_h = @ac_cv_have_stdint_h@ am__include = @am__include@ am__leading_dot = @am__leading_dot@ am__quote = @am__quote@ am__tar = @am__tar@ am__untar = @am__untar@ bindir = @bindir@ bug_uri = @bug_uri@ build = @build@ build_alias = @build_alias@ build_cpu = @build_cpu@ build_os = @build_os@ build_vendor = @build_vendor@ builddir = @builddir@ datadir = @datadir@ datarootdir = @datarootdir@ docdir = @docdir@ dvidir = @dvidir@ erlangbin = @erlangbin@ erlangversion = @erlangversion@ exec_prefix = @exec_prefix@ host = @host@ host_alias = @host_alias@ host_cpu = @host_cpu@ host_os = @host_os@ host_vendor = @host_vendor@ htmldir = @htmldir@ includedir = @includedir@ infodir = @infodir@ initdir = @initdir@ install_sh = @install_sh@ launchddir = @launchddir@ libdir = @libdir@ libexecdir = @libexecdir@ localconfdir = @localconfdir@ localdatadir = @localdatadir@ localdocdir = @localdocdir@ localedir = @localedir@ localerlanglibdir = @localerlanglibdir@ locallibbindir = @locallibbindir@ locallibdir = @locallibdir@ localstatedir = @localstatedir@ localstatelibdir = @localstatelibdir@ localstatelogdir = @localstatelogdir@ localstaterundir = @localstaterundir@ mandir = @mandir@ mkdir_p = @mkdir_p@ msvc_redist_dir = @msvc_redist_dir@ msvc_redist_name = @msvc_redist_name@ oldincludedir = @oldincludedir@ openssl_bin_dir = @openssl_bin_dir@ otp_release = @otp_release@ package_author_address = @package_author_address@ package_author_name = @package_author_name@ package_identifier = @package_identifier@ package_name = @package_name@ package_tarname = @package_tarname@ pdfdir = @pdfdir@ prefix = @prefix@ program_transform_name = @program_transform_name@ psdir = @psdir@ sbindir = @sbindir@ sharedstatedir = @sharedstatedir@ srcdir = @srcdir@ sysconfdir = @sysconfdir@ target_alias = @target_alias@ top_build_prefix = @top_build_prefix@ top_builddir = @top_builddir@ top_srcdir = @top_srcdir@ version = @version@ version_major = @version_major@ version_minor = @version_minor@ version_release = @version_release@ version_revision = @version_revision@ version_stage = @version_stage@ all: all-am .SUFFIXES: $(srcdir)/Makefile.in: $(srcdir)/Makefile.am $(am__configure_deps) @for dep in $?; do \ case '$(am__configure_deps)' in \ *$$dep*) \ ( cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh ) \ && { if test -f $@; then exit 0; else break; fi; }; \ exit 1;; \ esac; \ done; \ echo ' cd $(top_srcdir) && $(AUTOMAKE) --foreign etc/logrotate.d/Makefile'; \ $(am__cd) $(top_srcdir) && \ $(AUTOMAKE) --foreign etc/logrotate.d/Makefile .PRECIOUS: Makefile Makefile: $(srcdir)/Makefile.in $(top_builddir)/config.status @case '$?' in \ *config.status*) \ cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh;; \ *) \ echo ' cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ $(am__depfiles_maybe)'; \ cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ $(am__depfiles_maybe);; \ esac; $(top_builddir)/config.status: $(top_srcdir)/configure $(CONFIG_STATUS_DEPENDENCIES) cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh $(top_srcdir)/configure: $(am__configure_deps) cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh $(ACLOCAL_M4): $(am__aclocal_m4_deps) cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh $(am__aclocal_m4_deps): couchdb.tpl: $(top_builddir)/config.status $(srcdir)/couchdb.tpl.in cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ mostlyclean-libtool: -rm -f *.lo clean-libtool: -rm -rf .libs _libs tags: TAGS TAGS: ctags: CTAGS CTAGS: distdir: $(DISTFILES) @srcdirstrip=`echo "$(srcdir)" | sed 's/[].[^$$\\*]/\\\\&/g'`; \ topsrcdirstrip=`echo "$(top_srcdir)" | sed 's/[].[^$$\\*]/\\\\&/g'`; \ list='$(DISTFILES)'; \ dist_files=`for file in $$list; do echo $$file; done | \ sed -e "s|^$$srcdirstrip/||;t" \ -e "s|^$$topsrcdirstrip/|$(top_builddir)/|;t"`; \ case $$dist_files in \ */*) $(MKDIR_P) `echo "$$dist_files" | \ sed '/\//!d;s|^|$(distdir)/|;s,/[^/]*$$,,' | \ sort -u` ;; \ esac; \ for file in $$dist_files; do \ if test -f $$file || test -d $$file; then d=.; else d=$(srcdir); fi; \ if test -d $$d/$$file; then \ dir=`echo "/$$file" | sed -e 's,/[^/]*$$,,'`; \ if test -d "$(distdir)/$$file"; then \ find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} \;; \ fi; \ if test -d $(srcdir)/$$file && test $$d != $(srcdir); then \ cp -fpR $(srcdir)/$$file "$(distdir)$$dir" || exit 1; \ find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} \;; \ fi; \ cp -fpR $$d/$$file "$(distdir)$$dir" || exit 1; \ else \ test -f "$(distdir)/$$file" \ || cp -p $$d/$$file "$(distdir)/$$file" \ || exit 1; \ fi; \ done check-am: all-am check: check-am all-am: Makefile installdirs: install: install-am install-exec: install-exec-am install-data: install-data-am uninstall: uninstall-am install-am: all-am @$(MAKE) $(AM_MAKEFLAGS) install-exec-am install-data-am installcheck: installcheck-am install-strip: if test -z '$(STRIP)'; then \ $(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(INSTALL_STRIP_PROGRAM)" \ install_sh_PROGRAM="$(INSTALL_STRIP_PROGRAM)" INSTALL_STRIP_FLAG=-s \ install; \ else \ $(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(INSTALL_STRIP_PROGRAM)" \ install_sh_PROGRAM="$(INSTALL_STRIP_PROGRAM)" INSTALL_STRIP_FLAG=-s \ "INSTALL_PROGRAM_ENV=STRIPPROG='$(STRIP)'" install; \ fi mostlyclean-generic: clean-generic: distclean-generic: -test -z "$(CONFIG_CLEAN_FILES)" || rm -f $(CONFIG_CLEAN_FILES) -test . = "$(srcdir)" || test -z "$(CONFIG_CLEAN_VPATH_FILES)" || rm -f $(CONFIG_CLEAN_VPATH_FILES) maintainer-clean-generic: @echo "This command is intended for maintainers to use" @echo "it deletes files that may require special tools to rebuild." clean: clean-am clean-am: clean-generic clean-libtool mostlyclean-am distclean: distclean-am -rm -f Makefile distclean-am: clean-am distclean-generic dvi: dvi-am dvi-am: html: html-am html-am: info: info-am info-am: install-data-am: install-dvi: install-dvi-am install-dvi-am: install-exec-am: install-html: install-html-am install-html-am: install-info: install-info-am install-info-am: install-man: install-pdf: install-pdf-am install-pdf-am: install-ps: install-ps-am install-ps-am: installcheck-am: maintainer-clean: maintainer-clean-am -rm -f Makefile maintainer-clean-am: distclean-am maintainer-clean-generic mostlyclean: mostlyclean-am mostlyclean-am: mostlyclean-generic mostlyclean-libtool pdf: pdf-am pdf-am: ps: ps-am ps-am: uninstall-am: .MAKE: install-am install-strip .PHONY: all all-am check check-am clean clean-generic clean-libtool \ distclean distclean-generic distclean-libtool distdir dvi \ dvi-am html html-am info info-am install install-am \ install-data install-data-am install-dvi install-dvi-am \ install-exec install-exec-am install-html install-html-am \ install-info install-info-am install-man install-pdf \ install-pdf-am install-ps install-ps-am install-strip \ installcheck installcheck-am installdirs maintainer-clean \ maintainer-clean-generic mostlyclean mostlyclean-generic \ mostlyclean-libtool pdf pdf-am ps ps-am uninstall uninstall-am # Tell versions [3.59,3.63) of GNU make to not export all variables. # Otherwise a system limit (for SysV at least) may be exceeded. .NOEXPORT: apache-couchdb-1.5.0/etc/windows/0000755000175000001440000000000012230722302013576 500000000000000apache-couchdb-1.5.0/etc/windows/Makefile.am0000644000175000001440000000112112230722213015546 00000000000000## 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. ## This file intentionally left blank. apache-couchdb-1.5.0/etc/windows/Makefile.in0000644000175000001440000003011112230722242015562 00000000000000# Makefile.in generated by automake 1.11.6 from Makefile.am. # @configure_input@ # Copyright (C) 1994, 1995, 1996, 1997, 1998, 1999, 2000, 2001, 2002, # 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011 Free Software # Foundation, Inc. # This Makefile.in is free software; the Free Software Foundation # gives unlimited permission to copy and/or distribute it, # with or without modifications, as long as this notice is preserved. # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY, to the extent permitted by law; without # even the implied warranty of MERCHANTABILITY or FITNESS FOR A # PARTICULAR PURPOSE. @SET_MAKE@ VPATH = @srcdir@ am__make_dryrun = \ { \ am__dry=no; \ case $$MAKEFLAGS in \ *\\[\ \ ]*) \ echo 'am--echo: ; @echo "AM" OK' | $(MAKE) -f - 2>/dev/null \ | grep '^AM OK$$' >/dev/null || am__dry=yes;; \ *) \ for am__flg in $$MAKEFLAGS; do \ case $$am__flg in \ *=*|--*) ;; \ *n*) am__dry=yes; break;; \ esac; \ done;; \ esac; \ test $$am__dry = yes; \ } pkgdatadir = $(datadir)/@PACKAGE@ pkgincludedir = $(includedir)/@PACKAGE@ pkglibdir = $(libdir)/@PACKAGE@ pkglibexecdir = $(libexecdir)/@PACKAGE@ am__cd = CDPATH="$${ZSH_VERSION+.}$(PATH_SEPARATOR)" && cd install_sh_DATA = $(install_sh) -c -m 644 install_sh_PROGRAM = $(install_sh) -c install_sh_SCRIPT = $(install_sh) -c INSTALL_HEADER = $(INSTALL_DATA) transform = $(program_transform_name) NORMAL_INSTALL = : PRE_INSTALL = : POST_INSTALL = : NORMAL_UNINSTALL = : PRE_UNINSTALL = : POST_UNINSTALL = : build_triplet = @build@ host_triplet = @host@ subdir = etc/windows DIST_COMMON = $(srcdir)/Makefile.am $(srcdir)/Makefile.in ACLOCAL_M4 = $(top_srcdir)/aclocal.m4 am__aclocal_m4_deps = $(top_srcdir)/m4/libtool.m4 \ $(top_srcdir)/m4/ltoptions.m4 $(top_srcdir)/m4/ltsugar.m4 \ $(top_srcdir)/m4/ltversion.m4 $(top_srcdir)/m4/lt~obsolete.m4 \ $(top_srcdir)/acinclude.m4 $(top_srcdir)/configure.ac am__configure_deps = $(am__aclocal_m4_deps) $(CONFIGURE_DEPENDENCIES) \ $(ACLOCAL_M4) mkinstalldirs = $(install_sh) -d CONFIG_HEADER = $(top_builddir)/config.h \ $(top_builddir)/src/snappy/google-snappy/config.h CONFIG_CLEAN_FILES = CONFIG_CLEAN_VPATH_FILES = SOURCES = DIST_SOURCES = am__can_run_installinfo = \ case $$AM_UPDATE_INFO_DIR in \ n|no|NO) false;; \ *) (install-info --version) >/dev/null 2>&1;; \ esac DISTFILES = $(DIST_COMMON) $(DIST_SOURCES) $(TEXINFOS) $(EXTRA_DIST) ACLOCAL = @ACLOCAL@ AMTAR = @AMTAR@ AR = @AR@ AS = @AS@ AUTOCONF = @AUTOCONF@ AUTOHEADER = @AUTOHEADER@ AUTOMAKE = @AUTOMAKE@ AWK = @AWK@ CC = @CC@ CCDEPMODE = @CCDEPMODE@ CFLAGS = @CFLAGS@ CPP = @CPP@ CPPFLAGS = @CPPFLAGS@ CURL_CFLAGS = @CURL_CFLAGS@ CURL_CONFIG = @CURL_CONFIG@ CURL_LIBS = @CURL_LIBS@ CXX = @CXX@ CXXCPP = @CXXCPP@ CXXDEPMODE = @CXXDEPMODE@ CXXFLAGS = @CXXFLAGS@ CYGPATH_W = @CYGPATH_W@ DEFS = @DEFS@ DEPDIR = @DEPDIR@ DLLTOOL = @DLLTOOL@ DSYMUTIL = @DSYMUTIL@ DUMPBIN = @DUMPBIN@ ECHO_C = @ECHO_C@ ECHO_N = @ECHO_N@ ECHO_T = @ECHO_T@ EGREP = @EGREP@ ERL = @ERL@ ERLANG_FLAGS = @ERLANG_FLAGS@ ERLC = @ERLC@ ERLC_FLAGS = @ERLC_FLAGS@ ESCRIPT = @ESCRIPT@ EXEEXT = @EXEEXT@ FGREP = @FGREP@ FLAGS = @FLAGS@ GREP = @GREP@ HAS_HELP2MAN = @HAS_HELP2MAN@ HAS_INSTALLINFO = @HAS_INSTALLINFO@ HAS_MAKEINFO = @HAS_MAKEINFO@ HAS_PDFLATEX = @HAS_PDFLATEX@ HAS_SPHINX_BUILD = @HAS_SPHINX_BUILD@ ICU_BIN = @ICU_BIN@ ICU_CFLAGS = @ICU_CFLAGS@ ICU_CONFIG = @ICU_CONFIG@ ICU_CPPFLAGS = @ICU_CPPFLAGS@ ICU_CXXFLAGS = @ICU_CXXFLAGS@ ICU_LIBS = @ICU_LIBS@ INNO_COMPILER_EXECUTABLE = @INNO_COMPILER_EXECUTABLE@ INSTALL = @INSTALL@ INSTALL_DATA = @INSTALL_DATA@ INSTALL_PROGRAM = @INSTALL_PROGRAM@ INSTALL_SCRIPT = @INSTALL_SCRIPT@ INSTALL_STRIP_PROGRAM = @INSTALL_STRIP_PROGRAM@ JS_CFLAGS = @JS_CFLAGS@ JS_LIBS = @JS_LIBS@ JS_LIB_BINARY = @JS_LIB_BINARY@ LD = @LD@ LDFLAGS = @LDFLAGS@ LIBOBJS = @LIBOBJS@ LIBS = @LIBS@ LIBTOOL = @LIBTOOL@ LIPO = @LIPO@ LN_S = @LN_S@ LTLIBOBJS = @LTLIBOBJS@ MAKEINFO = @MAKEINFO@ MANIFEST_TOOL = @MANIFEST_TOOL@ MKDIR_P = @MKDIR_P@ NM = @NM@ NMEDIT = @NMEDIT@ OBJDUMP = @OBJDUMP@ OBJEXT = @OBJEXT@ OTOOL = @OTOOL@ OTOOL64 = @OTOOL64@ PACKAGE = @PACKAGE@ PACKAGE_BUGREPORT = @PACKAGE_BUGREPORT@ PACKAGE_NAME = @PACKAGE_NAME@ PACKAGE_STRING = @PACKAGE_STRING@ PACKAGE_TARNAME = @PACKAGE_TARNAME@ PACKAGE_URL = @PACKAGE_URL@ PACKAGE_VERSION = @PACKAGE_VERSION@ PATH_SEPARATOR = @PATH_SEPARATOR@ PKG_CONFIG = @PKG_CONFIG@ PKG_CONFIG_LIBDIR = @PKG_CONFIG_LIBDIR@ PKG_CONFIG_PATH = @PKG_CONFIG_PATH@ RANLIB = @RANLIB@ SED = @SED@ SET_MAKE = @SET_MAKE@ SHELL = @SHELL@ SNAPPY_MAJOR = @SNAPPY_MAJOR@ SNAPPY_MINOR = @SNAPPY_MINOR@ SNAPPY_PATCHLEVEL = @SNAPPY_PATCHLEVEL@ STRIP = @STRIP@ VERSION = @VERSION@ abs_builddir = @abs_builddir@ abs_srcdir = @abs_srcdir@ abs_top_builddir = @abs_top_builddir@ abs_top_srcdir = @abs_top_srcdir@ ac_ct_AR = @ac_ct_AR@ ac_ct_CC = @ac_ct_CC@ ac_ct_CXX = @ac_ct_CXX@ ac_ct_DUMPBIN = @ac_ct_DUMPBIN@ ac_cv_have_stddef_h = @ac_cv_have_stddef_h@ ac_cv_have_stdint_h = @ac_cv_have_stdint_h@ am__include = @am__include@ am__leading_dot = @am__leading_dot@ am__quote = @am__quote@ am__tar = @am__tar@ am__untar = @am__untar@ bindir = @bindir@ bug_uri = @bug_uri@ build = @build@ build_alias = @build_alias@ build_cpu = @build_cpu@ build_os = @build_os@ build_vendor = @build_vendor@ builddir = @builddir@ datadir = @datadir@ datarootdir = @datarootdir@ docdir = @docdir@ dvidir = @dvidir@ erlangbin = @erlangbin@ erlangversion = @erlangversion@ exec_prefix = @exec_prefix@ host = @host@ host_alias = @host_alias@ host_cpu = @host_cpu@ host_os = @host_os@ host_vendor = @host_vendor@ htmldir = @htmldir@ includedir = @includedir@ infodir = @infodir@ initdir = @initdir@ install_sh = @install_sh@ launchddir = @launchddir@ libdir = @libdir@ libexecdir = @libexecdir@ localconfdir = @localconfdir@ localdatadir = @localdatadir@ localdocdir = @localdocdir@ localedir = @localedir@ localerlanglibdir = @localerlanglibdir@ locallibbindir = @locallibbindir@ locallibdir = @locallibdir@ localstatedir = @localstatedir@ localstatelibdir = @localstatelibdir@ localstatelogdir = @localstatelogdir@ localstaterundir = @localstaterundir@ mandir = @mandir@ mkdir_p = @mkdir_p@ msvc_redist_dir = @msvc_redist_dir@ msvc_redist_name = @msvc_redist_name@ oldincludedir = @oldincludedir@ openssl_bin_dir = @openssl_bin_dir@ otp_release = @otp_release@ package_author_address = @package_author_address@ package_author_name = @package_author_name@ package_identifier = @package_identifier@ package_name = @package_name@ package_tarname = @package_tarname@ pdfdir = @pdfdir@ prefix = @prefix@ program_transform_name = @program_transform_name@ psdir = @psdir@ sbindir = @sbindir@ sharedstatedir = @sharedstatedir@ srcdir = @srcdir@ sysconfdir = @sysconfdir@ target_alias = @target_alias@ top_build_prefix = @top_build_prefix@ top_builddir = @top_builddir@ top_srcdir = @top_srcdir@ version = @version@ version_major = @version_major@ version_minor = @version_minor@ version_release = @version_release@ version_revision = @version_revision@ version_stage = @version_stage@ all: all-am .SUFFIXES: $(srcdir)/Makefile.in: $(srcdir)/Makefile.am $(am__configure_deps) @for dep in $?; do \ case '$(am__configure_deps)' in \ *$$dep*) \ ( cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh ) \ && { if test -f $@; then exit 0; else break; fi; }; \ exit 1;; \ esac; \ done; \ echo ' cd $(top_srcdir) && $(AUTOMAKE) --foreign etc/windows/Makefile'; \ $(am__cd) $(top_srcdir) && \ $(AUTOMAKE) --foreign etc/windows/Makefile .PRECIOUS: Makefile Makefile: $(srcdir)/Makefile.in $(top_builddir)/config.status @case '$?' in \ *config.status*) \ cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh;; \ *) \ echo ' cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ $(am__depfiles_maybe)'; \ cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ $(am__depfiles_maybe);; \ esac; $(top_builddir)/config.status: $(top_srcdir)/configure $(CONFIG_STATUS_DEPENDENCIES) cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh $(top_srcdir)/configure: $(am__configure_deps) cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh $(ACLOCAL_M4): $(am__aclocal_m4_deps) cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh $(am__aclocal_m4_deps): mostlyclean-libtool: -rm -f *.lo clean-libtool: -rm -rf .libs _libs tags: TAGS TAGS: ctags: CTAGS CTAGS: distdir: $(DISTFILES) @srcdirstrip=`echo "$(srcdir)" | sed 's/[].[^$$\\*]/\\\\&/g'`; \ topsrcdirstrip=`echo "$(top_srcdir)" | sed 's/[].[^$$\\*]/\\\\&/g'`; \ list='$(DISTFILES)'; \ dist_files=`for file in $$list; do echo $$file; done | \ sed -e "s|^$$srcdirstrip/||;t" \ -e "s|^$$topsrcdirstrip/|$(top_builddir)/|;t"`; \ case $$dist_files in \ */*) $(MKDIR_P) `echo "$$dist_files" | \ sed '/\//!d;s|^|$(distdir)/|;s,/[^/]*$$,,' | \ sort -u` ;; \ esac; \ for file in $$dist_files; do \ if test -f $$file || test -d $$file; then d=.; else d=$(srcdir); fi; \ if test -d $$d/$$file; then \ dir=`echo "/$$file" | sed -e 's,/[^/]*$$,,'`; \ if test -d "$(distdir)/$$file"; then \ find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} \;; \ fi; \ if test -d $(srcdir)/$$file && test $$d != $(srcdir); then \ cp -fpR $(srcdir)/$$file "$(distdir)$$dir" || exit 1; \ find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} \;; \ fi; \ cp -fpR $$d/$$file "$(distdir)$$dir" || exit 1; \ else \ test -f "$(distdir)/$$file" \ || cp -p $$d/$$file "$(distdir)/$$file" \ || exit 1; \ fi; \ done check-am: all-am check: check-am all-am: Makefile installdirs: install: install-am install-exec: install-exec-am install-data: install-data-am uninstall: uninstall-am install-am: all-am @$(MAKE) $(AM_MAKEFLAGS) install-exec-am install-data-am installcheck: installcheck-am install-strip: if test -z '$(STRIP)'; then \ $(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(INSTALL_STRIP_PROGRAM)" \ install_sh_PROGRAM="$(INSTALL_STRIP_PROGRAM)" INSTALL_STRIP_FLAG=-s \ install; \ else \ $(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(INSTALL_STRIP_PROGRAM)" \ install_sh_PROGRAM="$(INSTALL_STRIP_PROGRAM)" INSTALL_STRIP_FLAG=-s \ "INSTALL_PROGRAM_ENV=STRIPPROG='$(STRIP)'" install; \ fi mostlyclean-generic: clean-generic: distclean-generic: -test -z "$(CONFIG_CLEAN_FILES)" || rm -f $(CONFIG_CLEAN_FILES) -test . = "$(srcdir)" || test -z "$(CONFIG_CLEAN_VPATH_FILES)" || rm -f $(CONFIG_CLEAN_VPATH_FILES) maintainer-clean-generic: @echo "This command is intended for maintainers to use" @echo "it deletes files that may require special tools to rebuild." clean: clean-am clean-am: clean-generic clean-libtool mostlyclean-am distclean: distclean-am -rm -f Makefile distclean-am: clean-am distclean-generic dvi: dvi-am dvi-am: html: html-am html-am: info: info-am info-am: install-data-am: install-dvi: install-dvi-am install-dvi-am: install-exec-am: install-html: install-html-am install-html-am: install-info: install-info-am install-info-am: install-man: install-pdf: install-pdf-am install-pdf-am: install-ps: install-ps-am install-ps-am: installcheck-am: maintainer-clean: maintainer-clean-am -rm -f Makefile maintainer-clean-am: distclean-am maintainer-clean-generic mostlyclean: mostlyclean-am mostlyclean-am: mostlyclean-generic mostlyclean-libtool pdf: pdf-am pdf-am: ps: ps-am ps-am: uninstall-am: .MAKE: install-am install-strip .PHONY: all all-am check check-am clean clean-generic clean-libtool \ distclean distclean-generic distclean-libtool distdir dvi \ dvi-am html html-am info info-am install install-am \ install-data install-data-am install-dvi install-dvi-am \ install-exec install-exec-am install-html install-html-am \ install-info install-info-am install-man install-pdf \ install-pdf-am install-ps install-ps-am install-strip \ installcheck installcheck-am installdirs maintainer-clean \ maintainer-clean-generic mostlyclean mostlyclean-generic \ mostlyclean-libtool pdf pdf-am ps ps-am uninstall uninstall-am # Tell versions [3.59,3.63) of GNU make to not export all variables. # Otherwise a system limit (for SysV at least) may be exceeded. .NOEXPORT: apache-couchdb-1.5.0/etc/windows/README.txt.tpl0000644000175000001440000000265412230722213016022 00000000000000This is the README for the %package_name% binary distribution for Windows, version %version%. * Although CouchDB defaults to installing into your "Program Files" directory, the permissions on the 'var' and 'etc' sub-directories have been adjusted to allow modification by any authorized user so the couchdb databases, logs and .ini files can be written. You may like to further restrict these permissions to only the user who will be running couchdb. * The installer offers to install CouchDB as a Windows Service. If you select this option, the service will run as the "LocalSystem" user and be configured to start automatically. You can configure the service properties via the Windows 'Services' applet. * To start CouchDB in a "console" environment, execute couchdb.bat in the 'bin' directory. A shortcut to this batch file should have been installed. Don't try and start couchdb this way if the service is running - it will fail. * The Futon application which comes with CouchDB does not work with Internet Explorer - Mozilla Firefox is generally recommended. * The test suite is known to fail on Windows due to what appear to be permissions errors; this is due to couch being unable to delete a file while it is in use on Windows. See also https://issues.apache.org/jira/browse/COUCHDB-326 * Additional help with the Windows support is needed - please contact the couchdb-dev list if you can help. apache-couchdb-1.5.0/etc/windows/couchdb.iss.tpl0000644000175000001440000001166712230722213016457 00000000000000; 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. ; CouchDB inno installer script ; %configure_input% [Setup] AppID=ApacheCouchDB AppName=%package_name% AppVerName=%package_name% %version% AppPublisher=Apache Software Foundation AppPublisherURL=http://couchdb.apache.org/ LicenseFile=../../LICENSE DefaultDirName={pf}\Apache Software Foundation\CouchDB DefaultGroupName=%package_name% OutputBaseFilename=setup-couchdb-%version% OutputDir=. [Files] Source: "%locallibbindir%\..\*.*"; DestDir: "{app}"; Flags: ignoreversion uninsrestartdelete restartreplace ; bin dir Source: "%locallibbindir%\*.*"; DestDir: "{app}\bin"; Flags: ignoreversion uninsrestartdelete restartreplace recursesubdirs ; other dirs copied '*.*' Source: "%locallibbindir%\..\erts-%erts_version%\*.*"; DestDir: "{app}\erts-%erts_version%"; Flags: ignoreversion uninsrestartdelete restartreplace recursesubdirs Source: "%locallibbindir%\..\lib\*.*"; DestDir: "{app}\lib"; Flags: ignoreversion uninsrestartdelete restartreplace recursesubdirs Source: "%locallibbindir%\..\share\*.*"; DestDir: "{app}\share"; Flags: ignoreversion uninsrestartdelete restartreplace recursesubdirs Source: "%locallibbindir%\..\releases\*.*"; DestDir: "{app}\releases"; Flags: ignoreversion uninsrestartdelete restartreplace recursesubdirs ; skip ./usr, ./var ; These are erlang requirements and not copied by our makefiles. ; From R14B01 onwards OTP may be built with a static OpenSSL so ; thse DLLs are now optional. Source: "%openssl_bin_dir%\ssleay32.dll"; DestDir: "{app}\bin"; Flags: ignoreversion uninsrestartdelete restartreplace skipifsourcedoesntexist Source: "%openssl_bin_dir%\libeay32.dll"; DestDir: "{app}\bin"; Flags: ignoreversion uninsrestartdelete restartreplace skipifsourcedoesntexist ; custom stuff... ; ./etc/default.ini is unconditional Source: "%locallibbindir%\..\etc\couchdb\default.ini"; DestDir: "{app}\etc\couchdb"; Flags: ignoreversion uninsrestartdelete restartreplace ; ./etc/local.ini is preserved and should not be updated if it exists Source: "%locallibbindir%\..\etc\couchdb\local.ini"; DestDir: "{app}\etc\couchdb"; Flags: onlyifdoesntexist uninsneveruninstall ; readme Source: "README.txt"; DestDir: "{app}"; Flags: isreadme ; msvc redists - see comments in configure.ac for notes about these... ; ( deleteafterinstall - not needed - {tmp} auto cleaned???? Source: "%msvc_redist_dir%\%msvc_redist_name%"; DestDir: "{tmp}"; Flags: deleteafterinstall [Dirs] Name: "{app}\var\lib\couchdb"; Permissions: authusers-modify Name: "{app}\var\log\couchdb"; Permissions: authusers-modify Name: "{app}\var\run\couchdb"; Permissions: authusers-modify Name: "{app}\etc\couchdb"; Permissions: authusers-modify [Icons] Name: "{group}\Start CouchDB"; Filename: "{app}\bin\couchdb.bat" Name: "{group}\Futon (CouchDB web interface)"; Filename: "http://127.0.0.1:5984/_utils" Name: "{group}\CouchDB Web Site"; Filename: "http://couchdb.apache.org/" Name: "{group}\CouchDB Online Docs"; Filename: "http://docs.couchdb.org/" Name: "{group}\CouchDB Embedded Docs"; Filename: "http://localhost:5984/_utils/docs/" [Tasks] Name: service; Description: "Install couchdb as a Windows service" Name: service\start; Description: "Start the service after installation" [Run] Filename: "{tmp}\%msvc_redist_name%"; Parameters: "/q" ; This is erlang's Install.exe which updates erl.ini correctly. Filename: "{app}\Install.exe"; Parameters: "-s"; Flags: runhidden ; Commands for a service ; First attempt to nuke an existing service of this name, incase they are ; reinstalling without uninstalling Filename: "{app}\erts-%erts_version%\bin\erlsrv.exe"; Parameters: "remove ""%package_name%"""; Flags: runhidden; Tasks: service ; add a new service, including automatic restart by default on failure Filename: "{app}\erts-%erts_version%\bin\erlsrv.exe"; Parameters: "add ""%package_name%"" -workdir ""{app}\bin"" -onfail restart_always -args ""-sasl errlog_type error -s couch +A 4 +W w"" -comment ""%package_name% %version%"""; Flags: runhidden; Tasks: service ; and start it if requested Filename: "{app}\erts-%erts_version%\bin\erlsrv.exe"; Parameters: "start ""%package_name%"""; Flags: runhidden; Tasks: service\start [UninstallRun] ; erlsrv stops services prior to removing them Filename: "{app}\erts-%erts_version%\bin\erlsrv.exe"; Parameters: "remove ""%package_name%"""; Flags: runhidden; Tasks: service ; kill epmd.exe if running to ensure uninstaller is not prevented from removing all binaries Filename: "{app}\erts-%erts_version%\bin\epmd.exe"; Parameters: "-kill"; Flags: runhidden apache-couchdb-1.5.0/src/0000755000175000001440000000000012230722306012124 500000000000000apache-couchdb-1.5.0/src/etap/0000755000175000001440000000000012230722306013055 500000000000000apache-couchdb-1.5.0/src/etap/etap.erl0000644000175000001440000004635712230722213014446 00000000000000%% Copyright (c) 2008-2009 Nick Gerakines %% %% 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. %% %% @author Nick Gerakines [http://socklabs.com/] %% @author Jeremy Wall %% @version 0.3.4 %% @copyright 2007-2008 Jeremy Wall, 2008-2009 Nick Gerakines %% @reference http://testanything.org/wiki/index.php/Main_Page %% @reference http://en.wikipedia.org/wiki/Test_Anything_Protocol %% @todo Finish implementing the skip directive. %% @todo Document the messages handled by this receive loop. %% @todo Explain in documentation why we use a process to handle test input. %% @doc etap is a TAP testing module for Erlang components and applications. %% This module allows developers to test their software using the TAP method. %% %%

%% TAP, the Test Anything Protocol, is a simple text-based interface between %% testing modules in a test harness. TAP started life as part of the test %% harness for Perl but now has implementations in C/C++, Python, PHP, Perl %% and probably others by the time you read this. %%

%% %% The testing process begins by defining a plan using etap:plan/1, running %% a number of etap tests and then calling eta:end_tests/0. Please refer to %% the Erlang modules in the t directory of this project for example tests. -module(etap). -vsn("0.3.4"). -export([ ensure_test_server/0, start_etap_server/0, test_server/1, msg/1, msg/2, diag/1, diag/2, expectation_mismatch_message/3, plan/1, end_tests/0, not_ok/2, ok/2, is_ok/2, is/3, isnt/3, any/3, none/3, fun_is/3, expect_fun/3, expect_fun/4, is_greater/3, skip/1, skip/2, datetime/1, skip/3, bail/0, bail/1, test_state/0, failure_count/0 ]). -export([ contains_ok/3, is_before/4 ]). -export([ is_pid/2, is_alive/2, is_mfa/3 ]). -export([ loaded_ok/2, can_ok/2, can_ok/3, has_attrib/2, is_attrib/3, is_behaviour/2 ]). -export([ dies_ok/2, lives_ok/2, throws_ok/3 ]). -record(test_state, { planned = 0, count = 0, pass = 0, fail = 0, skip = 0, skip_reason = "" }). %% @spec plan(N) -> Result %% N = unknown | skip | {skip, string()} | integer() %% Result = ok %% @doc Create a test plan and boot strap the test server. plan(unknown) -> ensure_test_server(), etap_server ! {self(), plan, unknown}, ok; plan(skip) -> io:format("1..0 # skip~n"); plan({skip, Reason}) -> io:format("1..0 # skip ~s~n", [Reason]); plan(N) when is_integer(N), N > 0 -> ensure_test_server(), etap_server ! {self(), plan, N}, ok. %% @spec end_tests() -> ok %% @doc End the current test plan and output test results. %% @todo This should probably be done in the test_server process. end_tests() -> Ref = make_ref(), case whereis(etap_server) of undefined -> self() ! {Ref, true}; _ -> etap_server ! {self(), state, Ref} end, State = receive {Ref, X} -> X end, if is_record(State, test_state) andalso State#test_state.planned == -1 -> io:format("1..~p~n", [State#test_state.count]); true -> ok end, case whereis(etap_server) of undefined -> ok; _ -> etap_server ! done, ok end. bail() -> bail(""). bail(Reason) -> etap_server ! {self(), diag, "Bail out! " ++ Reason}, etap_server ! done, ok, ok. %% @spec test_state() -> Return %% Return = test_state_record() | {error, string()} %% @doc Return the current test state test_state() -> etap_server ! {self(), state}, receive X when is_record(X, test_state) -> X after 1000 -> {error, "Timed out waiting for etap server reply.~n"} end. %% @spec failure_count() -> Return %% Return = integer() | {error, string()} %% @doc Return the current failure count failure_count() -> case test_state() of #test_state{fail=FailureCount} -> FailureCount; X -> X end. %% @spec msg(S) -> ok %% S = string() %% @doc Print a message in the test output. msg(S) -> etap_server ! {self(), diag, S}, ok. %% @spec msg(Format, Data) -> ok %% Format = atom() | string() | binary() %% Data = [term()] %% UnicodeList = [Unicode] %% Unicode = int() %% @doc Print a message in the test output. %% Function arguments are passed through io_lib:format/2. msg(Format, Data) -> msg(io_lib:format(Format, Data)). %% @spec diag(S) -> ok %% S = string() %% @doc Print a debug/status message related to the test suite. diag(S) -> msg("# " ++ S). %% @spec diag(Format, Data) -> ok %% Format = atom() | string() | binary() %% Data = [term()] %% UnicodeList = [Unicode] %% Unicode = int() %% @doc Print a debug/status message related to the test suite. %% Function arguments are passed through io_lib:format/2. diag(Format, Data) -> diag(io_lib:format(Format, Data)). %% @spec expectation_mismatch_message(Got, Expected, Desc) -> ok %% Got = any() %% Expected = any() %% Desc = string() %% @doc Print an expectation mismatch message in the test output. expectation_mismatch_message(Got, Expected, Desc) -> msg(" ---"), msg(" description: ~p", [Desc]), msg(" found: ~p", [Got]), msg(" wanted: ~p", [Expected]), msg(" ..."), ok. % @spec evaluate(Pass, Got, Expected, Desc) -> Result %% Pass = true | false %% Got = any() %% Expected = any() %% Desc = string() %% Result = true | false %% @doc Evaluate a test statement, printing an expectation mismatch message %% if the test failed. evaluate(Pass, Got, Expected, Desc) -> case mk_tap(Pass, Desc) of false -> expectation_mismatch_message(Got, Expected, Desc), false; true -> true end. %% @spec ok(Expr, Desc) -> Result %% Expr = true | false %% Desc = string() %% Result = true | false %% @doc Assert that a statement is true. ok(Expr, Desc) -> evaluate(Expr == true, Expr, true, Desc). %% @spec not_ok(Expr, Desc) -> Result %% Expr = true | false %% Desc = string() %% Result = true | false %% @doc Assert that a statement is false. not_ok(Expr, Desc) -> evaluate(Expr == false, Expr, false, Desc). %% @spec is_ok(Expr, Desc) -> Result %% Expr = any() %% Desc = string() %% Result = true | false %% @doc Assert that two values are the same. is_ok(Expr, Desc) -> evaluate(Expr == ok, Expr, ok, Desc). %% @spec is(Got, Expected, Desc) -> Result %% Got = any() %% Expected = any() %% Desc = string() %% Result = true | false %% @doc Assert that two values are the same. is(Got, Expected, Desc) -> evaluate(Got == Expected, Got, Expected, Desc). %% @spec isnt(Got, Expected, Desc) -> Result %% Got = any() %% Expected = any() %% Desc = string() %% Result = true | false %% @doc Assert that two values are not the same. isnt(Got, Expected, Desc) -> evaluate(Got /= Expected, Got, Expected, Desc). %% @spec is_greater(ValueA, ValueB, Desc) -> Result %% ValueA = number() %% ValueB = number() %% Desc = string() %% Result = true | false %% @doc Assert that an integer is greater than another. is_greater(ValueA, ValueB, Desc) when is_integer(ValueA), is_integer(ValueB) -> mk_tap(ValueA > ValueB, Desc). %% @spec any(Got, Items, Desc) -> Result %% Got = any() %% Items = [any()] %% Desc = string() %% Result = true | false %% @doc Assert that an item is in a list. any(Got, Items, Desc) when is_function(Got) -> is(lists:any(Got, Items), true, Desc); any(Got, Items, Desc) -> is(lists:member(Got, Items), true, Desc). %% @spec none(Got, Items, Desc) -> Result %% Got = any() %% Items = [any()] %% Desc = string() %% Result = true | false %% @doc Assert that an item is not in a list. none(Got, Items, Desc) when is_function(Got) -> is(lists:any(Got, Items), false, Desc); none(Got, Items, Desc) -> is(lists:member(Got, Items), false, Desc). %% @spec fun_is(Fun, Expected, Desc) -> Result %% Fun = function() %% Expected = any() %% Desc = string() %% Result = true | false %% @doc Use an anonymous function to assert a pattern match. fun_is(Fun, Expected, Desc) when is_function(Fun) -> is(Fun(Expected), true, Desc). %% @spec expect_fun(ExpectFun, Got, Desc) -> Result %% ExpectFun = function() %% Got = any() %% Desc = string() %% Result = true | false %% @doc Use an anonymous function to assert a pattern match, using actual %% value as the argument to the function. expect_fun(ExpectFun, Got, Desc) -> evaluate(ExpectFun(Got), Got, ExpectFun, Desc). %% @spec expect_fun(ExpectFun, Got, Desc, ExpectStr) -> Result %% ExpectFun = function() %% Got = any() %% Desc = string() %% ExpectStr = string() %% Result = true | false %% @doc Use an anonymous function to assert a pattern match, using actual %% value as the argument to the function. expect_fun(ExpectFun, Got, Desc, ExpectStr) -> evaluate(ExpectFun(Got), Got, ExpectStr, Desc). %% @equiv skip(TestFun, "") skip(TestFun) when is_function(TestFun) -> skip(TestFun, ""). %% @spec skip(TestFun, Reason) -> ok %% TestFun = function() %% Reason = string() %% @doc Skip a test. skip(TestFun, Reason) when is_function(TestFun), is_list(Reason) -> begin_skip(Reason), catch TestFun(), end_skip(), ok. %% @spec skip(Q, TestFun, Reason) -> ok %% Q = true | false | function() %% TestFun = function() %% Reason = string() %% @doc Skips a test conditionally. The first argument to this function can %% either be the 'true' or 'false' atoms or a function that returns 'true' or %% 'false'. skip(QFun, TestFun, Reason) when is_function(QFun), is_function(TestFun), is_list(Reason) -> case QFun() of true -> begin_skip(Reason), TestFun(), end_skip(); _ -> TestFun() end, ok; skip(Q, TestFun, Reason) when is_function(TestFun), is_list(Reason), Q == true -> begin_skip(Reason), TestFun(), end_skip(), ok; skip(_, TestFun, Reason) when is_function(TestFun), is_list(Reason) -> TestFun(), ok. %% @private begin_skip(Reason) -> etap_server ! {self(), begin_skip, Reason}. %% @private end_skip() -> etap_server ! {self(), end_skip}. %% @spec contains_ok(string(), string(), string()) -> true | false %% @doc Assert that a string is contained in another string. contains_ok(Source, String, Desc) -> etap:isnt( string:str(Source, String), 0, Desc ). %% @spec is_before(string(), string(), string(), string()) -> true | false %% @doc Assert that a string comes before another string within a larger body. is_before(Source, StringA, StringB, Desc) -> etap:is_greater( string:str(Source, StringB), string:str(Source, StringA), Desc ). %% @doc Assert that a given variable is a pid. is_pid(Pid, Desc) when is_pid(Pid) -> etap:ok(true, Desc); is_pid(_, Desc) -> etap:ok(false, Desc). %% @doc Assert that a given process/pid is alive. is_alive(Pid, Desc) -> etap:ok(erlang:is_process_alive(Pid), Desc). %% @doc Assert that the current function of a pid is a given {M, F, A} tuple. is_mfa(Pid, MFA, Desc) -> etap:is({current_function, MFA}, erlang:process_info(Pid, current_function), Desc). %% @spec loaded_ok(atom(), string()) -> true | false %% @doc Assert that a module has been loaded successfully. loaded_ok(M, Desc) when is_atom(M) -> etap:fun_is(fun({module, _}) -> true; (_) -> false end, code:load_file(M), Desc). %% @spec can_ok(atom(), atom()) -> true | false %% @doc Assert that a module exports a given function. can_ok(M, F) when is_atom(M), is_atom(F) -> Matches = [X || {X, _} <- M:module_info(exports), X == F], etap:ok(Matches > 0, lists:concat([M, " can ", F])). %% @spec can_ok(atom(), atom(), integer()) -> true | false %% @doc Assert that a module exports a given function with a given arity. can_ok(M, F, A) when is_atom(M); is_atom(F), is_number(A) -> Matches = [X || X <- M:module_info(exports), X == {F, A}], etap:ok(Matches > 0, lists:concat([M, " can ", F, "/", A])). %% @spec has_attrib(M, A) -> true | false %% M = atom() %% A = atom() %% @doc Asserts that a module has a given attribute. has_attrib(M, A) when is_atom(M), is_atom(A) -> etap:isnt( proplists:get_value(A, M:module_info(attributes), 'asdlkjasdlkads'), 'asdlkjasdlkads', lists:concat([M, " has attribute ", A]) ). %% @spec has_attrib(M, A. V) -> true | false %% M = atom() %% A = atom() %% V = any() %% @doc Asserts that a module has a given attribute with a given value. is_attrib(M, A, V) when is_atom(M) andalso is_atom(A) -> etap:is( proplists:get_value(A, M:module_info(attributes)), [V], lists:concat([M, "'s ", A, " is ", V]) ). %% @spec is_behavior(M, B) -> true | false %% M = atom() %% B = atom() %% @doc Asserts that a given module has a specific behavior. is_behaviour(M, B) when is_atom(M) andalso is_atom(B) -> is_attrib(M, behaviour, B). %% @doc Assert that an exception is raised when running a given function. dies_ok(F, Desc) -> case (catch F()) of {'EXIT', _} -> etap:ok(true, Desc); _ -> etap:ok(false, Desc) end. %% @doc Assert that an exception is not raised when running a given function. lives_ok(F, Desc) -> etap:is(try_this(F), success, Desc). %% @doc Assert that the exception thrown by a function matches the given exception. throws_ok(F, Exception, Desc) -> try F() of _ -> etap:ok(nok, Desc) catch _:E -> etap:is(E, Exception, Desc) end. %% @private %% @doc Run a function and catch any exceptions. try_this(F) when is_function(F, 0) -> try F() of _ -> success catch throw:E -> {throw, E}; error:E -> {error, E}; exit:E -> {exit, E} end. %% @private %% @doc Start the etap_server process if it is not running already. ensure_test_server() -> case whereis(etap_server) of undefined -> proc_lib:start(?MODULE, start_etap_server,[]); _ -> diag("The test server is already running.") end. %% @private %% @doc Start the etap_server loop and register itself as the etap_server %% process. start_etap_server() -> catch register(etap_server, self()), proc_lib:init_ack(ok), etap:test_server(#test_state{ planned = 0, count = 0, pass = 0, fail = 0, skip = 0, skip_reason = "" }). %% @private %% @doc The main etap_server receive/run loop. The etap_server receive loop %% responds to seven messages apperatining to failure or passing of tests. %% It is also used to initiate the testing process with the {_, plan, _} %% message that clears the current test state. test_server(State) -> NewState = receive {_From, plan, unknown} -> io:format("# Current time local ~s~n", [datetime(erlang:localtime())]), io:format("# Using etap version ~p~n", [ proplists:get_value(vsn, proplists:get_value(attributes, etap:module_info())) ]), State#test_state{ planned = -1, count = 0, pass = 0, fail = 0, skip = 0, skip_reason = "" }; {_From, plan, N} -> io:format("# Current time local ~s~n", [datetime(erlang:localtime())]), io:format("# Using etap version ~p~n", [ proplists:get_value(vsn, proplists:get_value(attributes, etap:module_info())) ]), io:format("1..~p~n", [N]), State#test_state{ planned = N, count = 0, pass = 0, fail = 0, skip = 0, skip_reason = "" }; {_From, begin_skip, Reason} -> State#test_state{ skip = 1, skip_reason = Reason }; {_From, end_skip} -> State#test_state{ skip = 0, skip_reason = "" }; {_From, pass, Desc} -> FullMessage = skip_diag( " - " ++ Desc, State#test_state.skip, State#test_state.skip_reason ), io:format("ok ~p ~s~n", [State#test_state.count + 1, FullMessage]), State#test_state{ count = State#test_state.count + 1, pass = State#test_state.pass + 1 }; {_From, fail, Desc} -> FullMessage = skip_diag( " - " ++ Desc, State#test_state.skip, State#test_state.skip_reason ), io:format("not ok ~p ~s~n", [State#test_state.count + 1, FullMessage]), State#test_state{ count = State#test_state.count + 1, fail = State#test_state.fail + 1 }; {From, state, Ref} -> From ! {Ref, State}, State; {_From, diag, Message} -> io:format("~s~n", [Message]), State; {From, count} -> From ! State#test_state.count, State; {From, is_skip, Ref} -> From ! {Ref, State#test_state.skip}, State; done -> exit(normal) end, test_server(NewState). %% @private %% @doc Process the result of a test and send it to the etap_server process. mk_tap(Result, Desc) -> etap_server ! {self(), is_skip, Ref = make_ref()} , receive {Ref, IsSkip} -> ok end, case [IsSkip, Result] of [_, true] -> etap_server ! {self(), pass, Desc}, true; [1, _] -> etap_server ! {self(), pass, Desc}, true; _ -> etap_server ! {self(), fail, Desc}, false end. %% @private %% @doc Format a date/time string. datetime(DateTime) -> {{Year, Month, Day}, {Hour, Min, Sec}} = DateTime, io_lib:format("~4.10.0B-~2.10.0B-~2.10.0B ~2.10.0B:~2.10.0B:~2.10.0B", [Year, Month, Day, Hour, Min, Sec]). %% @private %% @doc Craft an output message taking skip/todo into consideration. skip_diag(Message, 0, _) -> Message; skip_diag(_Message, 1, "") -> " # SKIP"; skip_diag(_Message, 1, Reason) -> " # SKIP : " ++ Reason. apache-couchdb-1.5.0/src/etap/Makefile.am0000644000175000001440000000155612230722213015035 00000000000000## 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. etapebindir = $(localerlanglibdir)/etap/ebin etap_file_collection = \ etap.erl etapebin_make_generated_file_list = \ etap.beam etapebin_DATA = $(etapebin_make_generated_file_list) EXTRA_DIST = $(etap_file_collection) CLEANFILES = $(etapebin_make_generated_file_list) %.beam: %.erl $(ERLC) $(ERLC_FLAGS) $< apache-couchdb-1.5.0/src/etap/Makefile.in0000644000175000001440000003520412230722244015047 00000000000000# Makefile.in generated by automake 1.11.6 from Makefile.am. # @configure_input@ # Copyright (C) 1994, 1995, 1996, 1997, 1998, 1999, 2000, 2001, 2002, # 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011 Free Software # Foundation, Inc. # This Makefile.in is free software; the Free Software Foundation # gives unlimited permission to copy and/or distribute it, # with or without modifications, as long as this notice is preserved. # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY, to the extent permitted by law; without # even the implied warranty of MERCHANTABILITY or FITNESS FOR A # PARTICULAR PURPOSE. @SET_MAKE@ VPATH = @srcdir@ am__make_dryrun = \ { \ am__dry=no; \ case $$MAKEFLAGS in \ *\\[\ \ ]*) \ echo 'am--echo: ; @echo "AM" OK' | $(MAKE) -f - 2>/dev/null \ | grep '^AM OK$$' >/dev/null || am__dry=yes;; \ *) \ for am__flg in $$MAKEFLAGS; do \ case $$am__flg in \ *=*|--*) ;; \ *n*) am__dry=yes; break;; \ esac; \ done;; \ esac; \ test $$am__dry = yes; \ } pkgdatadir = $(datadir)/@PACKAGE@ pkgincludedir = $(includedir)/@PACKAGE@ pkglibdir = $(libdir)/@PACKAGE@ pkglibexecdir = $(libexecdir)/@PACKAGE@ am__cd = CDPATH="$${ZSH_VERSION+.}$(PATH_SEPARATOR)" && cd install_sh_DATA = $(install_sh) -c -m 644 install_sh_PROGRAM = $(install_sh) -c install_sh_SCRIPT = $(install_sh) -c INSTALL_HEADER = $(INSTALL_DATA) transform = $(program_transform_name) NORMAL_INSTALL = : PRE_INSTALL = : POST_INSTALL = : NORMAL_UNINSTALL = : PRE_UNINSTALL = : POST_UNINSTALL = : build_triplet = @build@ host_triplet = @host@ subdir = src/etap DIST_COMMON = $(srcdir)/Makefile.am $(srcdir)/Makefile.in ACLOCAL_M4 = $(top_srcdir)/aclocal.m4 am__aclocal_m4_deps = $(top_srcdir)/m4/libtool.m4 \ $(top_srcdir)/m4/ltoptions.m4 $(top_srcdir)/m4/ltsugar.m4 \ $(top_srcdir)/m4/ltversion.m4 $(top_srcdir)/m4/lt~obsolete.m4 \ $(top_srcdir)/acinclude.m4 $(top_srcdir)/configure.ac am__configure_deps = $(am__aclocal_m4_deps) $(CONFIGURE_DEPENDENCIES) \ $(ACLOCAL_M4) mkinstalldirs = $(install_sh) -d CONFIG_HEADER = $(top_builddir)/config.h \ $(top_builddir)/src/snappy/google-snappy/config.h CONFIG_CLEAN_FILES = CONFIG_CLEAN_VPATH_FILES = SOURCES = DIST_SOURCES = am__can_run_installinfo = \ case $$AM_UPDATE_INFO_DIR in \ n|no|NO) false;; \ *) (install-info --version) >/dev/null 2>&1;; \ esac am__vpath_adj_setup = srcdirstrip=`echo "$(srcdir)" | sed 's|.|.|g'`; am__vpath_adj = case $$p in \ $(srcdir)/*) f=`echo "$$p" | sed "s|^$$srcdirstrip/||"`;; \ *) f=$$p;; \ esac; am__strip_dir = f=`echo $$p | sed -e 's|^.*/||'`; am__install_max = 40 am__nobase_strip_setup = \ srcdirstrip=`echo "$(srcdir)" | sed 's/[].[^$$\\*|]/\\\\&/g'` am__nobase_strip = \ for p in $$list; do echo "$$p"; done | sed -e "s|$$srcdirstrip/||" am__nobase_list = $(am__nobase_strip_setup); \ for p in $$list; do echo "$$p $$p"; done | \ sed "s| $$srcdirstrip/| |;"' / .*\//!s/ .*/ ./; s,\( .*\)/[^/]*$$,\1,' | \ $(AWK) 'BEGIN { files["."] = "" } { files[$$2] = files[$$2] " " $$1; \ if (++n[$$2] == $(am__install_max)) \ { print $$2, files[$$2]; n[$$2] = 0; files[$$2] = "" } } \ END { for (dir in files) print dir, files[dir] }' am__base_list = \ sed '$$!N;$$!N;$$!N;$$!N;$$!N;$$!N;$$!N;s/\n/ /g' | \ sed '$$!N;$$!N;$$!N;$$!N;s/\n/ /g' am__uninstall_files_from_dir = { \ test -z "$$files" \ || { test ! -d "$$dir" && test ! -f "$$dir" && test ! -r "$$dir"; } \ || { echo " ( cd '$$dir' && rm -f" $$files ")"; \ $(am__cd) "$$dir" && rm -f $$files; }; \ } am__installdirs = "$(DESTDIR)$(etapebindir)" DATA = $(etapebin_DATA) DISTFILES = $(DIST_COMMON) $(DIST_SOURCES) $(TEXINFOS) $(EXTRA_DIST) ACLOCAL = @ACLOCAL@ AMTAR = @AMTAR@ AR = @AR@ AS = @AS@ AUTOCONF = @AUTOCONF@ AUTOHEADER = @AUTOHEADER@ AUTOMAKE = @AUTOMAKE@ AWK = @AWK@ CC = @CC@ CCDEPMODE = @CCDEPMODE@ CFLAGS = @CFLAGS@ CPP = @CPP@ CPPFLAGS = @CPPFLAGS@ CURL_CFLAGS = @CURL_CFLAGS@ CURL_CONFIG = @CURL_CONFIG@ CURL_LIBS = @CURL_LIBS@ CXX = @CXX@ CXXCPP = @CXXCPP@ CXXDEPMODE = @CXXDEPMODE@ CXXFLAGS = @CXXFLAGS@ CYGPATH_W = @CYGPATH_W@ DEFS = @DEFS@ DEPDIR = @DEPDIR@ DLLTOOL = @DLLTOOL@ DSYMUTIL = @DSYMUTIL@ DUMPBIN = @DUMPBIN@ ECHO_C = @ECHO_C@ ECHO_N = @ECHO_N@ ECHO_T = @ECHO_T@ EGREP = @EGREP@ ERL = @ERL@ ERLANG_FLAGS = @ERLANG_FLAGS@ ERLC = @ERLC@ ERLC_FLAGS = @ERLC_FLAGS@ ESCRIPT = @ESCRIPT@ EXEEXT = @EXEEXT@ FGREP = @FGREP@ FLAGS = @FLAGS@ GREP = @GREP@ HAS_HELP2MAN = @HAS_HELP2MAN@ HAS_INSTALLINFO = @HAS_INSTALLINFO@ HAS_MAKEINFO = @HAS_MAKEINFO@ HAS_PDFLATEX = @HAS_PDFLATEX@ HAS_SPHINX_BUILD = @HAS_SPHINX_BUILD@ ICU_BIN = @ICU_BIN@ ICU_CFLAGS = @ICU_CFLAGS@ ICU_CONFIG = @ICU_CONFIG@ ICU_CPPFLAGS = @ICU_CPPFLAGS@ ICU_CXXFLAGS = @ICU_CXXFLAGS@ ICU_LIBS = @ICU_LIBS@ INNO_COMPILER_EXECUTABLE = @INNO_COMPILER_EXECUTABLE@ INSTALL = @INSTALL@ INSTALL_DATA = @INSTALL_DATA@ INSTALL_PROGRAM = @INSTALL_PROGRAM@ INSTALL_SCRIPT = @INSTALL_SCRIPT@ INSTALL_STRIP_PROGRAM = @INSTALL_STRIP_PROGRAM@ JS_CFLAGS = @JS_CFLAGS@ JS_LIBS = @JS_LIBS@ JS_LIB_BINARY = @JS_LIB_BINARY@ LD = @LD@ LDFLAGS = @LDFLAGS@ LIBOBJS = @LIBOBJS@ LIBS = @LIBS@ LIBTOOL = @LIBTOOL@ LIPO = @LIPO@ LN_S = @LN_S@ LTLIBOBJS = @LTLIBOBJS@ MAKEINFO = @MAKEINFO@ MANIFEST_TOOL = @MANIFEST_TOOL@ MKDIR_P = @MKDIR_P@ NM = @NM@ NMEDIT = @NMEDIT@ OBJDUMP = @OBJDUMP@ OBJEXT = @OBJEXT@ OTOOL = @OTOOL@ OTOOL64 = @OTOOL64@ PACKAGE = @PACKAGE@ PACKAGE_BUGREPORT = @PACKAGE_BUGREPORT@ PACKAGE_NAME = @PACKAGE_NAME@ PACKAGE_STRING = @PACKAGE_STRING@ PACKAGE_TARNAME = @PACKAGE_TARNAME@ PACKAGE_URL = @PACKAGE_URL@ PACKAGE_VERSION = @PACKAGE_VERSION@ PATH_SEPARATOR = @PATH_SEPARATOR@ PKG_CONFIG = @PKG_CONFIG@ PKG_CONFIG_LIBDIR = @PKG_CONFIG_LIBDIR@ PKG_CONFIG_PATH = @PKG_CONFIG_PATH@ RANLIB = @RANLIB@ SED = @SED@ SET_MAKE = @SET_MAKE@ SHELL = @SHELL@ SNAPPY_MAJOR = @SNAPPY_MAJOR@ SNAPPY_MINOR = @SNAPPY_MINOR@ SNAPPY_PATCHLEVEL = @SNAPPY_PATCHLEVEL@ STRIP = @STRIP@ VERSION = @VERSION@ abs_builddir = @abs_builddir@ abs_srcdir = @abs_srcdir@ abs_top_builddir = @abs_top_builddir@ abs_top_srcdir = @abs_top_srcdir@ ac_ct_AR = @ac_ct_AR@ ac_ct_CC = @ac_ct_CC@ ac_ct_CXX = @ac_ct_CXX@ ac_ct_DUMPBIN = @ac_ct_DUMPBIN@ ac_cv_have_stddef_h = @ac_cv_have_stddef_h@ ac_cv_have_stdint_h = @ac_cv_have_stdint_h@ am__include = @am__include@ am__leading_dot = @am__leading_dot@ am__quote = @am__quote@ am__tar = @am__tar@ am__untar = @am__untar@ bindir = @bindir@ bug_uri = @bug_uri@ build = @build@ build_alias = @build_alias@ build_cpu = @build_cpu@ build_os = @build_os@ build_vendor = @build_vendor@ builddir = @builddir@ datadir = @datadir@ datarootdir = @datarootdir@ docdir = @docdir@ dvidir = @dvidir@ erlangbin = @erlangbin@ erlangversion = @erlangversion@ exec_prefix = @exec_prefix@ host = @host@ host_alias = @host_alias@ host_cpu = @host_cpu@ host_os = @host_os@ host_vendor = @host_vendor@ htmldir = @htmldir@ includedir = @includedir@ infodir = @infodir@ initdir = @initdir@ install_sh = @install_sh@ launchddir = @launchddir@ libdir = @libdir@ libexecdir = @libexecdir@ localconfdir = @localconfdir@ localdatadir = @localdatadir@ localdocdir = @localdocdir@ localedir = @localedir@ localerlanglibdir = @localerlanglibdir@ locallibbindir = @locallibbindir@ locallibdir = @locallibdir@ localstatedir = @localstatedir@ localstatelibdir = @localstatelibdir@ localstatelogdir = @localstatelogdir@ localstaterundir = @localstaterundir@ mandir = @mandir@ mkdir_p = @mkdir_p@ msvc_redist_dir = @msvc_redist_dir@ msvc_redist_name = @msvc_redist_name@ oldincludedir = @oldincludedir@ openssl_bin_dir = @openssl_bin_dir@ otp_release = @otp_release@ package_author_address = @package_author_address@ package_author_name = @package_author_name@ package_identifier = @package_identifier@ package_name = @package_name@ package_tarname = @package_tarname@ pdfdir = @pdfdir@ prefix = @prefix@ program_transform_name = @program_transform_name@ psdir = @psdir@ sbindir = @sbindir@ sharedstatedir = @sharedstatedir@ srcdir = @srcdir@ sysconfdir = @sysconfdir@ target_alias = @target_alias@ top_build_prefix = @top_build_prefix@ top_builddir = @top_builddir@ top_srcdir = @top_srcdir@ version = @version@ version_major = @version_major@ version_minor = @version_minor@ version_release = @version_release@ version_revision = @version_revision@ version_stage = @version_stage@ etapebindir = $(localerlanglibdir)/etap/ebin etap_file_collection = \ etap.erl etapebin_make_generated_file_list = \ etap.beam etapebin_DATA = $(etapebin_make_generated_file_list) EXTRA_DIST = $(etap_file_collection) CLEANFILES = $(etapebin_make_generated_file_list) all: all-am .SUFFIXES: $(srcdir)/Makefile.in: $(srcdir)/Makefile.am $(am__configure_deps) @for dep in $?; do \ case '$(am__configure_deps)' in \ *$$dep*) \ ( cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh ) \ && { if test -f $@; then exit 0; else break; fi; }; \ exit 1;; \ esac; \ done; \ echo ' cd $(top_srcdir) && $(AUTOMAKE) --foreign src/etap/Makefile'; \ $(am__cd) $(top_srcdir) && \ $(AUTOMAKE) --foreign src/etap/Makefile .PRECIOUS: Makefile Makefile: $(srcdir)/Makefile.in $(top_builddir)/config.status @case '$?' in \ *config.status*) \ cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh;; \ *) \ echo ' cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ $(am__depfiles_maybe)'; \ cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ $(am__depfiles_maybe);; \ esac; $(top_builddir)/config.status: $(top_srcdir)/configure $(CONFIG_STATUS_DEPENDENCIES) cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh $(top_srcdir)/configure: $(am__configure_deps) cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh $(ACLOCAL_M4): $(am__aclocal_m4_deps) cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh $(am__aclocal_m4_deps): mostlyclean-libtool: -rm -f *.lo clean-libtool: -rm -rf .libs _libs install-etapebinDATA: $(etapebin_DATA) @$(NORMAL_INSTALL) @list='$(etapebin_DATA)'; test -n "$(etapebindir)" || list=; \ if test -n "$$list"; then \ echo " $(MKDIR_P) '$(DESTDIR)$(etapebindir)'"; \ $(MKDIR_P) "$(DESTDIR)$(etapebindir)" || exit 1; \ fi; \ for p in $$list; do \ if test -f "$$p"; then d=; else d="$(srcdir)/"; fi; \ echo "$$d$$p"; \ done | $(am__base_list) | \ while read files; do \ echo " $(INSTALL_DATA) $$files '$(DESTDIR)$(etapebindir)'"; \ $(INSTALL_DATA) $$files "$(DESTDIR)$(etapebindir)" || exit $$?; \ done uninstall-etapebinDATA: @$(NORMAL_UNINSTALL) @list='$(etapebin_DATA)'; test -n "$(etapebindir)" || list=; \ files=`for p in $$list; do echo $$p; done | sed -e 's|^.*/||'`; \ dir='$(DESTDIR)$(etapebindir)'; $(am__uninstall_files_from_dir) tags: TAGS TAGS: ctags: CTAGS CTAGS: distdir: $(DISTFILES) @srcdirstrip=`echo "$(srcdir)" | sed 's/[].[^$$\\*]/\\\\&/g'`; \ topsrcdirstrip=`echo "$(top_srcdir)" | sed 's/[].[^$$\\*]/\\\\&/g'`; \ list='$(DISTFILES)'; \ dist_files=`for file in $$list; do echo $$file; done | \ sed -e "s|^$$srcdirstrip/||;t" \ -e "s|^$$topsrcdirstrip/|$(top_builddir)/|;t"`; \ case $$dist_files in \ */*) $(MKDIR_P) `echo "$$dist_files" | \ sed '/\//!d;s|^|$(distdir)/|;s,/[^/]*$$,,' | \ sort -u` ;; \ esac; \ for file in $$dist_files; do \ if test -f $$file || test -d $$file; then d=.; else d=$(srcdir); fi; \ if test -d $$d/$$file; then \ dir=`echo "/$$file" | sed -e 's,/[^/]*$$,,'`; \ if test -d "$(distdir)/$$file"; then \ find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} \;; \ fi; \ if test -d $(srcdir)/$$file && test $$d != $(srcdir); then \ cp -fpR $(srcdir)/$$file "$(distdir)$$dir" || exit 1; \ find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} \;; \ fi; \ cp -fpR $$d/$$file "$(distdir)$$dir" || exit 1; \ else \ test -f "$(distdir)/$$file" \ || cp -p $$d/$$file "$(distdir)/$$file" \ || exit 1; \ fi; \ done check-am: all-am check: check-am all-am: Makefile $(DATA) installdirs: for dir in "$(DESTDIR)$(etapebindir)"; do \ test -z "$$dir" || $(MKDIR_P) "$$dir"; \ done install: install-am install-exec: install-exec-am install-data: install-data-am uninstall: uninstall-am install-am: all-am @$(MAKE) $(AM_MAKEFLAGS) install-exec-am install-data-am installcheck: installcheck-am install-strip: if test -z '$(STRIP)'; then \ $(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(INSTALL_STRIP_PROGRAM)" \ install_sh_PROGRAM="$(INSTALL_STRIP_PROGRAM)" INSTALL_STRIP_FLAG=-s \ install; \ else \ $(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(INSTALL_STRIP_PROGRAM)" \ install_sh_PROGRAM="$(INSTALL_STRIP_PROGRAM)" INSTALL_STRIP_FLAG=-s \ "INSTALL_PROGRAM_ENV=STRIPPROG='$(STRIP)'" install; \ fi mostlyclean-generic: clean-generic: -test -z "$(CLEANFILES)" || rm -f $(CLEANFILES) distclean-generic: -test -z "$(CONFIG_CLEAN_FILES)" || rm -f $(CONFIG_CLEAN_FILES) -test . = "$(srcdir)" || test -z "$(CONFIG_CLEAN_VPATH_FILES)" || rm -f $(CONFIG_CLEAN_VPATH_FILES) maintainer-clean-generic: @echo "This command is intended for maintainers to use" @echo "it deletes files that may require special tools to rebuild." clean: clean-am clean-am: clean-generic clean-libtool mostlyclean-am distclean: distclean-am -rm -f Makefile distclean-am: clean-am distclean-generic dvi: dvi-am dvi-am: html: html-am html-am: info: info-am info-am: install-data-am: install-etapebinDATA install-dvi: install-dvi-am install-dvi-am: install-exec-am: install-html: install-html-am install-html-am: install-info: install-info-am install-info-am: install-man: install-pdf: install-pdf-am install-pdf-am: install-ps: install-ps-am install-ps-am: installcheck-am: maintainer-clean: maintainer-clean-am -rm -f Makefile maintainer-clean-am: distclean-am maintainer-clean-generic mostlyclean: mostlyclean-am mostlyclean-am: mostlyclean-generic mostlyclean-libtool pdf: pdf-am pdf-am: ps: ps-am ps-am: uninstall-am: uninstall-etapebinDATA .MAKE: install-am install-strip .PHONY: all all-am check check-am clean clean-generic clean-libtool \ distclean distclean-generic distclean-libtool distdir dvi \ dvi-am html html-am info info-am install install-am \ install-data install-data-am install-dvi install-dvi-am \ install-etapebinDATA install-exec install-exec-am install-html \ install-html-am install-info install-info-am install-man \ install-pdf install-pdf-am install-ps install-ps-am \ install-strip installcheck installcheck-am installdirs \ maintainer-clean maintainer-clean-generic mostlyclean \ mostlyclean-generic mostlyclean-libtool pdf pdf-am ps ps-am \ uninstall uninstall-am uninstall-etapebinDATA %.beam: %.erl $(ERLC) $(ERLC_FLAGS) $< # Tell versions [3.59,3.63) of GNU make to not export all variables. # Otherwise a system limit (for SysV at least) may be exceeded. .NOEXPORT: apache-couchdb-1.5.0/src/couchdb/0000755000175000001440000000000012230722304013531 500000000000000apache-couchdb-1.5.0/src/couchdb/couch_primary_sup.erl0000644000175000001440000000377512230722213017723 00000000000000% 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. -module(couch_primary_sup). -behaviour(supervisor). -export([init/1, start_link/0]). start_link() -> supervisor:start_link({local,couch_primary_services}, ?MODULE, []). init([]) -> Children = [ {collation_driver, {couch_drv, start_link, []}, permanent, infinity, supervisor, [couch_drv]}, {couch_task_status, {couch_task_status, start_link, []}, permanent, brutal_kill, worker, [couch_task_status]}, {couch_server, {couch_server, sup_start_link, []}, permanent, brutal_kill, worker, [couch_server]}, {couch_db_update_event, {gen_event, start_link, [{local, couch_db_update}]}, permanent, brutal_kill, worker, dynamic}, {couch_replication_event, {gen_event, start_link, [{local, couch_replication}]}, permanent, brutal_kill, worker, dynamic}, {couch_replicator_job_sup, {couch_replicator_job_sup, start_link, []}, permanent, infinity, supervisor, [couch_replicator_job_sup]}, {couch_log, {couch_log, start_link, []}, permanent, brutal_kill, worker, [couch_log]} ], {ok, {{one_for_one, 10, 3600}, Children}}. apache-couchdb-1.5.0/src/couchdb/priv/0000755000175000001440000000000012230722305014512 500000000000000apache-couchdb-1.5.0/src/couchdb/priv/spawnkillable/0000755000175000001440000000000012230722305017342 500000000000000apache-couchdb-1.5.0/src/couchdb/priv/spawnkillable/couchspawnkillable_win.c0000644000175000001440000001133712230722213024160 00000000000000// 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. // Do what 2 lines of shell script in couchspawnkillable does... // * Create a new suspended process with the same (duplicated) standard // handles as us. // * Write a line to stdout, consisting of the path to ourselves, plus // '--kill {pid}' where {pid} is the PID of the newly created process. // * Un-suspend the new process. // * Wait for the process to terminate. // * Terminate with the child's exit-code. // Later, couch will call us with --kill and the PID, so we dutifully // terminate the specified PID. #include #include "windows.h" char *get_child_cmdline(int argc, char **argv) { // make a new command-line, but skipping me. // XXX - todo - spaces etc in args??? int i; char *p, *cmdline; int nchars = 0; int nthis = 1; for (i=1;i #include #include "erl_nif_compat.h" #include "unicode/ucol.h" #include "unicode/ucasemap.h" #define MAX_DEPTH 10 #if (ERL_NIF_MAJOR_VERSION > 2) || \ (ERL_NIF_MAJOR_VERSION == 2 && ERL_NIF_MINOR_VERSION >= 3) /* OTP R15B or higher */ #define term_is_number(env, t) enif_is_number(env, t) #else #define term_is_number(env, t) \ (!enif_is_binary(env, t) && \ !enif_is_list(env, t) && \ !enif_is_tuple(env, t)) #endif static ERL_NIF_TERM ATOM_TRUE; static ERL_NIF_TERM ATOM_FALSE; static ERL_NIF_TERM ATOM_NULL; typedef struct { ErlNifEnv* env; int error; UCollator* coll; } ctx_t; static UCollator** collators = NULL; static int collStackTop = 0; static int numCollators = 0; static ErlNifMutex* collMutex = NULL; static ERL_NIF_TERM less_json_nif(ErlNifEnv*, int, const ERL_NIF_TERM []); static int on_load(ErlNifEnv*, void**, ERL_NIF_TERM); static void on_unload(ErlNifEnv*, void*); static __inline int less_json(int, ctx_t*, ERL_NIF_TERM, ERL_NIF_TERM); static __inline int atom_sort_order(ErlNifEnv*, ERL_NIF_TERM); static __inline int compare_strings(ctx_t*, ErlNifBinary, ErlNifBinary); static __inline int compare_lists(int, ctx_t*, ERL_NIF_TERM, ERL_NIF_TERM); static __inline int compare_props(int, ctx_t*, ERL_NIF_TERM, ERL_NIF_TERM); static __inline void reserve_coll(ctx_t*); static __inline void release_coll(ctx_t*); void reserve_coll(ctx_t *ctx) { if (ctx->coll == NULL) { enif_mutex_lock(collMutex); assert(collStackTop < numCollators); ctx->coll = collators[collStackTop]; collStackTop += 1; enif_mutex_unlock(collMutex); } } void release_coll(ctx_t *ctx) { if (ctx->coll != NULL) { enif_mutex_lock(collMutex); collStackTop -= 1; assert(collStackTop >= 0); enif_mutex_unlock(collMutex); } } ERL_NIF_TERM less_json_nif(ErlNifEnv* env, int argc, const ERL_NIF_TERM argv[]) { ctx_t ctx; int result; ctx.env = env; ctx.error = 0; ctx.coll = NULL; result = less_json(1, &ctx, argv[0], argv[1]); release_coll(&ctx); /* * There are 2 possible failure reasons: * * 1) We got an invalid EJSON operand; * 2) The EJSON structures are too deep - to avoid allocating too * many C stack frames (because less_json is a recursive function), * and running out of memory, we throw a badarg exception to Erlang * and do the comparison in Erlang land. In practice, views keys are * EJSON structures with very little nesting. */ return ctx.error ? enif_make_badarg(env) : enif_make_int(env, result); } int less_json(int depth, ctx_t* ctx, ERL_NIF_TERM a, ERL_NIF_TERM b) { int aIsAtom, bIsAtom; int aIsBin, bIsBin; int aIsNumber, bIsNumber; int aIsList, bIsList; int aArity, bArity; const ERL_NIF_TERM *aProps, *bProps; /* * Avoid too much recursion. Normally there isn't more than a few levels * of recursion, as in practice view keys do not go beyond 1 to 3 levels * of nesting. In case of too much recursion, signal it to the Erlang land * via an exception and do the EJSON comparison in Erlang land. */ if (depth > MAX_DEPTH) { ctx->error = 1; return 0; } aIsAtom = enif_is_atom(ctx->env, a); bIsAtom = enif_is_atom(ctx->env, b); if (aIsAtom) { if (bIsAtom) { int aSortOrd, bSortOrd; if ((aSortOrd = atom_sort_order(ctx->env, a)) == -1) { ctx->error = 1; return 0; } if ((bSortOrd = atom_sort_order(ctx->env, b)) == -1) { ctx->error = 1; return 0; } return aSortOrd - bSortOrd; } return -1; } if (bIsAtom) { return 1; } aIsNumber = term_is_number(ctx->env, a); bIsNumber = term_is_number(ctx->env, b); if (aIsNumber) { if (bIsNumber) { return enif_compare_compat(ctx->env, a, b); } return -1; } if (bIsNumber) { return 1; } aIsBin = enif_is_binary(ctx->env, a); bIsBin = enif_is_binary(ctx->env, b); if (aIsBin) { if (bIsBin) { ErlNifBinary binA, binB; enif_inspect_binary(ctx->env, a, &binA); enif_inspect_binary(ctx->env, b, &binB); return compare_strings(ctx, binA, binB); } return -1; } if (bIsBin) { return 1; } aIsList = enif_is_list(ctx->env, a); bIsList = enif_is_list(ctx->env, b); if (aIsList) { if (bIsList) { return compare_lists(depth, ctx, a, b); } return -1; } if (bIsList) { return 1; } if (!enif_get_tuple(ctx->env, a, &aArity, &aProps)) { ctx->error = 1; return 0; } if ((aArity != 1) || !enif_is_list(ctx->env, aProps[0])) { ctx->error = 1; return 0; } if (!enif_get_tuple(ctx->env, b, &bArity, &bProps)) { ctx->error = 1; return 0; } if ((bArity != 1) || !enif_is_list(ctx->env, bProps[0])) { ctx->error = 1; return 0; } return compare_props(depth, ctx, aProps[0], bProps[0]); } int atom_sort_order(ErlNifEnv* env, ERL_NIF_TERM a) { if (enif_compare_compat(env, a, ATOM_NULL) == 0) { return 1; } else if (enif_compare_compat(env, a, ATOM_FALSE) == 0) { return 2; } else if (enif_compare_compat(env, a, ATOM_TRUE) == 0) { return 3; } return -1; } int compare_lists(int depth, ctx_t* ctx, ERL_NIF_TERM a, ERL_NIF_TERM b) { ERL_NIF_TERM headA, tailA; ERL_NIF_TERM headB, tailB; int aIsEmpty, bIsEmpty; int result; while (1) { aIsEmpty = !enif_get_list_cell(ctx->env, a, &headA, &tailA); bIsEmpty = !enif_get_list_cell(ctx->env, b, &headB, &tailB); if (aIsEmpty) { if (bIsEmpty) { return 0; } return -1; } if (bIsEmpty) { return 1; } result = less_json(depth + 1, ctx, headA, headB); if (ctx->error || result != 0) { return result; } a = tailA; b = tailB; } return result; } int compare_props(int depth, ctx_t* ctx, ERL_NIF_TERM a, ERL_NIF_TERM b) { ERL_NIF_TERM headA, tailA; ERL_NIF_TERM headB, tailB; int aArity, bArity; const ERL_NIF_TERM *aKV, *bKV; ErlNifBinary keyA, keyB; int aIsEmpty, bIsEmpty; int keyCompResult, valueCompResult; while (1) { aIsEmpty = !enif_get_list_cell(ctx->env, a, &headA, &tailA); bIsEmpty = !enif_get_list_cell(ctx->env, b, &headB, &tailB); if (aIsEmpty) { if (bIsEmpty) { return 0; } return -1; } if (bIsEmpty) { return 1; } if (!enif_get_tuple(ctx->env, headA, &aArity, &aKV)) { ctx->error = 1; return 0; } if ((aArity != 2) || !enif_inspect_binary(ctx->env, aKV[0], &keyA)) { ctx->error = 1; return 0; } if (!enif_get_tuple(ctx->env, headB, &bArity, &bKV)) { ctx->error = 1; return 0; } if ((bArity != 2) || !enif_inspect_binary(ctx->env, bKV[0], &keyB)) { ctx->error = 1; return 0; } keyCompResult = compare_strings(ctx, keyA, keyB); if (ctx->error || keyCompResult != 0) { return keyCompResult; } valueCompResult = less_json(depth + 1, ctx, aKV[1], bKV[1]); if (ctx->error || valueCompResult != 0) { return valueCompResult; } a = tailA; b = tailB; } return 0; } int compare_strings(ctx_t* ctx, ErlNifBinary a, ErlNifBinary b) { UErrorCode status = U_ZERO_ERROR; UCharIterator iterA, iterB; int result; uiter_setUTF8(&iterA, (const char *) a.data, (uint32_t) a.size); uiter_setUTF8(&iterB, (const char *) b.data, (uint32_t) b.size); reserve_coll(ctx); result = ucol_strcollIter(ctx->coll, &iterA, &iterB, &status); if (U_FAILURE(status)) { ctx->error = 1; return 0; } /* ucol_strcollIter returns 0, -1 or 1 * (see type UCollationResult in unicode/ucol.h) */ return result; } int on_load(ErlNifEnv* env, void** priv, ERL_NIF_TERM info) { UErrorCode status = U_ZERO_ERROR; int i, j; if (!enif_get_int(env, info, &numCollators)) { return 1; } if (numCollators < 1) { return 2; } collMutex = enif_mutex_create("coll_mutex"); if (collMutex == NULL) { return 3; } collators = enif_alloc(sizeof(UCollator*) * numCollators); if (collators == NULL) { enif_mutex_destroy(collMutex); return 4; } for (i = 0; i < numCollators; i++) { collators[i] = ucol_open("", &status); if (U_FAILURE(status)) { for (j = 0; j < i; j++) { ucol_close(collators[j]); } enif_free(collators); enif_mutex_destroy(collMutex); return 5; } } ATOM_TRUE = enif_make_atom(env, "true"); ATOM_FALSE = enif_make_atom(env, "false"); ATOM_NULL = enif_make_atom(env, "null"); return 0; } void on_unload(ErlNifEnv* env, void* priv_data) { if (collators != NULL) { int i; for (i = 0; i < numCollators; i++) { ucol_close(collators[i]); } enif_free(collators); } if (collMutex != NULL) { enif_mutex_destroy(collMutex); } } static ErlNifFunc nif_functions[] = { {"less_nif", 2, less_json_nif} }; #ifdef __cplusplus extern "C" { #endif ERL_NIF_INIT(couch_ejson_compare, nif_functions, &on_load, NULL, NULL, &on_unload); #ifdef __cplusplus } #endif apache-couchdb-1.5.0/src/couchdb/priv/couch_ejson_compare/erl_nif_compat.h0000644000175000001440000000713412230722213023574 00000000000000/* Copyright (c) 2010-2011 Basho Technologies, Inc. * With some minor modifications for Apache CouchDB. * * This file is provided to you 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. */ #ifndef ERL_NIF_COMPAT_H_ #define ERL_NIF_COMPAT_H_ #ifdef __cplusplus extern "C" { #endif /* __cplusplus */ #include "erl_nif.h" #if ERL_NIF_MAJOR_VERSION == 0 && ERL_NIF_MINOR_VERSION == 1 #define OTP_R13B03 #elif ERL_NIF_MAJOR_VERSION == 1 && ERL_NIF_MINOR_VERSION == 0 #define OTP_R13B04 #elif ERL_NIF_MAJOR_VERSION == 2 && ERL_NIF_MINOR_VERSION == 0 #define OTP_R14A #define OTP_R14B #define OTP_R14B01 #elif ERL_NIF_MAJOR_VERSION == 2 && ERL_NIF_MINOR_VERSION == 1 #define OTP_R14B02 #elif ERL_NIF_MAJOR_VERSION == 2 && ERL_NIF_MINOR_VERSION == 2 #define OTP_R14B03 #endif #ifdef OTP_R13B03 #define enif_open_resource_type_compat enif_open_resource_type #define enif_alloc_resource_compat enif_alloc_resource #define enif_release_resource_compat enif_release_resource #define enif_alloc_binary_compat enif_alloc_binary #define enif_alloc_compat enif_alloc #define enif_release_binary_compat enif_release_binary #define enif_free_compat enif_free #define enif_get_atom_compat enif_get_atom #define enif_priv_data_compat enif_get_data #define enif_make_uint_compat enif_make_ulong #define enif_make_string_compat(E, B, Enc) \ enif_make_string(E, B) #define enif_compare_compat enif_compare #endif /* R13B03 */ #ifdef OTP_R13B04 #define enif_open_resource_type_compat enif_open_resource_type #define enif_alloc_resource_compat enif_alloc_resource #define enif_release_resource_compat enif_release_resource #define enif_alloc_binary_compat enif_alloc_binary #define enif_realloc_binary_compat enif_realloc_binary #define enif_release_binary_compat enif_release_binary #define enif_alloc_compat enif_alloc #define enif_free_compat enif_free #define enif_get_atom_compat enif_get_atom #define enif_priv_data_compat enif_priv_data #define enif_make_string_compat enif_make_string #define enif_make_uint_compat enif_make_uint #define enif_compare_compat enif_compare #endif /* R13B04 */ /* OTP R14 and future releases */ #if !defined(OTP_R13B03) && !defined(OTP_R13B04) #define enif_open_resource_type_compat(E, N, D, F, T) \ enif_open_resource_type(E, NULL, N, D, F, T) #define enif_alloc_resource_compat(E, T, S) \ enif_alloc_resource(T, S) #define enif_release_resource_compat(E, H) \ enif_release_resource(H) #define enif_alloc_binary_compat(E, S, B) \ enif_alloc_binary(S, B) #define enif_realloc_binary_compat(E, S, B) \ enif_realloc_binary(S, B) #define enif_release_binary_compat(E, B) \ enif_release_binary(B) #define enif_alloc_compat(E, S) \ enif_alloc(S) #define enif_free_compat(E, P) \ enif_free(P) #define enif_get_atom_compat(E, T, B, S) \ enif_get_atom(E, T, B, S, ERL_NIF_LATIN1) #define enif_priv_data_compat enif_priv_data #define enif_make_string_compat enif_make_string #define enif_make_uint_compat enif_make_uint #define enif_compare_compat(E, A, B) \ enif_compare(A, B) #endif /* R14 and future releases */ #ifdef __cplusplus } #endif /* __cplusplus */ #endif /* ERL_NIF_COMPAT_H_ */ apache-couchdb-1.5.0/src/couchdb/priv/couchjs.10000644000175000001440000000262712230722305016161 00000000000000.\" DO NOT MODIFY THIS FILE! It was generated by help2man 1.40.11. .TH COUCHJS "1" "October 2013" "couchjs - Apache CouchDB 1.5.0" "User Commands" .SH NAME couchjs \- Apache CouchDB JavaScript interpreter .SH SYNOPSIS .B couchjs [\fIFILE\fR] .SH DESCRIPTION The couchjs command runs the Apache CouchDB JavaScript interpreter. .PP The exit status is 0 for success or 1 for failure. .SH OPTIONS .TP \fB\-h\fR display a short help message and exit .TP \fB\-V\fR display version information and exit .TP \fB\-H\fR enable couchjs cURL bindings (only avaiable if package was built with cURL available) .TP \fB\-S\fR SIZE specify that the runtime should allow at most SIZE bytes of memory to be allocated .TP \fB\-u\fR FILE path to a .uri file containing the address (or addresses) of one or more servers .SH "REPORTING BUGS" Report bugs at . .PP .br 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 ofthe .br License at .IP http://www.apache.org/licenses/LICENSE\-2.0 .PP .br 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 .br CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. apache-couchdb-1.5.0/src/couchdb/priv/icu_driver/0000755000175000001440000000000012230722305016645 500000000000000apache-couchdb-1.5.0/src/couchdb/priv/icu_driver/couch_icu_driver.c0000644000175000001440000001317612230722213022253 00000000000000/* 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. */ /* This file is the C port driver for Erlang. It provides a low overhead * means of calling into C code, however coding errors in this module can * crash the entire Erlang server. */ #ifdef DARWIN #define U_HIDE_DRAFT_API 1 #define U_DISABLE_RENAMING 1 #endif #include "erl_driver.h" #include "unicode/ucol.h" #include "unicode/ucasemap.h" #ifndef WIN32 #include /* for memcpy */ #endif #if ERL_DRV_EXTENDED_MAJOR_VERSION < 2 typedef int COUCH_SSIZET; #else typedef ErlDrvSSizeT COUCH_SSIZET; #endif typedef struct { ErlDrvPort port; UCollator* collNoCase; UCollator* coll; } couch_drv_data; static void couch_drv_stop(ErlDrvData data) { couch_drv_data* pData = (couch_drv_data*)data; if (pData->coll) { ucol_close(pData->coll); } if (pData->collNoCase) { ucol_close(pData->collNoCase); } driver_free((void*)pData); } static ErlDrvData couch_drv_start(ErlDrvPort port, char *buff) { UErrorCode status = U_ZERO_ERROR; couch_drv_data* pData = (couch_drv_data*)driver_alloc(sizeof(couch_drv_data)); if (pData == NULL) return ERL_DRV_ERROR_GENERAL; pData->port = port; pData->coll = ucol_open("", &status); if (U_FAILURE(status)) { couch_drv_stop((ErlDrvData)pData); return ERL_DRV_ERROR_GENERAL; } pData->collNoCase = ucol_open("", &status); if (U_FAILURE(status)) { couch_drv_stop((ErlDrvData)pData); return ERL_DRV_ERROR_GENERAL; } ucol_setAttribute(pData->collNoCase, UCOL_STRENGTH, UCOL_PRIMARY, &status); if (U_FAILURE(status)) { couch_drv_stop((ErlDrvData)pData); return ERL_DRV_ERROR_GENERAL; } return (ErlDrvData)pData; } COUCH_SSIZET return_control_result(void* pLocalResult, int localLen, char **ppRetBuf, COUCH_SSIZET returnLen) { if (*ppRetBuf == NULL || localLen > returnLen) { *ppRetBuf = (char*)driver_alloc_binary(localLen); if(*ppRetBuf == NULL) { return -1; } } memcpy(*ppRetBuf, pLocalResult, localLen); return localLen; } static COUCH_SSIZET couch_drv_control(ErlDrvData drv_data, unsigned int command, char *pBuf, COUCH_SSIZET bufLen, char **rbuf, COUCH_SSIZET rlen) { couch_drv_data* pData = (couch_drv_data*)drv_data; switch(command) { case 0: /* COLLATE */ case 1: /* COLLATE_NO_CASE: */ { UErrorCode status = U_ZERO_ERROR; int collResult; char response; UCharIterator iterA; UCharIterator iterB; int32_t length; /* 2 strings are in the buffer, consecutively * The strings begin first with a 32 bit integer byte length, then the actual * string bytes follow. */ /* first 32bits are the length */ memcpy(&length, pBuf, sizeof(length)); pBuf += sizeof(length); /* point the iterator at it. */ uiter_setUTF8(&iterA, pBuf, length); pBuf += length; /* now on to string b */ /* first 32bits are the length */ memcpy(&length, pBuf, sizeof(length)); pBuf += sizeof(length); /* point the iterator at it. */ uiter_setUTF8(&iterB, pBuf, length); if (command == 0) /* COLLATE */ collResult = ucol_strcollIter(pData->coll, &iterA, &iterB, &status); else /* COLLATE_NO_CASE */ collResult = ucol_strcollIter(pData->collNoCase, &iterA, &iterB, &status); if (collResult < 0) response = 0; /*lt*/ else if (collResult > 0) response = 2; /*gt*/ else response = 1; /*eq*/ return return_control_result(&response, sizeof(response), rbuf, rlen); } default: return -1; } } ErlDrvEntry couch_driver_entry = { NULL, /* F_PTR init, N/A */ couch_drv_start, /* L_PTR start, called when port is opened */ couch_drv_stop, /* F_PTR stop, called when port is closed */ NULL, /* F_PTR output, called when erlang has sent */ NULL, /* F_PTR ready_input, called when input descriptor ready */ NULL, /* F_PTR ready_output, called when output descriptor ready */ "couch_icu_driver", /* char *driver_name, the argument to open_port */ NULL, /* F_PTR finish, called when unloaded */ NULL, /* Not used */ couch_drv_control, /* F_PTR control, port_command callback */ NULL, /* F_PTR timeout, reserved */ NULL, /* F_PTR outputv, reserved */ NULL, /* F_PTR ready_async */ NULL, /* F_PTR flush */ NULL, /* F_PTR call */ NULL, /* F_PTR event */ ERL_DRV_EXTENDED_MARKER, ERL_DRV_EXTENDED_MAJOR_VERSION, ERL_DRV_EXTENDED_MINOR_VERSION, ERL_DRV_FLAG_USE_PORT_LOCKING, NULL, /* Reserved -- Used by emulator internally */ NULL, /* F_PTR process_exit */ }; DRIVER_INIT(couch_icu_driver) /* must match name in driver_entry */ { return &couch_driver_entry; } apache-couchdb-1.5.0/src/couchdb/priv/stat_descriptions.cfg.in0000644000175000001440000000543212230722213021263 00000000000000%% 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. % Style guide for descriptions: Start with a lowercase letter & do not add % a trailing full-stop / period % Please keep this in alphabetical order {couchdb, database_writes, "number of times a database was changed"}. {couchdb, database_reads, "number of times a document was read from a database"}. {couchdb, open_databases, "number of open databases"}. {couchdb, open_os_files, "number of file descriptors CouchDB has open"}. {couchdb, request_time, "length of a request inside CouchDB without MochiWeb"}. {couchdb, auth_cache_hits, "number of authentication cache hits"}. {couchdb, auth_cache_misses, "number of authentication cache misses"}. {httpd, bulk_requests, "number of bulk requests"}. {httpd, requests, "number of HTTP requests"}. {httpd, temporary_view_reads, "number of temporary view reads"}. {httpd, view_reads, "number of view reads"}. {httpd, clients_requesting_changes, "number of clients for continuous _changes"}. {httpd_request_methods, 'COPY', "number of HTTP COPY requests"}. {httpd_request_methods, 'DELETE', "number of HTTP DELETE requests"}. {httpd_request_methods, 'GET', "number of HTTP GET requests"}. {httpd_request_methods, 'HEAD', "number of HTTP HEAD requests"}. {httpd_request_methods, 'POST', "number of HTTP POST requests"}. {httpd_request_methods, 'PUT', "number of HTTP PUT requests"}. {httpd_status_codes, '200', "number of HTTP 200 OK responses"}. {httpd_status_codes, '201', "number of HTTP 201 Created responses"}. {httpd_status_codes, '202', "number of HTTP 202 Accepted responses"}. {httpd_status_codes, '301', "number of HTTP 301 Moved Permanently responses"}. {httpd_status_codes, '304', "number of HTTP 304 Not Modified responses"}. {httpd_status_codes, '400', "number of HTTP 400 Bad Request responses"}. {httpd_status_codes, '401', "number of HTTP 401 Unauthorized responses"}. {httpd_status_codes, '403', "number of HTTP 403 Forbidden responses"}. {httpd_status_codes, '404', "number of HTTP 404 Not Found responses"}. {httpd_status_codes, '405', "number of HTTP 405 Method Not Allowed responses"}. {httpd_status_codes, '409', "number of HTTP 409 Conflict responses"}. {httpd_status_codes, '412', "number of HTTP 412 Precondition Failed responses"}. {httpd_status_codes, '500', "number of HTTP 500 Internal Server Error responses"}. apache-couchdb-1.5.0/src/couchdb/priv/Makefile.am0000644000175000001440000001124212230722213016464 00000000000000## 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. MAKE_SAFE = $(MAKE) couchlibdir = $(localerlanglibdir)/couch-$(version) couchprivdir = $(couchlibdir)/priv couchprivlibdir = $(couchlibdir)/priv/lib man1dir = $(mandir)/man1 man_file = couchjs.1 if BUILD_MAN man_file_build = $(man_file) else man_file_build = endif BUILT_SOURCES = $(man_file_build) EXTRA_DIST = \ spawnkillable/couchspawnkillable.sh \ stat_descriptions.cfg.in \ couch_ejson_compare/erl_nif_compat.h \ couch_js/sm170.c \ couch_js/sm180.c \ couch_js/sm185.c \ $(man_file_build) CLEANFILES = $(man_file_build) stat_descriptions.cfg couchprivlib_LTLIBRARIES = couch_icu_driver.la if USE_EJSON_COMPARE_NIF couchprivlib_LTLIBRARIES += couch_ejson_compare.la couch_ejson_compare_la_SOURCES = couch_ejson_compare/couch_ejson_compare.c couch_ejson_compare_la_CPPFLAGS = -D_BSD_SOURCE $(ICU_CPPFLAGS) $(ERLANG_FLAGS) couch_ejson_compare_la_LDFLAGS = -module -avoid-version couch_ejson_compare_la_LIBADD = $(ICU_LIBS) if WINDOWS couch_ejson_compare_la_LDFLAGS += -no-undefined endif endif couch_icu_driver_la_SOURCES = icu_driver/couch_icu_driver.c couch_icu_driver_la_LDFLAGS = -module -avoid-version couch_icu_driver_la_CPPFLAGS = $(ICU_CPPFLAGS) $(ERLANG_FLAGS) couch_icu_driver_la_LIBADD = $(ICU_LIBS) if WINDOWS couch_icu_driver_la_LDFLAGS += -no-undefined endif COUCHJS_SRCS = \ couch_js/help.h \ couch_js/http.c \ couch_js/http.h \ couch_js/main.c \ couch_js/utf8.c \ couch_js/utf8.h \ couch_js/util.h \ couch_js/util.c locallibbin_PROGRAMS = couchjs couchjs_SOURCES = $(COUCHJS_SRCS) couchjs_CFLAGS = -g -Wall -Werror -D_BSD_SOURCE $(CURL_CFLAGS) $(JS_CFLAGS) couchjs_LDADD = $(CURL_LIBS) $(JS_LIBS) couchpriv_DATA = stat_descriptions.cfg couchpriv_PROGRAMS = couchspawnkillable # Depend on source files so distributed man pages are not rebuilt for end user. $(man_file): $(COUCHJS_SRCS) $(MAKE_SAFE) -f Makefile couchjs; \ $(top_srcdir)/build-aux/missing --run \ help2man \ --no-info \ --help-option="-h" \ --version-option="-V" \ --name="$(package_name) JavaScript interpreter" \ ./couchjs --output $@ install-data-local: if test -s $(man_file); then \ if test `cat $(man_file) | wc -l` -gt 1; then \ $(INSTALL) -d $(DESTDIR)$(man1dir); \ $(INSTALL_DATA) $(man_file) $(DESTDIR)$(man1dir)/$(man_file); \ fi \ fi %.cfg: %.cfg.in cp $< $@ if WINDOWS couchspawnkillable_SOURCES = spawnkillable/couchspawnkillable_win.c endif if !WINDOWS couchspawnkillable: spawnkillable/couchspawnkillable.sh cp $< $@ chmod +x $@ endif # libtool and automake have defeated markh. For each of our executables # we end up with 2 copies - one directly in the 'target' folder (eg, 'priv') # and another - the correct one - in .libs. The former doesn't work but is # what gets installed for 'couchspawnkillable' - but the correct one for # couchjs.exe *does* get copied. *shrug* So just clobber it with the # correct one as the last step. See bug COUCHDB-439 install-data-hook: if test -f "$(DESTDIR)$(couchprivlibdir)/couch_icu_driver"; then \ rm -f "$(DESTDIR)$(couchprivlibdir)/couch_icu_driver.so"; \ cd "$(DESTDIR)$(couchprivlibdir)" && \ $(LN_S) couch_icu_driver couch_icu_driver.so; \ fi if test -f "$(DESTDIR)$(couchprivlibdir)/couch_ejson_compare_nif"; then \ rm -f "$(DESTDIR)$(couchprivlibdir)/couch_ejson_compare_nif.so"; \ cd "$(DESTDIR)$(couchprivlibdir)" && \ $(LN_S) couch_ejson_compare_nif couch_ejson_compare_nif.so; \ fi if WINDOWS $(INSTALL) $(ICU_BIN)/icuuc*.dll $(bindir) $(INSTALL) $(ICU_BIN)/icudt*.dll $(bindir) $(INSTALL) $(ICU_BIN)/icuin*.dll $(bindir) $(INSTALL) $(JS_LIB_BINARY) $(bindir) $(INSTALL) .libs/couchspawnkillable.exe \ "$(DESTDIR)$(couchprivdir)/couchspawnkillable.exe" endif uninstall-local: rm -f $(DESTDIR)$(man1dir)/$(man_file) if test -f "$(DESTDIR)$(couchprivlibdir)/couch_erl_driver"; then \ rm -f "$(DESTDIR)$(couchprivlibdir)/couch_erl_driver.so"; \ fi distcheck-hook: if test ! -s $(man_file); then \ $(top_srcdir)/build-aux/dist-error $(man_file); \ else \ if test ! `cat $(man_file) | wc -l` -gt 1; then \ $(top_srcdir)/build-aux/dist-error $(man_file); \ fi \ fi apache-couchdb-1.5.0/src/couchdb/priv/Makefile.in0000644000175000001440000012772012230722243016511 00000000000000# Makefile.in generated by automake 1.11.6 from Makefile.am. # @configure_input@ # Copyright (C) 1994, 1995, 1996, 1997, 1998, 1999, 2000, 2001, 2002, # 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011 Free Software # Foundation, Inc. # This Makefile.in is free software; the Free Software Foundation # gives unlimited permission to copy and/or distribute it, # with or without modifications, as long as this notice is preserved. # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY, to the extent permitted by law; without # even the implied warranty of MERCHANTABILITY or FITNESS FOR A # PARTICULAR PURPOSE. @SET_MAKE@ VPATH = @srcdir@ am__make_dryrun = \ { \ am__dry=no; \ case $$MAKEFLAGS in \ *\\[\ \ ]*) \ echo 'am--echo: ; @echo "AM" OK' | $(MAKE) -f - 2>/dev/null \ | grep '^AM OK$$' >/dev/null || am__dry=yes;; \ *) \ for am__flg in $$MAKEFLAGS; do \ case $$am__flg in \ *=*|--*) ;; \ *n*) am__dry=yes; break;; \ esac; \ done;; \ esac; \ test $$am__dry = yes; \ } pkgdatadir = $(datadir)/@PACKAGE@ pkgincludedir = $(includedir)/@PACKAGE@ pkglibdir = $(libdir)/@PACKAGE@ pkglibexecdir = $(libexecdir)/@PACKAGE@ am__cd = CDPATH="$${ZSH_VERSION+.}$(PATH_SEPARATOR)" && cd install_sh_DATA = $(install_sh) -c -m 644 install_sh_PROGRAM = $(install_sh) -c install_sh_SCRIPT = $(install_sh) -c INSTALL_HEADER = $(INSTALL_DATA) transform = $(program_transform_name) NORMAL_INSTALL = : PRE_INSTALL = : POST_INSTALL = : NORMAL_UNINSTALL = : PRE_UNINSTALL = : POST_UNINSTALL = : build_triplet = @build@ host_triplet = @host@ @USE_EJSON_COMPARE_NIF_TRUE@am__append_1 = couch_ejson_compare.la @USE_EJSON_COMPARE_NIF_TRUE@@WINDOWS_TRUE@am__append_2 = -no-undefined @WINDOWS_TRUE@am__append_3 = -no-undefined locallibbin_PROGRAMS = couchjs$(EXEEXT) couchpriv_PROGRAMS = couchspawnkillable$(EXEEXT) subdir = src/couchdb/priv DIST_COMMON = $(srcdir)/Makefile.am $(srcdir)/Makefile.in ACLOCAL_M4 = $(top_srcdir)/aclocal.m4 am__aclocal_m4_deps = $(top_srcdir)/m4/libtool.m4 \ $(top_srcdir)/m4/ltoptions.m4 $(top_srcdir)/m4/ltsugar.m4 \ $(top_srcdir)/m4/ltversion.m4 $(top_srcdir)/m4/lt~obsolete.m4 \ $(top_srcdir)/acinclude.m4 $(top_srcdir)/configure.ac am__configure_deps = $(am__aclocal_m4_deps) $(CONFIGURE_DEPENDENCIES) \ $(ACLOCAL_M4) mkinstalldirs = $(install_sh) -d CONFIG_HEADER = $(top_builddir)/config.h \ $(top_builddir)/src/snappy/google-snappy/config.h CONFIG_CLEAN_FILES = CONFIG_CLEAN_VPATH_FILES = am__vpath_adj_setup = srcdirstrip=`echo "$(srcdir)" | sed 's|.|.|g'`; am__vpath_adj = case $$p in \ $(srcdir)/*) f=`echo "$$p" | sed "s|^$$srcdirstrip/||"`;; \ *) f=$$p;; \ esac; am__strip_dir = f=`echo $$p | sed -e 's|^.*/||'`; am__install_max = 40 am__nobase_strip_setup = \ srcdirstrip=`echo "$(srcdir)" | sed 's/[].[^$$\\*|]/\\\\&/g'` am__nobase_strip = \ for p in $$list; do echo "$$p"; done | sed -e "s|$$srcdirstrip/||" am__nobase_list = $(am__nobase_strip_setup); \ for p in $$list; do echo "$$p $$p"; done | \ sed "s| $$srcdirstrip/| |;"' / .*\//!s/ .*/ ./; s,\( .*\)/[^/]*$$,\1,' | \ $(AWK) 'BEGIN { files["."] = "" } { files[$$2] = files[$$2] " " $$1; \ if (++n[$$2] == $(am__install_max)) \ { print $$2, files[$$2]; n[$$2] = 0; files[$$2] = "" } } \ END { for (dir in files) print dir, files[dir] }' am__base_list = \ sed '$$!N;$$!N;$$!N;$$!N;$$!N;$$!N;$$!N;s/\n/ /g' | \ sed '$$!N;$$!N;$$!N;$$!N;s/\n/ /g' am__uninstall_files_from_dir = { \ test -z "$$files" \ || { test ! -d "$$dir" && test ! -f "$$dir" && test ! -r "$$dir"; } \ || { echo " ( cd '$$dir' && rm -f" $$files ")"; \ $(am__cd) "$$dir" && rm -f $$files; }; \ } am__installdirs = "$(DESTDIR)$(couchprivlibdir)" \ "$(DESTDIR)$(couchprivdir)" "$(DESTDIR)$(locallibbindir)" \ "$(DESTDIR)$(couchprivdir)" LTLIBRARIES = $(couchprivlib_LTLIBRARIES) am__DEPENDENCIES_1 = @USE_EJSON_COMPARE_NIF_TRUE@couch_ejson_compare_la_DEPENDENCIES = \ @USE_EJSON_COMPARE_NIF_TRUE@ $(am__DEPENDENCIES_1) am__couch_ejson_compare_la_SOURCES_DIST = \ couch_ejson_compare/couch_ejson_compare.c @USE_EJSON_COMPARE_NIF_TRUE@am_couch_ejson_compare_la_OBJECTS = couch_ejson_compare_la-couch_ejson_compare.lo couch_ejson_compare_la_OBJECTS = $(am_couch_ejson_compare_la_OBJECTS) couch_ejson_compare_la_LINK = $(LIBTOOL) --tag=CC $(AM_LIBTOOLFLAGS) \ $(LIBTOOLFLAGS) --mode=link $(CCLD) $(AM_CFLAGS) $(CFLAGS) \ $(couch_ejson_compare_la_LDFLAGS) $(LDFLAGS) -o $@ @USE_EJSON_COMPARE_NIF_TRUE@am_couch_ejson_compare_la_rpath = -rpath \ @USE_EJSON_COMPARE_NIF_TRUE@ $(couchprivlibdir) couch_icu_driver_la_DEPENDENCIES = $(am__DEPENDENCIES_1) am_couch_icu_driver_la_OBJECTS = \ couch_icu_driver_la-couch_icu_driver.lo couch_icu_driver_la_OBJECTS = $(am_couch_icu_driver_la_OBJECTS) couch_icu_driver_la_LINK = $(LIBTOOL) --tag=CC $(AM_LIBTOOLFLAGS) \ $(LIBTOOLFLAGS) --mode=link $(CCLD) $(AM_CFLAGS) $(CFLAGS) \ $(couch_icu_driver_la_LDFLAGS) $(LDFLAGS) -o $@ PROGRAMS = $(couchpriv_PROGRAMS) $(locallibbin_PROGRAMS) am__objects_1 = couchjs-http.$(OBJEXT) couchjs-main.$(OBJEXT) \ couchjs-utf8.$(OBJEXT) couchjs-util.$(OBJEXT) am_couchjs_OBJECTS = $(am__objects_1) couchjs_OBJECTS = $(am_couchjs_OBJECTS) couchjs_DEPENDENCIES = $(am__DEPENDENCIES_1) $(am__DEPENDENCIES_1) couchjs_LINK = $(LIBTOOL) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) \ --mode=link $(CCLD) $(couchjs_CFLAGS) $(CFLAGS) $(AM_LDFLAGS) \ $(LDFLAGS) -o $@ am__couchspawnkillable_SOURCES_DIST = \ spawnkillable/couchspawnkillable_win.c @WINDOWS_TRUE@am_couchspawnkillable_OBJECTS = \ @WINDOWS_TRUE@ couchspawnkillable_win.$(OBJEXT) couchspawnkillable_OBJECTS = $(am_couchspawnkillable_OBJECTS) couchspawnkillable_LDADD = $(LDADD) DEFAULT_INCLUDES = -I.@am__isrc@ -I$(top_builddir) -I$(top_builddir)/src/snappy/google-snappy depcomp = $(SHELL) $(top_srcdir)/build-aux/depcomp am__depfiles_maybe = depfiles am__mv = mv -f COMPILE = $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) \ $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) LTCOMPILE = $(LIBTOOL) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) \ --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) \ $(AM_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) CCLD = $(CC) LINK = $(LIBTOOL) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) \ --mode=link $(CCLD) $(AM_CFLAGS) $(CFLAGS) $(AM_LDFLAGS) \ $(LDFLAGS) -o $@ SOURCES = $(couch_ejson_compare_la_SOURCES) \ $(couch_icu_driver_la_SOURCES) $(couchjs_SOURCES) \ $(couchspawnkillable_SOURCES) DIST_SOURCES = $(am__couch_ejson_compare_la_SOURCES_DIST) \ $(couch_icu_driver_la_SOURCES) $(couchjs_SOURCES) \ $(am__couchspawnkillable_SOURCES_DIST) am__can_run_installinfo = \ case $$AM_UPDATE_INFO_DIR in \ n|no|NO) false;; \ *) (install-info --version) >/dev/null 2>&1;; \ esac DATA = $(couchpriv_DATA) ETAGS = etags CTAGS = ctags DISTFILES = $(DIST_COMMON) $(DIST_SOURCES) $(TEXINFOS) $(EXTRA_DIST) ACLOCAL = @ACLOCAL@ AMTAR = @AMTAR@ AR = @AR@ AS = @AS@ AUTOCONF = @AUTOCONF@ AUTOHEADER = @AUTOHEADER@ AUTOMAKE = @AUTOMAKE@ AWK = @AWK@ CC = @CC@ CCDEPMODE = @CCDEPMODE@ CFLAGS = @CFLAGS@ CPP = @CPP@ CPPFLAGS = @CPPFLAGS@ CURL_CFLAGS = @CURL_CFLAGS@ CURL_CONFIG = @CURL_CONFIG@ CURL_LIBS = @CURL_LIBS@ CXX = @CXX@ CXXCPP = @CXXCPP@ CXXDEPMODE = @CXXDEPMODE@ CXXFLAGS = @CXXFLAGS@ CYGPATH_W = @CYGPATH_W@ DEFS = @DEFS@ DEPDIR = @DEPDIR@ DLLTOOL = @DLLTOOL@ DSYMUTIL = @DSYMUTIL@ DUMPBIN = @DUMPBIN@ ECHO_C = @ECHO_C@ ECHO_N = @ECHO_N@ ECHO_T = @ECHO_T@ EGREP = @EGREP@ ERL = @ERL@ ERLANG_FLAGS = @ERLANG_FLAGS@ ERLC = @ERLC@ ERLC_FLAGS = @ERLC_FLAGS@ ESCRIPT = @ESCRIPT@ EXEEXT = @EXEEXT@ FGREP = @FGREP@ FLAGS = @FLAGS@ GREP = @GREP@ HAS_HELP2MAN = @HAS_HELP2MAN@ HAS_INSTALLINFO = @HAS_INSTALLINFO@ HAS_MAKEINFO = @HAS_MAKEINFO@ HAS_PDFLATEX = @HAS_PDFLATEX@ HAS_SPHINX_BUILD = @HAS_SPHINX_BUILD@ ICU_BIN = @ICU_BIN@ ICU_CFLAGS = @ICU_CFLAGS@ ICU_CONFIG = @ICU_CONFIG@ ICU_CPPFLAGS = @ICU_CPPFLAGS@ ICU_CXXFLAGS = @ICU_CXXFLAGS@ ICU_LIBS = @ICU_LIBS@ INNO_COMPILER_EXECUTABLE = @INNO_COMPILER_EXECUTABLE@ INSTALL = @INSTALL@ INSTALL_DATA = @INSTALL_DATA@ INSTALL_PROGRAM = @INSTALL_PROGRAM@ INSTALL_SCRIPT = @INSTALL_SCRIPT@ INSTALL_STRIP_PROGRAM = @INSTALL_STRIP_PROGRAM@ JS_CFLAGS = @JS_CFLAGS@ JS_LIBS = @JS_LIBS@ JS_LIB_BINARY = @JS_LIB_BINARY@ LD = @LD@ LDFLAGS = @LDFLAGS@ LIBOBJS = @LIBOBJS@ LIBS = @LIBS@ LIBTOOL = @LIBTOOL@ LIPO = @LIPO@ LN_S = @LN_S@ LTLIBOBJS = @LTLIBOBJS@ MAKEINFO = @MAKEINFO@ MANIFEST_TOOL = @MANIFEST_TOOL@ MKDIR_P = @MKDIR_P@ NM = @NM@ NMEDIT = @NMEDIT@ OBJDUMP = @OBJDUMP@ OBJEXT = @OBJEXT@ OTOOL = @OTOOL@ OTOOL64 = @OTOOL64@ PACKAGE = @PACKAGE@ PACKAGE_BUGREPORT = @PACKAGE_BUGREPORT@ PACKAGE_NAME = @PACKAGE_NAME@ PACKAGE_STRING = @PACKAGE_STRING@ PACKAGE_TARNAME = @PACKAGE_TARNAME@ PACKAGE_URL = @PACKAGE_URL@ PACKAGE_VERSION = @PACKAGE_VERSION@ PATH_SEPARATOR = @PATH_SEPARATOR@ PKG_CONFIG = @PKG_CONFIG@ PKG_CONFIG_LIBDIR = @PKG_CONFIG_LIBDIR@ PKG_CONFIG_PATH = @PKG_CONFIG_PATH@ RANLIB = @RANLIB@ SED = @SED@ SET_MAKE = @SET_MAKE@ SHELL = @SHELL@ SNAPPY_MAJOR = @SNAPPY_MAJOR@ SNAPPY_MINOR = @SNAPPY_MINOR@ SNAPPY_PATCHLEVEL = @SNAPPY_PATCHLEVEL@ STRIP = @STRIP@ VERSION = @VERSION@ abs_builddir = @abs_builddir@ abs_srcdir = @abs_srcdir@ abs_top_builddir = @abs_top_builddir@ abs_top_srcdir = @abs_top_srcdir@ ac_ct_AR = @ac_ct_AR@ ac_ct_CC = @ac_ct_CC@ ac_ct_CXX = @ac_ct_CXX@ ac_ct_DUMPBIN = @ac_ct_DUMPBIN@ ac_cv_have_stddef_h = @ac_cv_have_stddef_h@ ac_cv_have_stdint_h = @ac_cv_have_stdint_h@ am__include = @am__include@ am__leading_dot = @am__leading_dot@ am__quote = @am__quote@ am__tar = @am__tar@ am__untar = @am__untar@ bindir = @bindir@ bug_uri = @bug_uri@ build = @build@ build_alias = @build_alias@ build_cpu = @build_cpu@ build_os = @build_os@ build_vendor = @build_vendor@ builddir = @builddir@ datadir = @datadir@ datarootdir = @datarootdir@ docdir = @docdir@ dvidir = @dvidir@ erlangbin = @erlangbin@ erlangversion = @erlangversion@ exec_prefix = @exec_prefix@ host = @host@ host_alias = @host_alias@ host_cpu = @host_cpu@ host_os = @host_os@ host_vendor = @host_vendor@ htmldir = @htmldir@ includedir = @includedir@ infodir = @infodir@ initdir = @initdir@ install_sh = @install_sh@ launchddir = @launchddir@ libdir = @libdir@ libexecdir = @libexecdir@ localconfdir = @localconfdir@ localdatadir = @localdatadir@ localdocdir = @localdocdir@ localedir = @localedir@ localerlanglibdir = @localerlanglibdir@ locallibbindir = @locallibbindir@ locallibdir = @locallibdir@ localstatedir = @localstatedir@ localstatelibdir = @localstatelibdir@ localstatelogdir = @localstatelogdir@ localstaterundir = @localstaterundir@ mandir = @mandir@ mkdir_p = @mkdir_p@ msvc_redist_dir = @msvc_redist_dir@ msvc_redist_name = @msvc_redist_name@ oldincludedir = @oldincludedir@ openssl_bin_dir = @openssl_bin_dir@ otp_release = @otp_release@ package_author_address = @package_author_address@ package_author_name = @package_author_name@ package_identifier = @package_identifier@ package_name = @package_name@ package_tarname = @package_tarname@ pdfdir = @pdfdir@ prefix = @prefix@ program_transform_name = @program_transform_name@ psdir = @psdir@ sbindir = @sbindir@ sharedstatedir = @sharedstatedir@ srcdir = @srcdir@ sysconfdir = @sysconfdir@ target_alias = @target_alias@ top_build_prefix = @top_build_prefix@ top_builddir = @top_builddir@ top_srcdir = @top_srcdir@ version = @version@ version_major = @version_major@ version_minor = @version_minor@ version_release = @version_release@ version_revision = @version_revision@ version_stage = @version_stage@ MAKE_SAFE = $(MAKE) couchlibdir = $(localerlanglibdir)/couch-$(version) couchprivdir = $(couchlibdir)/priv couchprivlibdir = $(couchlibdir)/priv/lib man1dir = $(mandir)/man1 man_file = couchjs.1 @BUILD_MAN_FALSE@man_file_build = @BUILD_MAN_TRUE@man_file_build = $(man_file) BUILT_SOURCES = $(man_file_build) EXTRA_DIST = \ spawnkillable/couchspawnkillable.sh \ stat_descriptions.cfg.in \ couch_ejson_compare/erl_nif_compat.h \ couch_js/sm170.c \ couch_js/sm180.c \ couch_js/sm185.c \ $(man_file_build) CLEANFILES = $(man_file_build) stat_descriptions.cfg couchprivlib_LTLIBRARIES = couch_icu_driver.la $(am__append_1) @USE_EJSON_COMPARE_NIF_TRUE@couch_ejson_compare_la_SOURCES = couch_ejson_compare/couch_ejson_compare.c @USE_EJSON_COMPARE_NIF_TRUE@couch_ejson_compare_la_CPPFLAGS = -D_BSD_SOURCE $(ICU_CPPFLAGS) $(ERLANG_FLAGS) @USE_EJSON_COMPARE_NIF_TRUE@couch_ejson_compare_la_LDFLAGS = -module \ @USE_EJSON_COMPARE_NIF_TRUE@ -avoid-version $(am__append_2) @USE_EJSON_COMPARE_NIF_TRUE@couch_ejson_compare_la_LIBADD = $(ICU_LIBS) couch_icu_driver_la_SOURCES = icu_driver/couch_icu_driver.c couch_icu_driver_la_LDFLAGS = -module -avoid-version $(am__append_3) couch_icu_driver_la_CPPFLAGS = $(ICU_CPPFLAGS) $(ERLANG_FLAGS) couch_icu_driver_la_LIBADD = $(ICU_LIBS) COUCHJS_SRCS = \ couch_js/help.h \ couch_js/http.c \ couch_js/http.h \ couch_js/main.c \ couch_js/utf8.c \ couch_js/utf8.h \ couch_js/util.h \ couch_js/util.c couchjs_SOURCES = $(COUCHJS_SRCS) couchjs_CFLAGS = -g -Wall -Werror -D_BSD_SOURCE $(CURL_CFLAGS) $(JS_CFLAGS) couchjs_LDADD = $(CURL_LIBS) $(JS_LIBS) couchpriv_DATA = stat_descriptions.cfg @WINDOWS_TRUE@couchspawnkillable_SOURCES = spawnkillable/couchspawnkillable_win.c all: $(BUILT_SOURCES) $(MAKE) $(AM_MAKEFLAGS) all-am .SUFFIXES: .SUFFIXES: .c .lo .o .obj $(srcdir)/Makefile.in: $(srcdir)/Makefile.am $(am__configure_deps) @for dep in $?; do \ case '$(am__configure_deps)' in \ *$$dep*) \ ( cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh ) \ && { if test -f $@; then exit 0; else break; fi; }; \ exit 1;; \ esac; \ done; \ echo ' cd $(top_srcdir) && $(AUTOMAKE) --foreign src/couchdb/priv/Makefile'; \ $(am__cd) $(top_srcdir) && \ $(AUTOMAKE) --foreign src/couchdb/priv/Makefile .PRECIOUS: Makefile Makefile: $(srcdir)/Makefile.in $(top_builddir)/config.status @case '$?' in \ *config.status*) \ cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh;; \ *) \ echo ' cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ $(am__depfiles_maybe)'; \ cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ $(am__depfiles_maybe);; \ esac; $(top_builddir)/config.status: $(top_srcdir)/configure $(CONFIG_STATUS_DEPENDENCIES) cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh $(top_srcdir)/configure: $(am__configure_deps) cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh $(ACLOCAL_M4): $(am__aclocal_m4_deps) cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh $(am__aclocal_m4_deps): install-couchprivlibLTLIBRARIES: $(couchprivlib_LTLIBRARIES) @$(NORMAL_INSTALL) @list='$(couchprivlib_LTLIBRARIES)'; test -n "$(couchprivlibdir)" || list=; \ list2=; for p in $$list; do \ if test -f $$p; then \ list2="$$list2 $$p"; \ else :; fi; \ done; \ test -z "$$list2" || { \ echo " $(MKDIR_P) '$(DESTDIR)$(couchprivlibdir)'"; \ $(MKDIR_P) "$(DESTDIR)$(couchprivlibdir)" || exit 1; \ echo " $(LIBTOOL) $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=install $(INSTALL) $(INSTALL_STRIP_FLAG) $$list2 '$(DESTDIR)$(couchprivlibdir)'"; \ $(LIBTOOL) $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=install $(INSTALL) $(INSTALL_STRIP_FLAG) $$list2 "$(DESTDIR)$(couchprivlibdir)"; \ } uninstall-couchprivlibLTLIBRARIES: @$(NORMAL_UNINSTALL) @list='$(couchprivlib_LTLIBRARIES)'; test -n "$(couchprivlibdir)" || list=; \ for p in $$list; do \ $(am__strip_dir) \ echo " $(LIBTOOL) $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=uninstall rm -f '$(DESTDIR)$(couchprivlibdir)/$$f'"; \ $(LIBTOOL) $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=uninstall rm -f "$(DESTDIR)$(couchprivlibdir)/$$f"; \ done clean-couchprivlibLTLIBRARIES: -test -z "$(couchprivlib_LTLIBRARIES)" || rm -f $(couchprivlib_LTLIBRARIES) @list='$(couchprivlib_LTLIBRARIES)'; for p in $$list; do \ dir="`echo $$p | sed -e 's|/[^/]*$$||'`"; \ test "$$dir" != "$$p" || dir=.; \ echo "rm -f \"$${dir}/so_locations\""; \ rm -f "$${dir}/so_locations"; \ done couch_ejson_compare.la: $(couch_ejson_compare_la_OBJECTS) $(couch_ejson_compare_la_DEPENDENCIES) $(EXTRA_couch_ejson_compare_la_DEPENDENCIES) $(couch_ejson_compare_la_LINK) $(am_couch_ejson_compare_la_rpath) $(couch_ejson_compare_la_OBJECTS) $(couch_ejson_compare_la_LIBADD) $(LIBS) couch_icu_driver.la: $(couch_icu_driver_la_OBJECTS) $(couch_icu_driver_la_DEPENDENCIES) $(EXTRA_couch_icu_driver_la_DEPENDENCIES) $(couch_icu_driver_la_LINK) -rpath $(couchprivlibdir) $(couch_icu_driver_la_OBJECTS) $(couch_icu_driver_la_LIBADD) $(LIBS) install-couchprivPROGRAMS: $(couchpriv_PROGRAMS) @$(NORMAL_INSTALL) @list='$(couchpriv_PROGRAMS)'; test -n "$(couchprivdir)" || list=; \ if test -n "$$list"; then \ echo " $(MKDIR_P) '$(DESTDIR)$(couchprivdir)'"; \ $(MKDIR_P) "$(DESTDIR)$(couchprivdir)" || exit 1; \ fi; \ for p in $$list; do echo "$$p $$p"; done | \ sed 's/$(EXEEXT)$$//' | \ while read p p1; do if test -f $$p || test -f $$p1; \ then echo "$$p"; echo "$$p"; else :; fi; \ done | \ sed -e 'p;s,.*/,,;n;h' -e 's|.*|.|' \ -e 'p;x;s,.*/,,;s/$(EXEEXT)$$//;$(transform);s/$$/$(EXEEXT)/' | \ sed 'N;N;N;s,\n, ,g' | \ $(AWK) 'BEGIN { files["."] = ""; dirs["."] = 1 } \ { d=$$3; if (dirs[d] != 1) { print "d", d; dirs[d] = 1 } \ if ($$2 == $$4) files[d] = files[d] " " $$1; \ else { print "f", $$3 "/" $$4, $$1; } } \ END { for (d in files) print "f", d, files[d] }' | \ while read type dir files; do \ if test "$$dir" = .; then dir=; else dir=/$$dir; fi; \ test -z "$$files" || { \ echo " $(INSTALL_PROGRAM_ENV) $(LIBTOOL) $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=install $(INSTALL_PROGRAM) $$files '$(DESTDIR)$(couchprivdir)$$dir'"; \ $(INSTALL_PROGRAM_ENV) $(LIBTOOL) $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=install $(INSTALL_PROGRAM) $$files "$(DESTDIR)$(couchprivdir)$$dir" || exit $$?; \ } \ ; done uninstall-couchprivPROGRAMS: @$(NORMAL_UNINSTALL) @list='$(couchpriv_PROGRAMS)'; test -n "$(couchprivdir)" || list=; \ files=`for p in $$list; do echo "$$p"; done | \ sed -e 'h;s,^.*/,,;s/$(EXEEXT)$$//;$(transform)' \ -e 's/$$/$(EXEEXT)/' `; \ test -n "$$list" || exit 0; \ echo " ( cd '$(DESTDIR)$(couchprivdir)' && rm -f" $$files ")"; \ cd "$(DESTDIR)$(couchprivdir)" && rm -f $$files clean-couchprivPROGRAMS: @list='$(couchpriv_PROGRAMS)'; test -n "$$list" || exit 0; \ echo " rm -f" $$list; \ rm -f $$list || exit $$?; \ test -n "$(EXEEXT)" || exit 0; \ list=`for p in $$list; do echo "$$p"; done | sed 's/$(EXEEXT)$$//'`; \ echo " rm -f" $$list; \ rm -f $$list install-locallibbinPROGRAMS: $(locallibbin_PROGRAMS) @$(NORMAL_INSTALL) @list='$(locallibbin_PROGRAMS)'; test -n "$(locallibbindir)" || list=; \ if test -n "$$list"; then \ echo " $(MKDIR_P) '$(DESTDIR)$(locallibbindir)'"; \ $(MKDIR_P) "$(DESTDIR)$(locallibbindir)" || exit 1; \ fi; \ for p in $$list; do echo "$$p $$p"; done | \ sed 's/$(EXEEXT)$$//' | \ while read p p1; do if test -f $$p || test -f $$p1; \ then echo "$$p"; echo "$$p"; else :; fi; \ done | \ sed -e 'p;s,.*/,,;n;h' -e 's|.*|.|' \ -e 'p;x;s,.*/,,;s/$(EXEEXT)$$//;$(transform);s/$$/$(EXEEXT)/' | \ sed 'N;N;N;s,\n, ,g' | \ $(AWK) 'BEGIN { files["."] = ""; dirs["."] = 1 } \ { d=$$3; if (dirs[d] != 1) { print "d", d; dirs[d] = 1 } \ if ($$2 == $$4) files[d] = files[d] " " $$1; \ else { print "f", $$3 "/" $$4, $$1; } } \ END { for (d in files) print "f", d, files[d] }' | \ while read type dir files; do \ if test "$$dir" = .; then dir=; else dir=/$$dir; fi; \ test -z "$$files" || { \ echo " $(INSTALL_PROGRAM_ENV) $(LIBTOOL) $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=install $(INSTALL_PROGRAM) $$files '$(DESTDIR)$(locallibbindir)$$dir'"; \ $(INSTALL_PROGRAM_ENV) $(LIBTOOL) $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=install $(INSTALL_PROGRAM) $$files "$(DESTDIR)$(locallibbindir)$$dir" || exit $$?; \ } \ ; done uninstall-locallibbinPROGRAMS: @$(NORMAL_UNINSTALL) @list='$(locallibbin_PROGRAMS)'; test -n "$(locallibbindir)" || list=; \ files=`for p in $$list; do echo "$$p"; done | \ sed -e 'h;s,^.*/,,;s/$(EXEEXT)$$//;$(transform)' \ -e 's/$$/$(EXEEXT)/' `; \ test -n "$$list" || exit 0; \ echo " ( cd '$(DESTDIR)$(locallibbindir)' && rm -f" $$files ")"; \ cd "$(DESTDIR)$(locallibbindir)" && rm -f $$files clean-locallibbinPROGRAMS: @list='$(locallibbin_PROGRAMS)'; test -n "$$list" || exit 0; \ echo " rm -f" $$list; \ rm -f $$list || exit $$?; \ test -n "$(EXEEXT)" || exit 0; \ list=`for p in $$list; do echo "$$p"; done | sed 's/$(EXEEXT)$$//'`; \ echo " rm -f" $$list; \ rm -f $$list couchjs$(EXEEXT): $(couchjs_OBJECTS) $(couchjs_DEPENDENCIES) $(EXTRA_couchjs_DEPENDENCIES) @rm -f couchjs$(EXEEXT) $(couchjs_LINK) $(couchjs_OBJECTS) $(couchjs_LDADD) $(LIBS) @WINDOWS_TRUE@couchspawnkillable$(EXEEXT): $(couchspawnkillable_OBJECTS) $(couchspawnkillable_DEPENDENCIES) $(EXTRA_couchspawnkillable_DEPENDENCIES) @WINDOWS_TRUE@ @rm -f couchspawnkillable$(EXEEXT) @WINDOWS_TRUE@ $(LINK) $(couchspawnkillable_OBJECTS) $(couchspawnkillable_LDADD) $(LIBS) mostlyclean-compile: -rm -f *.$(OBJEXT) distclean-compile: -rm -f *.tab.c @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/couch_ejson_compare_la-couch_ejson_compare.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/couch_icu_driver_la-couch_icu_driver.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/couchjs-http.Po@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/couchjs-main.Po@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/couchjs-utf8.Po@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/couchjs-util.Po@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/couchspawnkillable_win.Po@am__quote@ .c.o: @am__fastdepCC_TRUE@ $(COMPILE) -MT $@ -MD -MP -MF $(DEPDIR)/$*.Tpo -c -o $@ $< @am__fastdepCC_TRUE@ $(am__mv) $(DEPDIR)/$*.Tpo $(DEPDIR)/$*.Po @AMDEP_TRUE@@am__fastdepCC_FALSE@ source='$<' object='$@' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(COMPILE) -c $< .c.obj: @am__fastdepCC_TRUE@ $(COMPILE) -MT $@ -MD -MP -MF $(DEPDIR)/$*.Tpo -c -o $@ `$(CYGPATH_W) '$<'` @am__fastdepCC_TRUE@ $(am__mv) $(DEPDIR)/$*.Tpo $(DEPDIR)/$*.Po @AMDEP_TRUE@@am__fastdepCC_FALSE@ source='$<' object='$@' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(COMPILE) -c `$(CYGPATH_W) '$<'` .c.lo: @am__fastdepCC_TRUE@ $(LTCOMPILE) -MT $@ -MD -MP -MF $(DEPDIR)/$*.Tpo -c -o $@ $< @am__fastdepCC_TRUE@ $(am__mv) $(DEPDIR)/$*.Tpo $(DEPDIR)/$*.Plo @AMDEP_TRUE@@am__fastdepCC_FALSE@ source='$<' object='$@' libtool=yes @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(LTCOMPILE) -c -o $@ $< couch_ejson_compare_la-couch_ejson_compare.lo: couch_ejson_compare/couch_ejson_compare.c @am__fastdepCC_TRUE@ $(LIBTOOL) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(couch_ejson_compare_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT couch_ejson_compare_la-couch_ejson_compare.lo -MD -MP -MF $(DEPDIR)/couch_ejson_compare_la-couch_ejson_compare.Tpo -c -o couch_ejson_compare_la-couch_ejson_compare.lo `test -f 'couch_ejson_compare/couch_ejson_compare.c' || echo '$(srcdir)/'`couch_ejson_compare/couch_ejson_compare.c @am__fastdepCC_TRUE@ $(am__mv) $(DEPDIR)/couch_ejson_compare_la-couch_ejson_compare.Tpo $(DEPDIR)/couch_ejson_compare_la-couch_ejson_compare.Plo @AMDEP_TRUE@@am__fastdepCC_FALSE@ source='couch_ejson_compare/couch_ejson_compare.c' object='couch_ejson_compare_la-couch_ejson_compare.lo' libtool=yes @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(LIBTOOL) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(couch_ejson_compare_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o couch_ejson_compare_la-couch_ejson_compare.lo `test -f 'couch_ejson_compare/couch_ejson_compare.c' || echo '$(srcdir)/'`couch_ejson_compare/couch_ejson_compare.c couch_icu_driver_la-couch_icu_driver.lo: icu_driver/couch_icu_driver.c @am__fastdepCC_TRUE@ $(LIBTOOL) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(couch_icu_driver_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT couch_icu_driver_la-couch_icu_driver.lo -MD -MP -MF $(DEPDIR)/couch_icu_driver_la-couch_icu_driver.Tpo -c -o couch_icu_driver_la-couch_icu_driver.lo `test -f 'icu_driver/couch_icu_driver.c' || echo '$(srcdir)/'`icu_driver/couch_icu_driver.c @am__fastdepCC_TRUE@ $(am__mv) $(DEPDIR)/couch_icu_driver_la-couch_icu_driver.Tpo $(DEPDIR)/couch_icu_driver_la-couch_icu_driver.Plo @AMDEP_TRUE@@am__fastdepCC_FALSE@ source='icu_driver/couch_icu_driver.c' object='couch_icu_driver_la-couch_icu_driver.lo' libtool=yes @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(LIBTOOL) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(couch_icu_driver_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o couch_icu_driver_la-couch_icu_driver.lo `test -f 'icu_driver/couch_icu_driver.c' || echo '$(srcdir)/'`icu_driver/couch_icu_driver.c couchjs-http.o: couch_js/http.c @am__fastdepCC_TRUE@ $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(couchjs_CFLAGS) $(CFLAGS) -MT couchjs-http.o -MD -MP -MF $(DEPDIR)/couchjs-http.Tpo -c -o couchjs-http.o `test -f 'couch_js/http.c' || echo '$(srcdir)/'`couch_js/http.c @am__fastdepCC_TRUE@ $(am__mv) $(DEPDIR)/couchjs-http.Tpo $(DEPDIR)/couchjs-http.Po @AMDEP_TRUE@@am__fastdepCC_FALSE@ source='couch_js/http.c' object='couchjs-http.o' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(couchjs_CFLAGS) $(CFLAGS) -c -o couchjs-http.o `test -f 'couch_js/http.c' || echo '$(srcdir)/'`couch_js/http.c couchjs-http.obj: couch_js/http.c @am__fastdepCC_TRUE@ $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(couchjs_CFLAGS) $(CFLAGS) -MT couchjs-http.obj -MD -MP -MF $(DEPDIR)/couchjs-http.Tpo -c -o couchjs-http.obj `if test -f 'couch_js/http.c'; then $(CYGPATH_W) 'couch_js/http.c'; else $(CYGPATH_W) '$(srcdir)/couch_js/http.c'; fi` @am__fastdepCC_TRUE@ $(am__mv) $(DEPDIR)/couchjs-http.Tpo $(DEPDIR)/couchjs-http.Po @AMDEP_TRUE@@am__fastdepCC_FALSE@ source='couch_js/http.c' object='couchjs-http.obj' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(couchjs_CFLAGS) $(CFLAGS) -c -o couchjs-http.obj `if test -f 'couch_js/http.c'; then $(CYGPATH_W) 'couch_js/http.c'; else $(CYGPATH_W) '$(srcdir)/couch_js/http.c'; fi` couchjs-main.o: couch_js/main.c @am__fastdepCC_TRUE@ $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(couchjs_CFLAGS) $(CFLAGS) -MT couchjs-main.o -MD -MP -MF $(DEPDIR)/couchjs-main.Tpo -c -o couchjs-main.o `test -f 'couch_js/main.c' || echo '$(srcdir)/'`couch_js/main.c @am__fastdepCC_TRUE@ $(am__mv) $(DEPDIR)/couchjs-main.Tpo $(DEPDIR)/couchjs-main.Po @AMDEP_TRUE@@am__fastdepCC_FALSE@ source='couch_js/main.c' object='couchjs-main.o' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(couchjs_CFLAGS) $(CFLAGS) -c -o couchjs-main.o `test -f 'couch_js/main.c' || echo '$(srcdir)/'`couch_js/main.c couchjs-main.obj: couch_js/main.c @am__fastdepCC_TRUE@ $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(couchjs_CFLAGS) $(CFLAGS) -MT couchjs-main.obj -MD -MP -MF $(DEPDIR)/couchjs-main.Tpo -c -o couchjs-main.obj `if test -f 'couch_js/main.c'; then $(CYGPATH_W) 'couch_js/main.c'; else $(CYGPATH_W) '$(srcdir)/couch_js/main.c'; fi` @am__fastdepCC_TRUE@ $(am__mv) $(DEPDIR)/couchjs-main.Tpo $(DEPDIR)/couchjs-main.Po @AMDEP_TRUE@@am__fastdepCC_FALSE@ source='couch_js/main.c' object='couchjs-main.obj' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(couchjs_CFLAGS) $(CFLAGS) -c -o couchjs-main.obj `if test -f 'couch_js/main.c'; then $(CYGPATH_W) 'couch_js/main.c'; else $(CYGPATH_W) '$(srcdir)/couch_js/main.c'; fi` couchjs-utf8.o: couch_js/utf8.c @am__fastdepCC_TRUE@ $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(couchjs_CFLAGS) $(CFLAGS) -MT couchjs-utf8.o -MD -MP -MF $(DEPDIR)/couchjs-utf8.Tpo -c -o couchjs-utf8.o `test -f 'couch_js/utf8.c' || echo '$(srcdir)/'`couch_js/utf8.c @am__fastdepCC_TRUE@ $(am__mv) $(DEPDIR)/couchjs-utf8.Tpo $(DEPDIR)/couchjs-utf8.Po @AMDEP_TRUE@@am__fastdepCC_FALSE@ source='couch_js/utf8.c' object='couchjs-utf8.o' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(couchjs_CFLAGS) $(CFLAGS) -c -o couchjs-utf8.o `test -f 'couch_js/utf8.c' || echo '$(srcdir)/'`couch_js/utf8.c couchjs-utf8.obj: couch_js/utf8.c @am__fastdepCC_TRUE@ $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(couchjs_CFLAGS) $(CFLAGS) -MT couchjs-utf8.obj -MD -MP -MF $(DEPDIR)/couchjs-utf8.Tpo -c -o couchjs-utf8.obj `if test -f 'couch_js/utf8.c'; then $(CYGPATH_W) 'couch_js/utf8.c'; else $(CYGPATH_W) '$(srcdir)/couch_js/utf8.c'; fi` @am__fastdepCC_TRUE@ $(am__mv) $(DEPDIR)/couchjs-utf8.Tpo $(DEPDIR)/couchjs-utf8.Po @AMDEP_TRUE@@am__fastdepCC_FALSE@ source='couch_js/utf8.c' object='couchjs-utf8.obj' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(couchjs_CFLAGS) $(CFLAGS) -c -o couchjs-utf8.obj `if test -f 'couch_js/utf8.c'; then $(CYGPATH_W) 'couch_js/utf8.c'; else $(CYGPATH_W) '$(srcdir)/couch_js/utf8.c'; fi` couchjs-util.o: couch_js/util.c @am__fastdepCC_TRUE@ $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(couchjs_CFLAGS) $(CFLAGS) -MT couchjs-util.o -MD -MP -MF $(DEPDIR)/couchjs-util.Tpo -c -o couchjs-util.o `test -f 'couch_js/util.c' || echo '$(srcdir)/'`couch_js/util.c @am__fastdepCC_TRUE@ $(am__mv) $(DEPDIR)/couchjs-util.Tpo $(DEPDIR)/couchjs-util.Po @AMDEP_TRUE@@am__fastdepCC_FALSE@ source='couch_js/util.c' object='couchjs-util.o' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(couchjs_CFLAGS) $(CFLAGS) -c -o couchjs-util.o `test -f 'couch_js/util.c' || echo '$(srcdir)/'`couch_js/util.c couchjs-util.obj: couch_js/util.c @am__fastdepCC_TRUE@ $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(couchjs_CFLAGS) $(CFLAGS) -MT couchjs-util.obj -MD -MP -MF $(DEPDIR)/couchjs-util.Tpo -c -o couchjs-util.obj `if test -f 'couch_js/util.c'; then $(CYGPATH_W) 'couch_js/util.c'; else $(CYGPATH_W) '$(srcdir)/couch_js/util.c'; fi` @am__fastdepCC_TRUE@ $(am__mv) $(DEPDIR)/couchjs-util.Tpo $(DEPDIR)/couchjs-util.Po @AMDEP_TRUE@@am__fastdepCC_FALSE@ source='couch_js/util.c' object='couchjs-util.obj' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(couchjs_CFLAGS) $(CFLAGS) -c -o couchjs-util.obj `if test -f 'couch_js/util.c'; then $(CYGPATH_W) 'couch_js/util.c'; else $(CYGPATH_W) '$(srcdir)/couch_js/util.c'; fi` couchspawnkillable_win.o: spawnkillable/couchspawnkillable_win.c @am__fastdepCC_TRUE@ $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT couchspawnkillable_win.o -MD -MP -MF $(DEPDIR)/couchspawnkillable_win.Tpo -c -o couchspawnkillable_win.o `test -f 'spawnkillable/couchspawnkillable_win.c' || echo '$(srcdir)/'`spawnkillable/couchspawnkillable_win.c @am__fastdepCC_TRUE@ $(am__mv) $(DEPDIR)/couchspawnkillable_win.Tpo $(DEPDIR)/couchspawnkillable_win.Po @AMDEP_TRUE@@am__fastdepCC_FALSE@ source='spawnkillable/couchspawnkillable_win.c' object='couchspawnkillable_win.o' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o couchspawnkillable_win.o `test -f 'spawnkillable/couchspawnkillable_win.c' || echo '$(srcdir)/'`spawnkillable/couchspawnkillable_win.c couchspawnkillable_win.obj: spawnkillable/couchspawnkillable_win.c @am__fastdepCC_TRUE@ $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT couchspawnkillable_win.obj -MD -MP -MF $(DEPDIR)/couchspawnkillable_win.Tpo -c -o couchspawnkillable_win.obj `if test -f 'spawnkillable/couchspawnkillable_win.c'; then $(CYGPATH_W) 'spawnkillable/couchspawnkillable_win.c'; else $(CYGPATH_W) '$(srcdir)/spawnkillable/couchspawnkillable_win.c'; fi` @am__fastdepCC_TRUE@ $(am__mv) $(DEPDIR)/couchspawnkillable_win.Tpo $(DEPDIR)/couchspawnkillable_win.Po @AMDEP_TRUE@@am__fastdepCC_FALSE@ source='spawnkillable/couchspawnkillable_win.c' object='couchspawnkillable_win.obj' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o couchspawnkillable_win.obj `if test -f 'spawnkillable/couchspawnkillable_win.c'; then $(CYGPATH_W) 'spawnkillable/couchspawnkillable_win.c'; else $(CYGPATH_W) '$(srcdir)/spawnkillable/couchspawnkillable_win.c'; fi` mostlyclean-libtool: -rm -f *.lo clean-libtool: -rm -rf .libs _libs install-couchprivDATA: $(couchpriv_DATA) @$(NORMAL_INSTALL) @list='$(couchpriv_DATA)'; test -n "$(couchprivdir)" || list=; \ if test -n "$$list"; then \ echo " $(MKDIR_P) '$(DESTDIR)$(couchprivdir)'"; \ $(MKDIR_P) "$(DESTDIR)$(couchprivdir)" || exit 1; \ fi; \ for p in $$list; do \ if test -f "$$p"; then d=; else d="$(srcdir)/"; fi; \ echo "$$d$$p"; \ done | $(am__base_list) | \ while read files; do \ echo " $(INSTALL_DATA) $$files '$(DESTDIR)$(couchprivdir)'"; \ $(INSTALL_DATA) $$files "$(DESTDIR)$(couchprivdir)" || exit $$?; \ done uninstall-couchprivDATA: @$(NORMAL_UNINSTALL) @list='$(couchpriv_DATA)'; test -n "$(couchprivdir)" || list=; \ files=`for p in $$list; do echo $$p; done | sed -e 's|^.*/||'`; \ dir='$(DESTDIR)$(couchprivdir)'; $(am__uninstall_files_from_dir) ID: $(HEADERS) $(SOURCES) $(LISP) $(TAGS_FILES) list='$(SOURCES) $(HEADERS) $(LISP) $(TAGS_FILES)'; \ unique=`for i in $$list; do \ if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \ done | \ $(AWK) '{ files[$$0] = 1; nonempty = 1; } \ END { if (nonempty) { for (i in files) print i; }; }'`; \ mkid -fID $$unique tags: TAGS TAGS: $(HEADERS) $(SOURCES) $(TAGS_DEPENDENCIES) \ $(TAGS_FILES) $(LISP) set x; \ here=`pwd`; \ list='$(SOURCES) $(HEADERS) $(LISP) $(TAGS_FILES)'; \ unique=`for i in $$list; do \ if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \ done | \ $(AWK) '{ files[$$0] = 1; nonempty = 1; } \ END { if (nonempty) { for (i in files) print i; }; }'`; \ shift; \ if test -z "$(ETAGS_ARGS)$$*$$unique"; then :; else \ test -n "$$unique" || unique=$$empty_fix; \ if test $$# -gt 0; then \ $(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \ "$$@" $$unique; \ else \ $(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \ $$unique; \ fi; \ fi ctags: CTAGS CTAGS: $(HEADERS) $(SOURCES) $(TAGS_DEPENDENCIES) \ $(TAGS_FILES) $(LISP) list='$(SOURCES) $(HEADERS) $(LISP) $(TAGS_FILES)'; \ unique=`for i in $$list; do \ if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \ done | \ $(AWK) '{ files[$$0] = 1; nonempty = 1; } \ END { if (nonempty) { for (i in files) print i; }; }'`; \ test -z "$(CTAGS_ARGS)$$unique" \ || $(CTAGS) $(CTAGSFLAGS) $(AM_CTAGSFLAGS) $(CTAGS_ARGS) \ $$unique GTAGS: here=`$(am__cd) $(top_builddir) && pwd` \ && $(am__cd) $(top_srcdir) \ && gtags -i $(GTAGS_ARGS) "$$here" distclean-tags: -rm -f TAGS ID GTAGS GRTAGS GSYMS GPATH tags distdir: $(DISTFILES) @srcdirstrip=`echo "$(srcdir)" | sed 's/[].[^$$\\*]/\\\\&/g'`; \ topsrcdirstrip=`echo "$(top_srcdir)" | sed 's/[].[^$$\\*]/\\\\&/g'`; \ list='$(DISTFILES)'; \ dist_files=`for file in $$list; do echo $$file; done | \ sed -e "s|^$$srcdirstrip/||;t" \ -e "s|^$$topsrcdirstrip/|$(top_builddir)/|;t"`; \ case $$dist_files in \ */*) $(MKDIR_P) `echo "$$dist_files" | \ sed '/\//!d;s|^|$(distdir)/|;s,/[^/]*$$,,' | \ sort -u` ;; \ esac; \ for file in $$dist_files; do \ if test -f $$file || test -d $$file; then d=.; else d=$(srcdir); fi; \ if test -d $$d/$$file; then \ dir=`echo "/$$file" | sed -e 's,/[^/]*$$,,'`; \ if test -d "$(distdir)/$$file"; then \ find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} \;; \ fi; \ if test -d $(srcdir)/$$file && test $$d != $(srcdir); then \ cp -fpR $(srcdir)/$$file "$(distdir)$$dir" || exit 1; \ find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} \;; \ fi; \ cp -fpR $$d/$$file "$(distdir)$$dir" || exit 1; \ else \ test -f "$(distdir)/$$file" \ || cp -p $$d/$$file "$(distdir)/$$file" \ || exit 1; \ fi; \ done check-am: all-am check: $(BUILT_SOURCES) $(MAKE) $(AM_MAKEFLAGS) check-am all-am: Makefile $(LTLIBRARIES) $(PROGRAMS) $(DATA) installdirs: for dir in "$(DESTDIR)$(couchprivlibdir)" "$(DESTDIR)$(couchprivdir)" "$(DESTDIR)$(locallibbindir)" "$(DESTDIR)$(couchprivdir)"; do \ test -z "$$dir" || $(MKDIR_P) "$$dir"; \ done install: $(BUILT_SOURCES) $(MAKE) $(AM_MAKEFLAGS) install-am install-exec: install-exec-am install-data: install-data-am uninstall: uninstall-am install-am: all-am @$(MAKE) $(AM_MAKEFLAGS) install-exec-am install-data-am installcheck: installcheck-am install-strip: if test -z '$(STRIP)'; then \ $(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(INSTALL_STRIP_PROGRAM)" \ install_sh_PROGRAM="$(INSTALL_STRIP_PROGRAM)" INSTALL_STRIP_FLAG=-s \ install; \ else \ $(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(INSTALL_STRIP_PROGRAM)" \ install_sh_PROGRAM="$(INSTALL_STRIP_PROGRAM)" INSTALL_STRIP_FLAG=-s \ "INSTALL_PROGRAM_ENV=STRIPPROG='$(STRIP)'" install; \ fi mostlyclean-generic: clean-generic: -test -z "$(CLEANFILES)" || rm -f $(CLEANFILES) distclean-generic: -test -z "$(CONFIG_CLEAN_FILES)" || rm -f $(CONFIG_CLEAN_FILES) -test . = "$(srcdir)" || test -z "$(CONFIG_CLEAN_VPATH_FILES)" || rm -f $(CONFIG_CLEAN_VPATH_FILES) maintainer-clean-generic: @echo "This command is intended for maintainers to use" @echo "it deletes files that may require special tools to rebuild." -test -z "$(BUILT_SOURCES)" || rm -f $(BUILT_SOURCES) clean: clean-am clean-am: clean-couchprivPROGRAMS clean-couchprivlibLTLIBRARIES \ clean-generic clean-libtool clean-locallibbinPROGRAMS \ mostlyclean-am distclean: distclean-am -rm -rf ./$(DEPDIR) -rm -f Makefile distclean-am: clean-am distclean-compile distclean-generic \ distclean-tags dvi: dvi-am dvi-am: html: html-am html-am: info: info-am info-am: install-data-am: install-couchprivDATA install-couchprivPROGRAMS \ install-couchprivlibLTLIBRARIES install-data-local \ install-locallibbinPROGRAMS @$(NORMAL_INSTALL) $(MAKE) $(AM_MAKEFLAGS) install-data-hook install-dvi: install-dvi-am install-dvi-am: install-exec-am: install-html: install-html-am install-html-am: install-info: install-info-am install-info-am: install-man: install-pdf: install-pdf-am install-pdf-am: install-ps: install-ps-am install-ps-am: installcheck-am: maintainer-clean: maintainer-clean-am -rm -rf ./$(DEPDIR) -rm -f Makefile maintainer-clean-am: distclean-am maintainer-clean-generic mostlyclean: mostlyclean-am mostlyclean-am: mostlyclean-compile mostlyclean-generic \ mostlyclean-libtool pdf: pdf-am pdf-am: ps: ps-am ps-am: uninstall-am: uninstall-couchprivDATA uninstall-couchprivPROGRAMS \ uninstall-couchprivlibLTLIBRARIES uninstall-local \ uninstall-locallibbinPROGRAMS .MAKE: all check install install-am install-data-am install-strip .PHONY: CTAGS GTAGS all all-am check check-am clean \ clean-couchprivPROGRAMS clean-couchprivlibLTLIBRARIES \ clean-generic clean-libtool clean-locallibbinPROGRAMS ctags \ distclean distclean-compile distclean-generic \ distclean-libtool distclean-tags distdir dvi dvi-am html \ html-am info info-am install install-am install-couchprivDATA \ install-couchprivPROGRAMS install-couchprivlibLTLIBRARIES \ install-data install-data-am install-data-hook \ install-data-local install-dvi install-dvi-am install-exec \ install-exec-am install-html install-html-am install-info \ install-info-am install-locallibbinPROGRAMS install-man \ install-pdf install-pdf-am install-ps install-ps-am \ install-strip installcheck installcheck-am installdirs \ maintainer-clean maintainer-clean-generic mostlyclean \ mostlyclean-compile mostlyclean-generic mostlyclean-libtool \ pdf pdf-am ps ps-am tags uninstall uninstall-am \ uninstall-couchprivDATA uninstall-couchprivPROGRAMS \ uninstall-couchprivlibLTLIBRARIES uninstall-local \ uninstall-locallibbinPROGRAMS # Depend on source files so distributed man pages are not rebuilt for end user. $(man_file): $(COUCHJS_SRCS) $(MAKE_SAFE) -f Makefile couchjs; \ $(top_srcdir)/build-aux/missing --run \ help2man \ --no-info \ --help-option="-h" \ --version-option="-V" \ --name="$(package_name) JavaScript interpreter" \ ./couchjs --output $@ install-data-local: if test -s $(man_file); then \ if test `cat $(man_file) | wc -l` -gt 1; then \ $(INSTALL) -d $(DESTDIR)$(man1dir); \ $(INSTALL_DATA) $(man_file) $(DESTDIR)$(man1dir)/$(man_file); \ fi \ fi %.cfg: %.cfg.in cp $< $@ @WINDOWS_FALSE@couchspawnkillable: spawnkillable/couchspawnkillable.sh @WINDOWS_FALSE@ cp $< $@ @WINDOWS_FALSE@ chmod +x $@ # libtool and automake have defeated markh. For each of our executables # we end up with 2 copies - one directly in the 'target' folder (eg, 'priv') # and another - the correct one - in .libs. The former doesn't work but is # what gets installed for 'couchspawnkillable' - but the correct one for # couchjs.exe *does* get copied. *shrug* So just clobber it with the # correct one as the last step. See bug COUCHDB-439 install-data-hook: if test -f "$(DESTDIR)$(couchprivlibdir)/couch_icu_driver"; then \ rm -f "$(DESTDIR)$(couchprivlibdir)/couch_icu_driver.so"; \ cd "$(DESTDIR)$(couchprivlibdir)" && \ $(LN_S) couch_icu_driver couch_icu_driver.so; \ fi if test -f "$(DESTDIR)$(couchprivlibdir)/couch_ejson_compare_nif"; then \ rm -f "$(DESTDIR)$(couchprivlibdir)/couch_ejson_compare_nif.so"; \ cd "$(DESTDIR)$(couchprivlibdir)" && \ $(LN_S) couch_ejson_compare_nif couch_ejson_compare_nif.so; \ fi @WINDOWS_TRUE@ $(INSTALL) $(ICU_BIN)/icuuc*.dll $(bindir) @WINDOWS_TRUE@ $(INSTALL) $(ICU_BIN)/icudt*.dll $(bindir) @WINDOWS_TRUE@ $(INSTALL) $(ICU_BIN)/icuin*.dll $(bindir) @WINDOWS_TRUE@ $(INSTALL) $(JS_LIB_BINARY) $(bindir) @WINDOWS_TRUE@ $(INSTALL) .libs/couchspawnkillable.exe \ @WINDOWS_TRUE@ "$(DESTDIR)$(couchprivdir)/couchspawnkillable.exe" uninstall-local: rm -f $(DESTDIR)$(man1dir)/$(man_file) if test -f "$(DESTDIR)$(couchprivlibdir)/couch_erl_driver"; then \ rm -f "$(DESTDIR)$(couchprivlibdir)/couch_erl_driver.so"; \ fi distcheck-hook: if test ! -s $(man_file); then \ $(top_srcdir)/build-aux/dist-error $(man_file); \ else \ if test ! `cat $(man_file) | wc -l` -gt 1; then \ $(top_srcdir)/build-aux/dist-error $(man_file); \ fi \ fi # Tell versions [3.59,3.63) of GNU make to not export all variables. # Otherwise a system limit (for SysV at least) may be exceeded. .NOEXPORT: apache-couchdb-1.5.0/src/couchdb/priv/couch_js/0000755000175000001440000000000012230722305016307 500000000000000apache-couchdb-1.5.0/src/couchdb/priv/couch_js/sm170.c0000644000175000001440000002114712230722213017245 00000000000000// 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. #include #include #include #include #include "http.h" #include "utf8.h" #include "util.h" #ifdef JS_THREADSAFE #define SETUP_REQUEST(cx) \ JS_SetContextThread(cx); \ JS_BeginRequest(cx); #define FINISH_REQUEST(cx) \ JS_EndRequest(cx); \ JS_ClearContextThread(cx); #else #define SETUP_REQUEST(cx) #define FINISH_REQUEST(cx) #endif static JSBool req_ctor(JSContext* cx, JSObject* obj, uintN argc, jsval* argv, jsval* rval) { return http_ctor(cx, obj); } static void req_dtor(JSContext* cx, JSObject* obj) { http_dtor(cx, obj); } static JSBool req_open(JSContext* cx, JSObject* obj, uintN argc, jsval* argv, jsval* rval) { JSBool ret = JS_FALSE; if(argc == 2) { ret = http_open(cx, obj, argv[0], argv[1], JSVAL_FALSE); } else if(argc == 3) { ret = http_open(cx, obj, argv[0], argv[1], argv[2]); } else { JS_ReportError(cx, "Invalid call to CouchHTTP.open"); } *rval = JSVAL_VOID; return ret; } static JSBool req_set_hdr(JSContext* cx, JSObject* obj, uintN argc, jsval* argv, jsval* rval) { JSBool ret = JS_FALSE; if(argc == 2) { ret = http_set_hdr(cx, obj, argv[0], argv[1]); } else { JS_ReportError(cx, "Invalid call to CouchHTTP.set_header"); } *rval = JSVAL_VOID; return ret; } static JSBool req_send(JSContext* cx, JSObject* obj, uintN argc, jsval* argv, jsval* rval) { JSBool ret = JS_FALSE; if(argc == 1) { ret = http_send(cx, obj, argv[0]); } else { JS_ReportError(cx, "Invalid call to CouchHTTP.send"); } *rval = JSVAL_VOID; return ret; } static JSBool req_status(JSContext* cx, JSObject* obj, jsval idval, jsval* rval) { int status = http_status(cx, obj); if(status < 0) return JS_FALSE; if(INT_FITS_IN_JSVAL(status)) { *rval = INT_TO_JSVAL(status); return JS_TRUE; } else { JS_ReportError(cx, "Invalid HTTP status."); return JS_FALSE; } } static JSBool base_url(JSContext *cx, JSObject* obj, jsval idval, jsval* rval) { couch_args *args = (couch_args*)JS_GetContextPrivate(cx); return http_uri(cx, obj, args, rval); } static JSBool evalcx(JSContext *cx, JSObject *obj, uintN argc, jsval *argv, jsval *rval) { JSString *str; JSObject *sandbox; JSContext *subcx; const jschar *src; size_t srclen; JSBool ret = JS_FALSE; char *name = NULL; sandbox = NULL; if(!JS_ConvertArguments(cx, argc, argv, "S / o", &str, &sandbox)) { return JS_FALSE; } subcx = JS_NewContext(JS_GetRuntime(cx), 8L * 1024L); if(!subcx) { JS_ReportOutOfMemory(cx); return JS_FALSE; } SETUP_REQUEST(subcx); src = JS_GetStringChars(str); srclen = JS_GetStringLength(str); if(!sandbox) { sandbox = JS_NewObject(subcx, NULL, NULL, NULL); if(!sandbox || !JS_InitStandardClasses(subcx, sandbox)) { goto done; } } if(argc > 2) { name = enc_string(cx, argv[2], NULL); } if(srclen == 0) { *rval = OBJECT_TO_JSVAL(sandbox); } else { JS_EvaluateUCScript(subcx, sandbox, src, srclen, name, 1, rval); } ret = JS_TRUE; done: if(name) JS_free(cx, name); FINISH_REQUEST(subcx); JS_DestroyContext(subcx); return ret; } static JSBool gc(JSContext* cx, JSObject* obj, uintN argc, jsval* argv, jsval* rval) { JS_GC(cx); *rval = JSVAL_VOID; return JS_TRUE; } static JSBool print(JSContext* cx, JSObject* obj, uintN argc, jsval* argv, jsval* rval) { couch_print(cx, argc, argv); *rval = JSVAL_VOID; return JS_TRUE; } static JSBool quit(JSContext* cx, JSObject* obj, uintN argc, jsval* argv, jsval* rval) { int exit_code = 0; JS_ConvertArguments(cx, argc, argv, "/i", &exit_code); exit(exit_code); } static JSBool readline(JSContext* cx, JSObject* obj, uintN argc, jsval* argv, jsval* rval) { JSString* line; /* GC Occasionally */ JS_MaybeGC(cx); line = couch_readline(cx, stdin); if(line == NULL) return JS_FALSE; *rval = STRING_TO_JSVAL(line); return JS_TRUE; } static JSBool seal(JSContext* cx, JSObject* obj, uintN argc, jsval* argv, jsval* rval) { JSObject *target; JSBool deep = JS_FALSE; if(!JS_ConvertArguments(cx, argc, argv, "o/b", &target, &deep)) return JS_FALSE; if(!target) { *rval = JSVAL_VOID; return JS_TRUE; } if(JS_SealObject(cx, target, deep) != JS_TRUE) return JS_FALSE; *rval = JSVAL_VOID; return JS_TRUE; } JSClass CouchHTTPClass = { "CouchHTTP", JSCLASS_HAS_PRIVATE | JSCLASS_CONSTRUCT_PROTOTYPE | JSCLASS_HAS_RESERVED_SLOTS(2), JS_PropertyStub, JS_PropertyStub, JS_PropertyStub, JS_PropertyStub, JS_EnumerateStub, JS_ResolveStub, JS_ConvertStub, req_dtor, JSCLASS_NO_OPTIONAL_MEMBERS }; JSPropertySpec CouchHTTPProperties[] = { {"status", 0, JSPROP_READONLY, req_status, NULL}, {"base_url", 0, JSPROP_READONLY | JSPROP_SHARED, base_url, NULL}, {0, 0, 0, 0, 0} }; JSFunctionSpec CouchHTTPFunctions[] = { {"_open", req_open, 3, 0, 0}, {"_setRequestHeader", req_set_hdr, 2, 0, 0}, {"_send", req_send, 1, 0, 0}, {0, 0, 0, 0, 0} }; static JSClass global_class = { "GlobalClass", JSCLASS_GLOBAL_FLAGS, JS_PropertyStub, JS_PropertyStub, JS_PropertyStub, JS_PropertyStub, JS_EnumerateStub, JS_ResolveStub, JS_ConvertStub, JS_FinalizeStub, JSCLASS_NO_OPTIONAL_MEMBERS }; static JSFunctionSpec global_functions[] = { {"evalcx", evalcx, 0, 0, 0}, {"gc", gc, 0, 0, 0}, {"print", print, 0, 0, 0}, {"quit", quit, 0, 0, 0}, {"readline", readline, 0, 0, 0}, {"seal", seal, 0, 0, 0}, {0, 0, 0, 0, 0} }; int main(int argc, const char* argv[]) { JSRuntime* rt = NULL; JSContext* cx = NULL; JSObject* global = NULL; JSObject* klass = NULL; JSScript* script; JSString* scriptsrc; jschar* schars; size_t slen; jsval sroot; jsval result; int i; couch_args* args = couch_parse_args(argc, argv); rt = JS_NewRuntime(args->stack_size); if(rt == NULL) return 1; cx = JS_NewContext(rt, 8L * 1024L); if(cx == NULL) return 1; JS_SetErrorReporter(cx, couch_error); JS_ToggleOptions(cx, JSOPTION_XML); JS_SetContextPrivate(cx, args); SETUP_REQUEST(cx); global = JS_NewObject(cx, &global_class, NULL, NULL); if(global == NULL) return 1; JS_SetGlobalObject(cx, global); if(!JS_InitStandardClasses(cx, global)) return 1; if(couch_load_funcs(cx, global, global_functions) != JS_TRUE) return 1; if(args->use_http) { http_check_enabled(); klass = JS_InitClass( cx, global, NULL, &CouchHTTPClass, req_ctor, 0, CouchHTTPProperties, CouchHTTPFunctions, NULL, NULL ); if(!klass) { fprintf(stderr, "Failed to initialize CouchHTTP class.\n"); exit(2); } } for (i = 0 ; args->scripts[i] ; i++) { // Convert script source to jschars. scriptsrc = couch_readfile(cx, args->scripts[i]); if(!scriptsrc) return 1; schars = JS_GetStringChars(scriptsrc); slen = JS_GetStringLength(scriptsrc); // Root it so GC doesn't collect it. sroot = STRING_TO_JSVAL(scriptsrc); if(JS_AddRoot(cx, &sroot) != JS_TRUE) { fprintf(stderr, "Internal root error.\n"); return 1; } // Compile and run script = JS_CompileUCScript(cx, global, schars, slen, args->scripts[i], 1); if(!script) { fprintf(stderr, "Failed to compile script.\n"); return 1; } JS_ExecuteScript(cx, global, script, &result); // Warning message if we don't remove it. JS_RemoveRoot(cx, &sroot); } FINISH_REQUEST(cx); JS_DestroyContext(cx); JS_DestroyRuntime(rt); JS_ShutDown(); return 0; } apache-couchdb-1.5.0/src/couchdb/priv/couch_js/sm180.c0000644000175000001440000002211412230722213017241 00000000000000// 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. #include #include #include #include #include "http.h" #include "utf8.h" #include "util.h" #define SETUP_REQUEST(cx) \ JS_SetContextThread(cx); \ JS_BeginRequest(cx); #define FINISH_REQUEST(cx) \ JS_EndRequest(cx); \ JS_ClearContextThread(cx); static JSBool req_ctor(JSContext* cx, JSObject* obj, uintN argc, jsval* argv, jsval* rval) { return http_ctor(cx, obj); } static void req_dtor(JSContext* cx, JSObject* obj) { http_dtor(cx, obj); } static JSBool req_open(JSContext* cx, uintN argc, jsval* vp) { JSObject* obj = JS_THIS_OBJECT(cx, vp); jsval* argv = JS_ARGV(cx, vp); JSBool ret = JS_FALSE; if(argc == 2) { ret = http_open(cx, obj, argv[0], argv[1], JSVAL_FALSE); } else if(argc == 3) { ret = http_open(cx, obj, argv[0], argv[1], argv[2]); } else { JS_ReportError(cx, "Invalid call to CouchHTTP.open"); } JS_SET_RVAL(cx, vp, JSVAL_VOID); return ret; } static JSBool req_set_hdr(JSContext* cx, uintN argc, jsval* vp) { JSObject* obj = JS_THIS_OBJECT(cx, vp); jsval* argv = JS_ARGV(cx, vp); JSBool ret = JS_FALSE; if(argc == 2) { ret = http_set_hdr(cx, obj, argv[0], argv[1]); } else { JS_ReportError(cx, "Invalid call to CouchHTTP.set_header"); } JS_SET_RVAL(cx, vp, JSVAL_VOID); return ret; } static JSBool req_send(JSContext* cx, uintN argc, jsval* vp) { JSObject* obj = JS_THIS_OBJECT(cx, vp); jsval* argv = JS_ARGV(cx, vp); JSBool ret = JS_FALSE; if(argc == 1) { ret = http_send(cx, obj, argv[0]); } else { JS_ReportError(cx, "Invalid call to CouchHTTP.send"); } JS_SET_RVAL(cx, vp, JSVAL_VOID); return ret; } static JSBool req_status(JSContext* cx, JSObject* obj, jsval idval, jsval* vp) { int status = http_status(cx, obj); if(status < 0) return JS_FALSE; if(INT_FITS_IN_JSVAL(status)) { JS_SET_RVAL(cx, vp, INT_TO_JSVAL(status)); return JS_TRUE; } else { JS_ReportError(cx, "Invalid HTTP status."); return JS_FALSE; } } static JSBool base_url(JSContext *cx, JSObject* obj, jsid pid, jsval* vp) { couch_args *args = (couch_args*)JS_GetContextPrivate(cx); return http_uri(cx, obj, args, &JS_RVAL(cx, vp)); } static JSBool evalcx(JSContext *cx, uintN argc, jsval* vp) { jsval* argv = JS_ARGV(cx, vp); JSString *str; JSObject *sandbox; JSContext *subcx; const jschar *src; size_t srclen; jsval rval; JSBool ret = JS_FALSE; char *name = NULL; sandbox = NULL; if(!JS_ConvertArguments(cx, argc, argv, "S / o", &str, &sandbox)) { return JS_FALSE; } subcx = JS_NewContext(JS_GetRuntime(cx), 8L * 1024L); if(!subcx) { JS_ReportOutOfMemory(cx); return JS_FALSE; } SETUP_REQUEST(subcx); src = JS_GetStringChars(str); srclen = JS_GetStringLength(str); if(!sandbox) { sandbox = JS_NewObject(subcx, NULL, NULL, NULL); if(!sandbox || !JS_InitStandardClasses(subcx, sandbox)) { goto done; } } if(argc > 2) { name = enc_string(cx, argv[2], NULL); } if(srclen == 0) { JS_SET_RVAL(cx, vp, OBJECT_TO_JSVAL(sandbox)); } else { JS_EvaluateUCScript(subcx, sandbox, src, srclen, name, 1, &rval); JS_SET_RVAL(cx, vp, rval); } ret = JS_TRUE; done: if(name) JS_free(cx, name); FINISH_REQUEST(subcx); JS_DestroyContext(subcx); return ret; } static JSBool gc(JSContext* cx, uintN argc, jsval* vp) { JS_GC(cx); JS_SET_RVAL(cx, vp, JSVAL_VOID); return JS_TRUE; } static JSBool print(JSContext* cx, uintN argc, jsval* vp) { jsval* argv = JS_ARGV(cx, vp); couch_print(cx, argc, argv); JS_SET_RVAL(cx, vp, JSVAL_VOID); return JS_TRUE; } static JSBool quit(JSContext* cx, uintN argc, jsval* vp) { jsval* argv = JS_ARGV(cx, vp); int exit_code = 0; JS_ConvertArguments(cx, argc, argv, "/i", &exit_code); exit(exit_code); } static JSBool readline(JSContext* cx, uintN argc, jsval* vp) { JSString* line; /* GC Occasionally */ JS_MaybeGC(cx); line = couch_readline(cx, stdin); if(line == NULL) return JS_FALSE; JS_SET_RVAL(cx, vp, STRING_TO_JSVAL(line)); return JS_TRUE; } static JSBool seal(JSContext* cx, uintN argc, jsval* vp) { jsval* argv = JS_ARGV(cx, vp); JSObject *target; JSBool deep = JS_FALSE; if(!JS_ConvertArguments(cx, argc, argv, "o/b", &target, &deep)) return JS_FALSE; if(!target) { JS_SET_RVAL(cx, vp, JSVAL_VOID); return JS_TRUE; } if(JS_SealObject(cx, target, deep) != JS_TRUE) return JS_FALSE; JS_SET_RVAL(cx, vp, JSVAL_VOID); return JS_TRUE; } JSClass CouchHTTPClass = { "CouchHTTP", JSCLASS_HAS_PRIVATE | JSCLASS_CONSTRUCT_PROTOTYPE | JSCLASS_HAS_RESERVED_SLOTS(2), JS_PropertyStub, JS_PropertyStub, JS_PropertyStub, JS_PropertyStub, JS_EnumerateStub, JS_ResolveStub, JS_ConvertStub, req_dtor, JSCLASS_NO_OPTIONAL_MEMBERS }; JSPropertySpec CouchHTTPProperties[] = { {"status", 0, JSPROP_READONLY, req_status, NULL}, {"base_url", 0, JSPROP_READONLY | JSPROP_SHARED, base_url, NULL}, {0, 0, 0, 0, 0} }; JSFunctionSpec CouchHTTPFunctions[] = { JS_FS("_open", (JSNative) req_open, 3, JSFUN_FAST_NATIVE, 0), JS_FS("_setRequestHeader", (JSNative) req_set_hdr, 2, JSFUN_FAST_NATIVE, 0), JS_FS("_send", (JSNative) req_send, 1, JSFUN_FAST_NATIVE, 0), JS_FS_END }; static JSClass global_class = { "GlobalClass", JSCLASS_GLOBAL_FLAGS, JS_PropertyStub, JS_PropertyStub, JS_PropertyStub, JS_PropertyStub, JS_EnumerateStub, JS_ResolveStub, JS_ConvertStub, JS_FinalizeStub, JSCLASS_NO_OPTIONAL_MEMBERS }; static JSFunctionSpec global_functions[] = { JS_FS("evalcx", (JSNative) evalcx, 0, JSFUN_FAST_NATIVE, 0), JS_FS("gc", (JSNative) gc, 0, JSFUN_FAST_NATIVE, 0), JS_FS("print", (JSNative) print, 0, JSFUN_FAST_NATIVE, 0), JS_FS("quit", (JSNative) quit, 0, JSFUN_FAST_NATIVE, 0), JS_FS("readline", (JSNative) readline, 0, JSFUN_FAST_NATIVE, 0), JS_FS("seal", (JSNative) seal, 0, JSFUN_FAST_NATIVE, 0), JS_FS_END }; int main(int argc, const char* argv[]) { JSRuntime* rt = NULL; JSContext* cx = NULL; JSObject* global = NULL; JSObject* klass = NULL; JSScript* script; JSString* scriptsrc; jschar* schars; size_t slen; jsval sroot; jsval result; int i; couch_args* args = couch_parse_args(argc, argv); rt = JS_NewRuntime(args->stack_size); if(rt == NULL) return 1; cx = JS_NewContext(rt, 8L * 1024L); if(cx == NULL) return 1; JS_SetErrorReporter(cx, couch_error); JS_ToggleOptions(cx, JSOPTION_XML); JS_SetContextPrivate(cx, args); SETUP_REQUEST(cx); global = JS_NewObject(cx, &global_class, NULL, NULL); if(global == NULL) return 1; JS_SetGlobalObject(cx, global); if(!JS_InitStandardClasses(cx, global)) return 1; if(couch_load_funcs(cx, global, global_functions) != JS_TRUE) return 1; if(args->use_http) { http_check_enabled(); klass = JS_InitClass( cx, global, NULL, &CouchHTTPClass, req_ctor, 0, CouchHTTPProperties, CouchHTTPFunctions, NULL, NULL ); if(!klass) { fprintf(stderr, "Failed to initialize CouchHTTP class.\n"); exit(2); } } for (i = 0 ; args->scripts[i] ; i++) { // Convert script source to jschars. scriptsrc = couch_readfile(cx, args->scripts[i]); if(!scriptsrc) return 1; schars = JS_GetStringChars(scriptsrc); slen = JS_GetStringLength(scriptsrc); // Root it so GC doesn't collect it. sroot = STRING_TO_JSVAL(scriptsrc); if(JS_AddRoot(cx, &sroot) != JS_TRUE) { fprintf(stderr, "Internal root error.\n"); return 1; } // Compile and run script = JS_CompileUCScript(cx, global, schars, slen, args->scripts[i], 1); if(!script) { fprintf(stderr, "Failed to compile script.\n"); return 1; } JS_ExecuteScript(cx, global, script, &result); // Warning message if we don't remove it. JS_RemoveRoot(cx, &sroot); } FINISH_REQUEST(cx); JS_DestroyContext(cx); JS_DestroyRuntime(rt); JS_ShutDown(); return 0; } apache-couchdb-1.5.0/src/couchdb/priv/couch_js/sm185.c0000644000175000001440000002326412230722213017255 00000000000000// 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. #include #include #include #include #include "http.h" #include "utf8.h" #include "util.h" #define SETUP_REQUEST(cx) \ JS_SetContextThread(cx); \ JS_BeginRequest(cx); #define FINISH_REQUEST(cx) \ JS_EndRequest(cx); \ JS_ClearContextThread(cx); static JSClass global_class = { "GlobalClass", JSCLASS_GLOBAL_FLAGS, JS_PropertyStub, JS_PropertyStub, JS_PropertyStub, JS_StrictPropertyStub, JS_EnumerateStub, JS_ResolveStub, JS_ConvertStub, JS_FinalizeStub, JSCLASS_NO_OPTIONAL_MEMBERS }; static JSBool req_ctor(JSContext* cx, uintN argc, jsval* vp) { JSBool ret; JSObject* obj = JS_NewObjectForConstructor(cx, vp); if(!obj) { JS_ReportError(cx, "Failed to create CouchHTTP instance.\n"); return JS_FALSE; } ret = http_ctor(cx, obj); JS_SET_RVAL(cx, vp, OBJECT_TO_JSVAL(obj)); return ret; } static void req_dtor(JSContext* cx, JSObject* obj) { http_dtor(cx, obj); } static JSBool req_open(JSContext* cx, uintN argc, jsval* vp) { JSObject* obj = JS_THIS_OBJECT(cx, vp); jsval* argv = JS_ARGV(cx, vp); JSBool ret = JS_FALSE; if(argc == 2) { ret = http_open(cx, obj, argv[0], argv[1], JSVAL_FALSE); } else if(argc == 3) { ret = http_open(cx, obj, argv[0], argv[1], argv[2]); } else { JS_ReportError(cx, "Invalid call to CouchHTTP.open"); } JS_SET_RVAL(cx, vp, JSVAL_VOID); return ret; } static JSBool req_set_hdr(JSContext* cx, uintN argc, jsval* vp) { JSObject* obj = JS_THIS_OBJECT(cx, vp); jsval* argv = JS_ARGV(cx, vp); JSBool ret = JS_FALSE; if(argc == 2) { ret = http_set_hdr(cx, obj, argv[0], argv[1]); } else { JS_ReportError(cx, "Invalid call to CouchHTTP.set_header"); } JS_SET_RVAL(cx, vp, JSVAL_VOID); return ret; } static JSBool req_send(JSContext* cx, uintN argc, jsval* vp) { JSObject* obj = JS_THIS_OBJECT(cx, vp); jsval* argv = JS_ARGV(cx, vp); JSBool ret = JS_FALSE; if(argc == 1) { ret = http_send(cx, obj, argv[0]); } else { JS_ReportError(cx, "Invalid call to CouchHTTP.send"); } JS_SET_RVAL(cx, vp, JSVAL_VOID); return ret; } static JSBool req_status(JSContext* cx, JSObject* obj, jsid pid, jsval* vp) { int status = http_status(cx, obj); if(status < 0) return JS_FALSE; JS_SET_RVAL(cx, vp, INT_TO_JSVAL(status)); return JS_TRUE; } static JSBool base_url(JSContext *cx, JSObject* obj, jsid pid, jsval* vp) { couch_args *args = (couch_args*)JS_GetContextPrivate(cx); return http_uri(cx, obj, args, &JS_RVAL(cx, vp)); } static JSBool evalcx(JSContext *cx, uintN argc, jsval* vp) { jsval* argv = JS_ARGV(cx, vp); JSString* str; JSObject* sandbox; JSObject* global; JSContext* subcx; JSCrossCompartmentCall* call = NULL; const jschar* src; size_t srclen; jsval rval; JSBool ret = JS_FALSE; char *name = NULL; sandbox = NULL; if(!JS_ConvertArguments(cx, argc, argv, "S / o", &str, &sandbox)) { return JS_FALSE; } subcx = JS_NewContext(JS_GetRuntime(cx), 8L * 1024L); if(!subcx) { JS_ReportOutOfMemory(cx); return JS_FALSE; } SETUP_REQUEST(subcx); src = JS_GetStringCharsAndLength(cx, str, &srclen); // Re-use the compartment associated with the main context, // rather than creating a new compartment */ global = JS_GetGlobalObject(cx); if(global == NULL) goto done; call = JS_EnterCrossCompartmentCall(subcx, global); if(!sandbox) { sandbox = JS_NewGlobalObject(subcx, &global_class); if(!sandbox || !JS_InitStandardClasses(subcx, sandbox)) { goto done; } } if(argc > 2) { name = enc_string(cx, argv[2], NULL); } if(srclen == 0) { JS_SET_RVAL(cx, vp, OBJECT_TO_JSVAL(sandbox)); } else { JS_EvaluateUCScript(subcx, sandbox, src, srclen, name, 1, &rval); JS_SET_RVAL(cx, vp, rval); } ret = JS_TRUE; done: if(name) JS_free(cx, name); JS_LeaveCrossCompartmentCall(call); FINISH_REQUEST(subcx); JS_DestroyContext(subcx); return ret; } static JSBool gc(JSContext* cx, uintN argc, jsval* vp) { JS_GC(cx); JS_SET_RVAL(cx, vp, JSVAL_VOID); return JS_TRUE; } static JSBool print(JSContext* cx, uintN argc, jsval* vp) { jsval* argv = JS_ARGV(cx, vp); couch_print(cx, argc, argv); JS_SET_RVAL(cx, vp, JSVAL_VOID); return JS_TRUE; } static JSBool quit(JSContext* cx, uintN argc, jsval* vp) { jsval* argv = JS_ARGV(cx, vp); int exit_code = 0; JS_ConvertArguments(cx, argc, argv, "/i", &exit_code); exit(exit_code); } static JSBool readline(JSContext* cx, uintN argc, jsval* vp) { JSString* line; /* GC Occasionally */ JS_MaybeGC(cx); line = couch_readline(cx, stdin); if(line == NULL) return JS_FALSE; JS_SET_RVAL(cx, vp, STRING_TO_JSVAL(line)); return JS_TRUE; } static JSBool seal(JSContext* cx, uintN argc, jsval* vp) { jsval* argv = JS_ARGV(cx, vp); JSObject *target; JSBool deep = JS_FALSE; JSBool ret; if(!JS_ConvertArguments(cx, argc, argv, "o/b", &target, &deep)) return JS_FALSE; if(!target) { JS_SET_RVAL(cx, vp, JSVAL_VOID); return JS_TRUE; } ret = deep ? JS_DeepFreezeObject(cx, target) : JS_FreezeObject(cx, target); JS_SET_RVAL(cx, vp, JSVAL_VOID); return ret; } JSClass CouchHTTPClass = { "CouchHTTP", JSCLASS_HAS_PRIVATE | JSCLASS_CONSTRUCT_PROTOTYPE | JSCLASS_HAS_RESERVED_SLOTS(2), JS_PropertyStub, JS_PropertyStub, JS_PropertyStub, JS_StrictPropertyStub, JS_EnumerateStub, JS_ResolveStub, JS_ConvertStub, req_dtor, JSCLASS_NO_OPTIONAL_MEMBERS }; JSPropertySpec CouchHTTPProperties[] = { {"status", 0, JSPROP_READONLY, req_status, NULL}, {"base_url", 0, JSPROP_READONLY | JSPROP_SHARED, base_url, NULL}, {0, 0, 0, 0, 0} }; JSFunctionSpec CouchHTTPFunctions[] = { JS_FS("_open", req_open, 3, 0), JS_FS("_setRequestHeader", req_set_hdr, 2, 0), JS_FS("_send", req_send, 1, 0), JS_FS_END }; static JSFunctionSpec global_functions[] = { JS_FS("evalcx", evalcx, 0, 0), JS_FS("gc", gc, 0, 0), JS_FS("print", print, 0, 0), JS_FS("quit", quit, 0, 0), JS_FS("readline", readline, 0, 0), JS_FS("seal", seal, 0, 0), JS_FS_END }; int main(int argc, const char* argv[]) { JSRuntime* rt = NULL; JSContext* cx = NULL; JSObject* global = NULL; JSCrossCompartmentCall *call = NULL; JSObject* klass = NULL; JSSCRIPT_TYPE script; JSString* scriptsrc; const jschar* schars; size_t slen; jsval sroot; jsval result; int i; couch_args* args = couch_parse_args(argc, argv); rt = JS_NewRuntime(args->stack_size); if(rt == NULL) return 1; cx = JS_NewContext(rt, 8L * 1024L); if(cx == NULL) return 1; JS_SetErrorReporter(cx, couch_error); JS_ToggleOptions(cx, JSOPTION_XML); JS_SetOptions(cx, JSOPTION_METHODJIT); #ifdef JSOPTION_TYPE_INFERENCE JS_SetOptions(cx, JSOPTION_TYPE_INFERENCE); #endif JS_SetContextPrivate(cx, args); SETUP_REQUEST(cx); global = JS_NewCompartmentAndGlobalObject(cx, &global_class, NULL); if(global == NULL) return 1; call = JS_EnterCrossCompartmentCall(cx, global); JS_SetGlobalObject(cx, global); if(!JS_InitStandardClasses(cx, global)) return 1; if(couch_load_funcs(cx, global, global_functions) != JS_TRUE) return 1; if(args->use_http) { http_check_enabled(); klass = JS_InitClass( cx, global, NULL, &CouchHTTPClass, req_ctor, 0, CouchHTTPProperties, CouchHTTPFunctions, NULL, NULL ); if(!klass) { fprintf(stderr, "Failed to initialize CouchHTTP class.\n"); exit(2); } } for(i = 0 ; args->scripts[i] ; i++) { // Convert script source to jschars. scriptsrc = couch_readfile(cx, args->scripts[i]); if(!scriptsrc) return 1; schars = JS_GetStringCharsAndLength(cx, scriptsrc, &slen); // Root it so GC doesn't collect it. sroot = STRING_TO_JSVAL(scriptsrc); if(JS_AddValueRoot(cx, &sroot) != JS_TRUE) { fprintf(stderr, "Internal root error.\n"); return 1; } // Compile and run script = JS_CompileUCScript(cx, global, schars, slen, args->scripts[i], 1); if(!script) { fprintf(stderr, "Failed to compile script.\n"); return 1; } if(JS_ExecuteScript(cx, global, script, &result) != JS_TRUE) { fprintf(stderr, "Failed to execute script.\n"); return 1; } // Warning message if we don't remove it. JS_RemoveValueRoot(cx, &sroot); // Give the GC a chance to run. JS_MaybeGC(cx); } JS_LeaveCrossCompartmentCall(call); FINISH_REQUEST(cx); JS_DestroyContext(cx); JS_DestroyRuntime(rt); JS_ShutDown(); return 0; } apache-couchdb-1.5.0/src/couchdb/priv/couch_js/help.h0000644000175000001440000000552212230722213017332 00000000000000// 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. #ifndef COUCHJS_HELP_H #define COUCHJS_HELP_H #include "config.h" static const char VERSION_TEMPLATE[] = "%s - %s\n" "\n" "Licensed under the Apache License, Version 2.0 (the \"License\"); you may " "not use\n" "this file except in compliance with the License. You may obtain a copy of" "the\n" "License at\n" "\n" " http://www.apache.org/licenses/LICENSE-2.0\n" "\n" "Unless required by applicable law or agreed to in writing, software " "distributed\n" "under the License is distributed on an \"AS IS\" BASIS, WITHOUT " "WARRANTIES OR\n" "CONDITIONS OF ANY KIND, either express or implied. See the License " "for the\n" "specific language governing permissions and limitations under the " "License.\n"; static const char USAGE_TEMPLATE[] = "Usage: %s [FILE]\n" "\n" "The %s command runs the %s JavaScript interpreter.\n" "\n" "The exit status is 0 for success or 1 for failure.\n" "\n" "Options:\n" "\n" " -h display a short help message and exit\n" " -V display version information and exit\n" " -H enable %s cURL bindings (only avaiable\n" " if package was built with cURL available)\n" " -S SIZE specify that the runtime should allow at\n" " most SIZE bytes of memory to be allocated\n" " -u FILE path to a .uri file containing the address\n" " (or addresses) of one or more servers\n" "\n" "Report bugs at <%s>.\n"; #define BASENAME COUCHJS_NAME #define couch_version(basename) \ fprintf( \ stdout, \ VERSION_TEMPLATE, \ basename, \ PACKAGE_STRING) #define DISPLAY_VERSION couch_version(BASENAME) #define couch_usage(basename) \ fprintf( \ stdout, \ USAGE_TEMPLATE, \ basename, \ basename, \ PACKAGE_NAME, \ basename, \ PACKAGE_BUGREPORT) #define DISPLAY_USAGE couch_usage(BASENAME) #endif // Included help.h apache-couchdb-1.5.0/src/couchdb/priv/couch_js/http.c0000644000175000001440000004100212230722213017345 00000000000000// 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. #include #include #include #include #include #include #include "config.h" #include "utf8.h" #include "util.h" // Soft dependency on cURL bindings because they're // only used when running the JS tests from the // command line which is rare. #ifndef HAVE_CURL void http_check_enabled() { fprintf(stderr, "HTTP API was disabled at compile time.\n"); exit(3); } JSBool http_ctor(JSContext* cx, JSObject* req) { return JS_FALSE; } JSBool http_dtor(JSContext* cx, JSObject* req) { return JS_FALSE; } JSBool http_open(JSContext* cx, JSObject* req, jsval mth, jsval url, jsval snc) { return JS_FALSE; } JSBool http_set_hdr(JSContext* cx, JSObject* req, jsval name, jsval val) { return JS_FALSE; } JSBool http_send(JSContext* cx, JSObject* req, jsval body) { return JS_FALSE; } int http_status(JSContext* cx, JSObject* req, jsval body) { return -1; } JSBool http_uri(JSContext* cx, JSObject* req, couch_args* args, jsval* uri_val) { return JS_FALSE; } #else #include #include void http_check_enabled() { return; } // Map some of the string function names to things which exist on Windows #ifdef XP_WIN #define strcasecmp _strcmpi #define strncasecmp _strnicmp #define snprintf _snprintf #endif typedef struct curl_slist CurlHeaders; typedef struct { int method; char* url; CurlHeaders* req_headers; jsint last_status; } HTTPData; char* METHODS[] = {"GET", "HEAD", "POST", "PUT", "DELETE", "COPY", "OPTIONS", NULL}; #define GET 0 #define HEAD 1 #define POST 2 #define PUT 3 #define DELETE 4 #define COPY 5 #define OPTIONS 6 static JSBool go(JSContext* cx, JSObject* obj, HTTPData* http, char* body, size_t blen); static JSString* str_from_binary(JSContext* cx, char* data, size_t length); JSBool http_ctor(JSContext* cx, JSObject* req) { HTTPData* http = NULL; JSBool ret = JS_FALSE; http = (HTTPData*) malloc(sizeof(HTTPData)); if(!http) { JS_ReportError(cx, "Failed to create CouchHTTP instance."); goto error; } http->method = -1; http->url = NULL; http->req_headers = NULL; http->last_status = -1; if(!JS_SetPrivate(cx, req, http)) { JS_ReportError(cx, "Failed to set private CouchHTTP data."); goto error; } ret = JS_TRUE; goto success; error: if(http) free(http); success: return ret; } void http_dtor(JSContext* cx, JSObject* obj) { HTTPData* http = (HTTPData*) JS_GetPrivate(cx, obj); if(http) { if(http->url) free(http->url); if(http->req_headers) curl_slist_free_all(http->req_headers); free(http); } } JSBool http_open(JSContext* cx, JSObject* req, jsval mth, jsval url, jsval snc) { HTTPData* http = (HTTPData*) JS_GetPrivate(cx, req); char* method = NULL; int methid; JSBool ret = JS_FALSE; if(!http) { JS_ReportError(cx, "Invalid CouchHTTP instance."); goto done; } if(JSVAL_IS_VOID(mth)) { JS_ReportError(cx, "You must specify a method."); goto done; } method = enc_string(cx, mth, NULL); if(!method) { JS_ReportError(cx, "Failed to encode method."); goto done; } for(methid = 0; METHODS[methid] != NULL; methid++) { if(strcasecmp(METHODS[methid], method) == 0) break; } if(methid > OPTIONS) { JS_ReportError(cx, "Invalid method specified."); goto done; } http->method = methid; if(JSVAL_IS_VOID(url)) { JS_ReportError(cx, "You must specify a URL."); goto done; } if(http->url != NULL) { free(http->url); http->url = NULL; } http->url = enc_string(cx, url, NULL); if(http->url == NULL) { JS_ReportError(cx, "Failed to encode URL."); goto done; } if(JSVAL_IS_BOOLEAN(snc) && JSVAL_TO_BOOLEAN(snc)) { JS_ReportError(cx, "Synchronous flag must be false."); goto done; } if(http->req_headers) { curl_slist_free_all(http->req_headers); http->req_headers = NULL; } // Disable Expect: 100-continue http->req_headers = curl_slist_append(http->req_headers, "Expect:"); ret = JS_TRUE; done: if(method) free(method); return ret; } JSBool http_set_hdr(JSContext* cx, JSObject* req, jsval name, jsval val) { HTTPData* http = (HTTPData*) JS_GetPrivate(cx, req); char* keystr = NULL; char* valstr = NULL; char* hdrbuf = NULL; size_t hdrlen = -1; JSBool ret = JS_FALSE; if(!http) { JS_ReportError(cx, "Invalid CouchHTTP instance."); goto done; } if(JSVAL_IS_VOID(name)) { JS_ReportError(cx, "You must speciy a header name."); goto done; } keystr = enc_string(cx, name, NULL); if(!keystr) { JS_ReportError(cx, "Failed to encode header name."); goto done; } if(JSVAL_IS_VOID(val)) { JS_ReportError(cx, "You must specify a header value."); goto done; } valstr = enc_string(cx, val, NULL); if(!valstr) { JS_ReportError(cx, "Failed to encode header value."); goto done; } hdrlen = strlen(keystr) + strlen(valstr) + 3; hdrbuf = (char*) malloc(hdrlen * sizeof(char)); if(!hdrbuf) { JS_ReportError(cx, "Failed to allocate header buffer."); goto done; } snprintf(hdrbuf, hdrlen, "%s: %s", keystr, valstr); http->req_headers = curl_slist_append(http->req_headers, hdrbuf); ret = JS_TRUE; done: if(keystr) free(keystr); if(valstr) free(valstr); if(hdrbuf) free(hdrbuf); return ret; } JSBool http_send(JSContext* cx, JSObject* req, jsval body) { HTTPData* http = (HTTPData*) JS_GetPrivate(cx, req); char* bodystr = NULL; size_t bodylen = 0; JSBool ret = JS_FALSE; if(!http) { JS_ReportError(cx, "Invalid CouchHTTP instance."); goto done; } if(!JSVAL_IS_VOID(body)) { bodystr = enc_string(cx, body, &bodylen); if(!bodystr) { JS_ReportError(cx, "Failed to encode body."); goto done; } } ret = go(cx, req, http, bodystr, bodylen); done: if(bodystr) free(bodystr); return ret; } int http_status(JSContext* cx, JSObject* req) { HTTPData* http = (HTTPData*) JS_GetPrivate(cx, req); if(!http) { JS_ReportError(cx, "Invalid CouchHTTP instance."); return JS_FALSE; } return http->last_status; } JSBool http_uri(JSContext* cx, JSObject* req, couch_args* args, jsval* uri_val) { FILE* uri_fp = NULL; JSString* uri_str; // Default is http://localhost:5984/ when no uri file is specified if (!args->uri_file) { uri_str = JS_InternString(cx, "http://localhost:5984/"); *uri_val = STRING_TO_JSVAL(uri_str); return JS_TRUE; } // Else check to see if the base url is cached in a reserved slot if (JS_GetReservedSlot(cx, req, 0, uri_val) && !JSVAL_IS_VOID(*uri_val)) { return JS_TRUE; } // Read the first line of the couch.uri file. if(!((uri_fp = fopen(args->uri_file, "r")) && (uri_str = couch_readline(cx, uri_fp)))) { JS_ReportError(cx, "Failed to read couch.uri file."); goto error; } fclose(uri_fp); *uri_val = STRING_TO_JSVAL(uri_str); JS_SetReservedSlot(cx, req, 0, *uri_val); return JS_TRUE; error: if(uri_fp) fclose(uri_fp); return JS_FALSE; } // Curl Helpers typedef struct { HTTPData* http; JSContext* cx; JSObject* resp_headers; char* sendbuf; size_t sendlen; size_t sent; int sent_once; char* recvbuf; size_t recvlen; size_t read; } CurlState; /* * I really hate doing this but this doesn't have to be * uber awesome, it just has to work. */ CURL* HTTP_HANDLE = NULL; char ERRBUF[CURL_ERROR_SIZE]; static size_t send_body(void *ptr, size_t size, size_t nmem, void *data); static int seek_body(void *ptr, curl_off_t offset, int origin); static size_t recv_body(void *ptr, size_t size, size_t nmem, void *data); static size_t recv_header(void *ptr, size_t size, size_t nmem, void *data); static JSBool go(JSContext* cx, JSObject* obj, HTTPData* http, char* body, size_t bodylen) { CurlState state; char* referer; JSString* jsbody; JSBool ret = JS_FALSE; jsval tmp; state.cx = cx; state.http = http; state.sendbuf = body; state.sendlen = bodylen; state.sent = 0; state.sent_once = 0; state.recvbuf = NULL; state.recvlen = 0; state.read = 0; if(HTTP_HANDLE == NULL) { HTTP_HANDLE = curl_easy_init(); curl_easy_setopt(HTTP_HANDLE, CURLOPT_READFUNCTION, send_body); curl_easy_setopt(HTTP_HANDLE, CURLOPT_SEEKFUNCTION, (curl_seek_callback) seek_body); curl_easy_setopt(HTTP_HANDLE, CURLOPT_HEADERFUNCTION, recv_header); curl_easy_setopt(HTTP_HANDLE, CURLOPT_WRITEFUNCTION, recv_body); curl_easy_setopt(HTTP_HANDLE, CURLOPT_NOPROGRESS, 1); curl_easy_setopt(HTTP_HANDLE, CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V4); curl_easy_setopt(HTTP_HANDLE, CURLOPT_ERRORBUFFER, ERRBUF); curl_easy_setopt(HTTP_HANDLE, CURLOPT_COOKIEFILE, ""); curl_easy_setopt(HTTP_HANDLE, CURLOPT_USERAGENT, "CouchHTTP Client - Relax"); } if(!HTTP_HANDLE) { JS_ReportError(cx, "Failed to initialize cURL handle."); goto done; } if(!JS_GetReservedSlot(cx, obj, 0, &tmp)) { JS_ReportError(cx, "Failed to readreserved slot."); goto done; } if(!(referer = enc_string(cx, tmp, NULL))) { JS_ReportError(cx, "Failed to encode referer."); goto done; } curl_easy_setopt(HTTP_HANDLE, CURLOPT_REFERER, referer); free(referer); if(http->method < 0 || http->method > OPTIONS) { JS_ReportError(cx, "INTERNAL: Unknown method."); goto done; } curl_easy_setopt(HTTP_HANDLE, CURLOPT_CUSTOMREQUEST, METHODS[http->method]); curl_easy_setopt(HTTP_HANDLE, CURLOPT_NOBODY, 0); curl_easy_setopt(HTTP_HANDLE, CURLOPT_FOLLOWLOCATION, 1); curl_easy_setopt(HTTP_HANDLE, CURLOPT_UPLOAD, 0); if(http->method == HEAD) { curl_easy_setopt(HTTP_HANDLE, CURLOPT_NOBODY, 1); curl_easy_setopt(HTTP_HANDLE, CURLOPT_FOLLOWLOCATION, 0); } else if(http->method == POST || http->method == PUT) { curl_easy_setopt(HTTP_HANDLE, CURLOPT_UPLOAD, 1); curl_easy_setopt(HTTP_HANDLE, CURLOPT_FOLLOWLOCATION, 0); } if(body && bodylen) { curl_easy_setopt(HTTP_HANDLE, CURLOPT_INFILESIZE, bodylen); } else { curl_easy_setopt(HTTP_HANDLE, CURLOPT_INFILESIZE, 0); } // curl_easy_setopt(HTTP_HANDLE, CURLOPT_VERBOSE, 1); curl_easy_setopt(HTTP_HANDLE, CURLOPT_URL, http->url); curl_easy_setopt(HTTP_HANDLE, CURLOPT_HTTPHEADER, http->req_headers); curl_easy_setopt(HTTP_HANDLE, CURLOPT_READDATA, &state); curl_easy_setopt(HTTP_HANDLE, CURLOPT_SEEKDATA, &state); curl_easy_setopt(HTTP_HANDLE, CURLOPT_WRITEHEADER, &state); curl_easy_setopt(HTTP_HANDLE, CURLOPT_WRITEDATA, &state); if(curl_easy_perform(HTTP_HANDLE) != 0) { JS_ReportError(cx, "Failed to execute HTTP request: %s", ERRBUF); goto done; } if(!state.resp_headers) { JS_ReportError(cx, "Failed to recieve HTTP headers."); goto done; } tmp = OBJECT_TO_JSVAL(state.resp_headers); if(!JS_DefineProperty( cx, obj, "_headers", tmp, NULL, NULL, JSPROP_READONLY )) { JS_ReportError(cx, "INTERNAL: Failed to set response headers."); goto done; } if(state.recvbuf) { state.recvbuf[state.read] = '\0'; jsbody = dec_string(cx, state.recvbuf, state.read+1); if(!jsbody) { // If we can't decode the body as UTF-8 we forcefully // convert it to a string by just forcing each byte // to a jschar. jsbody = str_from_binary(cx, state.recvbuf, state.read); if(!jsbody) { if(!JS_IsExceptionPending(cx)) { JS_ReportError(cx, "INTERNAL: Failed to decode body."); } goto done; } } tmp = STRING_TO_JSVAL(jsbody); } else { tmp = JS_GetEmptyStringValue(cx); } if(!JS_DefineProperty( cx, obj, "responseText", tmp, NULL, NULL, JSPROP_READONLY )) { JS_ReportError(cx, "INTERNAL: Failed to set responseText."); goto done; } ret = JS_TRUE; done: if(state.recvbuf) JS_free(cx, state.recvbuf); return ret; } static size_t send_body(void *ptr, size_t size, size_t nmem, void *data) { CurlState* state = (CurlState*) data; size_t length = size * nmem; size_t towrite = state->sendlen - state->sent; // Assume this is cURL trying to resend a request that // failed. if(towrite == 0 && state->sent_once == 0) { state->sent_once = 1; return 0; } else if(towrite == 0) { state->sent = 0; state->sent_once = 0; towrite = state->sendlen; } if(length < towrite) towrite = length; memcpy(ptr, state->sendbuf + state->sent, towrite); state->sent += towrite; return towrite; } static int seek_body(void* ptr, curl_off_t offset, int origin) { CurlState* state = (CurlState*) ptr; if(origin != SEEK_SET) return -1; state->sent = (size_t) offset; return (int) state->sent; } static size_t recv_header(void *ptr, size_t size, size_t nmem, void *data) { CurlState* state = (CurlState*) data; char code[4]; char* header = (char*) ptr; size_t length = size * nmem; JSString* hdr = NULL; jsuint hdrlen; jsval hdrval; if(length > 7 && strncasecmp(header, "HTTP/1.", 7) == 0) { if(length < 12) { return CURLE_WRITE_ERROR; } memcpy(code, header+9, 3*sizeof(char)); code[3] = '\0'; state->http->last_status = atoi(code); state->resp_headers = JS_NewArrayObject(state->cx, 0, NULL); if(!state->resp_headers) { return CURLE_WRITE_ERROR; } return length; } // We get a notice at the \r\n\r\n after headers. if(length <= 2) { return length; } // Append the new header to our array. hdr = dec_string(state->cx, header, length); if(!hdr) { return CURLE_WRITE_ERROR; } if(!JS_GetArrayLength(state->cx, state->resp_headers, &hdrlen)) { return CURLE_WRITE_ERROR; } hdrval = STRING_TO_JSVAL(hdr); if(!JS_SetElement(state->cx, state->resp_headers, hdrlen, &hdrval)) { return CURLE_WRITE_ERROR; } return length; } static size_t recv_body(void *ptr, size_t size, size_t nmem, void *data) { CurlState* state = (CurlState*) data; size_t length = size * nmem; char* tmp = NULL; if(!state->recvbuf) { state->recvlen = 4096; state->read = 0; state->recvbuf = JS_malloc(state->cx, state->recvlen); } if(!state->recvbuf) { return CURLE_WRITE_ERROR; } // +1 so we can add '\0' back up in the go function. while(length+1 > state->recvlen - state->read) state->recvlen *= 2; tmp = JS_realloc(state->cx, state->recvbuf, state->recvlen); if(!tmp) return CURLE_WRITE_ERROR; state->recvbuf = tmp; memcpy(state->recvbuf + state->read, ptr, length); state->read += length; return length; } JSString* str_from_binary(JSContext* cx, char* data, size_t length) { jschar* conv = (jschar*) JS_malloc(cx, length * sizeof(jschar)); JSString* ret = NULL; size_t i; if(!conv) return NULL; for(i = 0; i < length; i++) { conv[i] = (jschar) data[i]; } ret = JS_NewUCString(cx, conv, length); if(!ret) JS_free(cx, conv); return ret; } #endif /* HAVE_CURL */ apache-couchdb-1.5.0/src/couchdb/priv/couch_js/http.h0000644000175000001440000000210212230722213017350 00000000000000// 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. #ifndef COUCH_JS_HTTP_H #define COUCH_JS_HTTP_H #include "util.h" void http_check_enabled(); JSBool http_ctor(JSContext* cx, JSObject* req); void http_dtor(JSContext* cx, JSObject* req); JSBool http_open(JSContext* cx, JSObject* req, jsval mth, jsval url, jsval snc); JSBool http_set_hdr(JSContext* cx, JSObject* req, jsval name, jsval val); JSBool http_send(JSContext* cx, JSObject* req, jsval body); int http_status(JSContext* cx, JSObject* req); JSBool http_uri(JSContext* cx, JSObject *req, couch_args* args, jsval* uri); #endif apache-couchdb-1.5.0/src/couchdb/priv/couch_js/main.c0000644000175000001440000000125512230722213017320 00000000000000// 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. #include "config.h" #if defined(SM185) #include "sm185.c" #elif defined(SM180) #include "sm180.c" #else #include "sm170.c" #endif apache-couchdb-1.5.0/src/couchdb/priv/couch_js/utf8.c0000644000175000001440000001516112230722213017263 00000000000000// 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. #include #include "config.h" static int enc_char(uint8 *utf8Buffer, uint32 ucs4Char) { int utf8Length = 1; if (ucs4Char < 0x80) { *utf8Buffer = (uint8)ucs4Char; } else { int i; uint32 a = ucs4Char >> 11; utf8Length = 2; while(a) { a >>= 5; utf8Length++; } i = utf8Length; while(--i) { utf8Buffer[i] = (uint8)((ucs4Char & 0x3F) | 0x80); ucs4Char >>= 6; } *utf8Buffer = (uint8)(0x100 - (1 << (8-utf8Length)) + ucs4Char); } return utf8Length; } static JSBool enc_charbuf(const jschar* src, size_t srclen, char* dst, size_t* dstlenp) { size_t i; size_t utf8Len; size_t dstlen = *dstlenp; size_t origDstlen = dstlen; jschar c; jschar c2; uint32 v; uint8 utf8buf[6]; if(!dst) { dstlen = origDstlen = (size_t) -1; } while(srclen) { c = *src++; srclen--; if(c <= 0xD7FF || c >= 0xE000) { v = (uint32) c; } else if(c >= 0xD800 && c <= 0xDBFF) { if(srclen < 1) goto buffer_too_small; c2 = *src++; srclen--; if(c2 >= 0xDC00 && c2 <= 0xDFFF) { v = (uint32) (((c - 0xD800) << 10) + (c2 - 0xDC00) + 0x10000); } else { // Invalid second half of surrogate pair v = (uint32) 0xFFFD; } } else { // Invalid first half surrogate pair v = (uint32) 0xFFFD; } if(v < 0x0080) { /* no encoding necessary - performance hack */ if(!dstlen) goto buffer_too_small; if(dst) *dst++ = (char) v; utf8Len = 1; } else { utf8Len = enc_char(utf8buf, v); if(utf8Len > dstlen) goto buffer_too_small; if(dst) { for (i = 0; i < utf8Len; i++) { *dst++ = (char) utf8buf[i]; } } } dstlen -= utf8Len; } *dstlenp = (origDstlen - dstlen); return JS_TRUE; buffer_too_small: *dstlenp = (origDstlen - dstlen); return JS_FALSE; } char* enc_string(JSContext* cx, jsval arg, size_t* buflen) { JSString* str = NULL; const jschar* src = NULL; char* bytes = NULL; size_t srclen = 0; size_t byteslen = 0; str = JS_ValueToString(cx, arg); if(!str) goto error; #ifdef HAVE_JS_GET_STRING_CHARS_AND_LENGTH src = JS_GetStringCharsAndLength(cx, str, &srclen); #else src = JS_GetStringChars(str); srclen = JS_GetStringLength(str); #endif if(!enc_charbuf(src, srclen, NULL, &byteslen)) goto error; bytes = JS_malloc(cx, (byteslen) + 1); bytes[byteslen] = 0; if(!enc_charbuf(src, srclen, bytes, &byteslen)) goto error; if(buflen) *buflen = byteslen; goto success; error: if(bytes != NULL) JS_free(cx, bytes); bytes = NULL; success: return bytes; } static uint32 dec_char(const uint8 *utf8Buffer, int utf8Length) { uint32 ucs4Char; uint32 minucs4Char; /* from Unicode 3.1, non-shortest form is illegal */ static const uint32 minucs4Table[] = { 0x00000080, 0x00000800, 0x0001000, 0x0020000, 0x0400000 }; if (utf8Length == 1) { ucs4Char = *utf8Buffer; } else { ucs4Char = *utf8Buffer++ & ((1<<(7-utf8Length))-1); minucs4Char = minucs4Table[utf8Length-2]; while(--utf8Length) { ucs4Char = ucs4Char<<6 | (*utf8Buffer++ & 0x3F); } if(ucs4Char < minucs4Char || ucs4Char == 0xFFFE || ucs4Char == 0xFFFF) { ucs4Char = 0xFFFD; } } return ucs4Char; } static JSBool dec_charbuf(const char *src, size_t srclen, jschar *dst, size_t *dstlenp) { uint32 v; size_t offset = 0; size_t j; size_t n; size_t dstlen = *dstlenp; size_t origDstlen = dstlen; if(!dst) dstlen = origDstlen = (size_t) -1; while(srclen) { v = (uint8) *src; n = 1; if(v & 0x80) { while(v & (0x80 >> n)) { n++; } if(n > srclen) goto buffer_too_small; if(n == 1 || n > 6) goto bad_character; for(j = 1; j < n; j++) { if((src[j] & 0xC0) != 0x80) goto bad_character; } v = dec_char((const uint8 *) src, n); if(v >= 0x10000) { v -= 0x10000; if(v > 0xFFFFF || dstlen < 2) { *dstlenp = (origDstlen - dstlen); return JS_FALSE; } if(dstlen < 2) goto buffer_too_small; if(dst) { *dst++ = (jschar)((v >> 10) + 0xD800); v = (jschar)((v & 0x3FF) + 0xDC00); } dstlen--; } } if(!dstlen) goto buffer_too_small; if(dst) *dst++ = (jschar) v; dstlen--; offset += n; src += n; srclen -= n; } *dstlenp = (origDstlen - dstlen); return JS_TRUE; bad_character: *dstlenp = (origDstlen - dstlen); return JS_FALSE; buffer_too_small: *dstlenp = (origDstlen - dstlen); return JS_FALSE; } JSString* dec_string(JSContext* cx, const char* bytes, size_t byteslen) { JSString* str = NULL; jschar* chars = NULL; size_t charslen; if(!dec_charbuf(bytes, byteslen, NULL, &charslen)) goto error; chars = JS_malloc(cx, (charslen + 1) * sizeof(jschar)); if(!chars) return NULL; chars[charslen] = 0; if(!dec_charbuf(bytes, byteslen, chars, &charslen)) goto error; str = JS_NewUCString(cx, chars, charslen - 1); if(!str) goto error; goto success; error: if(chars != NULL) JS_free(cx, chars); str = NULL; success: return str; } apache-couchdb-1.5.0/src/couchdb/priv/couch_js/utf8.h0000644000175000001440000000134612230722213017270 00000000000000// 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. #ifndef COUCH_JS_UTF_8_H #define COUCH_JS_UTF_8_H char* enc_string(JSContext* cx, jsval arg, size_t* buflen); JSString* dec_string(JSContext* cx, const char* buf, size_t buflen); #endif apache-couchdb-1.5.0/src/couchdb/priv/couch_js/util.c0000644000175000001440000001635212230722213017355 00000000000000// 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. #include #include #include #include "help.h" #include "util.h" #include "utf8.h" size_t slurp_file(const char* file, char** outbuf_p) { FILE* fp; char fbuf[16384]; char *buf = NULL; char* tmp; size_t nread = 0; size_t buflen = 0; if(strcmp(file, "-") == 0) { fp = stdin; } else { fp = fopen(file, "r"); if(fp == NULL) { fprintf(stderr, "Failed to read file: %s\n", file); exit(3); } } while((nread = fread(fbuf, 1, 16384, fp)) > 0) { if(buf == NULL) { buf = (char*) malloc(nread + 1); if(buf == NULL) { fprintf(stderr, "Out of memory.\n"); exit(3); } memcpy(buf, fbuf, nread); } else { tmp = (char*) malloc(buflen + nread + 1); if(tmp == NULL) { fprintf(stderr, "Out of memory.\n"); exit(3); } memcpy(tmp, buf, buflen); memcpy(tmp+buflen, fbuf, nread); free(buf); buf = tmp; } buflen += nread; buf[buflen] = '\0'; } *outbuf_p = buf; return buflen + 1; } couch_args* couch_parse_args(int argc, const char* argv[]) { couch_args* args; int i = 1; args = (couch_args*) malloc(sizeof(couch_args)); if(args == NULL) return NULL; memset(args, '\0', sizeof(couch_args)); args->stack_size = 64L * 1024L * 1024L; while(i < argc) { if(strcmp("-h", argv[i]) == 0) { DISPLAY_USAGE; exit(0); } else if(strcmp("-V", argv[i]) == 0) { DISPLAY_VERSION; exit(0); } else if(strcmp("-H", argv[i]) == 0) { args->use_http = 1; } else if(strcmp("-S", argv[i]) == 0) { args->stack_size = atoi(argv[++i]); if(args->stack_size <= 0) { fprintf(stderr, "Invalid stack size.\n"); exit(2); } } else if(strcmp("-u", argv[i]) == 0) { args->uri_file = argv[++i]; } else if(strcmp("--", argv[i]) == 0) { i++; break; } else { break; } i++; } if(i >= argc) { DISPLAY_USAGE; exit(3); } args->scripts = argv + i; return args; } int couch_fgets(char* buf, int size, FILE* fp) { int n, i, c; if(size <= 0) return -1; n = size - 1; for(i = 0; i < n && (c = getc(fp)) != EOF; i++) { buf[i] = c; if(c == '\n') { i++; break; } } buf[i] = '\0'; return i; } JSString* couch_readline(JSContext* cx, FILE* fp) { JSString* str; char* bytes = NULL; char* tmp = NULL; size_t used = 0; size_t byteslen = 256; size_t readlen = 0; bytes = JS_malloc(cx, byteslen); if(bytes == NULL) return NULL; while((readlen = couch_fgets(bytes+used, byteslen-used, fp)) > 0) { used += readlen; if(bytes[used-1] == '\n') { bytes[used-1] = '\0'; break; } // Double our buffer and read more. byteslen *= 2; tmp = JS_realloc(cx, bytes, byteslen); if(!tmp) { JS_free(cx, bytes); return NULL; } bytes = tmp; } // Treat empty strings specially if(used == 0) { JS_free(cx, bytes); return JSVAL_TO_STRING(JS_GetEmptyStringValue(cx)); } // Shring the buffer to the actual data size tmp = JS_realloc(cx, bytes, used); if(!tmp) { JS_free(cx, bytes); return NULL; } bytes = tmp; byteslen = used; str = dec_string(cx, bytes, byteslen); JS_free(cx, bytes); return str; } JSString* couch_readfile(JSContext* cx, const char* filename) { JSString *string; size_t byteslen; char *bytes; if((byteslen = slurp_file(filename, &bytes))) { string = dec_string(cx, bytes, byteslen); free(bytes); return string; } return NULL; } void couch_print(JSContext* cx, uintN argc, jsval* argv) { char *bytes = NULL; FILE *stream = stdout; if (argc) { if (argc > 1 && argv[1] == JSVAL_TRUE) { stream = stderr; } bytes = enc_string(cx, argv[0], NULL); if(!bytes) return; fprintf(stream, "%s", bytes); JS_free(cx, bytes); } fputc('\n', stream); fflush(stream); } void couch_error(JSContext* cx, const char* mesg, JSErrorReport* report) { jsval v, replace; char* bytes; JSObject* regexp, *stack; jsval re_args[2]; if(!report || !JSREPORT_IS_WARNING(report->flags)) { fprintf(stderr, "%s\n", mesg); // Print a stack trace, if available. if (JSREPORT_IS_EXCEPTION(report->flags) && JS_GetPendingException(cx, &v)) { // Clear the exception before an JS method calls or the result is // infinite, recursive error report generation. JS_ClearPendingException(cx); // Use JS regexp to indent the stack trace. // If the regexp can't be created, don't JS_ReportError since it is // probably not productive to wind up here again. #ifdef SM185 if(JS_GetProperty(cx, JSVAL_TO_OBJECT(v), "stack", &v) && (regexp = JS_NewRegExpObjectNoStatics( cx, "^(?=.)", 6, JSREG_GLOB | JSREG_MULTILINE))) #else if(JS_GetProperty(cx, JSVAL_TO_OBJECT(v), "stack", &v) && (regexp = JS_NewRegExpObject( cx, "^(?=.)", 6, JSREG_GLOB | JSREG_MULTILINE))) #endif { // Set up the arguments to ``String.replace()`` re_args[0] = OBJECT_TO_JSVAL(regexp); re_args[1] = STRING_TO_JSVAL(JS_InternString(cx, "\t")); // Perform the replacement if(JS_ValueToObject(cx, v, &stack) && JS_GetProperty(cx, stack, "replace", &replace) && JS_CallFunctionValue(cx, stack, replace, 2, re_args, &v)) { // Print the result bytes = enc_string(cx, v, NULL); fprintf(stderr, "Stacktrace:\n%s", bytes); JS_free(cx, bytes); } } } } } JSBool couch_load_funcs(JSContext* cx, JSObject* obj, JSFunctionSpec* funcs) { JSFunctionSpec* f; for(f = funcs; f->name != NULL; f++) { if(!JS_DefineFunction(cx, obj, f->name, f->call, f->nargs, f->flags)) { fprintf(stderr, "Failed to create function: %s\n", f->name); return JS_FALSE; } } return JS_TRUE; } apache-couchdb-1.5.0/src/couchdb/priv/couch_js/util.h0000644000175000001440000000233412230722213017355 00000000000000// 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. #ifndef COUCHJS_UTIL_H #define COUCHJS_UTIL_H #include typedef struct { int use_http; int stack_size; const char** scripts; const char* uri_file; JSString* uri; } couch_args; couch_args* couch_parse_args(int argc, const char* argv[]); int couch_fgets(char* buf, int size, FILE* fp); JSString* couch_readline(JSContext* cx, FILE* fp); JSString* couch_readfile(JSContext* cx, const char* filename); void couch_print(JSContext* cx, uintN argc, jsval* argv); void couch_error(JSContext* cx, const char* mesg, JSErrorReport* report); JSBool couch_load_funcs(JSContext* cx, JSObject* obj, JSFunctionSpec* funcs); #endif // Included util.h apache-couchdb-1.5.0/src/couchdb/couch_server.erl0000644000175000001440000004222412230722213016647 00000000000000% 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. -module(couch_server). -behaviour(gen_server). -export([open/2,create/2,delete/2,get_version/0,get_version/1,get_uuid/0]). -export([all_databases/0, all_databases/2]). -export([init/1, handle_call/3,sup_start_link/0]). -export([handle_cast/2,code_change/3,handle_info/2,terminate/2]). -export([dev_start/0,is_admin/2,has_admins/0,get_stats/0]). -include("couch_db.hrl"). -record(server,{ root_dir = [], dbname_regexp, max_dbs_open=100, dbs_open=0, start_time="" }). dev_start() -> couch:stop(), up_to_date = make:all([load, debug_info]), couch:start(). get_version() -> Apps = application:loaded_applications(), case lists:keysearch(couch, 1, Apps) of {value, {_, _, Vsn}} -> Vsn; false -> "0.0.0" end. get_version(short) -> %% strip git hash from version string [Version|_Rest] = string:tokens(get_version(), "+"), Version. get_uuid() -> case couch_config:get("couchdb", "uuid", nil) of nil -> UUID = couch_uuids:random(), couch_config:set("couchdb", "uuid", ?b2l(UUID)), UUID; UUID -> ?l2b(UUID) end. get_stats() -> {ok, #server{start_time=Time,dbs_open=Open}} = gen_server:call(couch_server, get_server), [{start_time, ?l2b(Time)}, {dbs_open, Open}]. sup_start_link() -> gen_server:start_link({local, couch_server}, couch_server, [], []). open(DbName, Options0) -> Options = maybe_add_sys_db_callbacks(DbName, Options0), case gen_server:call(couch_server, {open, DbName, Options}, infinity) of {ok, Db} -> Ctx = couch_util:get_value(user_ctx, Options, #user_ctx{}), {ok, Db#db{user_ctx=Ctx}}; Error -> Error end. create(DbName, Options0) -> Options = maybe_add_sys_db_callbacks(DbName, Options0), case gen_server:call(couch_server, {create, DbName, Options}, infinity) of {ok, Db} -> Ctx = couch_util:get_value(user_ctx, Options, #user_ctx{}), {ok, Db#db{user_ctx=Ctx}}; Error -> Error end. delete(DbName, Options) -> gen_server:call(couch_server, {delete, DbName, Options}, infinity). maybe_add_sys_db_callbacks(DbName, Options) when is_binary(DbName) -> maybe_add_sys_db_callbacks(?b2l(DbName), Options); maybe_add_sys_db_callbacks(DbName, Options) -> case couch_config:get("replicator", "db", "_replicator") of DbName -> [ {before_doc_update, fun couch_replicator_manager:before_doc_update/2}, {after_doc_read, fun couch_replicator_manager:after_doc_read/2}, sys_db | Options ]; _ -> case couch_config:get("couch_httpd_auth", "authentication_db", "_users") of DbName -> [ {before_doc_update, fun couch_users_db:before_doc_update/2}, {after_doc_read, fun couch_users_db:after_doc_read/2}, sys_db | Options ]; _ -> Options end end. check_dbname(#server{dbname_regexp=RegExp}, DbName) -> case re:run(DbName, RegExp, [{capture, none}]) of nomatch -> case DbName of "_users" -> ok; "_replicator" -> ok; _Else -> {error, illegal_database_name, DbName} end; match -> ok end. is_admin(User, ClearPwd) -> case couch_config:get("admins", User) of "-hashed-" ++ HashedPwdAndSalt -> [HashedPwd, Salt] = string:tokens(HashedPwdAndSalt, ","), couch_util:to_hex(crypto:sha(ClearPwd ++ Salt)) == HashedPwd; _Else -> false end. has_admins() -> couch_config:get("admins") /= []. get_full_filename(Server, DbName) -> filename:join([Server#server.root_dir, "./" ++ DbName ++ ".couch"]). hash_admin_passwords() -> hash_admin_passwords(true). hash_admin_passwords(Persist) -> lists:foreach( fun({User, ClearPassword}) -> HashedPassword = couch_passwords:hash_admin_password(ClearPassword), couch_config:set("admins", User, ?b2l(HashedPassword), Persist) end, couch_passwords:get_unhashed_admins()). init([]) -> % read config and register for configuration changes % just stop if one of the config settings change. couch_server_sup % will restart us and then we will pick up the new settings. RootDir = couch_config:get("couchdb", "database_dir", "."), MaxDbsOpen = list_to_integer( couch_config:get("couchdb", "max_dbs_open")), Self = self(), ok = couch_config:register( fun("couchdb", "database_dir") -> exit(Self, config_change) end), ok = couch_config:register( fun("couchdb", "max_dbs_open", Max) -> gen_server:call(couch_server, {set_max_dbs_open, list_to_integer(Max)}) end), ok = couch_file:init_delete_dir(RootDir), hash_admin_passwords(), ok = couch_config:register( fun("admins", _Key, _Value, Persist) -> % spawn here so couch_config doesn't try to call itself spawn(fun() -> hash_admin_passwords(Persist) end) end, false), {ok, RegExp} = re:compile("^[a-z][a-z0-9\\_\\$()\\+\\-\\/]*$"), ets:new(couch_dbs_by_name, [set, private, named_table]), ets:new(couch_dbs_by_pid, [set, private, named_table]), ets:new(couch_dbs_by_lru, [ordered_set, private, named_table]), ets:new(couch_sys_dbs, [set, private, named_table]), process_flag(trap_exit, true), {ok, #server{root_dir=RootDir, dbname_regexp=RegExp, max_dbs_open=MaxDbsOpen, start_time=couch_util:rfc1123_date()}}. terminate(_Reason, _Srv) -> lists:foreach( fun({_, {_, Pid, _}}) -> couch_util:shutdown_sync(Pid) end, ets:tab2list(couch_dbs_by_name)). all_databases() -> {ok, DbList} = all_databases( fun(DbName, Acc) -> {ok, [DbName | Acc]} end, []), {ok, lists:usort(DbList)}. all_databases(Fun, Acc0) -> {ok, #server{root_dir=Root}} = gen_server:call(couch_server, get_server), NormRoot = couch_util:normpath(Root), FinalAcc = try filelib:fold_files(Root, "^[a-z0-9\\_\\$()\\+\\-]*[\\.]couch$", true, fun(Filename, AccIn) -> NormFilename = couch_util:normpath(Filename), case NormFilename -- NormRoot of [$/ | RelativeFilename] -> ok; RelativeFilename -> ok end, case Fun(?l2b(filename:rootname(RelativeFilename, ".couch")), AccIn) of {ok, NewAcc} -> NewAcc; {stop, NewAcc} -> throw({stop, Fun, NewAcc}) end end, Acc0) catch throw:{stop, Fun, Acc1} -> Acc1 end, {ok, FinalAcc}. maybe_close_lru_db(#server{dbs_open=NumOpen, max_dbs_open=MaxOpen}=Server) when NumOpen < MaxOpen -> {ok, Server}; maybe_close_lru_db(#server{dbs_open=NumOpen}=Server) -> % must free up the lru db. case try_close_lru(now()) of ok -> {ok, Server#server{dbs_open=NumOpen - 1}}; Error -> Error end. try_close_lru(StartTime) -> LruTime = get_lru(), if LruTime > StartTime -> % this means we've looped through all our opened dbs and found them % all in use. {error, all_dbs_active}; true -> [{_, DbName}] = ets:lookup(couch_dbs_by_lru, LruTime), [{_, {opened, MainPid, LruTime}}] = ets:lookup(couch_dbs_by_name, DbName), case couch_db:is_idle(MainPid) of true -> ok = shutdown_idle_db(DbName, MainPid, LruTime); false -> % this still has referrers. Go ahead and give it a current lru time % and try the next one in the table. NewLruTime = now(), true = ets:insert(couch_dbs_by_name, {DbName, {opened, MainPid, NewLruTime}}), true = ets:insert(couch_dbs_by_pid, {MainPid, DbName}), true = ets:delete(couch_dbs_by_lru, LruTime), true = ets:insert(couch_dbs_by_lru, {NewLruTime, DbName}), try_close_lru(StartTime) end end. get_lru() -> get_lru(ets:first(couch_dbs_by_lru)). get_lru(LruTime) -> [{LruTime, DbName}] = ets:lookup(couch_dbs_by_lru, LruTime), case ets:member(couch_sys_dbs, DbName) of false -> LruTime; true -> [{_, {opened, MainPid, _}}] = ets:lookup(couch_dbs_by_name, DbName), case couch_db:is_idle(MainPid) of true -> NextLru = ets:next(couch_dbs_by_lru, LruTime), ok = shutdown_idle_db(DbName, MainPid, LruTime), get_lru(NextLru); false -> get_lru(ets:next(couch_dbs_by_lru, LruTime)) end end. shutdown_idle_db(DbName, MainPid, LruTime) -> couch_util:shutdown_sync(MainPid), true = ets:delete(couch_dbs_by_lru, LruTime), true = ets:delete(couch_dbs_by_name, DbName), true = ets:delete(couch_dbs_by_pid, MainPid), true = ets:delete(couch_sys_dbs, DbName), ok. open_async(Server, From, DbName, Filepath, Options) -> Parent = self(), Opener = spawn_link(fun() -> Res = couch_db:start_link(DbName, Filepath, Options), gen_server:call( Parent, {open_result, DbName, Res, Options}, infinity ), unlink(Parent), case Res of {ok, DbReader} -> unlink(DbReader); _ -> ok end end), true = ets:insert(couch_dbs_by_name, {DbName, {opening, Opener, [From]}}), true = ets:insert(couch_dbs_by_pid, {Opener, DbName}), DbsOpen = case lists:member(sys_db, Options) of true -> true = ets:insert(couch_sys_dbs, {DbName, true}), Server#server.dbs_open; false -> Server#server.dbs_open + 1 end, Server#server{dbs_open = DbsOpen}. handle_call({set_max_dbs_open, Max}, _From, Server) -> {reply, ok, Server#server{max_dbs_open=Max}}; handle_call(get_server, _From, Server) -> {reply, {ok, Server}, Server}; handle_call({open_result, DbName, {ok, OpenedDbPid}, Options}, _From, Server) -> link(OpenedDbPid), [{DbName, {opening,Opener,Froms}}] = ets:lookup(couch_dbs_by_name, DbName), lists:foreach(fun({FromPid,_}=From) -> gen_server:reply(From, catch couch_db:open_ref_counted(OpenedDbPid, FromPid)) end, Froms), LruTime = now(), true = ets:insert(couch_dbs_by_name, {DbName, {opened, OpenedDbPid, LruTime}}), true = ets:delete(couch_dbs_by_pid, Opener), true = ets:insert(couch_dbs_by_pid, {OpenedDbPid, DbName}), true = ets:insert(couch_dbs_by_lru, {LruTime, DbName}), case lists:member(create, Options) of true -> couch_db_update_notifier:notify({created, DbName}); false -> ok end, {reply, ok, Server}; handle_call({open_result, DbName, {error, eexist}, Options}, From, Server) -> handle_call({open_result, DbName, file_exists, Options}, From, Server); handle_call({open_result, DbName, Error, Options}, _From, Server) -> [{DbName, {opening,Opener,Froms}}] = ets:lookup(couch_dbs_by_name, DbName), lists:foreach(fun(From) -> gen_server:reply(From, Error) end, Froms), true = ets:delete(couch_dbs_by_name, DbName), true = ets:delete(couch_dbs_by_pid, Opener), DbsOpen = case lists:member(sys_db, Options) of true -> true = ets:delete(couch_sys_dbs, DbName), Server#server.dbs_open; false -> Server#server.dbs_open - 1 end, {reply, ok, Server#server{dbs_open = DbsOpen}}; handle_call({open, DbName, Options}, {FromPid,_}=From, Server) -> LruTime = now(), case ets:lookup(couch_dbs_by_name, DbName) of [] -> open_db(DbName, Server, Options, From); [{_, {opening, Opener, Froms}}] -> true = ets:insert(couch_dbs_by_name, {DbName, {opening, Opener, [From|Froms]}}), {noreply, Server}; [{_, {opened, MainPid, PrevLruTime}}] -> true = ets:insert(couch_dbs_by_name, {DbName, {opened, MainPid, LruTime}}), true = ets:delete(couch_dbs_by_lru, PrevLruTime), true = ets:insert(couch_dbs_by_lru, {LruTime, DbName}), {reply, couch_db:open_ref_counted(MainPid, FromPid), Server} end; handle_call({create, DbName, Options}, From, Server) -> case ets:lookup(couch_dbs_by_name, DbName) of [] -> open_db(DbName, Server, [create | Options], From); [_AlreadyRunningDb] -> {reply, file_exists, Server} end; handle_call({delete, DbName, _Options}, _From, Server) -> DbNameList = binary_to_list(DbName), case check_dbname(Server, DbNameList) of ok -> FullFilepath = get_full_filename(Server, DbNameList), UpdateState = case ets:lookup(couch_dbs_by_name, DbName) of [] -> false; [{_, {opening, Pid, Froms}}] -> couch_util:shutdown_sync(Pid), true = ets:delete(couch_dbs_by_name, DbName), true = ets:delete(couch_dbs_by_pid, Pid), [gen_server:reply(F, not_found) || F <- Froms], true; [{_, {opened, Pid, LruTime}}] -> couch_util:shutdown_sync(Pid), true = ets:delete(couch_dbs_by_name, DbName), true = ets:delete(couch_dbs_by_pid, Pid), true = ets:delete(couch_dbs_by_lru, LruTime), true end, Server2 = case UpdateState of true -> DbsOpen = case ets:member(couch_sys_dbs, DbName) of true -> true = ets:delete(couch_sys_dbs, DbName), Server#server.dbs_open; false -> Server#server.dbs_open - 1 end, Server#server{dbs_open = DbsOpen}; false -> Server end, %% Delete any leftover .compact files. If we don't do this a subsequent %% request for this DB will try to open the .compact file and use it. couch_file:delete(Server#server.root_dir, FullFilepath ++ ".compact"), case couch_file:delete(Server#server.root_dir, FullFilepath) of ok -> couch_db_update_notifier:notify({deleted, DbName}), {reply, ok, Server2}; {error, enoent} -> {reply, not_found, Server2}; Else -> {reply, Else, Server2} end; Error -> {reply, Error, Server} end. handle_cast(Msg, _Server) -> exit({unknown_cast_message, Msg}). code_change(_OldVsn, State, _Extra) -> {ok, State}. handle_info({'EXIT', _Pid, config_change}, Server) -> {noreply, shutdown, Server}; handle_info({'EXIT', Pid, Reason}, Server) -> Server2 = case ets:lookup(couch_dbs_by_pid, Pid) of [{Pid, DbName}] -> % If the Pid is known, the name should be as well. % If not, that's an error, which is why there is no [] clause. case ets:lookup(couch_dbs_by_name, DbName) of [{_, {opening, Pid, Froms}}] -> Msg = case Reason of snappy_nif_not_loaded -> io_lib:format( "To open the database `~s`, Apache CouchDB " "must be built with Erlang OTP R13B04 or higher.", [DbName] ); true -> io_lib:format("Error opening database ~p: ~p", [DbName, Reason]) end, ?LOG_ERROR(Msg, []), lists:foreach( fun(F) -> gen_server:reply(F, {bad_otp_release, Msg}) end, Froms ); [{_, {opened, Pid, LruTime}}] -> ?LOG_ERROR( "Unexpected exit of database process ~p [~p]: ~p", [Pid, DbName, Reason] ), true = ets:delete(couch_dbs_by_lru, LruTime) end, true = ets:delete(couch_dbs_by_pid, DbName), true = ets:delete(couch_dbs_by_name, DbName), case ets:lookup(couch_sys_dbs, DbName) of [{DbName, _}] -> true = ets:delete(couch_sys_dbs, DbName), Server; [] -> Server#server{dbs_open = Server#server.dbs_open - 1} end end, {noreply, Server2}; handle_info(Error, _Server) -> ?LOG_ERROR("Unexpected message, restarting couch_server: ~p", [Error]), exit(kill). open_db(DbName, Server, Options, From) -> DbNameList = binary_to_list(DbName), case check_dbname(Server, DbNameList) of ok -> Filepath = get_full_filename(Server, DbNameList), case lists:member(sys_db, Options) of true -> {noreply, open_async(Server, From, DbName, Filepath, Options)}; false -> case maybe_close_lru_db(Server) of {ok, Server2} -> {noreply, open_async(Server2, From, DbName, Filepath, Options)}; CloseError -> {reply, CloseError, Server} end end; Error -> {reply, Error, Server} end. apache-couchdb-1.5.0/src/couchdb/couch_js_functions.hrl0000644000175000001440000001326412230722213020052 00000000000000% 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. -define(AUTH_DB_DOC_VALIDATE_FUNCTION, <<" function(newDoc, oldDoc, userCtx, secObj) { if (newDoc._deleted === true) { // allow deletes by admins and matching users // without checking the other fields if ((userCtx.roles.indexOf('_admin') !== -1) || (userCtx.name == oldDoc.name)) { return; } else { throw({forbidden: 'Only admins may delete other user docs.'}); } } if ((oldDoc && oldDoc.type !== 'user') || newDoc.type !== 'user') { throw({forbidden : 'doc.type must be user'}); } // we only allow user docs for now if (!newDoc.name) { throw({forbidden: 'doc.name is required'}); } if (!newDoc.roles) { throw({forbidden: 'doc.roles must exist'}); } if (!isArray(newDoc.roles)) { throw({forbidden: 'doc.roles must be an array'}); } for (var idx = 0; idx < newDoc.roles.length; idx++) { if (typeof newDoc.roles[idx] !== 'string') { throw({forbidden: 'doc.roles can only contain strings'}); } } if (newDoc._id !== ('org.couchdb.user:' + newDoc.name)) { throw({ forbidden: 'Doc ID must be of the form org.couchdb.user:name' }); } if (oldDoc) { // validate all updates if (oldDoc.name !== newDoc.name) { throw({forbidden: 'Usernames can not be changed.'}); } } if (newDoc.password_sha && !newDoc.salt) { throw({ forbidden: 'Users with password_sha must have a salt.' + 'See /_utils/script/couch.js for example code.' }); } var is_server_or_database_admin = function(userCtx, secObj) { // see if the user is a server admin if(userCtx.roles.indexOf('_admin') !== -1) { return true; // a server admin } // see if the user a database admin specified by name if(secObj && secObj.admins && secObj.admins.names) { if(secObj.admins.names.indexOf(userCtx.name) !== -1) { return true; // database admin } } // see if the user a database admin specified by role if(secObj && secObj.admins && secObj.admins.roles) { var db_roles = secObj.admins.roles; for(var idx = 0; idx < userCtx.roles.length; idx++) { var user_role = userCtx.roles[idx]; if(db_roles.indexOf(user_role) !== -1) { return true; // role matches! } } } return false; // default to no admin } if (!is_server_or_database_admin(userCtx, secObj)) { if (oldDoc) { // validate non-admin updates if (userCtx.name !== newDoc.name) { throw({ forbidden: 'You may only update your own user document.' }); } // validate role updates var oldRoles = oldDoc.roles.sort(); var newRoles = newDoc.roles.sort(); if (oldRoles.length !== newRoles.length) { throw({forbidden: 'Only _admin may edit roles'}); } for (var i = 0; i < oldRoles.length; i++) { if (oldRoles[i] !== newRoles[i]) { throw({forbidden: 'Only _admin may edit roles'}); } } } else if (newDoc.roles.length > 0) { throw({forbidden: 'Only _admin may set roles'}); } } // no system roles in users db for (var i = 0; i < newDoc.roles.length; i++) { if (newDoc.roles[i][0] === '_') { throw({ forbidden: 'No system roles (starting with underscore) in users db.' }); } } // no system names as names if (newDoc.name[0] === '_') { throw({forbidden: 'Username may not start with underscore.'}); } var badUserNameChars = [':']; for (var i = 0; i < badUserNameChars.length; i++) { if (newDoc.name.indexOf(badUserNameChars[i]) >= 0) { throw({forbidden: 'Character `' + badUserNameChars[i] + '` is not allowed in usernames.'}); } } } ">>). -define(OAUTH_MAP_FUN, <<" function(doc) { if (doc.type === 'user' && doc.oauth && doc.oauth.consumer_keys) { for (var consumer_key in doc.oauth.consumer_keys) { for (var token in doc.oauth.tokens) { var obj = { 'consumer_secret': doc.oauth.consumer_keys[consumer_key], 'token_secret': doc.oauth.tokens[token], 'username': doc.name }; emit([consumer_key, token], obj); } } } } ">>). apache-couchdb-1.5.0/src/couchdb/couch_external_manager.erl0000644000175000001440000000643612230722213020662 00000000000000% 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. -module(couch_external_manager). -behaviour(gen_server). -export([start_link/0, execute/2, config_change/2]). -export([init/1, terminate/2, code_change/3, handle_call/3, handle_cast/2, handle_info/2]). -include("couch_db.hrl"). start_link() -> gen_server:start_link({local, couch_external_manager}, couch_external_manager, [], []). execute(UrlName, JsonReq) -> Pid = gen_server:call(couch_external_manager, {get, UrlName}), case Pid of {error, Reason} -> Reason; _ -> couch_external_server:execute(Pid, JsonReq) end. config_change("external", UrlName) -> gen_server:call(couch_external_manager, {config, UrlName}). % gen_server API init([]) -> process_flag(trap_exit, true), Handlers = ets:new(couch_external_manager_handlers, [set, private]), couch_config:register(fun ?MODULE:config_change/2), {ok, Handlers}. terminate(_Reason, Handlers) -> ets:foldl(fun({_UrlName, Pid}, nil) -> couch_external_server:stop(Pid), nil end, nil, Handlers), ok. handle_call({get, UrlName}, _From, Handlers) -> case ets:lookup(Handlers, UrlName) of [] -> case couch_config:get("external", UrlName, nil) of nil -> Msg = lists:flatten( io_lib:format("No server configured for ~p.", [UrlName])), {reply, {error, {unknown_external_server, ?l2b(Msg)}}, Handlers}; Command -> {ok, NewPid} = couch_external_server:start_link(UrlName, Command), true = ets:insert(Handlers, {UrlName, NewPid}), {reply, NewPid, Handlers} end; [{UrlName, Pid}] -> {reply, Pid, Handlers} end; handle_call({config, UrlName}, _From, Handlers) -> % A newly added handler and a handler that had it's command % changed are treated exactly the same. % Shutdown the old handler. case ets:lookup(Handlers, UrlName) of [{UrlName, Pid}] -> couch_external_server:stop(Pid); [] -> ok end, % Wait for next request to boot the handler. {reply, ok, Handlers}. handle_cast(_Whatever, State) -> {noreply, State}. handle_info({'EXIT', Pid, normal}, Handlers) -> ?LOG_INFO("EXTERNAL: Server ~p terminated normally", [Pid]), % The process terminated normally without us asking - Remove Pid from the % handlers table so we don't attempt to reuse it ets:match_delete(Handlers, {'_', Pid}), {noreply, Handlers}; handle_info({'EXIT', Pid, Reason}, Handlers) -> ?LOG_INFO("EXTERNAL: Server ~p died. (reason: ~p)", [Pid, Reason]), % Remove Pid from the handlers table so we don't try closing % it a second time in terminate/2. ets:match_delete(Handlers, {'_', Pid}), {stop, normal, Handlers}. code_change(_OldVsn, State, _Extra) -> {ok, State}. apache-couchdb-1.5.0/src/couchdb/couch_httpd_proxy.erl0000644000175000001440000003345512230722213017733 00000000000000% 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. -module(couch_httpd_proxy). -export([handle_proxy_req/2]). -include("couch_db.hrl"). -include("../ibrowse/ibrowse.hrl"). -define(TIMEOUT, infinity). -define(PKT_SIZE, 4096). handle_proxy_req(Req, ProxyDest) -> Method = get_method(Req), Url = get_url(Req, ProxyDest), Version = get_version(Req), Headers = get_headers(Req), Body = get_body(Req), Options = [ {http_vsn, Version}, {headers_as_is, true}, {response_format, binary}, {stream_to, {self(), once}} ], case ibrowse:send_req(Url, Headers, Method, Body, Options, ?TIMEOUT) of {ibrowse_req_id, ReqId} -> stream_response(Req, ProxyDest, ReqId); {error, Reason} -> throw({error, Reason}) end. get_method(#httpd{mochi_req=MochiReq}) -> case MochiReq:get(method) of Method when is_atom(Method) -> list_to_atom(string:to_lower(atom_to_list(Method))); Method when is_list(Method) -> list_to_atom(string:to_lower(Method)); Method when is_binary(Method) -> list_to_atom(string:to_lower(?b2l(Method))) end. get_url(Req, ProxyDest) when is_binary(ProxyDest) -> get_url(Req, ?b2l(ProxyDest)); get_url(#httpd{mochi_req=MochiReq}=Req, ProxyDest) -> BaseUrl = case mochiweb_util:partition(ProxyDest, "/") of {[], "/", _} -> couch_httpd:absolute_uri(Req, ProxyDest); _ -> ProxyDest end, ProxyPrefix = "/" ++ ?b2l(hd(Req#httpd.path_parts)), RequestedPath = MochiReq:get(raw_path), case mochiweb_util:partition(RequestedPath, ProxyPrefix) of {[], ProxyPrefix, []} -> BaseUrl; {[], ProxyPrefix, [$/ | DestPath]} -> remove_trailing_slash(BaseUrl) ++ "/" ++ DestPath; {[], ProxyPrefix, DestPath} -> remove_trailing_slash(BaseUrl) ++ "/" ++ DestPath; _Else -> throw({invalid_url_path, {ProxyPrefix, RequestedPath}}) end. get_version(#httpd{mochi_req=MochiReq}) -> MochiReq:get(version). get_headers(#httpd{mochi_req=MochiReq}) -> to_ibrowse_headers(mochiweb_headers:to_list(MochiReq:get(headers)), []). to_ibrowse_headers([], Acc) -> lists:reverse(Acc); to_ibrowse_headers([{K, V} | Rest], Acc) when is_atom(K) -> to_ibrowse_headers([{atom_to_list(K), V} | Rest], Acc); to_ibrowse_headers([{K, V} | Rest], Acc) when is_list(K) -> case string:to_lower(K) of "content-length" -> to_ibrowse_headers(Rest, [{content_length, V} | Acc]); % This appears to make ibrowse too smart. %"transfer-encoding" -> % to_ibrowse_headers(Rest, [{transfer_encoding, V} | Acc]); _ -> to_ibrowse_headers(Rest, [{K, V} | Acc]) end. get_body(#httpd{method='GET'}) -> fun() -> eof end; get_body(#httpd{method='HEAD'}) -> fun() -> eof end; get_body(#httpd{method='DELETE'}) -> fun() -> eof end; get_body(#httpd{mochi_req=MochiReq}) -> case MochiReq:get(body_length) of undefined -> <<>>; {unknown_transfer_encoding, Unknown} -> exit({unknown_transfer_encoding, Unknown}); chunked -> {fun stream_chunked_body/1, {init, MochiReq, 0}}; 0 -> <<>>; Length when is_integer(Length) andalso Length > 0 -> {fun stream_length_body/1, {init, MochiReq, Length}}; Length -> exit({invalid_body_length, Length}) end. remove_trailing_slash(Url) -> rem_slash(lists:reverse(Url)). rem_slash([]) -> []; rem_slash([$\s | RevUrl]) -> rem_slash(RevUrl); rem_slash([$\t | RevUrl]) -> rem_slash(RevUrl); rem_slash([$\r | RevUrl]) -> rem_slash(RevUrl); rem_slash([$\n | RevUrl]) -> rem_slash(RevUrl); rem_slash([$/ | RevUrl]) -> rem_slash(RevUrl); rem_slash(RevUrl) -> lists:reverse(RevUrl). stream_chunked_body({init, MReq, 0}) -> % First chunk, do expect-continue dance. init_body_stream(MReq), stream_chunked_body({stream, MReq, 0, [], ?PKT_SIZE}); stream_chunked_body({stream, MReq, 0, Buf, BRem}) -> % Finished a chunk, get next length. If next length % is 0, its time to try and read trailers. {CRem, Data} = read_chunk_length(MReq), case CRem of 0 -> BodyData = lists:reverse(Buf, Data), {ok, BodyData, {trailers, MReq, [], ?PKT_SIZE}}; _ -> stream_chunked_body( {stream, MReq, CRem, [Data | Buf], BRem-size(Data)} ) end; stream_chunked_body({stream, MReq, CRem, Buf, BRem}) when BRem =< 0 -> % Time to empty our buffers to the upstream socket. BodyData = lists:reverse(Buf), {ok, BodyData, {stream, MReq, CRem, [], ?PKT_SIZE}}; stream_chunked_body({stream, MReq, CRem, Buf, BRem}) -> % Buffer some more data from the client. Length = lists:min([CRem, BRem]), Socket = MReq:get(socket), NewState = case mochiweb_socket:recv(Socket, Length, ?TIMEOUT) of {ok, Data} when size(Data) == CRem -> case mochiweb_socket:recv(Socket, 2, ?TIMEOUT) of {ok, <<"\r\n">>} -> {stream, MReq, 0, [<<"\r\n">>, Data | Buf], BRem-Length-2}; _ -> exit(normal) end; {ok, Data} -> {stream, MReq, CRem-Length, [Data | Buf], BRem-Length}; _ -> exit(normal) end, stream_chunked_body(NewState); stream_chunked_body({trailers, MReq, Buf, BRem}) when BRem =< 0 -> % Empty our buffers and send data upstream. BodyData = lists:reverse(Buf), {ok, BodyData, {trailers, MReq, [], ?PKT_SIZE}}; stream_chunked_body({trailers, MReq, Buf, BRem}) -> % Read another trailer into the buffer or stop on an % empty line. Socket = MReq:get(socket), mochiweb_socket:setopts(Socket, [{packet, line}]), case mochiweb_socket:recv(Socket, 0, ?TIMEOUT) of {ok, <<"\r\n">>} -> mochiweb_socket:setopts(Socket, [{packet, raw}]), BodyData = lists:reverse(Buf, <<"\r\n">>), {ok, BodyData, eof}; {ok, Footer} -> mochiweb_socket:setopts(Socket, [{packet, raw}]), NewState = {trailers, MReq, [Footer | Buf], BRem-size(Footer)}, stream_chunked_body(NewState); _ -> exit(normal) end; stream_chunked_body(eof) -> % Tell ibrowse we're done sending data. eof. stream_length_body({init, MochiReq, Length}) -> % Do the expect-continue dance init_body_stream(MochiReq), stream_length_body({stream, MochiReq, Length}); stream_length_body({stream, _MochiReq, 0}) -> % Finished streaming. eof; stream_length_body({stream, MochiReq, Length}) -> BufLen = lists:min([Length, ?PKT_SIZE]), case MochiReq:recv(BufLen) of <<>> -> eof; Bin -> {ok, Bin, {stream, MochiReq, Length-BufLen}} end. init_body_stream(MochiReq) -> Expect = case MochiReq:get_header_value("expect") of undefined -> undefined; Value when is_list(Value) -> string:to_lower(Value) end, case Expect of "100-continue" -> MochiReq:start_raw_response({100, gb_trees:empty()}); _Else -> ok end. read_chunk_length(MochiReq) -> Socket = MochiReq:get(socket), mochiweb_socket:setopts(Socket, [{packet, line}]), case mochiweb_socket:recv(Socket, 0, ?TIMEOUT) of {ok, Header} -> mochiweb_socket:setopts(Socket, [{packet, raw}]), Splitter = fun(C) -> C =/= $\r andalso C =/= $\n andalso C =/= $\s end, {Hex, _Rest} = lists:splitwith(Splitter, ?b2l(Header)), {mochihex:to_int(Hex), Header}; _ -> exit(normal) end. stream_response(Req, ProxyDest, ReqId) -> receive {ibrowse_async_headers, ReqId, "100", _} -> % ibrowse doesn't handle 100 Continue responses which % means we have to discard them so the proxy client % doesn't get confused. ibrowse:stream_next(ReqId), stream_response(Req, ProxyDest, ReqId); {ibrowse_async_headers, ReqId, Status, Headers} -> {Source, Dest} = get_urls(Req, ProxyDest), FixedHeaders = fix_headers(Source, Dest, Headers, []), case body_length(FixedHeaders) of chunked -> {ok, Resp} = couch_httpd:start_chunked_response( Req, list_to_integer(Status), FixedHeaders ), ibrowse:stream_next(ReqId), stream_chunked_response(Req, ReqId, Resp), {ok, Resp}; Length when is_integer(Length) -> {ok, Resp} = couch_httpd:start_response_length( Req, list_to_integer(Status), FixedHeaders, Length ), ibrowse:stream_next(ReqId), stream_length_response(Req, ReqId, Resp), {ok, Resp}; _ -> {ok, Resp} = couch_httpd:start_response( Req, list_to_integer(Status), FixedHeaders ), ibrowse:stream_next(ReqId), stream_length_response(Req, ReqId, Resp), % XXX: MochiWeb apparently doesn't look at the % response to see if it must force close the % connection. So we help it out here. erlang:put(mochiweb_request_force_close, true), {ok, Resp} end end. stream_chunked_response(Req, ReqId, Resp) -> receive {ibrowse_async_response, ReqId, {error, Reason}} -> throw({error, Reason}); {ibrowse_async_response, ReqId, Chunk} -> couch_httpd:send_chunk(Resp, Chunk), ibrowse:stream_next(ReqId), stream_chunked_response(Req, ReqId, Resp); {ibrowse_async_response_end, ReqId} -> couch_httpd:last_chunk(Resp) end. stream_length_response(Req, ReqId, Resp) -> receive {ibrowse_async_response, ReqId, {error, Reason}} -> throw({error, Reason}); {ibrowse_async_response, ReqId, Chunk} -> couch_httpd:send(Resp, Chunk), ibrowse:stream_next(ReqId), stream_length_response(Req, ReqId, Resp); {ibrowse_async_response_end, ReqId} -> ok end. get_urls(Req, ProxyDest) -> SourceUrl = couch_httpd:absolute_uri(Req, "/" ++ hd(Req#httpd.path_parts)), Source = parse_url(?b2l(iolist_to_binary(SourceUrl))), case (catch parse_url(ProxyDest)) of Dest when is_record(Dest, url) -> {Source, Dest}; _ -> DestUrl = couch_httpd:absolute_uri(Req, ProxyDest), {Source, parse_url(DestUrl)} end. fix_headers(_, _, [], Acc) -> lists:reverse(Acc); fix_headers(Source, Dest, [{K, V} | Rest], Acc) -> Fixed = case string:to_lower(K) of "location" -> rewrite_location(Source, Dest, V); "content-location" -> rewrite_location(Source, Dest, V); "uri" -> rewrite_location(Source, Dest, V); "destination" -> rewrite_location(Source, Dest, V); "set-cookie" -> rewrite_cookie(Source, Dest, V); _ -> V end, fix_headers(Source, Dest, Rest, [{K, Fixed} | Acc]). rewrite_location(Source, #url{host=Host, port=Port, protocol=Proto}, Url) -> case (catch parse_url(Url)) of #url{host=Host, port=Port, protocol=Proto} = Location -> DestLoc = #url{ protocol=Source#url.protocol, host=Source#url.host, port=Source#url.port, path=join_url_path(Source#url.path, Location#url.path) }, url_to_url(DestLoc); #url{} -> Url; _ -> url_to_url(Source#url{path=join_url_path(Source#url.path, Url)}) end. rewrite_cookie(_Source, _Dest, Cookie) -> Cookie. parse_url(Url) when is_binary(Url) -> ibrowse_lib:parse_url(?b2l(Url)); parse_url(Url) when is_list(Url) -> ibrowse_lib:parse_url(?b2l(iolist_to_binary(Url))). join_url_path(Src, Dst) -> Src2 = case lists:reverse(Src) of "/" ++ RestSrc -> lists:reverse(RestSrc); _ -> Src end, Dst2 = case Dst of "/" ++ RestDst -> RestDst; _ -> Dst end, Src2 ++ "/" ++ Dst2. url_to_url(#url{host=Host, port=Port, path=Path, protocol=Proto} = Url) -> LPort = case {Proto, Port} of {http, 80} -> ""; {https, 443} -> ""; _ -> ":" ++ integer_to_list(Port) end, LPath = case Path of "/" ++ _RestPath -> Path; _ -> "/" ++ Path end, HostPart = case Url#url.host_type of ipv6_address -> "[" ++ Host ++ "]"; _ -> Host end, atom_to_list(Proto) ++ "://" ++ HostPart ++ LPort ++ LPath. body_length(Headers) -> case is_chunked(Headers) of true -> chunked; _ -> content_length(Headers) end. is_chunked([]) -> false; is_chunked([{K, V} | Rest]) -> case string:to_lower(K) of "transfer-encoding" -> string:to_lower(V) == "chunked"; _ -> is_chunked(Rest) end. content_length([]) -> undefined; content_length([{K, V} | Rest]) -> case string:to_lower(K) of "content-length" -> list_to_integer(V); _ -> content_length(Rest) end. apache-couchdb-1.5.0/src/couchdb/couch_stream.erl0000644000175000001440000002302512230722213016632 00000000000000% 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. -module(couch_stream). -behaviour(gen_server). % public API -export([open/1, open/2, close/1]). -export([foldl/4, foldl/5, foldl_decode/6, range_foldl/6]). -export([copy_to_new_stream/3, write/2]). % gen_server callbacks -export([init/1, terminate/2, code_change/3]). -export([handle_cast/2, handle_call/3, handle_info/2]). -include("couch_db.hrl"). -define(DEFAULT_BUFFER_SIZE, 4096). -record(stream, {fd = 0, written_pointers=[], buffer_list = [], buffer_len = 0, max_buffer, written_len = 0, md5, % md5 of the content without any transformation applied (e.g. compression) % needed for the attachment upload integrity check (ticket 558) identity_md5, identity_len = 0, encoding_fun, end_encoding_fun }). %%% Interface functions %%% open(Fd) -> open(Fd, []). open(Fd, Options) -> gen_server:start_link(couch_stream, {Fd, Options}, []). close(Pid) -> gen_server:call(Pid, close, infinity). copy_to_new_stream(Fd, PosList, DestFd) -> {ok, Dest} = open(DestFd), foldl(Fd, PosList, fun(Bin, _) -> ok = write(Dest, Bin) end, ok), close(Dest). foldl(_Fd, [], _Fun, Acc) -> Acc; foldl(Fd, [Pos|Rest], Fun, Acc) -> {ok, Bin} = couch_file:pread_iolist(Fd, Pos), foldl(Fd, Rest, Fun, Fun(Bin, Acc)). foldl(Fd, PosList, <<>>, Fun, Acc) -> foldl(Fd, PosList, Fun, Acc); foldl(Fd, PosList, Md5, Fun, Acc) -> foldl(Fd, PosList, Md5, couch_util:md5_init(), Fun, Acc). foldl_decode(Fd, PosList, Md5, Enc, Fun, Acc) -> {DecDataFun, DecEndFun} = case Enc of gzip -> ungzip_init(); identity -> identity_enc_dec_funs() end, Result = foldl_decode( DecDataFun, Fd, PosList, Md5, couch_util:md5_init(), Fun, Acc ), DecEndFun(), Result. foldl(_Fd, [], Md5, Md5Acc, _Fun, Acc) -> Md5 = couch_util:md5_final(Md5Acc), Acc; foldl(Fd, [{Pos, _Size}], Md5, Md5Acc, Fun, Acc) -> % 0110 UPGRADE CODE foldl(Fd, [Pos], Md5, Md5Acc, Fun, Acc); foldl(Fd, [Pos], Md5, Md5Acc, Fun, Acc) -> {ok, Bin} = couch_file:pread_iolist(Fd, Pos), Md5 = couch_util:md5_final(couch_util:md5_update(Md5Acc, Bin)), Fun(Bin, Acc); foldl(Fd, [{Pos, _Size}|Rest], Md5, Md5Acc, Fun, Acc) -> foldl(Fd, [Pos|Rest], Md5, Md5Acc, Fun, Acc); foldl(Fd, [Pos|Rest], Md5, Md5Acc, Fun, Acc) -> {ok, Bin} = couch_file:pread_iolist(Fd, Pos), foldl(Fd, Rest, Md5, couch_util:md5_update(Md5Acc, Bin), Fun, Fun(Bin, Acc)). range_foldl(Fd, PosList, From, To, Fun, Acc) -> range_foldl(Fd, PosList, From, To, 0, Fun, Acc). range_foldl(_Fd, _PosList, _From, To, Off, _Fun, Acc) when Off >= To -> Acc; range_foldl(Fd, [Pos|Rest], From, To, Off, Fun, Acc) when is_integer(Pos) -> % old-style attachment {ok, Bin} = couch_file:pread_iolist(Fd, Pos), range_foldl(Fd, [{Pos, iolist_size(Bin)}] ++ Rest, From, To, Off, Fun, Acc); range_foldl(Fd, [{_Pos, Size}|Rest], From, To, Off, Fun, Acc) when From > Off + Size -> range_foldl(Fd, Rest, From, To, Off + Size, Fun, Acc); range_foldl(Fd, [{Pos, Size}|Rest], From, To, Off, Fun, Acc) -> {ok, Bin} = couch_file:pread_iolist(Fd, Pos), Bin1 = if From =< Off andalso To >= Off + Size -> Bin; %% the whole block is covered true -> PrefixLen = clip(From - Off, 0, Size), PostfixLen = clip(Off + Size - To, 0, Size), MatchLen = Size - PrefixLen - PostfixLen, <<_Prefix:PrefixLen/binary,Match:MatchLen/binary,_Postfix:PostfixLen/binary>> = iolist_to_binary(Bin), Match end, range_foldl(Fd, Rest, From, To, Off + Size, Fun, Fun(Bin1, Acc)). clip(Value, Lo, Hi) -> if Value < Lo -> Lo; Value > Hi -> Hi; true -> Value end. foldl_decode(_DecFun, _Fd, [], Md5, Md5Acc, _Fun, Acc) -> Md5 = couch_util:md5_final(Md5Acc), Acc; foldl_decode(DecFun, Fd, [{Pos, _Size}], Md5, Md5Acc, Fun, Acc) -> foldl_decode(DecFun, Fd, [Pos], Md5, Md5Acc, Fun, Acc); foldl_decode(DecFun, Fd, [Pos], Md5, Md5Acc, Fun, Acc) -> {ok, EncBin} = couch_file:pread_iolist(Fd, Pos), Md5 = couch_util:md5_final(couch_util:md5_update(Md5Acc, EncBin)), Bin = DecFun(EncBin), Fun(Bin, Acc); foldl_decode(DecFun, Fd, [{Pos, _Size}|Rest], Md5, Md5Acc, Fun, Acc) -> foldl_decode(DecFun, Fd, [Pos|Rest], Md5, Md5Acc, Fun, Acc); foldl_decode(DecFun, Fd, [Pos|Rest], Md5, Md5Acc, Fun, Acc) -> {ok, EncBin} = couch_file:pread_iolist(Fd, Pos), Bin = DecFun(EncBin), Md5Acc2 = couch_util:md5_update(Md5Acc, EncBin), foldl_decode(DecFun, Fd, Rest, Md5, Md5Acc2, Fun, Fun(Bin, Acc)). gzip_init(Options) -> case couch_util:get_value(compression_level, Options, 0) of Lvl when Lvl >= 1 andalso Lvl =< 9 -> Z = zlib:open(), % 15 = ?MAX_WBITS (defined in the zlib module) % the 16 + ?MAX_WBITS formula was obtained by inspecting zlib:gzip/1 ok = zlib:deflateInit(Z, Lvl, deflated, 16 + 15, 8, default), { fun(Data) -> zlib:deflate(Z, Data) end, fun() -> Last = zlib:deflate(Z, [], finish), ok = zlib:deflateEnd(Z), ok = zlib:close(Z), Last end }; _ -> identity_enc_dec_funs() end. ungzip_init() -> Z = zlib:open(), zlib:inflateInit(Z, 16 + 15), { fun(Data) -> zlib:inflate(Z, Data) end, fun() -> ok = zlib:inflateEnd(Z), ok = zlib:close(Z) end }. identity_enc_dec_funs() -> { fun(Data) -> Data end, fun() -> [] end }. write(_Pid, <<>>) -> ok; write(Pid, Bin) -> gen_server:call(Pid, {write, Bin}, infinity). init({Fd, Options}) -> {EncodingFun, EndEncodingFun} = case couch_util:get_value(encoding, Options, identity) of identity -> identity_enc_dec_funs(); gzip -> gzip_init(Options) end, {ok, #stream{ fd=Fd, md5=couch_util:md5_init(), identity_md5=couch_util:md5_init(), encoding_fun=EncodingFun, end_encoding_fun=EndEncodingFun, max_buffer=couch_util:get_value( buffer_size, Options, ?DEFAULT_BUFFER_SIZE) } }. terminate(_Reason, _Stream) -> ok. handle_call({write, Bin}, _From, Stream) -> BinSize = iolist_size(Bin), #stream{ fd = Fd, written_len = WrittenLen, written_pointers = Written, buffer_len = BufferLen, buffer_list = Buffer, max_buffer = Max, md5 = Md5, identity_md5 = IdenMd5, identity_len = IdenLen, encoding_fun = EncodingFun} = Stream, if BinSize + BufferLen > Max -> WriteBin = lists:reverse(Buffer, [Bin]), IdenMd5_2 = couch_util:md5_update(IdenMd5, WriteBin), case EncodingFun(WriteBin) of [] -> % case where the encoder did some internal buffering % (zlib does it for example) WrittenLen2 = WrittenLen, Md5_2 = Md5, Written2 = Written; WriteBin2 -> {ok, Pos, _} = couch_file:append_binary(Fd, WriteBin2), WrittenLen2 = WrittenLen + iolist_size(WriteBin2), Md5_2 = couch_util:md5_update(Md5, WriteBin2), Written2 = [{Pos, iolist_size(WriteBin2)}|Written] end, {reply, ok, Stream#stream{ written_len=WrittenLen2, written_pointers=Written2, buffer_list=[], buffer_len=0, md5=Md5_2, identity_md5=IdenMd5_2, identity_len=IdenLen + BinSize}}; true -> {reply, ok, Stream#stream{ buffer_list=[Bin|Buffer], buffer_len=BufferLen + BinSize, identity_len=IdenLen + BinSize}} end; handle_call(close, _From, Stream) -> #stream{ fd = Fd, written_len = WrittenLen, written_pointers = Written, buffer_list = Buffer, md5 = Md5, identity_md5 = IdenMd5, identity_len = IdenLen, encoding_fun = EncodingFun, end_encoding_fun = EndEncodingFun} = Stream, WriteBin = lists:reverse(Buffer), IdenMd5Final = couch_util:md5_final(couch_util:md5_update(IdenMd5, WriteBin)), WriteBin2 = EncodingFun(WriteBin) ++ EndEncodingFun(), Md5Final = couch_util:md5_final(couch_util:md5_update(Md5, WriteBin2)), Result = case WriteBin2 of [] -> {lists:reverse(Written), WrittenLen, IdenLen, Md5Final, IdenMd5Final}; _ -> {ok, Pos, _} = couch_file:append_binary(Fd, WriteBin2), StreamInfo = lists:reverse(Written, [{Pos, iolist_size(WriteBin2)}]), StreamLen = WrittenLen + iolist_size(WriteBin2), {StreamInfo, StreamLen, IdenLen, Md5Final, IdenMd5Final} end, {stop, normal, Result, Stream}. handle_cast(_Msg, State) -> {noreply,State}. code_change(_OldVsn, State, _Extra) -> {ok, State}. handle_info(_Info, State) -> {noreply, State}. apache-couchdb-1.5.0/src/couchdb/couch_native_process.erl0000644000175000001440000003201612230722213020363 00000000000000% 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. % % This file drew much inspiration from erlview, which was written by and % copyright Michael McDaniel [http://autosys.us], and is also under APL 2.0 % % % This module provides the smallest possible native view-server. % With this module in-place, you can add the following to your couch INI files: % [native_query_servers] % erlang={couch_native_process, start_link, []} % % Which will then allow following example map function to be used: % % fun({Doc}) -> % % Below, we emit a single record - the _id as key, null as value % DocId = couch_util:get_value(<<"_id">>, Doc, null), % Emit(DocId, null) % end. % % which should be roughly the same as the javascript: % emit(doc._id, null); % % This module exposes enough functions such that a native erlang server can % act as a fully-fleged view server, but no 'helper' functions specifically % for simplifying your erlang view code. It is expected other third-party % extensions will evolve which offer useful layers on top of this view server % to help simplify your view code. -module(couch_native_process). -behaviour(gen_server). -export([start_link/0,init/1,terminate/2,handle_call/3,handle_cast/2,code_change/3, handle_info/2]). -export([set_timeout/2, prompt/2]). -define(STATE, native_proc_state). -record(evstate, {ddocs, funs=[], query_config=[], list_pid=nil, timeout=5000}). -include("couch_db.hrl"). start_link() -> gen_server:start_link(?MODULE, [], []). % this is a bit messy, see also couch_query_servers handle_info % stop(_Pid) -> % ok. set_timeout(Pid, TimeOut) -> gen_server:call(Pid, {set_timeout, TimeOut}). prompt(Pid, Data) when is_list(Data) -> gen_server:call(Pid, {prompt, Data}). % gen_server callbacks init([]) -> {ok, #evstate{ddocs=dict:new()}}. handle_call({set_timeout, TimeOut}, _From, State) -> {reply, ok, State#evstate{timeout=TimeOut}}; handle_call({prompt, Data}, _From, State) -> ?LOG_DEBUG("Prompt native qs: ~s",[?JSON_ENCODE(Data)]), {NewState, Resp} = try run(State, to_binary(Data)) of {S, R} -> {S, R} catch throw:{error, Why} -> {State, [<<"error">>, Why, Why]} end, case Resp of {error, Reason} -> Msg = io_lib:format("couch native server error: ~p", [Reason]), {reply, [<<"error">>, <<"native_query_server">>, list_to_binary(Msg)], NewState}; [<<"error">> | Rest] -> % Msg = io_lib:format("couch native server error: ~p", [Rest]), % TODO: markh? (jan) {reply, [<<"error">> | Rest], NewState}; [<<"fatal">> | Rest] -> % Msg = io_lib:format("couch native server error: ~p", [Rest]), % TODO: markh? (jan) {stop, fatal, [<<"error">> | Rest], NewState}; Resp -> {reply, Resp, NewState} end. handle_cast(foo, State) -> {noreply, State}. handle_info({'EXIT',_,normal}, State) -> {noreply, State}; handle_info({'EXIT',_,Reason}, State) -> {stop, Reason, State}. terminate(_Reason, _State) -> ok. code_change(_OldVersion, State, _Extra) -> {ok, State}. run(#evstate{list_pid=Pid}=State, [<<"list_row">>, Row]) when is_pid(Pid) -> Pid ! {self(), list_row, Row}, receive {Pid, chunks, Data} -> {State, [<<"chunks">>, Data]}; {Pid, list_end, Data} -> receive {'EXIT', Pid, normal} -> ok after State#evstate.timeout -> throw({timeout, list_cleanup}) end, process_flag(trap_exit, erlang:get(do_trap)), {State#evstate{list_pid=nil}, [<<"end">>, Data]} after State#evstate.timeout -> throw({timeout, list_row}) end; run(#evstate{list_pid=Pid}=State, [<<"list_end">>]) when is_pid(Pid) -> Pid ! {self(), list_end}, Resp = receive {Pid, list_end, Data} -> receive {'EXIT', Pid, normal} -> ok after State#evstate.timeout -> throw({timeout, list_cleanup}) end, [<<"end">>, Data] after State#evstate.timeout -> throw({timeout, list_end}) end, process_flag(trap_exit, erlang:get(do_trap)), {State#evstate{list_pid=nil}, Resp}; run(#evstate{list_pid=Pid}=State, _Command) when is_pid(Pid) -> {State, [<<"error">>, list_error, list_error]}; run(#evstate{ddocs=DDocs}, [<<"reset">>]) -> {#evstate{ddocs=DDocs}, true}; run(#evstate{ddocs=DDocs}, [<<"reset">>, QueryConfig]) -> {#evstate{ddocs=DDocs, query_config=QueryConfig}, true}; run(#evstate{funs=Funs}=State, [<<"add_fun">> , BinFunc]) -> FunInfo = makefun(State, BinFunc), {State#evstate{funs=Funs ++ [FunInfo]}, true}; run(State, [<<"map_doc">> , Doc]) -> Resp = lists:map(fun({Sig, Fun}) -> erlang:put(Sig, []), Fun(Doc), lists:reverse(erlang:get(Sig)) end, State#evstate.funs), {State, Resp}; run(State, [<<"reduce">>, Funs, KVs]) -> {Keys, Vals} = lists:foldl(fun([K, V], {KAcc, VAcc}) -> {[K | KAcc], [V | VAcc]} end, {[], []}, KVs), Keys2 = lists:reverse(Keys), Vals2 = lists:reverse(Vals), {State, catch reduce(State, Funs, Keys2, Vals2, false)}; run(State, [<<"rereduce">>, Funs, Vals]) -> {State, catch reduce(State, Funs, null, Vals, true)}; run(#evstate{ddocs=DDocs}=State, [<<"ddoc">>, <<"new">>, DDocId, DDoc]) -> DDocs2 = store_ddoc(DDocs, DDocId, DDoc), {State#evstate{ddocs=DDocs2}, true}; run(#evstate{ddocs=DDocs}=State, [<<"ddoc">>, DDocId | Rest]) -> DDoc = load_ddoc(DDocs, DDocId), ddoc(State, DDoc, Rest); run(_, Unknown) -> ?LOG_ERROR("Native Process: Unknown command: ~p~n", [Unknown]), throw({error, unknown_command}). ddoc(State, {DDoc}, [FunPath, Args]) -> % load fun from the FunPath BFun = lists:foldl(fun (Key, {Props}) when is_list(Props) -> couch_util:get_value(Key, Props, nil); (_Key, Fun) when is_binary(Fun) -> Fun; (_Key, nil) -> throw({error, not_found}); (_Key, _Fun) -> throw({error, malformed_ddoc}) end, {DDoc}, FunPath), ddoc(State, makefun(State, BFun, {DDoc}), FunPath, Args). ddoc(State, {_, Fun}, [<<"validate_doc_update">>], Args) -> {State, (catch apply(Fun, Args))}; ddoc(State, {_, Fun}, [<<"filters">>|_], [Docs, Req]) -> FilterFunWrapper = fun(Doc) -> case catch Fun(Doc, Req) of true -> true; false -> false; {'EXIT', Error} -> ?LOG_ERROR("~p", [Error]) end end, Resp = lists:map(FilterFunWrapper, Docs), {State, [true, Resp]}; ddoc(State, {_, Fun}, [<<"shows">>|_], Args) -> Resp = case (catch apply(Fun, Args)) of FunResp when is_list(FunResp) -> FunResp; {FunResp} -> [<<"resp">>, {FunResp}]; FunResp -> FunResp end, {State, Resp}; ddoc(State, {_, Fun}, [<<"updates">>|_], Args) -> Resp = case (catch apply(Fun, Args)) of [JsonDoc, JsonResp] -> [<<"up">>, JsonDoc, JsonResp] end, {State, Resp}; ddoc(State, {Sig, Fun}, [<<"lists">>|_], Args) -> Self = self(), SpawnFun = fun() -> LastChunk = (catch apply(Fun, Args)), case start_list_resp(Self, Sig) of started -> receive {Self, list_row, _Row} -> ignore; {Self, list_end} -> ignore after State#evstate.timeout -> throw({timeout, list_cleanup_pid}) end; _ -> ok end, LastChunks = case erlang:get(Sig) of undefined -> [LastChunk]; OtherChunks -> [LastChunk | OtherChunks] end, Self ! {self(), list_end, lists:reverse(LastChunks)} end, erlang:put(do_trap, process_flag(trap_exit, true)), Pid = spawn_link(SpawnFun), Resp = receive {Pid, start, Chunks, JsonResp} -> [<<"start">>, Chunks, JsonResp] after State#evstate.timeout -> throw({timeout, list_start}) end, {State#evstate{list_pid=Pid}, Resp}. store_ddoc(DDocs, DDocId, DDoc) -> dict:store(DDocId, DDoc, DDocs). load_ddoc(DDocs, DDocId) -> try dict:fetch(DDocId, DDocs) of {DDoc} -> {DDoc} catch _:_Else -> throw({error, ?l2b(io_lib:format("Native Query Server missing DDoc with Id: ~s",[DDocId]))}) end. bindings(State, Sig) -> bindings(State, Sig, nil). bindings(State, Sig, DDoc) -> Self = self(), Log = fun(Msg) -> ?LOG_INFO(Msg, []) end, Emit = fun(Id, Value) -> Curr = erlang:get(Sig), erlang:put(Sig, [[Id, Value] | Curr]) end, Start = fun(Headers) -> erlang:put(list_headers, Headers) end, Send = fun(Chunk) -> Curr = case erlang:get(Sig) of undefined -> []; Else -> Else end, erlang:put(Sig, [Chunk | Curr]) end, GetRow = fun() -> case start_list_resp(Self, Sig) of started -> ok; _ -> Chunks = case erlang:get(Sig) of undefined -> []; CurrChunks -> CurrChunks end, Self ! {self(), chunks, lists:reverse(Chunks)} end, erlang:put(Sig, []), receive {Self, list_row, Row} -> Row; {Self, list_end} -> nil after State#evstate.timeout -> throw({timeout, list_pid_getrow}) end end, FoldRows = fun(Fun, Acc) -> foldrows(GetRow, Fun, Acc) end, Bindings = [ {'Log', Log}, {'Emit', Emit}, {'Start', Start}, {'Send', Send}, {'GetRow', GetRow}, {'FoldRows', FoldRows} ], case DDoc of {_Props} -> Bindings ++ [{'DDoc', DDoc}]; _Else -> Bindings end. % thanks to erlview, via: % http://erlang.org/pipermail/erlang-questions/2003-November/010544.html makefun(State, Source) -> Sig = couch_util:md5(Source), BindFuns = bindings(State, Sig), {Sig, makefun(State, Source, BindFuns)}. makefun(State, Source, {DDoc}) -> Sig = couch_util:md5(lists:flatten([Source, term_to_binary(DDoc)])), BindFuns = bindings(State, Sig, {DDoc}), {Sig, makefun(State, Source, BindFuns)}; makefun(_State, Source, BindFuns) when is_list(BindFuns) -> FunStr = binary_to_list(Source), {ok, Tokens, _} = erl_scan:string(FunStr), Form = case (catch erl_parse:parse_exprs(Tokens)) of {ok, [ParsedForm]} -> ParsedForm; {error, {LineNum, _Mod, [Mesg, Params]}}=Error -> io:format(standard_error, "Syntax error on line: ~p~n", [LineNum]), io:format(standard_error, "~s~p~n", [Mesg, Params]), throw(Error) end, Bindings = lists:foldl(fun({Name, Fun}, Acc) -> erl_eval:add_binding(Name, Fun, Acc) end, erl_eval:new_bindings(), BindFuns), {value, Fun, _} = erl_eval:expr(Form, Bindings), Fun. reduce(State, BinFuns, Keys, Vals, ReReduce) -> Funs = case is_list(BinFuns) of true -> lists:map(fun(BF) -> makefun(State, BF) end, BinFuns); _ -> [makefun(State, BinFuns)] end, Reds = lists:map(fun({_Sig, Fun}) -> Fun(Keys, Vals, ReReduce) end, Funs), [true, Reds]. foldrows(GetRow, ProcRow, Acc) -> case GetRow() of nil -> {ok, Acc}; Row -> case (catch ProcRow(Row, Acc)) of {ok, Acc2} -> foldrows(GetRow, ProcRow, Acc2); {stop, Acc2} -> {ok, Acc2} end end. start_list_resp(Self, Sig) -> case erlang:get(list_started) of undefined -> Headers = case erlang:get(list_headers) of undefined -> {[{<<"headers">>, {[]}}]}; CurrHdrs -> CurrHdrs end, Chunks = case erlang:get(Sig) of undefined -> []; CurrChunks -> CurrChunks end, Self ! {self(), start, lists:reverse(Chunks), Headers}, erlang:put(list_started, true), erlang:put(Sig, []), started; _ -> ok end. to_binary({Data}) -> Pred = fun({Key, Value}) -> {to_binary(Key), to_binary(Value)} end, {lists:map(Pred, Data)}; to_binary(Data) when is_list(Data) -> [to_binary(D) || D <- Data]; to_binary(null) -> null; to_binary(true) -> true; to_binary(false) -> false; to_binary(Data) when is_atom(Data) -> list_to_binary(atom_to_list(Data)); to_binary(Data) -> Data. apache-couchdb-1.5.0/src/couchdb/couch_httpd_db.erl0000644000175000001440000013363712230722213017142 00000000000000% 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. -module(couch_httpd_db). -include("couch_db.hrl"). -export([handle_request/1, handle_compact_req/2, handle_design_req/2, db_req/2, couch_doc_open/4,handle_changes_req/2, update_doc_result_to_json/1, update_doc_result_to_json/2, handle_design_info_req/3]). -import(couch_httpd, [send_json/2,send_json/3,send_json/4,send_method_not_allowed/2, start_json_response/2,send_chunk/2,last_chunk/1,end_json_response/1, start_chunked_response/3, absolute_uri/2, send/2, start_response_length/4, send_error/4]). -record(doc_query_args, { options = [], rev = nil, open_revs = [], update_type = interactive_edit, atts_since = nil }). % Database request handlers handle_request(#httpd{path_parts=[DbName|RestParts],method=Method, db_url_handlers=DbUrlHandlers}=Req)-> case {Method, RestParts} of {'PUT', []} -> create_db_req(Req, DbName); {'DELETE', []} -> % if we get ?rev=... the user is using a faulty script where the % document id is empty by accident. Let them recover safely. case couch_httpd:qs_value(Req, "rev", false) of false -> delete_db_req(Req, DbName); _Rev -> throw({bad_request, "You tried to DELETE a database with a ?=rev parameter. " ++ "Did you mean to DELETE a document instead?"}) end; {_, []} -> do_db_req(Req, fun db_req/2); {_, [SecondPart|_]} -> Handler = couch_util:dict_find(SecondPart, DbUrlHandlers, fun db_req/2), do_db_req(Req, Handler) end. handle_changes_req(#httpd{method='POST'}=Req, Db) -> couch_httpd:validate_ctype(Req, "application/json"), handle_changes_req1(Req, Db); handle_changes_req(#httpd{method='GET'}=Req, Db) -> handle_changes_req1(Req, Db); handle_changes_req(#httpd{path_parts=[_,<<"_changes">>]}=Req, _Db) -> send_method_not_allowed(Req, "GET,HEAD,POST"). handle_changes_req1(Req, #db{name=DbName}=Db) -> AuthDbName = ?l2b(couch_config:get("couch_httpd_auth", "authentication_db")), case AuthDbName of DbName -> % in the authentication database, _changes is admin-only. ok = couch_db:check_is_admin(Db); _Else -> % on other databases, _changes is free for all. ok end, handle_changes_req2(Req, Db). handle_changes_req2(Req, Db) -> MakeCallback = fun(Resp) -> fun({change, {ChangeProp}=Change, _}, "eventsource") -> Seq = proplists:get_value(<<"seq">>, ChangeProp), send_chunk(Resp, ["data: ", ?JSON_ENCODE(Change), "\n", "id: ", ?JSON_ENCODE(Seq), "\n\n"]); ({change, Change, _}, "continuous") -> send_chunk(Resp, [?JSON_ENCODE(Change) | "\n"]); ({change, Change, Prepend}, _) -> send_chunk(Resp, [Prepend, ?JSON_ENCODE(Change)]); (start, "eventsource") -> ok; (start, "continuous") -> ok; (start, _) -> send_chunk(Resp, "{\"results\":[\n"); ({stop, _EndSeq}, "eventsource") -> end_json_response(Resp); ({stop, EndSeq}, "continuous") -> send_chunk( Resp, [?JSON_ENCODE({[{<<"last_seq">>, EndSeq}]}) | "\n"] ), end_json_response(Resp); ({stop, EndSeq}, _) -> send_chunk( Resp, io_lib:format("\n],\n\"last_seq\":~w}\n", [EndSeq]) ), end_json_response(Resp); (timeout, _) -> send_chunk(Resp, "\n") end end, ChangesArgs = parse_changes_query(Req, Db), ChangesFun = couch_changes:handle_changes(ChangesArgs, Req, Db), WrapperFun = case ChangesArgs#changes_args.feed of "normal" -> {ok, Info} = couch_db:get_db_info(Db), CurrentEtag = couch_httpd:make_etag(Info), fun(FeedChangesFun) -> couch_httpd:etag_respond( Req, CurrentEtag, fun() -> {ok, Resp} = couch_httpd:start_json_response( Req, 200, [{"ETag", CurrentEtag}] ), FeedChangesFun(MakeCallback(Resp)) end ) end; "eventsource" -> Headers = [ {"Content-Type", "text/event-stream"}, {"Cache-Control", "no-cache"} ], {ok, Resp} = couch_httpd:start_chunked_response(Req, 200, Headers), fun(FeedChangesFun) -> FeedChangesFun(MakeCallback(Resp)) end; _ -> % "longpoll" or "continuous" {ok, Resp} = couch_httpd:start_json_response(Req, 200), fun(FeedChangesFun) -> FeedChangesFun(MakeCallback(Resp)) end end, couch_stats_collector:increment( {httpd, clients_requesting_changes} ), try WrapperFun(ChangesFun) after couch_stats_collector:decrement( {httpd, clients_requesting_changes} ) end. handle_compact_req(#httpd{method='POST'}=Req, Db) -> case Req#httpd.path_parts of [_DbName, <<"_compact">>] -> ok = couch_db:check_is_admin(Db), couch_httpd:validate_ctype(Req, "application/json"), {ok, _} = couch_db:start_compact(Db), send_json(Req, 202, {[{ok, true}]}); [_DbName, <<"_compact">>, DesignName | _] -> DesignId = <<"_design/", DesignName/binary>>, DDoc = couch_httpd_db:couch_doc_open( Db, DesignId, nil, [ejson_body] ), couch_mrview_http:handle_compact_req(Req, Db, DDoc) end; handle_compact_req(Req, _Db) -> send_method_not_allowed(Req, "POST"). handle_design_req(#httpd{ path_parts=[_DbName, _Design, DesignName, <<"_",_/binary>> = Action | _Rest], design_url_handlers = DesignUrlHandlers }=Req, Db) -> case couch_db:is_system_db(Db) of true -> case (catch couch_db:check_is_admin(Db)) of ok -> ok; _ -> throw({forbidden, <<"Only admins can access design document", " actions for system databases.">>}) end; false -> ok end, % load ddoc DesignId = <<"_design/", DesignName/binary>>, DDoc = couch_httpd_db:couch_doc_open(Db, DesignId, nil, [ejson_body]), Handler = couch_util:dict_find(Action, DesignUrlHandlers, fun(_, _, _) -> throw({not_found, <<"missing handler: ", Action/binary>>}) end), Handler(Req, Db, DDoc); handle_design_req(Req, Db) -> db_req(Req, Db). handle_design_info_req(#httpd{ method='GET', path_parts=[_DbName, _Design, DesignName, _] }=Req, Db, _DDoc) -> DesignId = <<"_design/", DesignName/binary>>, DDoc = couch_httpd_db:couch_doc_open(Db, DesignId, nil, [ejson_body]), couch_mrview_http:handle_info_req(Req, Db, DDoc). create_db_req(#httpd{user_ctx=UserCtx}=Req, DbName) -> ok = couch_httpd:verify_is_server_admin(Req), case couch_server:create(DbName, [{user_ctx, UserCtx}]) of {ok, Db} -> couch_db:close(Db), DbUrl = absolute_uri(Req, "/" ++ couch_util:url_encode(DbName)), send_json(Req, 201, [{"Location", DbUrl}], {[{ok, true}]}); Error -> throw(Error) end. delete_db_req(#httpd{user_ctx=UserCtx}=Req, DbName) -> ok = couch_httpd:verify_is_server_admin(Req), case couch_server:delete(DbName, [{user_ctx, UserCtx}]) of ok -> send_json(Req, 200, {[{ok, true}]}); Error -> throw(Error) end. do_db_req(#httpd{user_ctx=UserCtx,path_parts=[DbName|_]}=Req, Fun) -> case couch_db:open(DbName, [{user_ctx, UserCtx}]) of {ok, Db} -> try Fun(Req, Db) after catch couch_db:close(Db) end; Error -> throw(Error) end. db_req(#httpd{method='GET',path_parts=[_DbName]}=Req, Db) -> {ok, DbInfo} = couch_db:get_db_info(Db), send_json(Req, {DbInfo}); db_req(#httpd{method='POST',path_parts=[_DbName]}=Req, Db) -> couch_httpd:validate_ctype(Req, "application/json"), Doc = couch_doc:from_json_obj(couch_httpd:json_body(Req)), validate_attachment_names(Doc), Doc2 = case Doc#doc.id of <<"">> -> Doc#doc{id=couch_uuids:new(), revs={0, []}}; _ -> Doc end, DocId = Doc2#doc.id, update_doc(Req, Db, DocId, Doc2); db_req(#httpd{path_parts=[_DbName]}=Req, _Db) -> send_method_not_allowed(Req, "DELETE,GET,HEAD,POST"); db_req(#httpd{method='POST',path_parts=[_,<<"_ensure_full_commit">>]}=Req, Db) -> couch_httpd:validate_ctype(Req, "application/json"), UpdateSeq = couch_db:get_update_seq(Db), CommittedSeq = couch_db:get_committed_update_seq(Db), {ok, StartTime} = case couch_httpd:qs_value(Req, "seq") of undefined -> couch_db:ensure_full_commit(Db); RequiredStr -> RequiredSeq = list_to_integer(RequiredStr), if RequiredSeq > UpdateSeq -> throw({bad_request, "can't do a full commit ahead of current update_seq"}); RequiredSeq > CommittedSeq -> couch_db:ensure_full_commit(Db); true -> {ok, Db#db.instance_start_time} end end, send_json(Req, 201, {[ {ok, true}, {instance_start_time, StartTime} ]}); db_req(#httpd{path_parts=[_,<<"_ensure_full_commit">>]}=Req, _Db) -> send_method_not_allowed(Req, "POST"); db_req(#httpd{method='POST',path_parts=[_,<<"_bulk_docs">>]}=Req, Db) -> couch_stats_collector:increment({httpd, bulk_requests}), couch_httpd:validate_ctype(Req, "application/json"), {JsonProps} = couch_httpd:json_body_obj(Req), case couch_util:get_value(<<"docs">>, JsonProps) of undefined -> send_error(Req, 400, <<"bad_request">>, <<"Missing JSON list of 'docs'">>); DocsArray -> case couch_httpd:header_value(Req, "X-Couch-Full-Commit") of "true" -> Options = [full_commit]; "false" -> Options = [delay_commit]; _ -> Options = [] end, case couch_util:get_value(<<"new_edits">>, JsonProps, true) of true -> Docs = lists:map( fun({ObjProps} = JsonObj) -> Doc = couch_doc:from_json_obj(JsonObj), validate_attachment_names(Doc), Id = case Doc#doc.id of <<>> -> couch_uuids:new(); Id0 -> Id0 end, case couch_util:get_value(<<"_rev">>, ObjProps) of undefined -> Revs = {0, []}; Rev -> {Pos, RevId} = couch_doc:parse_rev(Rev), Revs = {Pos, [RevId]} end, Doc#doc{id=Id,revs=Revs} end, DocsArray), Options2 = case couch_util:get_value(<<"all_or_nothing">>, JsonProps) of true -> [all_or_nothing|Options]; _ -> Options end, case couch_db:update_docs(Db, Docs, Options2) of {ok, Results} -> % output the results DocResults = lists:zipwith(fun update_doc_result_to_json/2, Docs, Results), send_json(Req, 201, DocResults); {aborted, Errors} -> ErrorsJson = lists:map(fun update_doc_result_to_json/1, Errors), send_json(Req, 417, ErrorsJson) end; false -> Docs = lists:map(fun(JsonObj) -> Doc = couch_doc:from_json_obj(JsonObj), validate_attachment_names(Doc), Doc end, DocsArray), {ok, Errors} = couch_db:update_docs(Db, Docs, Options, replicated_changes), ErrorsJson = lists:map(fun update_doc_result_to_json/1, Errors), send_json(Req, 201, ErrorsJson) end end; db_req(#httpd{path_parts=[_,<<"_bulk_docs">>]}=Req, _Db) -> send_method_not_allowed(Req, "POST"); db_req(#httpd{method='POST',path_parts=[_,<<"_purge">>]}=Req, Db) -> couch_httpd:validate_ctype(Req, "application/json"), {IdsRevs} = couch_httpd:json_body_obj(Req), IdsRevs2 = [{Id, couch_doc:parse_revs(Revs)} || {Id, Revs} <- IdsRevs], case couch_db:purge_docs(Db, IdsRevs2) of {ok, PurgeSeq, PurgedIdsRevs} -> PurgedIdsRevs2 = [{Id, couch_doc:revs_to_strs(Revs)} || {Id, Revs} <- PurgedIdsRevs], send_json(Req, 200, {[{<<"purge_seq">>, PurgeSeq}, {<<"purged">>, {PurgedIdsRevs2}}]}); Error -> throw(Error) end; db_req(#httpd{path_parts=[_,<<"_purge">>]}=Req, _Db) -> send_method_not_allowed(Req, "POST"); db_req(#httpd{method='POST',path_parts=[_,<<"_missing_revs">>]}=Req, Db) -> {JsonDocIdRevs} = couch_httpd:json_body_obj(Req), JsonDocIdRevs2 = [{Id, [couch_doc:parse_rev(RevStr) || RevStr <- RevStrs]} || {Id, RevStrs} <- JsonDocIdRevs], {ok, Results} = couch_db:get_missing_revs(Db, JsonDocIdRevs2), Results2 = [{Id, couch_doc:revs_to_strs(Revs)} || {Id, Revs, _} <- Results], send_json(Req, {[ {missing_revs, {Results2}} ]}); db_req(#httpd{path_parts=[_,<<"_missing_revs">>]}=Req, _Db) -> send_method_not_allowed(Req, "POST"); db_req(#httpd{method='POST',path_parts=[_,<<"_revs_diff">>]}=Req, Db) -> {JsonDocIdRevs} = couch_httpd:json_body_obj(Req), JsonDocIdRevs2 = [{Id, couch_doc:parse_revs(RevStrs)} || {Id, RevStrs} <- JsonDocIdRevs], {ok, Results} = couch_db:get_missing_revs(Db, JsonDocIdRevs2), Results2 = lists:map(fun({Id, MissingRevs, PossibleAncestors}) -> {Id, {[{missing, couch_doc:revs_to_strs(MissingRevs)}] ++ if PossibleAncestors == [] -> []; true -> [{possible_ancestors, couch_doc:revs_to_strs(PossibleAncestors)}] end}} end, Results), send_json(Req, {Results2}); db_req(#httpd{path_parts=[_,<<"_revs_diff">>]}=Req, _Db) -> send_method_not_allowed(Req, "POST"); db_req(#httpd{method='PUT',path_parts=[_,<<"_security">>]}=Req, Db) -> SecObj = couch_httpd:json_body(Req), ok = couch_db:set_security(Db, SecObj), send_json(Req, {[{<<"ok">>, true}]}); db_req(#httpd{method='GET',path_parts=[_,<<"_security">>]}=Req, Db) -> send_json(Req, couch_db:get_security(Db)); db_req(#httpd{path_parts=[_,<<"_security">>]}=Req, _Db) -> send_method_not_allowed(Req, "PUT,GET"); db_req(#httpd{method='PUT',path_parts=[_,<<"_revs_limit">>]}=Req, Db) -> Limit = couch_httpd:json_body(Req), case is_integer(Limit) of true -> ok = couch_db:set_revs_limit(Db, Limit), send_json(Req, {[{<<"ok">>, true}]}); false -> throw({bad_request, <<"Rev limit has to be an integer">>}) end; db_req(#httpd{method='GET',path_parts=[_,<<"_revs_limit">>]}=Req, Db) -> send_json(Req, couch_db:get_revs_limit(Db)); db_req(#httpd{path_parts=[_,<<"_revs_limit">>]}=Req, _Db) -> send_method_not_allowed(Req, "PUT,GET"); % Special case to enable using an unencoded slash in the URL of design docs, % as slashes in document IDs must otherwise be URL encoded. db_req(#httpd{method='GET',mochi_req=MochiReq, path_parts=[DbName,<<"_design/",_/binary>>|_]}=Req, _Db) -> PathFront = "/" ++ couch_httpd:quote(binary_to_list(DbName)) ++ "/", [_|PathTail] = re:split(MochiReq:get(raw_path), "_design%2F", [{return, list}]), couch_httpd:send_redirect(Req, PathFront ++ "_design/" ++ mochiweb_util:join(PathTail, "_design%2F")); db_req(#httpd{path_parts=[_DbName,<<"_design">>,Name]}=Req, Db) -> db_doc_req(Req, Db, <<"_design/",Name/binary>>); db_req(#httpd{path_parts=[_DbName,<<"_design">>,Name|FileNameParts]}=Req, Db) -> db_attachment_req(Req, Db, <<"_design/",Name/binary>>, FileNameParts); % Special case to allow for accessing local documents without %2F % encoding the docid. Throws out requests that don't have the second % path part or that specify an attachment name. db_req(#httpd{path_parts=[_DbName, <<"_local">>]}, _Db) -> throw({bad_request, <<"Invalid _local document id.">>}); db_req(#httpd{path_parts=[_DbName, <<"_local/">>]}, _Db) -> throw({bad_request, <<"Invalid _local document id.">>}); db_req(#httpd{path_parts=[_DbName, <<"_local">>, Name]}=Req, Db) -> db_doc_req(Req, Db, <<"_local/", Name/binary>>); db_req(#httpd{path_parts=[_DbName, <<"_local">> | _Rest]}, _Db) -> throw({bad_request, <<"_local documents do not accept attachments.">>}); db_req(#httpd{path_parts=[_, DocId]}=Req, Db) -> db_doc_req(Req, Db, DocId); db_req(#httpd{path_parts=[_, DocId | FileNameParts]}=Req, Db) -> db_attachment_req(Req, Db, DocId, FileNameParts). db_doc_req(#httpd{method='DELETE'}=Req, Db, DocId) -> % check for the existence of the doc to handle the 404 case. couch_doc_open(Db, DocId, nil, []), case couch_httpd:qs_value(Req, "rev") of undefined -> update_doc(Req, Db, DocId, couch_doc_from_req(Req, DocId, {[{<<"_deleted">>,true}]})); Rev -> update_doc(Req, Db, DocId, couch_doc_from_req(Req, DocId, {[{<<"_rev">>, ?l2b(Rev)},{<<"_deleted">>,true}]})) end; db_doc_req(#httpd{method = 'GET', mochi_req = MochiReq} = Req, Db, DocId) -> #doc_query_args{ rev = Rev, open_revs = Revs, options = Options1, atts_since = AttsSince } = parse_doc_query(Req), Options = case AttsSince of nil -> Options1; RevList when is_list(RevList) -> [{atts_since, RevList}, attachments | Options1] end, case Revs of [] -> Doc = couch_doc_open(Db, DocId, Rev, Options), send_doc(Req, Doc, Options); _ -> {ok, Results} = couch_db:open_doc_revs(Db, DocId, Revs, Options), case MochiReq:accepts_content_type("multipart/mixed") of false -> {ok, Resp} = start_json_response(Req, 200), send_chunk(Resp, "["), % We loop through the docs. The first time through the separator % is whitespace, then a comma on subsequent iterations. lists:foldl( fun(Result, AccSeparator) -> case Result of {ok, Doc} -> JsonDoc = couch_doc:to_json_obj(Doc, Options), Json = ?JSON_ENCODE({[{ok, JsonDoc}]}), send_chunk(Resp, AccSeparator ++ Json); {{not_found, missing}, RevId} -> RevStr = couch_doc:rev_to_str(RevId), Json = ?JSON_ENCODE({[{"missing", RevStr}]}), send_chunk(Resp, AccSeparator ++ Json) end, "," % AccSeparator now has a comma end, "", Results), send_chunk(Resp, "]"), end_json_response(Resp); true -> send_docs_multipart(Req, Results, Options) end end; db_doc_req(#httpd{method='POST'}=Req, Db, DocId) -> couch_httpd:validate_referer(Req), couch_doc:validate_docid(DocId), couch_httpd:validate_ctype(Req, "multipart/form-data"), Form = couch_httpd:parse_form(Req), case couch_util:get_value("_doc", Form) of undefined -> Rev = couch_doc:parse_rev(couch_util:get_value("_rev", Form)), {ok, [{ok, Doc}]} = couch_db:open_doc_revs(Db, DocId, [Rev], []); Json -> Doc = couch_doc_from_req(Req, DocId, ?JSON_DECODE(Json)) end, UpdatedAtts = [ #att{name=validate_attachment_name(Name), type=list_to_binary(ContentType), data=Content} || {Name, {ContentType, _}, Content} <- proplists:get_all_values("_attachments", Form) ], #doc{atts=OldAtts} = Doc, OldAtts2 = lists:flatmap( fun(#att{name=OldName}=Att) -> case [1 || A <- UpdatedAtts, A#att.name == OldName] of [] -> [Att]; % the attachment wasn't in the UpdatedAtts, return it _ -> [] % the attachment was in the UpdatedAtts, drop it end end, OldAtts), NewDoc = Doc#doc{ atts = UpdatedAtts ++ OldAtts2 }, update_doc(Req, Db, DocId, NewDoc); db_doc_req(#httpd{method='PUT'}=Req, Db, DocId) -> couch_doc:validate_docid(DocId), case couch_util:to_list(couch_httpd:header_value(Req, "Content-Type")) of ("multipart/related;" ++ _) = ContentType -> {ok, Doc0, WaitFun, Parser} = couch_doc:doc_from_multi_part_stream( ContentType, fun() -> receive_request_data(Req) end), Doc = couch_doc_from_req(Req, DocId, Doc0), try Result = update_doc(Req, Db, DocId, Doc), WaitFun(), Result catch throw:Err -> % Document rejected by a validate_doc_update function. couch_doc:abort_multi_part_stream(Parser), throw(Err) end; _Else -> Body = couch_httpd:json_body(Req), Doc = couch_doc_from_req(Req, DocId, Body), update_doc(Req, Db, DocId, Doc) end; db_doc_req(#httpd{method='COPY'}=Req, Db, SourceDocId) -> SourceRev = case extract_header_rev(Req, couch_httpd:qs_value(Req, "rev")) of missing_rev -> nil; Rev -> Rev end, {TargetDocId, TargetRevs} = parse_copy_destination_header(Req), % open old doc Doc = couch_doc_open(Db, SourceDocId, SourceRev, []), % save new doc update_doc(Req, Db, TargetDocId, Doc#doc{id=TargetDocId, revs=TargetRevs}); db_doc_req(Req, _Db, _DocId) -> send_method_not_allowed(Req, "DELETE,GET,HEAD,POST,PUT,COPY"). send_doc(Req, Doc, Options) -> case Doc#doc.meta of [] -> DiskEtag = couch_httpd:doc_etag(Doc), % output etag only when we have no meta couch_httpd:etag_respond(Req, DiskEtag, fun() -> send_doc_efficiently(Req, Doc, [{"ETag", DiskEtag}], Options) end); _ -> send_doc_efficiently(Req, Doc, [], Options) end. send_doc_efficiently(Req, #doc{atts=[]}=Doc, Headers, Options) -> send_json(Req, 200, Headers, couch_doc:to_json_obj(Doc, Options)); send_doc_efficiently(#httpd{mochi_req = MochiReq} = Req, #doc{atts = Atts} = Doc, Headers, Options) -> case lists:member(attachments, Options) of true -> case MochiReq:accepts_content_type("multipart/related") of false -> send_json(Req, 200, Headers, couch_doc:to_json_obj(Doc, Options)); true -> Boundary = couch_uuids:random(), JsonBytes = ?JSON_ENCODE(couch_doc:to_json_obj(Doc, [attachments, follows, att_encoding_info | Options])), {ContentType, Len} = couch_doc:len_doc_to_multi_part_stream( Boundary,JsonBytes, Atts, true), CType = {"Content-Type", ?b2l(ContentType)}, {ok, Resp} = start_response_length(Req, 200, [CType|Headers], Len), couch_doc:doc_to_multi_part_stream(Boundary,JsonBytes,Atts, fun(Data) -> couch_httpd:send(Resp, Data) end, true) end; false -> send_json(Req, 200, Headers, couch_doc:to_json_obj(Doc, Options)) end. send_docs_multipart(Req, Results, Options1) -> OuterBoundary = couch_uuids:random(), InnerBoundary = couch_uuids:random(), Options = [attachments, follows, att_encoding_info | Options1], CType = {"Content-Type", "multipart/mixed; boundary=\"" ++ ?b2l(OuterBoundary) ++ "\""}, {ok, Resp} = start_chunked_response(Req, 200, [CType]), couch_httpd:send_chunk(Resp, <<"--", OuterBoundary/binary>>), lists:foreach( fun({ok, #doc{atts=Atts}=Doc}) -> JsonBytes = ?JSON_ENCODE(couch_doc:to_json_obj(Doc, Options)), {ContentType, _Len} = couch_doc:len_doc_to_multi_part_stream( InnerBoundary, JsonBytes, Atts, true), couch_httpd:send_chunk(Resp, <<"\r\nContent-Type: ", ContentType/binary, "\r\n\r\n">>), couch_doc:doc_to_multi_part_stream(InnerBoundary, JsonBytes, Atts, fun(Data) -> couch_httpd:send_chunk(Resp, Data) end, true), couch_httpd:send_chunk(Resp, <<"\r\n--", OuterBoundary/binary>>); ({{not_found, missing}, RevId}) -> RevStr = couch_doc:rev_to_str(RevId), Json = ?JSON_ENCODE({[{"missing", RevStr}]}), couch_httpd:send_chunk(Resp, [<<"\r\nContent-Type: application/json; error=\"true\"\r\n\r\n">>, Json, <<"\r\n--", OuterBoundary/binary>>]) end, Results), couch_httpd:send_chunk(Resp, <<"--">>), couch_httpd:last_chunk(Resp). send_ranges_multipart(Req, ContentType, Len, Att, Ranges) -> Boundary = couch_uuids:random(), CType = {"Content-Type", "multipart/byteranges; boundary=\"" ++ ?b2l(Boundary) ++ "\""}, {ok, Resp} = start_chunked_response(Req, 206, [CType]), couch_httpd:send_chunk(Resp, <<"--", Boundary/binary>>), lists:foreach(fun({From, To}) -> ContentRange = ?l2b(make_content_range(From, To, Len)), couch_httpd:send_chunk(Resp, <<"\r\nContent-Type: ", ContentType/binary, "\r\n", "Content-Range: ", ContentRange/binary, "\r\n", "\r\n">>), couch_doc:range_att_foldl(Att, From, To + 1, fun(Seg, _) -> send_chunk(Resp, Seg) end, {ok, Resp}), couch_httpd:send_chunk(Resp, <<"\r\n--", Boundary/binary>>) end, Ranges), couch_httpd:send_chunk(Resp, <<"--">>), couch_httpd:last_chunk(Resp), {ok, Resp}. receive_request_data(Req) -> receive_request_data(Req, couch_httpd:body_length(Req)). receive_request_data(Req, LenLeft) when LenLeft > 0 -> Len = erlang:min(4096, LenLeft), Data = couch_httpd:recv(Req, Len), {Data, fun() -> receive_request_data(Req, LenLeft - iolist_size(Data)) end}; receive_request_data(_Req, _) -> throw(<<"expected more data">>). make_content_range(From, To, Len) -> io_lib:format("bytes ~B-~B/~B", [From, To, Len]). update_doc_result_to_json({{Id, Rev}, Error}) -> {_Code, Err, Msg} = couch_httpd:error_info(Error), {[{id, Id}, {rev, couch_doc:rev_to_str(Rev)}, {error, Err}, {reason, Msg}]}. update_doc_result_to_json(#doc{id=DocId}, Result) -> update_doc_result_to_json(DocId, Result); update_doc_result_to_json(DocId, {ok, NewRev}) -> {[{ok, true}, {id, DocId}, {rev, couch_doc:rev_to_str(NewRev)}]}; update_doc_result_to_json(DocId, Error) -> {_Code, ErrorStr, Reason} = couch_httpd:error_info(Error), {[{id, DocId}, {error, ErrorStr}, {reason, Reason}]}. update_doc(Req, Db, DocId, #doc{deleted=false}=Doc) -> Loc = absolute_uri(Req, "/" ++ ?b2l(Db#db.name) ++ "/" ++ ?b2l(DocId)), update_doc(Req, Db, DocId, Doc, [{"Location", Loc}]); update_doc(Req, Db, DocId, Doc) -> update_doc(Req, Db, DocId, Doc, []). update_doc(Req, Db, DocId, Doc, Headers) -> #doc_query_args{ update_type = UpdateType } = parse_doc_query(Req), update_doc(Req, Db, DocId, Doc, Headers, UpdateType). update_doc(Req, Db, DocId, #doc{deleted=Deleted}=Doc, Headers, UpdateType) -> case couch_httpd:header_value(Req, "X-Couch-Full-Commit") of "true" -> Options = [full_commit]; "false" -> Options = [delay_commit]; _ -> Options = [] end, case couch_httpd:qs_value(Req, "batch") of "ok" -> % async batching spawn(fun() -> case catch(couch_db:update_doc(Db, Doc, Options, UpdateType)) of {ok, _} -> ok; Error -> ?LOG_INFO("Batch doc error (~s): ~p",[DocId, Error]) end end), send_json(Req, 202, Headers, {[ {ok, true}, {id, DocId} ]}); _Normal -> % normal {ok, NewRev} = couch_db:update_doc(Db, Doc, Options, UpdateType), NewRevStr = couch_doc:rev_to_str(NewRev), ResponseHeaders = [{"ETag", <<"\"", NewRevStr/binary, "\"">>}] ++ Headers, send_json(Req, if Deleted orelse Req#httpd.method == 'DELETE' -> 200; true -> 201 end, ResponseHeaders, {[ {ok, true}, {id, DocId}, {rev, NewRevStr}]}) end. couch_doc_from_req(Req, DocId, #doc{revs=Revs}=Doc) -> validate_attachment_names(Doc), Rev = case couch_httpd:qs_value(Req, "rev") of undefined -> undefined; QSRev -> couch_doc:parse_rev(QSRev) end, Revs2 = case Revs of {Start, [RevId|_]} -> if Rev /= undefined andalso Rev /= {Start, RevId} -> throw({bad_request, "Document rev from request body and query " "string have different values"}); true -> case extract_header_rev(Req, {Start, RevId}) of missing_rev -> {0, []}; _ -> Revs end end; _ -> case extract_header_rev(Req, Rev) of missing_rev -> {0, []}; {Pos, RevId2} -> {Pos, [RevId2]} end end, Doc#doc{id=DocId, revs=Revs2}; couch_doc_from_req(Req, DocId, Json) -> couch_doc_from_req(Req, DocId, couch_doc:from_json_obj(Json)). % Useful for debugging % couch_doc_open(Db, DocId) -> % couch_doc_open(Db, DocId, nil, []). couch_doc_open(Db, DocId, Rev, Options) -> case Rev of nil -> % open most recent rev case couch_db:open_doc(Db, DocId, Options) of {ok, Doc} -> Doc; Error -> throw(Error) end; _ -> % open a specific rev (deletions come back as stubs) case couch_db:open_doc_revs(Db, DocId, [Rev], Options) of {ok, [{ok, Doc}]} -> Doc; {ok, [{{not_found, missing}, Rev}]} -> throw(not_found); {ok, [Else]} -> throw(Else) end end. % Attachment request handlers db_attachment_req(#httpd{method='GET',mochi_req=MochiReq}=Req, Db, DocId, FileNameParts) -> FileName = list_to_binary(mochiweb_util:join(lists:map(fun binary_to_list/1, FileNameParts),"/")), #doc_query_args{ rev=Rev, options=Options } = parse_doc_query(Req), #doc{ atts=Atts } = Doc = couch_doc_open(Db, DocId, Rev, Options), case [A || A <- Atts, A#att.name == FileName] of [] -> throw({not_found, "Document is missing attachment"}); [#att{type=Type, encoding=Enc, disk_len=DiskLen, att_len=AttLen}=Att] -> Etag = case Att#att.md5 of <<>> -> couch_httpd:doc_etag(Doc); Md5 -> "\"" ++ ?b2l(base64:encode(Md5)) ++ "\"" end, ReqAcceptsAttEnc = lists:member( atom_to_list(Enc), couch_httpd:accepted_encodings(Req) ), Len = case {Enc, ReqAcceptsAttEnc} of {identity, _} -> % stored and served in identity form DiskLen; {_, false} when DiskLen =/= AttLen -> % Stored encoded, but client doesn't accept the encoding we used, % so we need to decode on the fly. DiskLen is the identity length % of the attachment. DiskLen; {_, true} -> % Stored and served encoded. AttLen is the encoded length. AttLen; _ -> % We received an encoded attachment and stored it as such, so we % don't know the identity length. The client doesn't accept the % encoding, and since we cannot serve a correct Content-Length % header we'll fall back to a chunked response. undefined end, Headers = [ {"ETag", Etag}, {"Cache-Control", "must-revalidate"}, {"Content-Type", binary_to_list(Type)} ] ++ case ReqAcceptsAttEnc of true when Enc =/= identity -> % RFC 2616 says that the 'identify' encoding should not be used in % the Content-Encoding header [{"Content-Encoding", atom_to_list(Enc)}]; _ -> [] end ++ case Enc of identity -> [{"Accept-Ranges", "bytes"}]; _ -> [{"Accept-Ranges", "none"}] end, AttFun = case ReqAcceptsAttEnc of false -> fun couch_doc:att_foldl_decode/3; true -> fun couch_doc:att_foldl/3 end, couch_httpd:etag_respond( Req, Etag, fun() -> case Len of undefined -> {ok, Resp} = start_chunked_response(Req, 200, Headers), AttFun(Att, fun(Seg, _) -> send_chunk(Resp, Seg) end, {ok, Resp}), last_chunk(Resp); _ -> Ranges = parse_ranges(MochiReq:get(range), Len), case {Enc, Ranges} of {identity, [{From, To}]} -> Headers1 = [{"Content-Range", make_content_range(From, To, Len)}] ++ Headers, {ok, Resp} = start_response_length(Req, 206, Headers1, To - From + 1), couch_doc:range_att_foldl(Att, From, To + 1, fun(Seg, _) -> send(Resp, Seg) end, {ok, Resp}); {identity, Ranges} when is_list(Ranges) andalso length(Ranges) < 10 -> send_ranges_multipart(Req, Type, Len, Att, Ranges); _ -> Headers1 = Headers ++ if Enc =:= identity orelse ReqAcceptsAttEnc =:= true -> [{"Content-MD5", base64:encode(Att#att.md5)}]; true -> [] end, {ok, Resp} = start_response_length(Req, 200, Headers1, Len), AttFun(Att, fun(Seg, _) -> send(Resp, Seg) end, {ok, Resp}) end end end ) end; db_attachment_req(#httpd{method=Method,mochi_req=MochiReq}=Req, Db, DocId, FileNameParts) when (Method == 'PUT') or (Method == 'DELETE') -> FileName = validate_attachment_name( mochiweb_util:join( lists:map(fun binary_to_list/1, FileNameParts),"/")), NewAtt = case Method of 'DELETE' -> []; _ -> [#att{ name = FileName, type = case couch_httpd:header_value(Req,"Content-Type") of undefined -> % We could throw an error here or guess by the FileName. % Currently, just giving it a default. <<"application/octet-stream">>; CType -> list_to_binary(CType) end, data = case couch_httpd:body_length(Req) of undefined -> <<"">>; {unknown_transfer_encoding, Unknown} -> exit({unknown_transfer_encoding, Unknown}); chunked -> fun(MaxChunkSize, ChunkFun, InitState) -> couch_httpd:recv_chunked(Req, MaxChunkSize, ChunkFun, InitState) end; 0 -> <<"">>; Length when is_integer(Length) -> Expect = case couch_httpd:header_value(Req, "expect") of undefined -> undefined; Value when is_list(Value) -> string:to_lower(Value) end, case Expect of "100-continue" -> MochiReq:start_raw_response({100, gb_trees:empty()}); _Else -> ok end, fun(Size) -> couch_httpd:recv(Req, Size) end end, att_len = case couch_httpd:header_value(Req,"Content-Length") of undefined -> undefined; Length -> list_to_integer(Length) end, md5 = get_md5_header(Req), encoding = case string:to_lower(string:strip( couch_httpd:header_value(Req,"Content-Encoding","identity") )) of "identity" -> identity; "gzip" -> gzip; _ -> throw({ bad_ctype, "Only gzip and identity content-encodings are supported" }) end }] end, Doc = case extract_header_rev(Req, couch_httpd:qs_value(Req, "rev")) of missing_rev -> % make the new doc couch_doc:validate_docid(DocId), #doc{id=DocId}; Rev -> case couch_db:open_doc_revs(Db, DocId, [Rev], []) of {ok, [{ok, Doc0}]} -> Doc0; {ok, [{{not_found, missing}, Rev}]} -> throw(conflict); {ok, [Error]} -> throw(Error) end end, #doc{atts=Atts} = Doc, DocEdited = Doc#doc{ atts = NewAtt ++ [A || A <- Atts, A#att.name /= FileName] }, Headers = case Method of 'DELETE' -> []; _ -> [{"Location", absolute_uri(Req, "/" ++ ?b2l(Db#db.name) ++ "/" ++ ?b2l(DocId) ++ "/" ++ ?b2l(FileName) )}] end, update_doc(Req, Db, DocId, DocEdited, Headers); db_attachment_req(Req, _Db, _DocId, _FileNameParts) -> send_method_not_allowed(Req, "DELETE,GET,HEAD,PUT"). parse_ranges(undefined, _Len) -> undefined; parse_ranges(fail, _Len) -> undefined; parse_ranges(Ranges, Len) -> parse_ranges(Ranges, Len, []). parse_ranges([], _Len, Acc) -> lists:reverse(Acc); parse_ranges([{0, none}|_], _Len, _Acc) -> undefined; parse_ranges([{From, To}|_], _Len, _Acc) when is_integer(From) andalso is_integer(To) andalso To < From -> throw(requested_range_not_satisfiable); parse_ranges([{From, To}|Rest], Len, Acc) when is_integer(To) andalso To >= Len -> parse_ranges([{From, Len-1}] ++ Rest, Len, Acc); parse_ranges([{none, To}|Rest], Len, Acc) -> parse_ranges([{Len - To, Len - 1}] ++ Rest, Len, Acc); parse_ranges([{From, none}|Rest], Len, Acc) -> parse_ranges([{From, Len - 1}] ++ Rest, Len, Acc); parse_ranges([{From,To}|Rest], Len, Acc) -> parse_ranges(Rest, Len, [{From, To}] ++ Acc). get_md5_header(Req) -> ContentMD5 = couch_httpd:header_value(Req, "Content-MD5"), Length = couch_httpd:body_length(Req), Trailer = couch_httpd:header_value(Req, "Trailer"), case {ContentMD5, Length, Trailer} of _ when is_list(ContentMD5) orelse is_binary(ContentMD5) -> base64:decode(ContentMD5); {_, chunked, undefined} -> <<>>; {_, chunked, _} -> case re:run(Trailer, "\\bContent-MD5\\b", [caseless]) of {match, _} -> md5_in_footer; _ -> <<>> end; _ -> <<>> end. parse_doc_query(Req) -> lists:foldl(fun({Key,Value}, Args) -> case {Key, Value} of {"attachments", "true"} -> Options = [attachments | Args#doc_query_args.options], Args#doc_query_args{options=Options}; {"meta", "true"} -> Options = [revs_info, conflicts, deleted_conflicts | Args#doc_query_args.options], Args#doc_query_args{options=Options}; {"revs", "true"} -> Options = [revs | Args#doc_query_args.options], Args#doc_query_args{options=Options}; {"local_seq", "true"} -> Options = [local_seq | Args#doc_query_args.options], Args#doc_query_args{options=Options}; {"revs_info", "true"} -> Options = [revs_info | Args#doc_query_args.options], Args#doc_query_args{options=Options}; {"conflicts", "true"} -> Options = [conflicts | Args#doc_query_args.options], Args#doc_query_args{options=Options}; {"deleted_conflicts", "true"} -> Options = [deleted_conflicts | Args#doc_query_args.options], Args#doc_query_args{options=Options}; {"rev", Rev} -> Args#doc_query_args{rev=couch_doc:parse_rev(Rev)}; {"open_revs", "all"} -> Args#doc_query_args{open_revs=all}; {"open_revs", RevsJsonStr} -> JsonArray = ?JSON_DECODE(RevsJsonStr), Args#doc_query_args{open_revs=couch_doc:parse_revs(JsonArray)}; {"latest", "true"} -> Options = [latest | Args#doc_query_args.options], Args#doc_query_args{options=Options}; {"atts_since", RevsJsonStr} -> JsonArray = ?JSON_DECODE(RevsJsonStr), Args#doc_query_args{atts_since = couch_doc:parse_revs(JsonArray)}; {"new_edits", "false"} -> Args#doc_query_args{update_type=replicated_changes}; {"new_edits", "true"} -> Args#doc_query_args{update_type=interactive_edit}; {"att_encoding_info", "true"} -> Options = [att_encoding_info | Args#doc_query_args.options], Args#doc_query_args{options=Options}; _Else -> % unknown key value pair, ignore. Args end end, #doc_query_args{}, couch_httpd:qs(Req)). parse_changes_query(Req, Db) -> ChangesArgs = lists:foldl(fun({Key, Value}, Args) -> case {string:to_lower(Key), Value} of {"feed", _} -> Args#changes_args{feed=Value}; {"descending", "true"} -> Args#changes_args{dir=rev}; {"since", "now"} -> UpdateSeq = couch_util:with_db(Db#db.name, fun(WDb) -> couch_db:get_update_seq(WDb) end), Args#changes_args{since=UpdateSeq}; {"since", _} -> Args#changes_args{since=list_to_integer(Value)}; {"last-event-id", _} -> Args#changes_args{since=list_to_integer(Value)}; {"limit", _} -> Args#changes_args{limit=list_to_integer(Value)}; {"style", _} -> Args#changes_args{style=list_to_existing_atom(Value)}; {"heartbeat", "true"} -> Args#changes_args{heartbeat=true}; {"heartbeat", _} -> Args#changes_args{heartbeat=list_to_integer(Value)}; {"timeout", _} -> Args#changes_args{timeout=list_to_integer(Value)}; {"include_docs", "true"} -> Args#changes_args{include_docs=true}; {"conflicts", "true"} -> Args#changes_args{conflicts=true}; {"filter", _} -> Args#changes_args{filter=Value}; _Else -> % unknown key value pair, ignore. Args end end, #changes_args{}, couch_httpd:qs(Req)), %% if it's an EventSource request with a Last-event-ID header %% that should override the `since` query string, since it's %% probably the browser reconnecting. case ChangesArgs#changes_args.feed of "eventsource" -> case couch_httpd:header_value(Req, "last-event-id") of undefined -> ChangesArgs; Value -> ChangesArgs#changes_args{since=list_to_integer(Value)} end; _ -> ChangesArgs end. extract_header_rev(Req, ExplicitRev) when is_binary(ExplicitRev) or is_list(ExplicitRev)-> extract_header_rev(Req, couch_doc:parse_rev(ExplicitRev)); extract_header_rev(Req, ExplicitRev) -> Etag = case couch_httpd:header_value(Req, "If-Match") of undefined -> undefined; Value -> couch_doc:parse_rev(string:strip(Value, both, $")) end, case {ExplicitRev, Etag} of {undefined, undefined} -> missing_rev; {_, undefined} -> ExplicitRev; {undefined, _} -> Etag; _ when ExplicitRev == Etag -> Etag; _ -> throw({bad_request, "Document rev and etag have different values"}) end. parse_copy_destination_header(Req) -> case couch_httpd:header_value(Req, "Destination") of undefined -> throw({bad_request, "Destination header is mandatory for COPY."}); Destination -> case re:run(Destination, "^https?://", [{capture, none}]) of match -> throw({bad_request, "Destination URL must be relative."}); nomatch -> % see if ?rev=revid got appended to the Destination header case re:run(Destination, "\\?", [{capture, none}]) of nomatch -> {list_to_binary(Destination), {0, []}}; match -> [DocId, RevQs] = re:split(Destination, "\\?", [{return, list}]), [_RevQueryKey, Rev] = re:split(RevQs, "=", [{return, list}]), {Pos, RevId} = couch_doc:parse_rev(Rev), {list_to_binary(DocId), {Pos, [RevId]}} end end end. validate_attachment_names(Doc) -> lists:foreach(fun(#att{name=Name}) -> validate_attachment_name(Name) end, Doc#doc.atts). validate_attachment_name(Name) when is_list(Name) -> validate_attachment_name(list_to_binary(Name)); validate_attachment_name(<<"_",_/binary>>) -> throw({bad_request, <<"Attachment name can't start with '_'">>}); validate_attachment_name(Name) -> case couch_util:validate_utf8(Name) of true -> Name; false -> throw({bad_request, <<"Attachment name is not UTF-8 encoded">>}) end. apache-couchdb-1.5.0/src/couchdb/couch_uuids.erl0000644000175000001440000000601512230722213016470 00000000000000% 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. -module(couch_uuids). -include("couch_db.hrl"). -behaviour(gen_server). -export([start/0, stop/0]). -export([new/0, random/0, utc_random/0]). -export([init/1, terminate/2, code_change/3]). -export([handle_call/3, handle_cast/2, handle_info/2]). start() -> gen_server:start_link({local, ?MODULE}, ?MODULE, [], []). stop() -> gen_server:cast(?MODULE, stop). new() -> gen_server:call(?MODULE, create). random() -> list_to_binary(couch_util:to_hex(crypto:rand_bytes(16))). utc_random() -> utc_suffix(couch_util:to_hex(crypto:rand_bytes(9))). utc_suffix(Suffix) -> Now = {_, _, Micro} = now(), Nowish = calendar:now_to_universal_time(Now), Nowsecs = calendar:datetime_to_gregorian_seconds(Nowish), Then = calendar:datetime_to_gregorian_seconds({{1970, 1, 1}, {0, 0, 0}}), Prefix = io_lib:format("~14.16.0b", [(Nowsecs - Then) * 1000000 + Micro]), list_to_binary(Prefix ++ Suffix). init([]) -> ok = couch_config:register( fun("uuids", _) -> gen_server:cast(?MODULE, change) end ), {ok, state()}. terminate(_Reason, _State) -> ok. handle_call(create, _From, random) -> {reply, random(), random}; handle_call(create, _From, utc_random) -> {reply, utc_random(), utc_random}; handle_call(create, _From, {utc_id, UtcIdSuffix}) -> {reply, utc_suffix(UtcIdSuffix), {utc_id, UtcIdSuffix}}; handle_call(create, _From, {sequential, Pref, Seq}) -> Result = ?l2b(Pref ++ io_lib:format("~6.16.0b", [Seq])), case Seq >= 16#fff000 of true -> {reply, Result, {sequential, new_prefix(), inc()}}; _ -> {reply, Result, {sequential, Pref, Seq + inc()}} end. handle_cast(change, _State) -> {noreply, state()}; handle_cast(stop, State) -> {stop, normal, State}; handle_cast(_Msg, State) -> {noreply, State}. handle_info(_Info, State) -> {noreply, State}. code_change(_OldVsn, State, _Extra) -> {ok, State}. new_prefix() -> couch_util:to_hex((crypto:rand_bytes(13))). inc() -> crypto:rand_uniform(1, 16#ffe). state() -> AlgoStr = couch_config:get("uuids", "algorithm", "random"), case couch_util:to_existing_atom(AlgoStr) of random -> random; utc_random -> utc_random; utc_id -> UtcIdSuffix = couch_config:get("uuids", "utc_id_suffix", ""), {utc_id, UtcIdSuffix}; sequential -> {sequential, new_prefix(), inc()}; Unknown -> throw({unknown_uuid_algorithm, Unknown}) end. apache-couchdb-1.5.0/src/couchdb/couch_auth_cache.erl0000644000175000001440000003130612230722213017424 00000000000000% 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. -module(couch_auth_cache). -behaviour(gen_server). % public API -export([get_user_creds/1]). % gen_server API -export([start_link/0, init/1, handle_call/3, handle_info/2, handle_cast/2]). -export([code_change/3, terminate/2]). -include("couch_db.hrl"). -include("couch_js_functions.hrl"). -define(STATE, auth_state_ets). -define(BY_USER, auth_by_user_ets). -define(BY_ATIME, auth_by_atime_ets). -record(state, { max_cache_size = 0, cache_size = 0, db_notifier = nil, db_mon_ref = nil }). -spec get_user_creds(UserName::string() | binary()) -> Credentials::list() | nil. get_user_creds(UserName) when is_list(UserName) -> get_user_creds(?l2b(UserName)); get_user_creds(UserName) -> UserCreds = case couch_config:get("admins", ?b2l(UserName)) of "-hashed-" ++ HashedPwdAndSalt -> % the name is an admin, now check to see if there is a user doc % which has a matching name, salt, and password_sha [HashedPwd, Salt] = string:tokens(HashedPwdAndSalt, ","), case get_from_cache(UserName) of nil -> make_admin_doc(HashedPwd, Salt, []); UserProps when is_list(UserProps) -> make_admin_doc(HashedPwd, Salt, couch_util:get_value(<<"roles">>, UserProps)) end; "-pbkdf2-" ++ HashedPwdSaltAndIterations -> [HashedPwd, Salt, Iterations] = string:tokens(HashedPwdSaltAndIterations, ","), case get_from_cache(UserName) of nil -> make_admin_doc(HashedPwd, Salt, Iterations, []); UserProps when is_list(UserProps) -> make_admin_doc(HashedPwd, Salt, Iterations, couch_util:get_value(<<"roles">>, UserProps)) end; _Else -> get_from_cache(UserName) end, validate_user_creds(UserCreds). make_admin_doc(HashedPwd, Salt, ExtraRoles) -> [{<<"roles">>, [<<"_admin">>|ExtraRoles]}, {<<"salt">>, ?l2b(Salt)}, {<<"password_scheme">>, <<"simple">>}, {<<"password_sha">>, ?l2b(HashedPwd)}]. make_admin_doc(DerivedKey, Salt, Iterations, ExtraRoles) -> [{<<"roles">>, [<<"_admin">>|ExtraRoles]}, {<<"salt">>, ?l2b(Salt)}, {<<"iterations">>, list_to_integer(Iterations)}, {<<"password_scheme">>, <<"pbkdf2">>}, {<<"derived_key">>, ?l2b(DerivedKey)}]. get_from_cache(UserName) -> exec_if_auth_db( fun(_AuthDb) -> maybe_refresh_cache(), case ets:lookup(?BY_USER, UserName) of [] -> gen_server:call(?MODULE, {fetch, UserName}, infinity); [{UserName, {Credentials, _ATime}}] -> couch_stats_collector:increment({couchdb, auth_cache_hits}), gen_server:cast(?MODULE, {cache_hit, UserName}), Credentials end end, nil ). validate_user_creds(nil) -> nil; validate_user_creds(UserCreds) -> case couch_util:get_value(<<"_conflicts">>, UserCreds) of undefined -> ok; _ConflictList -> throw({unauthorized, <<"User document conflicts must be resolved before the document", " is used for authentication purposes.">> }) end, UserCreds. start_link() -> gen_server:start_link({local, ?MODULE}, ?MODULE, [], []). init(_) -> ?STATE = ets:new(?STATE, [set, protected, named_table]), ?BY_USER = ets:new(?BY_USER, [set, protected, named_table]), ?BY_ATIME = ets:new(?BY_ATIME, [ordered_set, private, named_table]), process_flag(trap_exit, true), ok = couch_config:register( fun("couch_httpd_auth", "auth_cache_size", SizeList) -> Size = list_to_integer(SizeList), ok = gen_server:call(?MODULE, {new_max_cache_size, Size}, infinity); ("couch_httpd_auth", "authentication_db", _DbName) -> ok = gen_server:call(?MODULE, reinit_cache, infinity) end ), {ok, Notifier} = couch_db_update_notifier:start_link(fun handle_db_event/1), State = #state{ db_notifier = Notifier, max_cache_size = list_to_integer( couch_config:get("couch_httpd_auth", "auth_cache_size", "50") ) }, {ok, reinit_cache(State)}. handle_db_event({Event, DbName}) -> [{auth_db_name, AuthDbName}] = ets:lookup(?STATE, auth_db_name), case DbName =:= AuthDbName of true -> case Event of created -> gen_server:call(?MODULE, reinit_cache, infinity); compacted -> gen_server:call(?MODULE, auth_db_compacted, infinity); _Else -> ok end; false -> ok end. handle_call(reinit_cache, _From, State) -> catch erlang:demonitor(State#state.db_mon_ref, [flush]), exec_if_auth_db(fun(AuthDb) -> catch couch_db:close(AuthDb) end), {reply, ok, reinit_cache(State)}; handle_call(auth_db_compacted, _From, State) -> exec_if_auth_db( fun(AuthDb) -> true = ets:insert(?STATE, {auth_db, reopen_auth_db(AuthDb)}) end ), {reply, ok, State}; handle_call({new_max_cache_size, NewSize}, _From, #state{cache_size = Size} = State) when NewSize >= Size -> {reply, ok, State#state{max_cache_size = NewSize}}; handle_call({new_max_cache_size, NewSize}, _From, State) -> free_mru_cache_entries(State#state.cache_size - NewSize), {reply, ok, State#state{max_cache_size = NewSize, cache_size = NewSize}}; handle_call({fetch, UserName}, _From, State) -> {Credentials, NewState} = case ets:lookup(?BY_USER, UserName) of [{UserName, {Creds, ATime}}] -> couch_stats_collector:increment({couchdb, auth_cache_hits}), cache_hit(UserName, Creds, ATime), {Creds, State}; [] -> couch_stats_collector:increment({couchdb, auth_cache_misses}), Creds = get_user_props_from_db(UserName), State1 = add_cache_entry(UserName, Creds, erlang:now(), State), {Creds, State1} end, {reply, Credentials, NewState}; handle_call(refresh, _From, State) -> exec_if_auth_db(fun refresh_entries/1), {reply, ok, State}. handle_cast({cache_hit, UserName}, State) -> case ets:lookup(?BY_USER, UserName) of [{UserName, {Credentials, ATime}}] -> cache_hit(UserName, Credentials, ATime); _ -> ok end, {noreply, State}. handle_info({'DOWN', Ref, _, _, _Reason}, #state{db_mon_ref = Ref} = State) -> {noreply, reinit_cache(State)}. terminate(_Reason, #state{db_notifier = Notifier}) -> couch_db_update_notifier:stop(Notifier), exec_if_auth_db(fun(AuthDb) -> catch couch_db:close(AuthDb) end), true = ets:delete(?BY_USER), true = ets:delete(?BY_ATIME), true = ets:delete(?STATE). code_change(_OldVsn, State, _Extra) -> {ok, State}. clear_cache(State) -> exec_if_auth_db(fun(AuthDb) -> catch couch_db:close(AuthDb) end), true = ets:delete_all_objects(?BY_USER), true = ets:delete_all_objects(?BY_ATIME), State#state{cache_size = 0}. reinit_cache(State) -> NewState = clear_cache(State), AuthDbName = ?l2b(couch_config:get("couch_httpd_auth", "authentication_db")), true = ets:insert(?STATE, {auth_db_name, AuthDbName}), AuthDb = open_auth_db(), true = ets:insert(?STATE, {auth_db, AuthDb}), NewState#state{db_mon_ref = couch_db:monitor(AuthDb)}. add_cache_entry(_, _, _, #state{max_cache_size = 0} = State) -> State; add_cache_entry(UserName, Credentials, ATime, State) -> case State#state.cache_size >= State#state.max_cache_size of true -> free_mru_cache_entry(); false -> ok end, true = ets:insert(?BY_ATIME, {ATime, UserName}), true = ets:insert(?BY_USER, {UserName, {Credentials, ATime}}), State#state{cache_size = couch_util:get_value(size, ets:info(?BY_USER))}. free_mru_cache_entries(0) -> ok; free_mru_cache_entries(N) when N > 0 -> free_mru_cache_entry(), free_mru_cache_entries(N - 1). free_mru_cache_entry() -> MruTime = ets:last(?BY_ATIME), [{MruTime, UserName}] = ets:lookup(?BY_ATIME, MruTime), true = ets:delete(?BY_ATIME, MruTime), true = ets:delete(?BY_USER, UserName). cache_hit(UserName, Credentials, ATime) -> NewATime = erlang:now(), true = ets:delete(?BY_ATIME, ATime), true = ets:insert(?BY_ATIME, {NewATime, UserName}), true = ets:insert(?BY_USER, {UserName, {Credentials, NewATime}}). refresh_entries(AuthDb) -> case reopen_auth_db(AuthDb) of nil -> ok; AuthDb2 -> case AuthDb2#db.update_seq > AuthDb#db.update_seq of true -> {ok, _, _} = couch_db:enum_docs_since( AuthDb2, AuthDb#db.update_seq, fun(DocInfo, _, _) -> refresh_entry(AuthDb2, DocInfo) end, AuthDb#db.update_seq, [] ), true = ets:insert(?STATE, {auth_db, AuthDb2}); false -> ok end end. refresh_entry(Db, #doc_info{high_seq = DocSeq} = DocInfo) -> case is_user_doc(DocInfo) of {true, UserName} -> case ets:lookup(?BY_USER, UserName) of [] -> ok; [{UserName, {_OldCreds, ATime}}] -> {ok, Doc} = couch_db:open_doc(Db, DocInfo, [conflicts, deleted]), NewCreds = user_creds(Doc), true = ets:insert(?BY_USER, {UserName, {NewCreds, ATime}}) end; false -> ok end, {ok, DocSeq}. user_creds(#doc{deleted = true}) -> nil; user_creds(#doc{} = Doc) -> {Creds} = couch_doc:to_json_obj(Doc, []), Creds. is_user_doc(#doc_info{id = <<"org.couchdb.user:", UserName/binary>>}) -> {true, UserName}; is_user_doc(_) -> false. maybe_refresh_cache() -> case cache_needs_refresh() of true -> ok = gen_server:call(?MODULE, refresh, infinity); false -> ok end. cache_needs_refresh() -> exec_if_auth_db( fun(AuthDb) -> case reopen_auth_db(AuthDb) of nil -> false; AuthDb2 -> AuthDb2#db.update_seq > AuthDb#db.update_seq end end, false ). reopen_auth_db(AuthDb) -> case (catch couch_db:reopen(AuthDb)) of {ok, AuthDb2} -> AuthDb2; _ -> nil end. exec_if_auth_db(Fun) -> exec_if_auth_db(Fun, ok). exec_if_auth_db(Fun, DefRes) -> case ets:lookup(?STATE, auth_db) of [{auth_db, #db{} = AuthDb}] -> Fun(AuthDb); _ -> DefRes end. open_auth_db() -> [{auth_db_name, DbName}] = ets:lookup(?STATE, auth_db_name), {ok, AuthDb} = ensure_users_db_exists(DbName, [sys_db]), AuthDb. get_user_props_from_db(UserName) -> exec_if_auth_db( fun(AuthDb) -> Db = reopen_auth_db(AuthDb), DocId = <<"org.couchdb.user:", UserName/binary>>, try {ok, Doc} = couch_db:open_doc(Db, DocId, [conflicts]), {DocProps} = couch_doc:to_json_obj(Doc, []), DocProps catch _:_Error -> nil end end, nil ). ensure_users_db_exists(DbName, Options) -> Options1 = [{user_ctx, #user_ctx{roles=[<<"_admin">>]}}, nologifmissing | Options], case couch_db:open(DbName, Options1) of {ok, Db} -> ensure_auth_ddoc_exists(Db, <<"_design/_auth">>), {ok, Db}; _Error -> {ok, Db} = couch_db:create(DbName, Options1), ok = ensure_auth_ddoc_exists(Db, <<"_design/_auth">>), {ok, Db} end. ensure_auth_ddoc_exists(Db, DDocId) -> case couch_db:open_doc(Db, DDocId) of {not_found, _Reason} -> {ok, AuthDesign} = auth_design_doc(DDocId), {ok, _Rev} = couch_db:update_doc(Db, AuthDesign, []); {ok, Doc} -> {Props} = couch_doc:to_json_obj(Doc, []), case couch_util:get_value(<<"validate_doc_update">>, Props, []) of ?AUTH_DB_DOC_VALIDATE_FUNCTION -> ok; _ -> Props1 = lists:keyreplace(<<"validate_doc_update">>, 1, Props, {<<"validate_doc_update">>, ?AUTH_DB_DOC_VALIDATE_FUNCTION}), couch_db:update_doc(Db, couch_doc:from_json_obj({Props1}), []) end end, ok. auth_design_doc(DocId) -> DocProps = [ {<<"_id">>, DocId}, {<<"language">>,<<"javascript">>}, {<<"validate_doc_update">>, ?AUTH_DB_DOC_VALIDATE_FUNCTION} ], {ok, couch_doc:from_json_obj({DocProps})}. apache-couchdb-1.5.0/src/couchdb/couch.erl0000644000175000001440000000203612230722213015256 00000000000000% 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. -module(couch). -compile(export_all). start() -> ok = application:start(couch). stop() -> application:stop(couch). restart() -> case stop() of ok -> start(); {error, {not_started,couch}} -> start(); {error, Reason} -> {error, Reason} end. reload() -> case supervisor:terminate_child(couch_server_sup, couch_config) of ok -> supervisor:restart_child(couch_server_sup, couch_config); {error, Reason} -> {error, Reason} end. apache-couchdb-1.5.0/src/couchdb/couch_query_servers.erl0000644000175000001440000005230012230722213020253 00000000000000% 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. -module(couch_query_servers). -behaviour(gen_server). -export([start_link/0, config_change/1]). -export([init/1, terminate/2, handle_call/3, handle_cast/2, handle_info/2,code_change/3]). -export([start_doc_map/3, map_docs/2, map_doc_raw/2, stop_doc_map/1, raw_to_ejson/1]). -export([reduce/3, rereduce/3,validate_doc_update/5]). -export([filter_docs/5]). -export([filter_view/3]). -export([with_ddoc_proc/2, proc_prompt/2, ddoc_prompt/3, ddoc_proc_prompt/3, json_doc/1]). % For 210-os-proc-pool.t -export([get_os_process/1, ret_os_process/1]). -include("couch_db.hrl"). -record(proc, { pid, lang, ddoc_keys = [], prompt_fun, set_timeout_fun, stop_fun }). -record(qserver, { langs, % Keyed by language name, value is {Mod,Func,Arg} pid_procs, % Keyed by PID, valus is a #proc record. lang_procs, % Keyed by language name, value is a #proc record lang_limits, % Keyed by language name, value is {Lang, Limit, Current} waitlist = [], config }). start_link() -> gen_server:start_link({local, couch_query_servers}, couch_query_servers, [], []). start_doc_map(Lang, Functions, Lib) -> Proc = get_os_process(Lang), case Lib of {[]} -> ok; Lib -> true = proc_prompt(Proc, [<<"add_lib">>, Lib]) end, lists:foreach(fun(FunctionSource) -> true = proc_prompt(Proc, [<<"add_fun">>, FunctionSource]) end, Functions), {ok, Proc}. map_docs(Proc, Docs) -> % send the documents Results = lists:map( fun(Doc) -> Json = couch_doc:to_json_obj(Doc, []), FunsResults = proc_prompt(Proc, [<<"map_doc">>, Json]), % the results are a json array of function map yields like this: % [FunResults1, FunResults2 ...] % where funresults is are json arrays of key value pairs: % [[Key1, Value1], [Key2, Value2]] % Convert the key, value pairs to tuples like % [{Key1, Value1}, {Key2, Value2}] lists:map( fun(FunRs) -> [list_to_tuple(FunResult) || FunResult <- FunRs] end, FunsResults) end, Docs), {ok, Results}. map_doc_raw(Proc, Doc) -> Json = couch_doc:to_json_obj(Doc, []), {ok, proc_prompt_raw(Proc, [<<"map_doc">>, Json])}. stop_doc_map(nil) -> ok; stop_doc_map(Proc) -> ok = ret_os_process(Proc). group_reductions_results([]) -> []; group_reductions_results(List) -> {Heads, Tails} = lists:foldl( fun([H|T], {HAcc,TAcc}) -> {[H|HAcc], [T|TAcc]} end, {[], []}, List), case Tails of [[]|_] -> % no tails left [Heads]; _ -> [Heads | group_reductions_results(Tails)] end. rereduce(_Lang, [], _ReducedValues) -> {ok, []}; rereduce(Lang, RedSrcs, ReducedValues) -> Grouped = group_reductions_results(ReducedValues), Results = lists:zipwith( fun (<<"_", _/binary>> = FunSrc, Values) -> {ok, [Result]} = builtin_reduce(rereduce, [FunSrc], [[[], V] || V <- Values], []), Result; (FunSrc, Values) -> os_rereduce(Lang, [FunSrc], Values) end, RedSrcs, Grouped), {ok, Results}. reduce(_Lang, [], _KVs) -> {ok, []}; reduce(Lang, RedSrcs, KVs) -> {OsRedSrcs, BuiltinReds} = lists:partition(fun (<<"_", _/binary>>) -> false; (_OsFun) -> true end, RedSrcs), {ok, OsResults} = os_reduce(Lang, OsRedSrcs, KVs), {ok, BuiltinResults} = builtin_reduce(reduce, BuiltinReds, KVs, []), recombine_reduce_results(RedSrcs, OsResults, BuiltinResults, []). recombine_reduce_results([], [], [], Acc) -> {ok, lists:reverse(Acc)}; recombine_reduce_results([<<"_", _/binary>>|RedSrcs], OsResults, [BRes|BuiltinResults], Acc) -> recombine_reduce_results(RedSrcs, OsResults, BuiltinResults, [BRes|Acc]); recombine_reduce_results([_OsFun|RedSrcs], [OsR|OsResults], BuiltinResults, Acc) -> recombine_reduce_results(RedSrcs, OsResults, BuiltinResults, [OsR|Acc]). os_reduce(_Lang, [], _KVs) -> {ok, []}; os_reduce(Lang, OsRedSrcs, KVs) -> Proc = get_os_process(Lang), OsResults = try proc_prompt(Proc, [<<"reduce">>, OsRedSrcs, KVs]) of [true, Reductions] -> Reductions after ok = ret_os_process(Proc) end, {ok, OsResults}. os_rereduce(Lang, OsRedSrcs, KVs) -> Proc = get_os_process(Lang), try proc_prompt(Proc, [<<"rereduce">>, OsRedSrcs, KVs]) of [true, [Reduction]] -> Reduction after ok = ret_os_process(Proc) end. builtin_reduce(_Re, [], _KVs, Acc) -> {ok, lists:reverse(Acc)}; builtin_reduce(Re, [<<"_sum",_/binary>>|BuiltinReds], KVs, Acc) -> Sum = builtin_sum_rows(KVs), builtin_reduce(Re, BuiltinReds, KVs, [Sum|Acc]); builtin_reduce(reduce, [<<"_count",_/binary>>|BuiltinReds], KVs, Acc) -> Count = length(KVs), builtin_reduce(reduce, BuiltinReds, KVs, [Count|Acc]); builtin_reduce(rereduce, [<<"_count",_/binary>>|BuiltinReds], KVs, Acc) -> Count = builtin_sum_rows(KVs), builtin_reduce(rereduce, BuiltinReds, KVs, [Count|Acc]); builtin_reduce(Re, [<<"_stats",_/binary>>|BuiltinReds], KVs, Acc) -> Stats = builtin_stats(Re, KVs), builtin_reduce(Re, BuiltinReds, KVs, [Stats|Acc]). builtin_sum_rows(KVs) -> lists:foldl(fun ([_Key, Value], Acc) when is_number(Value), is_number(Acc) -> Acc + Value; ([_Key, Value], Acc) when is_list(Value), is_list(Acc) -> sum_terms(Acc, Value); ([_Key, Value], Acc) when is_number(Value), is_list(Acc) -> sum_terms(Acc, [Value]); ([_Key, Value], Acc) when is_list(Value), is_number(Acc) -> sum_terms([Acc], Value); (_Else, _Acc) -> throw({invalid_value, <<"builtin _sum function requires map values to be numbers or lists of numbers">>}) end, 0, KVs). sum_terms([], []) -> []; sum_terms([_|_]=Xs, []) -> Xs; sum_terms([], [_|_]=Ys) -> Ys; sum_terms([X|Xs], [Y|Ys]) when is_number(X), is_number(Y) -> [X+Y | sum_terms(Xs,Ys)]; sum_terms(_, _) -> throw({invalid_value, <<"builtin _sum function requires map values to be numbers or lists of numbers">>}). builtin_stats(reduce, []) -> {[]}; builtin_stats(reduce, [[_,First]|Rest]) when is_number(First) -> Stats = lists:foldl(fun([_K,V], {S,C,Mi,Ma,Sq}) when is_number(V) -> {S+V, C+1, lists:min([Mi, V]), lists:max([Ma, V]), Sq+(V*V)}; (_, _) -> throw({invalid_value, <<"builtin _stats function requires map values to be numbers">>}) end, {First,1,First,First,First*First}, Rest), {Sum, Cnt, Min, Max, Sqr} = Stats, {[{sum,Sum}, {count,Cnt}, {min,Min}, {max,Max}, {sumsqr,Sqr}]}; builtin_stats(rereduce, [[_,First]|Rest]) -> {[{sum,Sum0}, {count,Cnt0}, {min,Min0}, {max,Max0}, {sumsqr,Sqr0}]} = First, Stats = lists:foldl(fun([_K,Red], {S,C,Mi,Ma,Sq}) -> {[{sum,Sum}, {count,Cnt}, {min,Min}, {max,Max}, {sumsqr,Sqr}]} = Red, {Sum+S, Cnt+C, lists:min([Min, Mi]), lists:max([Max, Ma]), Sqr+Sq} end, {Sum0,Cnt0,Min0,Max0,Sqr0}, Rest), {Sum, Cnt, Min, Max, Sqr} = Stats, {[{sum,Sum}, {count,Cnt}, {min,Min}, {max,Max}, {sumsqr,Sqr}]}. % use the function stored in ddoc.validate_doc_update to test an update. validate_doc_update(DDoc, EditDoc, DiskDoc, Ctx, SecObj) -> JsonEditDoc = couch_doc:to_json_obj(EditDoc, [revs]), JsonDiskDoc = json_doc(DiskDoc), case ddoc_prompt(DDoc, [<<"validate_doc_update">>], [JsonEditDoc, JsonDiskDoc, Ctx, SecObj]) of 1 -> ok; {[{<<"forbidden">>, Message}]} -> throw({forbidden, Message}); {[{<<"unauthorized">>, Message}]} -> throw({unauthorized, Message}) end. json_doc(nil) -> null; json_doc(Doc) -> couch_doc:to_json_obj(Doc, [revs]). filter_view(DDoc, VName, Docs) -> JsonDocs = [couch_doc:to_json_obj(Doc, [revs]) || Doc <- Docs], [true, Passes] = ddoc_prompt(DDoc, [<<"views">>, VName, <<"map">>], [JsonDocs]), {ok, Passes}. filter_docs(Req, Db, DDoc, FName, Docs) -> JsonReq = case Req of {json_req, JsonObj} -> JsonObj; #httpd{} = HttpReq -> couch_httpd_external:json_req_obj(HttpReq, Db) end, JsonDocs = [couch_doc:to_json_obj(Doc, [revs]) || Doc <- Docs], [true, Passes] = ddoc_prompt(DDoc, [<<"filters">>, FName], [JsonDocs, JsonReq]), {ok, Passes}. ddoc_proc_prompt({Proc, DDocId}, FunPath, Args) -> proc_prompt(Proc, [<<"ddoc">>, DDocId, FunPath, Args]). ddoc_prompt(DDoc, FunPath, Args) -> with_ddoc_proc(DDoc, fun({Proc, DDocId}) -> proc_prompt(Proc, [<<"ddoc">>, DDocId, FunPath, Args]) end). with_ddoc_proc(#doc{id=DDocId,revs={Start, [DiskRev|_]}}=DDoc, Fun) -> Rev = couch_doc:rev_to_str({Start, DiskRev}), DDocKey = {DDocId, Rev}, Proc = get_ddoc_process(DDoc, DDocKey), try Fun({Proc, DDocId}) after ok = ret_os_process(Proc) end. init([]) -> % register async to avoid deadlock on restart_child Self = self(), spawn(couch_config, register, [fun ?MODULE:config_change/1, Self]), Langs = ets:new(couch_query_server_langs, [set, private]), LangLimits = ets:new(couch_query_server_lang_limits, [set, private]), PidProcs = ets:new(couch_query_server_pid_langs, [set, private]), LangProcs = ets:new(couch_query_server_procs, [set, private]), ProcTimeout = list_to_integer(couch_config:get( "couchdb", "os_process_timeout", "5000")), ReduceLimit = list_to_atom( couch_config:get("query_server_config","reduce_limit","true")), OsProcLimit = list_to_integer( couch_config:get("query_server_config","os_process_limit","10")), % 'query_servers' specifies an OS command-line to execute. lists:foreach(fun({Lang, Command}) -> true = ets:insert(LangLimits, {?l2b(Lang), OsProcLimit, 0}), true = ets:insert(Langs, {?l2b(Lang), couch_os_process, start_link, [Command]}) end, couch_config:get("query_servers")), % 'native_query_servers' specifies a {Module, Func, Arg} tuple. lists:foreach(fun({Lang, SpecStr}) -> {ok, {Mod, Fun, SpecArg}} = couch_util:parse_term(SpecStr), true = ets:insert(LangLimits, {?l2b(Lang), 0, 0}), % 0 means no limit true = ets:insert(Langs, {?l2b(Lang), Mod, Fun, SpecArg}) end, couch_config:get("native_query_servers")), process_flag(trap_exit, true), {ok, #qserver{ langs = Langs, % Keyed by language name, value is {Mod,Func,Arg} pid_procs = PidProcs, % Keyed by PID, valus is a #proc record. lang_procs = LangProcs, % Keyed by language name, value is a #proc record lang_limits = LangLimits, % Keyed by language name, value is {Lang, Limit, Current} config = {[{<<"reduce_limit">>, ReduceLimit},{<<"timeout">>, ProcTimeout}]} }}. terminate(_Reason, #qserver{pid_procs=PidProcs}) -> [couch_util:shutdown_sync(P) || {P,_} <- ets:tab2list(PidProcs)], ok. handle_call({get_proc, DDoc1, DDocKey}, From, Server) -> #doc{body = {Props}} = DDoc = couch_doc:with_ejson_body(DDoc1), Lang = couch_util:get_value(<<"language">>, Props, <<"javascript">>), case lang_proc(Lang, Server, fun(Procs) -> % find a proc in the set that has the DDoc proc_with_ddoc(DDoc, DDocKey, Procs) end) of {ok, Proc} -> {reply, {ok, Proc, Server#qserver.config}, Server}; wait -> {noreply, add_to_waitlist({DDoc, DDocKey}, From, Server)}; Error -> {reply, Error, Server} end; handle_call({get_proc, Lang}, From, Server) -> case lang_proc(Lang, Server, fun([P|_Procs]) -> {ok, P} end) of {ok, Proc} -> {reply, {ok, Proc, Server#qserver.config}, Server}; wait -> {noreply, add_to_waitlist({Lang}, From, Server)}; Error -> {reply, Error, Server} end; handle_call({unlink_proc, Pid}, _From, Server) -> unlink(Pid), {reply, ok, Server}; handle_call({ret_proc, Proc}, _From, #qserver{ pid_procs=PidProcs, lang_procs=LangProcs}=Server) -> % Along with max process limit, here we should check % if we're over the limit and discard when we are. case is_process_alive(Proc#proc.pid) of true -> add_value(PidProcs, Proc#proc.pid, Proc), add_to_list(LangProcs, Proc#proc.lang, Proc), link(Proc#proc.pid); false -> ok end, {reply, true, service_waitlist(Server)}. handle_cast(_Whatever, Server) -> {noreply, Server}. handle_info({'EXIT', _, _}, Server) -> {noreply, Server}; handle_info({'DOWN', _, process, Pid, Status}, #qserver{ pid_procs=PidProcs, lang_procs=LangProcs, lang_limits=LangLimits}=Server) -> case ets:lookup(PidProcs, Pid) of [{Pid, Proc}] -> case Status of normal -> ok; _ -> ?LOG_DEBUG("Linked process died abnormally: ~p (reason: ~p)", [Pid, Status]) end, rem_value(PidProcs, Pid), catch rem_from_list(LangProcs, Proc#proc.lang, Proc), [{Lang, Lim, Current}] = ets:lookup(LangLimits, Proc#proc.lang), true = ets:insert(LangLimits, {Lang, Lim, Current-1}), {noreply, service_waitlist(Server)}; [] -> case Status of normal -> {noreply, Server}; _ -> {stop, Status, Server} end end. code_change(_OldVsn, State, _Extra) -> {ok, State}. config_change("query_servers") -> supervisor:terminate_child(couch_secondary_services, query_servers), supervisor:restart_child(couch_secondary_services, query_servers); config_change("native_query_servers") -> supervisor:terminate_child(couch_secondary_services, query_servers), supervisor:restart_child(couch_secondary_services, query_servers); config_change("query_server_config") -> supervisor:terminate_child(couch_secondary_services, query_servers), supervisor:restart_child(couch_secondary_services, query_servers). % Private API add_to_waitlist(Info, From, #qserver{waitlist=Waitlist}=Server) -> Server#qserver{waitlist=[{Info, From}|Waitlist]}. service_waitlist(#qserver{waitlist=[]}=Server) -> Server; service_waitlist(#qserver{waitlist=Waitlist}=Server) -> [Oldest|RevWList] = lists:reverse(Waitlist), case service_waiting(Oldest, Server) of ok -> Server#qserver{waitlist=lists:reverse(RevWList)}; wait -> Server#qserver{waitlist=Waitlist} end. % todo get rid of duplication service_waiting({{#doc{body={Props}}=DDoc, DDocKey}, From}, Server) -> Lang = couch_util:get_value(<<"language">>, Props, <<"javascript">>), case lang_proc(Lang, Server, fun(Procs) -> % find a proc in the set that has the DDoc proc_with_ddoc(DDoc, DDocKey, Procs) end) of {ok, Proc} -> gen_server:reply(From, {ok, Proc, Server#qserver.config}), ok; wait -> % this should never happen wait; Error -> gen_server:reply(From, Error), ok end; service_waiting({{Lang}, From}, Server) -> case lang_proc(Lang, Server, fun([P|_Procs]) -> {ok, P} end) of {ok, Proc} -> gen_server:reply(From, {ok, Proc, Server#qserver.config}), ok; wait -> % this should never happen wait; Error -> gen_server:reply(From, Error), ok end. lang_proc(Lang, #qserver{ langs=Langs, pid_procs=PidProcs, lang_procs=LangProcs, lang_limits=LangLimits}, PickFun) -> % Note to future self. Add max process limit. case ets:lookup(LangProcs, Lang) of [{Lang, [P|Procs]}] -> {ok, Proc} = PickFun([P|Procs]), rem_from_list(LangProcs, Lang, Proc), {ok, Proc}; _ -> case (catch new_process(Langs, LangLimits, Lang)) of {ok, Proc} -> add_value(PidProcs, Proc#proc.pid, Proc), PickFun([Proc]); ErrorOrWait -> ErrorOrWait end end. new_process(Langs, LangLimits, Lang) -> [{Lang, Lim, Current}] = ets:lookup(LangLimits, Lang), if (Lim == 0) or (Current < Lim) -> % Lim == 0 means no limit % we are below the limit for our language, make a new one case ets:lookup(Langs, Lang) of [{Lang, Mod, Func, Arg}] -> {ok, Pid} = apply(Mod, Func, Arg), erlang:monitor(process, Pid), true = ets:insert(LangLimits, {Lang, Lim, Current+1}), {ok, #proc{lang=Lang, pid=Pid, % Called via proc_prompt, proc_set_timeout, and proc_stop prompt_fun={Mod, prompt}, set_timeout_fun={Mod, set_timeout}, stop_fun={Mod, stop}}}; _ -> {unknown_query_language, Lang} end; true -> wait end. proc_with_ddoc(DDoc, DDocKey, LangProcs) -> DDocProcs = lists:filter(fun(#proc{ddoc_keys=Keys}) -> lists:any(fun(Key) -> Key == DDocKey end, Keys) end, LangProcs), case DDocProcs of [DDocProc|_] -> ?LOG_DEBUG("DDocProc found for DDocKey: ~p",[DDocKey]), {ok, DDocProc}; [] -> [TeachProc|_] = LangProcs, ?LOG_DEBUG("Teach ddoc to new proc ~p with DDocKey: ~p",[TeachProc, DDocKey]), {ok, SmartProc} = teach_ddoc(DDoc, DDocKey, TeachProc), {ok, SmartProc} end. proc_prompt(Proc, Args) -> case proc_prompt_raw(Proc, Args) of {json, Json} -> ?JSON_DECODE(Json); EJson -> EJson end. proc_prompt_raw(#proc{prompt_fun = {Mod, Func}} = Proc, Args) -> apply(Mod, Func, [Proc#proc.pid, Args]). raw_to_ejson({json, Json}) -> ?JSON_DECODE(Json); raw_to_ejson(EJson) -> EJson. proc_stop(Proc) -> {Mod, Func} = Proc#proc.stop_fun, apply(Mod, Func, [Proc#proc.pid]). proc_set_timeout(Proc, Timeout) -> {Mod, Func} = Proc#proc.set_timeout_fun, apply(Mod, Func, [Proc#proc.pid, Timeout]). teach_ddoc(DDoc, {DDocId, _Rev}=DDocKey, #proc{ddoc_keys=Keys}=Proc) -> % send ddoc over the wire % we only share the rev with the client we know to update code % but it only keeps the latest copy, per each ddoc, around. true = proc_prompt(Proc, [<<"ddoc">>, <<"new">>, DDocId, couch_doc:to_json_obj(DDoc, [])]), % we should remove any other ddocs keys for this docid % because the query server overwrites without the rev Keys2 = [{D,R} || {D,R} <- Keys, D /= DDocId], % add ddoc to the proc {ok, Proc#proc{ddoc_keys=[DDocKey|Keys2]}}. get_ddoc_process(#doc{} = DDoc, DDocKey) -> % remove this case statement case gen_server:call(couch_query_servers, {get_proc, DDoc, DDocKey}, infinity) of {ok, Proc, {QueryConfig}} -> % process knows the ddoc case (catch proc_prompt(Proc, [<<"reset">>, {QueryConfig}])) of true -> proc_set_timeout(Proc, couch_util:get_value(<<"timeout">>, QueryConfig)), link(Proc#proc.pid), gen_server:call(couch_query_servers, {unlink_proc, Proc#proc.pid}, infinity), Proc; _ -> catch proc_stop(Proc), get_ddoc_process(DDoc, DDocKey) end; Error -> throw(Error) end. get_os_process(Lang) -> case gen_server:call(couch_query_servers, {get_proc, Lang}, infinity) of {ok, Proc, {QueryConfig}} -> case (catch proc_prompt(Proc, [<<"reset">>, {QueryConfig}])) of true -> proc_set_timeout(Proc, couch_util:get_value(<<"timeout">>, QueryConfig)), link(Proc#proc.pid), gen_server:call(couch_query_servers, {unlink_proc, Proc#proc.pid}, infinity), Proc; _ -> catch proc_stop(Proc), get_os_process(Lang) end; Error -> throw(Error) end. ret_os_process(Proc) -> true = gen_server:call(couch_query_servers, {ret_proc, Proc}, infinity), catch unlink(Proc#proc.pid), ok. add_value(Tid, Key, Value) -> true = ets:insert(Tid, {Key, Value}). rem_value(Tid, Key) -> true = ets:delete(Tid, Key). add_to_list(Tid, Key, Value) -> case ets:lookup(Tid, Key) of [{Key, Vals}] -> true = ets:insert(Tid, {Key, [Value|Vals]}); [] -> true = ets:insert(Tid, {Key, [Value]}) end. rem_from_list(Tid, Key, Value) when is_record(Value, proc)-> Pid = Value#proc.pid, case ets:lookup(Tid, Key) of [{Key, Vals}] -> % make a new values list that doesn't include the Value arg NewValues = [Val || #proc{pid=P}=Val <- Vals, P /= Pid], ets:insert(Tid, {Key, NewValues}); [] -> ok end; rem_from_list(Tid, Key, Value) -> case ets:lookup(Tid, Key) of [{Key, Vals}] -> % make a new values list that doesn't include the Value arg NewValues = [Val || Val <- Vals, Val /= Value], ets:insert(Tid, {Key, NewValues}); [] -> ok end. apache-couchdb-1.5.0/src/couchdb/couch_httpd_misc_handlers.erl0000644000175000001440000002754012230722213021363 00000000000000% 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. -module(couch_httpd_misc_handlers). -export([handle_welcome_req/2,handle_favicon_req/2,handle_utils_dir_req/2, handle_all_dbs_req/1,handle_restart_req/1, handle_uuids_req/1,handle_config_req/1,handle_log_req/1, handle_task_status_req/1, handle_file_req/2]). -export([increment_update_seq_req/2]). -include("couch_db.hrl"). -import(couch_httpd, [send_json/2,send_json/3,send_json/4,send_method_not_allowed/2, start_json_response/2,send_chunk/2,last_chunk/1,end_json_response/1, start_chunked_response/3, send_error/4]). % httpd global handlers handle_welcome_req(#httpd{method='GET'}=Req, WelcomeMessage) -> send_json(Req, {[ {couchdb, WelcomeMessage}, {uuid, couch_server:get_uuid()}, {version, list_to_binary(couch_server:get_version())} ] ++ case couch_config:get("vendor") of [] -> []; Properties -> [{vendor, {[{?l2b(K), ?l2b(V)} || {K, V} <- Properties]}}] end }); handle_welcome_req(Req, _) -> send_method_not_allowed(Req, "GET,HEAD"). handle_favicon_req(#httpd{method='GET'}=Req, DocumentRoot) -> {{Year,Month,Day},Time} = erlang:universaltime(), OneYearFromNow = {{Year+1,Month,Day},Time}, CachingHeaders = [ %favicon should expire a year from now {"Cache-Control", "public, max-age=31536000"}, {"Expires", couch_util:rfc1123_date(OneYearFromNow)} ], couch_httpd:serve_file(Req, "favicon.ico", DocumentRoot, CachingHeaders); handle_favicon_req(Req, _) -> send_method_not_allowed(Req, "GET,HEAD"). handle_file_req(#httpd{method='GET'}=Req, Document) -> couch_httpd:serve_file(Req, filename:basename(Document), filename:dirname(Document)); handle_file_req(Req, _) -> send_method_not_allowed(Req, "GET,HEAD"). handle_utils_dir_req(#httpd{method='GET'}=Req, DocumentRoot) -> "/" ++ UrlPath = couch_httpd:path(Req), case couch_httpd:partition(UrlPath) of {_ActionKey, "/", RelativePath} -> % GET /_utils/path or GET /_utils/ CachingHeaders = [{"Cache-Control", "private, must-revalidate"}], couch_httpd:serve_file(Req, RelativePath, DocumentRoot, CachingHeaders); {_ActionKey, "", _RelativePath} -> % GET /_utils RedirectPath = couch_httpd:path(Req) ++ "/", couch_httpd:send_redirect(Req, RedirectPath) end; handle_utils_dir_req(Req, _) -> send_method_not_allowed(Req, "GET,HEAD"). handle_all_dbs_req(#httpd{method='GET'}=Req) -> {ok, DbNames} = couch_server:all_databases(), send_json(Req, DbNames); handle_all_dbs_req(Req) -> send_method_not_allowed(Req, "GET,HEAD"). handle_task_status_req(#httpd{method='GET'}=Req) -> ok = couch_httpd:verify_is_server_admin(Req), % convert the list of prop lists to a list of json objects send_json(Req, [{Props} || Props <- couch_task_status:all()]); handle_task_status_req(Req) -> send_method_not_allowed(Req, "GET,HEAD"). handle_restart_req(#httpd{method='POST'}=Req) -> couch_httpd:validate_ctype(Req, "application/json"), ok = couch_httpd:verify_is_server_admin(Req), Result = send_json(Req, 202, {[{ok, true}]}), couch_server_sup:restart_core_server(), Result; handle_restart_req(Req) -> send_method_not_allowed(Req, "POST"). handle_uuids_req(#httpd{method='GET'}=Req) -> Count = list_to_integer(couch_httpd:qs_value(Req, "count", "1")), UUIDs = [couch_uuids:new() || _ <- lists:seq(1, Count)], Etag = couch_httpd:make_etag(UUIDs), couch_httpd:etag_respond(Req, Etag, fun() -> CacheBustingHeaders = [ {"Date", couch_util:rfc1123_date()}, {"Cache-Control", "no-cache"}, % Past date, ON PURPOSE! {"Expires", "Fri, 01 Jan 1990 00:00:00 GMT"}, {"Pragma", "no-cache"}, {"ETag", Etag} ], send_json(Req, 200, CacheBustingHeaders, {[{<<"uuids">>, UUIDs}]}) end); handle_uuids_req(Req) -> send_method_not_allowed(Req, "GET"). % Config request handler % GET /_config/ % GET /_config handle_config_req(#httpd{method='GET', path_parts=[_]}=Req) -> ok = couch_httpd:verify_is_server_admin(Req), Grouped = lists:foldl(fun({{Section, Key}, Value}, Acc) -> case dict:is_key(Section, Acc) of true -> dict:append(Section, {list_to_binary(Key), list_to_binary(Value)}, Acc); false -> dict:store(Section, [{list_to_binary(Key), list_to_binary(Value)}], Acc) end end, dict:new(), couch_config:all()), KVs = dict:fold(fun(Section, Values, Acc) -> [{list_to_binary(Section), {Values}} | Acc] end, [], Grouped), send_json(Req, 200, {KVs}); % GET /_config/Section handle_config_req(#httpd{method='GET', path_parts=[_,Section]}=Req) -> ok = couch_httpd:verify_is_server_admin(Req), KVs = [{list_to_binary(Key), list_to_binary(Value)} || {Key, Value} <- couch_config:get(Section)], send_json(Req, 200, {KVs}); % GET /_config/Section/Key handle_config_req(#httpd{method='GET', path_parts=[_, Section, Key]}=Req) -> ok = couch_httpd:verify_is_server_admin(Req), case couch_config:get(Section, Key, null) of null -> throw({not_found, unknown_config_value}); Value -> send_json(Req, 200, list_to_binary(Value)) end; % PUT or DELETE /_config/Section/Key handle_config_req(#httpd{method=Method, path_parts=[_, Section, Key]}=Req) when (Method == 'PUT') or (Method == 'DELETE') -> ok = couch_httpd:verify_is_server_admin(Req), Persist = couch_httpd:header_value(Req, "X-Couch-Persist") /= "false", case couch_config:get(<<"httpd">>, <<"config_whitelist">>, null) of null -> % No whitelist; allow all changes. handle_approved_config_req(Req, Persist); WhitelistValue -> % Provide a failsafe to protect against inadvertently locking % onesself out of the config by supplying a syntactically-incorrect % Erlang term. To intentionally lock down the whitelist, supply a % well-formed list which does not include the whitelist config % variable itself. FallbackWhitelist = [{<<"httpd">>, <<"config_whitelist">>}], Whitelist = case couch_util:parse_term(WhitelistValue) of {ok, Value} when is_list(Value) -> Value; {ok, _NonListValue} -> FallbackWhitelist; {error, _} -> [{WhitelistSection, WhitelistKey}] = FallbackWhitelist, ?LOG_ERROR("Only whitelisting ~s/~s due to error parsing: ~p", [WhitelistSection, WhitelistKey, WhitelistValue]), FallbackWhitelist end, IsRequestedKeyVal = fun(Element) -> case Element of {A, B} -> % For readability, tuples may be used instead of binaries % in the whitelist. case {couch_util:to_binary(A), couch_util:to_binary(B)} of {Section, Key} -> true; {Section, <<"*">>} -> true; _Else -> false end; _Else -> false end end, case lists:any(IsRequestedKeyVal, Whitelist) of true -> % Allow modifying this whitelisted variable. handle_approved_config_req(Req, Persist); _NotWhitelisted -> % Disallow modifying this non-whitelisted variable. send_error(Req, 400, <<"modification_not_allowed">>, ?l2b("This config variable is read-only")) end end; handle_config_req(Req) -> send_method_not_allowed(Req, "GET,PUT,DELETE"). % PUT /_config/Section/Key % "value" handle_approved_config_req(Req, Persist) -> Query = couch_httpd:qs(Req), UseRawValue = case lists:keyfind("raw", 1, Query) of false -> false; % Not specified {"raw", ""} -> false; % Specified with no value, i.e. "?raw" and "?raw=" {"raw", "false"} -> false; {"raw", "true"} -> true; {"raw", InvalidValue} -> InvalidValue end, handle_approved_config_req(Req, Persist, UseRawValue). handle_approved_config_req(#httpd{method='PUT', path_parts=[_, Section, Key]}=Req, Persist, UseRawValue) when UseRawValue =:= false orelse UseRawValue =:= true -> RawValue = couch_httpd:json_body(Req), Value = case UseRawValue of true -> % Client requests no change to the provided value. RawValue; false -> % Pre-process the value as necessary. case Section of <<"admins">> -> couch_passwords:hash_admin_password(RawValue); _ -> RawValue end end, OldValue = couch_config:get(Section, Key, ""), case couch_config:set(Section, Key, ?b2l(Value), Persist) of ok -> send_json(Req, 200, list_to_binary(OldValue)); Error -> throw(Error) end; handle_approved_config_req(#httpd{method='PUT'}=Req, _Persist, UseRawValue) -> Err = io_lib:format("Bad value for 'raw' option: ~s", [UseRawValue]), send_json(Req, 400, {[{error, ?l2b(Err)}]}); % DELETE /_config/Section/Key handle_approved_config_req(#httpd{method='DELETE',path_parts=[_,Section,Key]}=Req, Persist, _UseRawValue) -> case couch_config:get(Section, Key, null) of null -> throw({not_found, unknown_config_value}); OldValue -> couch_config:delete(Section, Key, Persist), send_json(Req, 200, list_to_binary(OldValue)) end. % httpd db handlers increment_update_seq_req(#httpd{method='POST'}=Req, Db) -> couch_httpd:validate_ctype(Req, "application/json"), {ok, NewSeq} = couch_db:increment_update_seq(Db), send_json(Req, {[{ok, true}, {update_seq, NewSeq} ]}); increment_update_seq_req(Req, _Db) -> send_method_not_allowed(Req, "POST"). % httpd log handlers handle_log_req(#httpd{method='GET'}=Req) -> ok = couch_httpd:verify_is_server_admin(Req), Bytes = list_to_integer(couch_httpd:qs_value(Req, "bytes", "1000")), Offset = list_to_integer(couch_httpd:qs_value(Req, "offset", "0")), Chunk = couch_log:read(Bytes, Offset), {ok, Resp} = start_chunked_response(Req, 200, [ % send a plaintext response {"Content-Type", "text/plain; charset=utf-8"}, {"Content-Length", integer_to_list(length(Chunk))} ]), send_chunk(Resp, Chunk), last_chunk(Resp); handle_log_req(#httpd{method='POST'}=Req) -> {PostBody} = couch_httpd:json_body_obj(Req), Level = couch_util:get_value(<<"level">>, PostBody), Message = ?b2l(couch_util:get_value(<<"message">>, PostBody)), case Level of <<"debug">> -> ?LOG_DEBUG(Message, []), send_json(Req, 200, {[{ok, true}]}); <<"info">> -> ?LOG_INFO(Message, []), send_json(Req, 200, {[{ok, true}]}); <<"error">> -> ?LOG_ERROR(Message, []), send_json(Req, 200, {[{ok, true}]}); _ -> send_json(Req, 400, {[{error, ?l2b(io_lib:format("Unrecognized log level '~s'", [Level]))}]}) end; handle_log_req(Req) -> send_method_not_allowed(Req, "GET,POST"). apache-couchdb-1.5.0/src/couchdb/couch_external_server.erl0000644000175000001440000000446012230722213020551 00000000000000% 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. -module(couch_external_server). -behaviour(gen_server). -export([start_link/2, stop/1, execute/2]). -export([init/1, terminate/2, handle_call/3, handle_cast/2, handle_info/2, code_change/3]). -include("couch_db.hrl"). % External API start_link(Name, Command) -> gen_server:start_link(couch_external_server, [Name, Command], []). stop(Pid) -> gen_server:cast(Pid, stop). execute(Pid, JsonReq) -> {json, Json} = gen_server:call(Pid, {execute, JsonReq}, infinity), ?JSON_DECODE(Json). % Gen Server Handlers init([Name, Command]) -> ?LOG_INFO("EXTERNAL: Starting process for: ~s", [Name]), ?LOG_INFO("COMMAND: ~s", [Command]), process_flag(trap_exit, true), Timeout = list_to_integer(couch_config:get("couchdb", "os_process_timeout", "5000")), {ok, Pid} = couch_os_process:start_link(Command, [{timeout, Timeout}]), couch_config:register(fun("couchdb", "os_process_timeout", NewTimeout) -> couch_os_process:set_timeout(Pid, list_to_integer(NewTimeout)) end), {ok, {Name, Command, Pid}}. terminate(_Reason, {_Name, _Command, Pid}) -> couch_os_process:stop(Pid), ok. handle_call({execute, JsonReq}, _From, {Name, Command, Pid}) -> {reply, couch_os_process:prompt(Pid, JsonReq), {Name, Command, Pid}}. handle_info({'EXIT', _Pid, normal}, State) -> {noreply, State}; handle_info({'EXIT', Pid, Reason}, {Name, Command, Pid}) -> ?LOG_INFO("EXTERNAL: Process for ~s exiting. (reason: ~w)", [Name, Reason]), {stop, Reason, {Name, Command, Pid}}. handle_cast(stop, {Name, Command, Pid}) -> ?LOG_INFO("EXTERNAL: Shutting down ~s", [Name]), exit(Pid, normal), {stop, normal, {Name, Command, Pid}}; handle_cast(_Whatever, State) -> {noreply, State}. code_change(_OldVsn, State, _Extra) -> {ok, State}. apache-couchdb-1.5.0/src/couchdb/couch_stats_collector.erl0000644000175000001440000000703712230722213020550 00000000000000% 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. % todo % - remove existance check on increment(), decrement() and record(). have % modules initialize counters on startup. -module(couch_stats_collector). -behaviour(gen_server). -export([start/0, stop/0]). -export([all/0, all/1, get/1, increment/1, decrement/1, record/2, clear/1]). -export([track_process_count/1, track_process_count/2]). -export([init/1, terminate/2, code_change/3]). -export([handle_call/3, handle_cast/2, handle_info/2]). -define(HIT_TABLE, stats_hit_table). -define(ABS_TABLE, stats_abs_table). start() -> gen_server:start_link({local, ?MODULE}, ?MODULE, [], []). stop() -> gen_server:call(?MODULE, stop). all() -> ets:tab2list(?HIT_TABLE) ++ abs_to_list(). all(Type) -> case Type of incremental -> ets:tab2list(?HIT_TABLE); absolute -> abs_to_list() end. get(Key) -> case ets:lookup(?HIT_TABLE, Key) of [] -> case ets:lookup(?ABS_TABLE, Key) of [] -> nil; AbsVals -> lists:map(fun({_, Value}) -> Value end, AbsVals) end; [{_, Counter}] -> Counter end. increment(Key) -> Key2 = make_key(Key), case catch ets:update_counter(?HIT_TABLE, Key2, 1) of {'EXIT', {badarg, _}} -> catch ets:insert(?HIT_TABLE, {Key2, 1}), ok; _ -> ok end. decrement(Key) -> Key2 = make_key(Key), case catch ets:update_counter(?HIT_TABLE, Key2, -1) of {'EXIT', {badarg, _}} -> catch ets:insert(?HIT_TABLE, {Key2, -1}), ok; _ -> ok end. record(Key, Value) -> catch ets:insert(?ABS_TABLE, {make_key(Key), Value}). clear(Key) -> catch ets:delete(?ABS_TABLE, make_key(Key)). track_process_count(Stat) -> track_process_count(self(), Stat). track_process_count(Pid, Stat) -> MonitorFun = fun() -> Ref = erlang:monitor(process, Pid), receive {'DOWN', Ref, _, _, _} -> ok end, couch_stats_collector:decrement(Stat) end, case (catch couch_stats_collector:increment(Stat)) of ok -> spawn(MonitorFun); _ -> ok end. init(_) -> ets:new(?HIT_TABLE, [named_table, set, public]), ets:new(?ABS_TABLE, [named_table, duplicate_bag, public]), {ok, nil}. terminate(_Reason, _State) -> ok. handle_call(stop, _, State) -> {stop, normal, stopped, State}. handle_cast(foo, State) -> {noreply, State}. handle_info(_Info, State) -> {noreply, State}. code_change(_OldVersion, State, _Extra) -> {ok, State}. make_key({Module, Key}) when is_integer(Key) -> {Module, list_to_atom(integer_to_list(Key))}; make_key(Key) -> Key. abs_to_list() -> SortedKVs = lists:sort(ets:tab2list(?ABS_TABLE)), lists:foldl(fun({Key, Val}, Acc) -> case Acc of [] -> [{Key, [Val]}]; [{Key, Prev} | Rest] -> [{Key, [Val | Prev]} | Rest]; Others -> [{Key, [Val]} | Others] end end, [], SortedKVs).apache-couchdb-1.5.0/src/couchdb/couch_compaction_daemon.erl0000644000175000001440000003647012230722213021026 00000000000000% 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. -module(couch_compaction_daemon). -behaviour(gen_server). % public API -export([start_link/0, config_change/3]). % gen_server callbacks -export([init/1, handle_call/3, handle_info/2, handle_cast/2]). -export([code_change/3, terminate/2]). -include("couch_db.hrl"). -define(CONFIG_ETS, couch_compaction_daemon_config). -record(state, { loop_pid }). -record(config, { db_frag = nil, view_frag = nil, period = nil, cancel = false, parallel_view_compact = false }). -record(period, { from = nil, to = nil }). start_link() -> gen_server:start_link({local, ?MODULE}, ?MODULE, [], []). init(_) -> process_flag(trap_exit, true), ?CONFIG_ETS = ets:new(?CONFIG_ETS, [named_table, set, protected]), ok = couch_config:register(fun ?MODULE:config_change/3), load_config(), Server = self(), Loop = spawn_link(fun() -> compact_loop(Server) end), {ok, #state{loop_pid = Loop}}. config_change("compactions", DbName, NewValue) -> ok = gen_server:cast(?MODULE, {config_update, DbName, NewValue}). handle_cast({config_update, DbName, deleted}, State) -> true = ets:delete(?CONFIG_ETS, ?l2b(DbName)), {noreply, State}; handle_cast({config_update, DbName, Config}, #state{loop_pid = Loop} = State) -> case parse_config(DbName, Config) of {ok, NewConfig} -> WasEmpty = (ets:info(?CONFIG_ETS, size) =:= 0), true = ets:insert(?CONFIG_ETS, {?l2b(DbName), NewConfig}), case WasEmpty of true -> Loop ! {self(), have_config}; false -> ok end; error -> ok end, {noreply, State}. handle_call(Msg, _From, State) -> {stop, {unexpected_call, Msg}, State}. handle_info({'EXIT', Pid, Reason}, #state{loop_pid = Pid} = State) -> {stop, {compaction_loop_died, Reason}, State}. terminate(_Reason, _State) -> true = ets:delete(?CONFIG_ETS). code_change(_OldVsn, State, _Extra) -> {ok, State}. compact_loop(Parent) -> {ok, _} = couch_server:all_databases( fun(DbName, Acc) -> case ets:info(?CONFIG_ETS, size) =:= 0 of true -> {stop, Acc}; false -> case get_db_config(DbName) of nil -> ok; {ok, Config} -> case check_period(Config) of true -> maybe_compact_db(DbName, Config); false -> ok end end, {ok, Acc} end end, ok), case ets:info(?CONFIG_ETS, size) =:= 0 of true -> receive {Parent, have_config} -> ok end; false -> PausePeriod = list_to_integer( couch_config:get("compaction_daemon", "check_interval", "300")), ok = timer:sleep(PausePeriod * 1000) end, compact_loop(Parent). maybe_compact_db(DbName, Config) -> case (catch couch_db:open_int(DbName, [{user_ctx, #user_ctx{roles=[<<"_admin">>]}}])) of {ok, Db} -> DDocNames = db_ddoc_names(Db), case can_db_compact(Config, Db) of true -> {ok, DbCompactPid} = couch_db:start_compact(Db), TimeLeft = compact_time_left(Config), case Config#config.parallel_view_compact of true -> ViewsCompactPid = spawn_link(fun() -> maybe_compact_views(DbName, DDocNames, Config) end), ViewsMonRef = erlang:monitor(process, ViewsCompactPid); false -> ViewsCompactPid = nil, ViewsMonRef = nil end, DbMonRef = erlang:monitor(process, DbCompactPid), receive {'DOWN', DbMonRef, process, _, normal} -> couch_db:close(Db), case Config#config.parallel_view_compact of true -> ok; false -> maybe_compact_views(DbName, DDocNames, Config) end; {'DOWN', DbMonRef, process, _, Reason} -> couch_db:close(Db), ?LOG_ERROR("Compaction daemon - an error ocurred while" " compacting the database `~s`: ~p", [DbName, Reason]) after TimeLeft -> ?LOG_INFO("Compaction daemon - canceling compaction for database" " `~s` because it's exceeding the allowed period.", [DbName]), erlang:demonitor(DbMonRef, [flush]), ok = couch_db:cancel_compact(Db), couch_db:close(Db) end, case ViewsMonRef of nil -> ok; _ -> receive {'DOWN', ViewsMonRef, process, _, _Reason} -> ok after TimeLeft + 1000 -> % Under normal circunstances, the view compaction process % should have finished already. erlang:demonitor(ViewsMonRef, [flush]), unlink(ViewsCompactPid), exit(ViewsCompactPid, kill) end end; false -> couch_db:close(Db), maybe_compact_views(DbName, DDocNames, Config) end; _ -> ok end. maybe_compact_views(_DbName, [], _Config) -> ok; maybe_compact_views(DbName, [DDocName | Rest], Config) -> case check_period(Config) of true -> case maybe_compact_view(DbName, DDocName, Config) of ok -> maybe_compact_views(DbName, Rest, Config); timeout -> ok end; false -> ok end. db_ddoc_names(Db) -> {ok, _, DDocNames} = couch_db:enum_docs( Db, fun(#full_doc_info{id = <<"_design/", _/binary>>, deleted = true}, _, Acc) -> {ok, Acc}; (#full_doc_info{id = <<"_design/", Id/binary>>}, _, Acc) -> {ok, [Id | Acc]}; (_, _, Acc) -> {stop, Acc} end, [], [{start_key, <<"_design/">>}, {end_key_gt, <<"_design0">>}]), DDocNames. maybe_compact_view(DbName, GroupId, Config) -> DDocId = <<"_design/", GroupId/binary>>, case (catch couch_mrview:get_info(DbName, DDocId)) of {ok, GroupInfo} -> case can_view_compact(Config, DbName, GroupId, GroupInfo) of true -> {ok, MonRef} = couch_mrview:compact(DbName, DDocId, [monitor]), TimeLeft = compact_time_left(Config), receive {'DOWN', MonRef, process, _, normal} -> ok; {'DOWN', MonRef, process, _, Reason} -> ?LOG_ERROR("Compaction daemon - an error ocurred while compacting" " the view group `~s` from database `~s`: ~p", [GroupId, DbName, Reason]), ok after TimeLeft -> ?LOG_INFO("Compaction daemon - canceling the compaction for the " "view group `~s` of the database `~s` because it's exceeding" " the allowed period.", [GroupId, DbName]), erlang:demonitor(MonRef, [flush]), ok = couch_mrview:cancel_compaction(DbName, DDocId), timeout end; false -> ok end; Error -> ?LOG_ERROR("Error opening view group `~s` from database `~s`: ~p", [GroupId, DbName, Error]), ok end. compact_time_left(#config{cancel = false}) -> infinity; compact_time_left(#config{period = nil}) -> infinity; compact_time_left(#config{period = #period{to = {ToH, ToM} = To}}) -> {H, M, _} = time(), case To > {H, M} of true -> ((ToH - H) * 60 * 60 * 1000) + (abs(ToM - M) * 60 * 1000); false -> ((24 - H + ToH) * 60 * 60 * 1000) + (abs(ToM - M) * 60 * 1000) end. get_db_config(DbName) -> case ets:lookup(?CONFIG_ETS, DbName) of [] -> case ets:lookup(?CONFIG_ETS, <<"_default">>) of [] -> nil; [{<<"_default">>, Config}] -> {ok, Config} end; [{DbName, Config}] -> {ok, Config} end. can_db_compact(#config{db_frag = Threshold} = Config, Db) -> case check_period(Config) of false -> false; true -> {ok, DbInfo} = couch_db:get_db_info(Db), {Frag, SpaceRequired} = frag(DbInfo), ?LOG_DEBUG("Fragmentation for database `~s` is ~p%, estimated space for" " compaction is ~p bytes.", [Db#db.name, Frag, SpaceRequired]), case check_frag(Threshold, Frag) of false -> false; true -> Free = free_space(couch_config:get("couchdb", "database_dir")), case Free >= SpaceRequired of true -> true; false -> ?LOG_WARN("Compaction daemon - skipping database `~s` " "compaction: the estimated necessary disk space is about ~p" " bytes but the currently available disk space is ~p bytes.", [Db#db.name, SpaceRequired, Free]), false end end end. can_view_compact(Config, DbName, GroupId, GroupInfo) -> case check_period(Config) of false -> false; true -> case couch_util:get_value(updater_running, GroupInfo) of true -> false; false -> {Frag, SpaceRequired} = frag(GroupInfo), ?LOG_DEBUG("Fragmentation for view group `~s` (database `~s`) is " "~p%, estimated space for compaction is ~p bytes.", [GroupId, DbName, Frag, SpaceRequired]), case check_frag(Config#config.view_frag, Frag) of false -> false; true -> Free = free_space(couch_index_util:root_dir()), case Free >= SpaceRequired of true -> true; false -> ?LOG_WARN("Compaction daemon - skipping view group `~s` " "compaction (database `~s`): the estimated necessary " "disk space is about ~p bytes but the currently available" " disk space is ~p bytes.", [GroupId, DbName, SpaceRequired, Free]), false end end end end. check_period(#config{period = nil}) -> true; check_period(#config{period = #period{from = From, to = To}}) -> {HH, MM, _} = erlang:time(), case From < To of true -> ({HH, MM} >= From) andalso ({HH, MM} < To); false -> ({HH, MM} >= From) orelse ({HH, MM} < To) end. check_frag(nil, _) -> true; check_frag(Threshold, Frag) -> Frag >= Threshold. frag(Props) -> FileSize = couch_util:get_value(disk_size, Props), MinFileSize = list_to_integer( couch_config:get("compaction_daemon", "min_file_size", "131072")), case FileSize < MinFileSize of true -> {0, FileSize}; false -> case couch_util:get_value(data_size, Props) of null -> {100, FileSize}; 0 -> {0, FileSize}; DataSize -> Frag = round(((FileSize - DataSize) / FileSize * 100)), {Frag, space_required(DataSize)} end end. % Rough, and pessimistic, estimation of necessary disk space to compact a % database or view index. space_required(DataSize) -> round(DataSize * 2.0). load_config() -> lists:foreach( fun({DbName, ConfigString}) -> case parse_config(DbName, ConfigString) of {ok, Config} -> true = ets:insert(?CONFIG_ETS, {?l2b(DbName), Config}); error -> ok end end, couch_config:get("compactions")). parse_config(DbName, ConfigString) -> case (catch do_parse_config(ConfigString)) of {ok, Conf} -> {ok, Conf}; incomplete_period -> ?LOG_ERROR("Incomplete period ('to' or 'from' missing) in the compaction" " configuration for database `~s`", [DbName]), error; _ -> ?LOG_ERROR("Invalid compaction configuration for database " "`~s`: `~s`", [DbName, ConfigString]), error end. do_parse_config(ConfigString) -> {ok, ConfProps} = couch_util:parse_term(ConfigString), {ok, #config{period = Period} = Conf} = config_record(ConfProps, #config{}), case Period of nil -> {ok, Conf}; #period{from = From, to = To} when From =/= nil, To =/= nil -> {ok, Conf}; #period{} -> incomplete_period end. config_record([], Config) -> {ok, Config}; config_record([{db_fragmentation, V} | Rest], Config) -> [Frag] = string:tokens(V, "%"), config_record(Rest, Config#config{db_frag = list_to_integer(Frag)}); config_record([{view_fragmentation, V} | Rest], Config) -> [Frag] = string:tokens(V, "%"), config_record(Rest, Config#config{view_frag = list_to_integer(Frag)}); config_record([{from, V} | Rest], #config{period = Period0} = Config) -> Time = parse_time(V), Period = case Period0 of nil -> #period{from = Time}; #period{} -> Period0#period{from = Time} end, config_record(Rest, Config#config{period = Period}); config_record([{to, V} | Rest], #config{period = Period0} = Config) -> Time = parse_time(V), Period = case Period0 of nil -> #period{to = Time}; #period{} -> Period0#period{to = Time} end, config_record(Rest, Config#config{period = Period}); config_record([{strict_window, true} | Rest], Config) -> config_record(Rest, Config#config{cancel = true}); config_record([{strict_window, false} | Rest], Config) -> config_record(Rest, Config#config{cancel = false}); config_record([{parallel_view_compaction, true} | Rest], Config) -> config_record(Rest, Config#config{parallel_view_compact = true}); config_record([{parallel_view_compaction, false} | Rest], Config) -> config_record(Rest, Config#config{parallel_view_compact = false}). parse_time(String) -> [HH, MM] = string:tokens(String, ":"), {list_to_integer(HH), list_to_integer(MM)}. free_space(Path) -> DiskData = lists:sort( fun({PathA, _, _}, {PathB, _, _}) -> length(filename:split(PathA)) > length(filename:split(PathB)) end, disksup:get_disk_data()), free_space_rec(abs_path(Path), DiskData). free_space_rec(_Path, []) -> undefined; free_space_rec(Path, [{MountPoint0, Total, Usage} | Rest]) -> MountPoint = abs_path(MountPoint0), case MountPoint =:= string:substr(Path, 1, length(MountPoint)) of false -> free_space_rec(Path, Rest); true -> trunc(Total - (Total * (Usage / 100))) * 1024 end. abs_path(Path0) -> Path = filename:absname(Path0), case lists:last(Path) of $/ -> Path; _ -> Path ++ "/" end. apache-couchdb-1.5.0/src/couchdb/couch_stats_aggregator.erl0000644000175000001440000002127612230722213020705 00000000000000% 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. -module(couch_stats_aggregator). -behaviour(gen_server). -export([start/0, start/1, stop/0]). -export([all/0, all/1, get/1, get/2, get_json/1, get_json/2, collect_sample/0]). -export([init/1, terminate/2, code_change/3]). -export([handle_call/3, handle_cast/2, handle_info/2]). -record(aggregate, { description = <<"">>, seconds = 0, count = 0, current = null, sum = null, mean = null, variance = null, stddev = null, min = null, max = null, samples = [] }). start() -> PrivDir = couch_util:priv_dir(), start(filename:join(PrivDir, "stat_descriptions.cfg")). start(FileName) -> gen_server:start_link({local, ?MODULE}, ?MODULE, [FileName], []). stop() -> gen_server:cast(?MODULE, stop). all() -> ?MODULE:all(0). all(Time) when is_binary(Time) -> ?MODULE:all(list_to_integer(binary_to_list(Time))); all(Time) when is_atom(Time) -> ?MODULE:all(list_to_integer(atom_to_list(Time))); all(Time) when is_integer(Time) -> Aggs = ets:match(?MODULE, {{'$1', Time}, '$2'}), Stats = lists:map(fun([Key, Agg]) -> {Key, Agg} end, Aggs), case Stats of [] -> {[]}; _ -> Ret = lists:foldl(fun({{Mod, Key}, Agg}, Acc) -> CurrKeys = case proplists:lookup(Mod, Acc) of none -> []; {Mod, {Keys}} -> Keys end, NewMod = {[{Key, to_json_term(Agg)} | CurrKeys]}, [{Mod, NewMod} | proplists:delete(Mod, Acc)] end, [], Stats), {Ret} end. get(Key) -> ?MODULE:get(Key, 0). get(Key, Time) when is_binary(Time) -> ?MODULE:get(Key, list_to_integer(binary_to_list(Time))); get(Key, Time) when is_atom(Time) -> ?MODULE:get(Key, list_to_integer(atom_to_list(Time))); get(Key, Time) when is_integer(Time) -> case ets:lookup(?MODULE, {make_key(Key), Time}) of [] -> #aggregate{seconds=Time}; [{_, Agg}] -> Agg end. get_json(Key) -> get_json(Key, 0). get_json(Key, Time) -> to_json_term(?MODULE:get(Key, Time)). collect_sample() -> gen_server:call(?MODULE, collect_sample, infinity). init(StatDescsFileName) -> % Create an aggregate entry for each {description, rate} pair. ets:new(?MODULE, [named_table, set, protected]), SampleStr = couch_config:get("stats", "samples", "[0]"), {ok, Samples} = couch_util:parse_term(SampleStr), {ok, Descs} = file:consult(StatDescsFileName), lists:foreach(fun({Sect, Key, Value}) -> lists:foreach(fun(Secs) -> Agg = #aggregate{ description=list_to_binary(Value), seconds=Secs }, ets:insert(?MODULE, {{{Sect, Key}, Secs}, Agg}) end, Samples) end, Descs), Self = self(), ok = couch_config:register( fun("stats", _) -> exit(Self, config_change) end ), Rate = list_to_integer(couch_config:get("stats", "rate", "1000")), % TODO: Add timer_start to kernel start options. {ok, TRef} = timer:apply_after(Rate, ?MODULE, collect_sample, []), {ok, {TRef, Rate}}. terminate(_Reason, {TRef, _Rate}) -> timer:cancel(TRef), ok. handle_call(collect_sample, _, {OldTRef, SampleInterval}) -> timer:cancel(OldTRef), {ok, TRef} = timer:apply_after(SampleInterval, ?MODULE, collect_sample, []), % Gather new stats values to add. Incs = lists:map(fun({Key, Value}) -> {Key, {incremental, Value}} end, couch_stats_collector:all(incremental)), Abs = lists:map(fun({Key, Values}) -> couch_stats_collector:clear(Key), Values2 = case Values of X when is_list(X) -> X; Else -> [Else] end, {_, Mean} = lists:foldl(fun(Val, {Count, Curr}) -> {Count+1, Curr + (Val - Curr) / (Count+1)} end, {0, 0}, Values2), {Key, {absolute, Mean}} end, couch_stats_collector:all(absolute)), Values = Incs ++ Abs, Now = erlang:now(), lists:foreach(fun({{Key, Rate}, Agg}) -> NewAgg = case proplists:lookup(Key, Values) of none -> rem_values(Now, Agg); {Key, {Type, Value}} -> NewValue = new_value(Type, Value, Agg#aggregate.current), Agg2 = add_value(Now, NewValue, Agg), rem_values(Now, Agg2) end, ets:insert(?MODULE, {{Key, Rate}, NewAgg}) end, ets:tab2list(?MODULE)), {reply, ok, {TRef, SampleInterval}}. handle_cast(stop, State) -> {stop, normal, State}. handle_info(_Info, State) -> {noreply, State}. code_change(_OldVersion, State, _Extra) -> {ok, State}. new_value(incremental, Value, null) -> Value; new_value(incremental, Value, Current) -> Value - Current; new_value(absolute, Value, _Current) -> Value. add_value(Time, Value, #aggregate{count=Count, seconds=Secs}=Agg) when Count < 1 -> Samples = case Secs of 0 -> []; _ -> [{Time, Value}] end, Agg#aggregate{ count=1, current=Value, sum=Value, mean=Value, variance=0.0, stddev=null, min=Value, max=Value, samples=Samples }; add_value(Time, Value, Agg) -> #aggregate{ count=Count, current=Current, sum=Sum, mean=Mean, variance=Variance, samples=Samples } = Agg, NewCount = Count + 1, NewMean = Mean + (Value - Mean) / NewCount, NewVariance = Variance + (Value - Mean) * (Value - NewMean), StdDev = case NewCount > 1 of false -> null; _ -> math:sqrt(NewVariance / (NewCount - 1)) end, Agg2 = Agg#aggregate{ count=NewCount, current=Current + Value, sum=Sum + Value, mean=NewMean, variance=NewVariance, stddev=StdDev, min=lists:min([Agg#aggregate.min, Value]), max=lists:max([Agg#aggregate.max, Value]) }, case Agg2#aggregate.seconds of 0 -> Agg2; _ -> Agg2#aggregate{samples=[{Time, Value} | Samples]} end. rem_values(Time, Agg) -> Seconds = Agg#aggregate.seconds, Samples = Agg#aggregate.samples, Pred = fun({When, _Value}) -> timer:now_diff(Time, When) =< (Seconds * 1000000) end, {Keep, Remove} = lists:splitwith(Pred, Samples), Agg2 = lists:foldl(fun({_, Value}, Acc) -> rem_value(Value, Acc) end, Agg, Remove), Agg2#aggregate{samples=Keep}. rem_value(_Value, #aggregate{count=Count, seconds=Secs}) when Count =< 1 -> #aggregate{seconds=Secs}; rem_value(Value, Agg) -> #aggregate{ count=Count, sum=Sum, mean=Mean, variance=Variance } = Agg, OldMean = (Mean * Count - Value) / (Count - 1), OldVariance = Variance - (Value - OldMean) * (Value - Mean), OldCount = Count - 1, StdDev = case OldCount > 1 of false -> null; _ -> math:sqrt(clamp_value(OldVariance / (OldCount - 1))) end, Agg#aggregate{ count=OldCount, sum=Sum-Value, mean=clamp_value(OldMean), variance=clamp_value(OldVariance), stddev=StdDev }. to_json_term(Agg) -> {Min, Max} = case Agg#aggregate.seconds > 0 of false -> {Agg#aggregate.min, Agg#aggregate.max}; _ -> case length(Agg#aggregate.samples) > 0 of true -> Extract = fun({_Time, Value}) -> Value end, Samples = lists:map(Extract, Agg#aggregate.samples), {lists:min(Samples), lists:max(Samples)}; _ -> {null, null} end end, {[ {description, Agg#aggregate.description}, {current, round_value(Agg#aggregate.sum)}, {sum, round_value(Agg#aggregate.sum)}, {mean, round_value(Agg#aggregate.mean)}, {stddev, round_value(Agg#aggregate.stddev)}, {min, Min}, {max, Max} ]}. make_key({Mod, Val}) when is_integer(Val) -> {Mod, list_to_atom(integer_to_list(Val))}; make_key(Key) -> Key. round_value(Val) when not is_number(Val) -> Val; round_value(Val) when Val == 0 -> Val; round_value(Val) -> erlang:round(Val * 1000.0) / 1000.0. clamp_value(Val) when Val > 0.00000000000001 -> Val; clamp_value(_) -> 0.0. apache-couchdb-1.5.0/src/couchdb/couch_db_updater.erl0000644000175000001440000011756412230722213017464 00000000000000% 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. -module(couch_db_updater). -behaviour(gen_server). -export([btree_by_id_reduce/2,btree_by_seq_reduce/2]). -export([make_doc_summary/2]). -export([init/1,terminate/2,handle_call/3,handle_cast/2,code_change/3,handle_info/2]). -include("couch_db.hrl"). init({MainPid, DbName, Filepath, Fd, Options}) -> process_flag(trap_exit, true), case lists:member(create, Options) of true -> % create a new header and writes it to the file Header = #db_header{}, ok = couch_file:write_header(Fd, Header), % delete any old compaction files that might be hanging around RootDir = couch_config:get("couchdb", "database_dir", "."), couch_file:delete(RootDir, Filepath ++ ".compact"); false -> case couch_file:read_header(Fd) of {ok, Header} -> ok; no_valid_header -> % create a new header and writes it to the file Header = #db_header{}, ok = couch_file:write_header(Fd, Header), % delete any old compaction files that might be hanging around file:delete(Filepath ++ ".compact") end end, ReaderFd = open_reader_fd(Filepath, Options), Db = init_db(DbName, Filepath, Fd, ReaderFd, Header, Options), Db2 = refresh_validate_doc_funs(Db), {ok, Db2#db{main_pid = MainPid}}. terminate(_Reason, Db) -> ok = couch_file:close(Db#db.updater_fd), ok = couch_file:close(Db#db.fd), couch_util:shutdown_sync(Db#db.compactor_pid), couch_util:shutdown_sync(Db#db.fd_ref_counter), ok. handle_call(get_db, _From, Db) -> {reply, {ok, Db}, Db}; handle_call(full_commit, _From, #db{waiting_delayed_commit=nil}=Db) -> {reply, ok, Db}; % no data waiting, return ok immediately handle_call(full_commit, _From, Db) -> {reply, ok, commit_data(Db)}; % commit the data and return ok handle_call(increment_update_seq, _From, Db) -> Db2 = commit_data(Db#db{update_seq=Db#db.update_seq+1}), ok = gen_server:call(Db2#db.main_pid, {db_updated, Db2}), couch_db_update_notifier:notify({updated, Db#db.name}), {reply, {ok, Db2#db.update_seq}, Db2}; handle_call({set_security, NewSec}, _From, #db{compression = Comp} = Db) -> {ok, Ptr, _} = couch_file:append_term( Db#db.updater_fd, NewSec, [{compression, Comp}]), Db2 = commit_data(Db#db{security=NewSec, security_ptr=Ptr, update_seq=Db#db.update_seq+1}), ok = gen_server:call(Db2#db.main_pid, {db_updated, Db2}), {reply, ok, Db2}; handle_call({set_revs_limit, Limit}, _From, Db) -> Db2 = commit_data(Db#db{revs_limit=Limit, update_seq=Db#db.update_seq+1}), ok = gen_server:call(Db2#db.main_pid, {db_updated, Db2}), {reply, ok, Db2}; handle_call({purge_docs, _IdRevs}, _From, #db{compactor_pid=Pid}=Db) when Pid /= nil -> {reply, {error, purge_during_compaction}, Db}; handle_call({purge_docs, IdRevs}, _From, Db) -> #db{ updater_fd = Fd, fulldocinfo_by_id_btree = DocInfoByIdBTree, docinfo_by_seq_btree = DocInfoBySeqBTree, update_seq = LastSeq, header = Header = #db_header{purge_seq=PurgeSeq}, compression = Comp } = Db, DocLookups = couch_btree:lookup(DocInfoByIdBTree, [Id || {Id, _Revs} <- IdRevs]), NewDocInfos = lists:zipwith( fun({_Id, Revs}, {ok, #full_doc_info{rev_tree=Tree}=FullDocInfo}) -> case couch_key_tree:remove_leafs(Tree, Revs) of {_, []=_RemovedRevs} -> % no change nil; {NewTree, RemovedRevs} -> {FullDocInfo#full_doc_info{rev_tree=NewTree},RemovedRevs} end; (_, not_found) -> nil end, IdRevs, DocLookups), SeqsToRemove = [Seq || {#full_doc_info{update_seq=Seq},_} <- NewDocInfos], FullDocInfoToUpdate = [FullInfo || {#full_doc_info{rev_tree=Tree}=FullInfo,_} <- NewDocInfos, Tree /= []], IdRevsPurged = [{Id, Revs} || {#full_doc_info{id=Id}, Revs} <- NewDocInfos], {DocInfoToUpdate, NewSeq} = lists:mapfoldl( fun(#full_doc_info{rev_tree=Tree}=FullInfo, SeqAcc) -> Tree2 = couch_key_tree:map_leafs( fun(_RevId, LeafVal) -> IsDeleted = element(1, LeafVal), BodyPointer = element(2, LeafVal), {IsDeleted, BodyPointer, SeqAcc + 1} end, Tree), {couch_doc:to_doc_info(FullInfo#full_doc_info{rev_tree=Tree2}), SeqAcc + 1} end, LastSeq, FullDocInfoToUpdate), IdsToRemove = [Id || {#full_doc_info{id=Id,rev_tree=[]},_} <- NewDocInfos], {ok, DocInfoBySeqBTree2} = couch_btree:add_remove(DocInfoBySeqBTree, DocInfoToUpdate, SeqsToRemove), {ok, DocInfoByIdBTree2} = couch_btree:add_remove(DocInfoByIdBTree, FullDocInfoToUpdate, IdsToRemove), {ok, Pointer, _} = couch_file:append_term( Fd, IdRevsPurged, [{compression, Comp}]), Db2 = commit_data( Db#db{ fulldocinfo_by_id_btree = DocInfoByIdBTree2, docinfo_by_seq_btree = DocInfoBySeqBTree2, update_seq = NewSeq + 1, header=Header#db_header{purge_seq=PurgeSeq+1, purged_docs=Pointer}}), ok = gen_server:call(Db2#db.main_pid, {db_updated, Db2}), couch_db_update_notifier:notify({updated, Db#db.name}), {reply, {ok, (Db2#db.header)#db_header.purge_seq, IdRevsPurged}, Db2}; handle_call(start_compact, _From, Db) -> case Db#db.compactor_pid of nil -> ?LOG_INFO("Starting compaction for db \"~s\"", [Db#db.name]), Pid = spawn_link(fun() -> start_copy_compact(Db) end), Db2 = Db#db{compactor_pid=Pid}, ok = gen_server:call(Db#db.main_pid, {db_updated, Db2}), {reply, {ok, Pid}, Db2}; _ -> % compact currently running, this is a no-op {reply, {ok, Db#db.compactor_pid}, Db} end; handle_call(cancel_compact, _From, #db{compactor_pid = nil} = Db) -> {reply, ok, Db}; handle_call(cancel_compact, _From, #db{compactor_pid = Pid} = Db) -> unlink(Pid), exit(Pid, kill), RootDir = couch_config:get("couchdb", "database_dir", "."), ok = couch_file:delete(RootDir, Db#db.filepath ++ ".compact"), {reply, ok, Db#db{compactor_pid = nil}}; handle_call({compact_done, CompactFilepath}, _From, #db{filepath=Filepath}=Db) -> {ok, NewFd} = couch_file:open(CompactFilepath), ReaderFd = open_reader_fd(CompactFilepath, Db#db.options), {ok, NewHeader} = couch_file:read_header(NewFd), #db{update_seq=NewSeq} = NewDb = init_db(Db#db.name, Filepath, NewFd, ReaderFd, NewHeader, Db#db.options), unlink(NewFd), case Db#db.update_seq == NewSeq of true -> % suck up all the local docs into memory and write them to the new db {ok, _, LocalDocs} = couch_btree:foldl(Db#db.local_docs_btree, fun(Value, _Offset, Acc) -> {ok, [Value | Acc]} end, []), {ok, NewLocalBtree} = couch_btree:add(NewDb#db.local_docs_btree, LocalDocs), NewDb2 = commit_data(NewDb#db{ local_docs_btree = NewLocalBtree, main_pid = Db#db.main_pid, filepath = Filepath, instance_start_time = Db#db.instance_start_time, revs_limit = Db#db.revs_limit }), ?LOG_DEBUG("CouchDB swapping files ~s and ~s.", [Filepath, CompactFilepath]), RootDir = couch_config:get("couchdb", "database_dir", "."), couch_file:delete(RootDir, Filepath), ok = file:rename(CompactFilepath, Filepath), close_db(Db), NewDb3 = refresh_validate_doc_funs(NewDb2), ok = gen_server:call(Db#db.main_pid, {db_updated, NewDb3}, infinity), couch_db_update_notifier:notify({compacted, NewDb3#db.name}), ?LOG_INFO("Compaction for db \"~s\" completed.", [Db#db.name]), {reply, ok, NewDb3#db{compactor_pid=nil}}; false -> ?LOG_INFO("Compaction file still behind main file " "(update seq=~p. compact update seq=~p). Retrying.", [Db#db.update_seq, NewSeq]), close_db(NewDb), {reply, {retry, Db}, Db} end. handle_cast(Msg, #db{name = Name} = Db) -> ?LOG_ERROR("Database `~s` updater received unexpected cast: ~p", [Name, Msg]), {stop, Msg, Db}. handle_info({update_docs, Client, GroupedDocs, NonRepDocs, MergeConflicts, FullCommit}, Db) -> GroupedDocs2 = [[{Client, D} || D <- DocGroup] || DocGroup <- GroupedDocs], if NonRepDocs == [] -> {GroupedDocs3, Clients, FullCommit2} = collect_updates(GroupedDocs2, [Client], MergeConflicts, FullCommit); true -> GroupedDocs3 = GroupedDocs2, FullCommit2 = FullCommit, Clients = [Client] end, NonRepDocs2 = [{Client, NRDoc} || NRDoc <- NonRepDocs], try update_docs_int(Db, GroupedDocs3, NonRepDocs2, MergeConflicts, FullCommit2) of {ok, Db2, UpdatedDDocIds} -> ok = gen_server:call(Db#db.main_pid, {db_updated, Db2}), if Db2#db.update_seq /= Db#db.update_seq -> couch_db_update_notifier:notify({updated, Db2#db.name}); true -> ok end, [catch(ClientPid ! {done, self()}) || ClientPid <- Clients], lists:foreach(fun(DDocId) -> couch_db_update_notifier:notify({ddoc_updated, {Db#db.name, DDocId}}) end, UpdatedDDocIds), {noreply, Db2} catch throw: retry -> [catch(ClientPid ! {retry, self()}) || ClientPid <- Clients], {noreply, Db} end; handle_info(delayed_commit, #db{waiting_delayed_commit=nil}=Db) -> %no outstanding delayed commits, ignore {noreply, Db}; handle_info(delayed_commit, Db) -> case commit_data(Db) of Db -> {noreply, Db}; Db2 -> ok = gen_server:call(Db2#db.main_pid, {db_updated, Db2}), {noreply, Db2} end; handle_info({'EXIT', _Pid, normal}, Db) -> {noreply, Db}; handle_info({'EXIT', _Pid, Reason}, Db) -> {stop, Reason, Db}. code_change(_OldVsn, State, _Extra) -> {ok, State}. merge_updates([], RestB, AccOutGroups) -> lists:reverse(AccOutGroups, RestB); merge_updates(RestA, [], AccOutGroups) -> lists:reverse(AccOutGroups, RestA); merge_updates([[{_, {#doc{id=IdA}, _}}|_]=GroupA | RestA], [[{_, {#doc{id=IdB}, _}}|_]=GroupB | RestB], AccOutGroups) -> if IdA == IdB -> merge_updates(RestA, RestB, [GroupA ++ GroupB | AccOutGroups]); IdA < IdB -> merge_updates(RestA, [GroupB | RestB], [GroupA | AccOutGroups]); true -> merge_updates([GroupA | RestA], RestB, [GroupB | AccOutGroups]) end. collect_updates(GroupedDocsAcc, ClientsAcc, MergeConflicts, FullCommit) -> receive % Only collect updates with the same MergeConflicts flag and without % local docs. It's easier to just avoid multiple _local doc % updaters than deal with their possible conflicts, and local docs % writes are relatively rare. Can be optmized later if really needed. {update_docs, Client, GroupedDocs, [], MergeConflicts, FullCommit2} -> GroupedDocs2 = [[{Client, Doc} || Doc <- DocGroup] || DocGroup <- GroupedDocs], GroupedDocsAcc2 = merge_updates(GroupedDocsAcc, GroupedDocs2, []), collect_updates(GroupedDocsAcc2, [Client | ClientsAcc], MergeConflicts, (FullCommit or FullCommit2)) after 0 -> {GroupedDocsAcc, ClientsAcc, FullCommit} end. btree_by_seq_split(#doc_info{id=Id, high_seq=KeySeq, revs=Revs}) -> {RevInfos, DeletedRevInfos} = lists:foldl( fun(#rev_info{deleted = false, seq = Seq} = Ri, {Acc, AccDel}) -> {[{Ri#rev_info.rev, Seq, Ri#rev_info.body_sp} | Acc], AccDel}; (#rev_info{deleted = true, seq = Seq} = Ri, {Acc, AccDel}) -> {Acc, [{Ri#rev_info.rev, Seq, Ri#rev_info.body_sp} | AccDel]} end, {[], []}, Revs), {KeySeq, {Id, lists:reverse(RevInfos), lists:reverse(DeletedRevInfos)}}. btree_by_seq_join(KeySeq, {Id, RevInfos, DeletedRevInfos}) -> #doc_info{ id = Id, high_seq=KeySeq, revs = [#rev_info{rev=Rev,seq=Seq,deleted=false,body_sp = Bp} || {Rev, Seq, Bp} <- RevInfos] ++ [#rev_info{rev=Rev,seq=Seq,deleted=true,body_sp = Bp} || {Rev, Seq, Bp} <- DeletedRevInfos]}. btree_by_id_split(#full_doc_info{id=Id, update_seq=Seq, deleted=Deleted, rev_tree=Tree}) -> DiskTree = couch_key_tree:map( fun(_RevId, ?REV_MISSING) -> ?REV_MISSING; (_RevId, RevValue) -> IsDeleted = element(1, RevValue), BodyPointer = element(2, RevValue), UpdateSeq = element(3, RevValue), Size = case tuple_size(RevValue) of 4 -> element(4, RevValue); 3 -> % pre 1.2 format, will be upgraded on compaction nil end, {if IsDeleted -> 1; true -> 0 end, BodyPointer, UpdateSeq, Size} end, Tree), {Id, {Seq, if Deleted -> 1; true -> 0 end, DiskTree}}. btree_by_id_join(Id, {HighSeq, Deleted, DiskTree}) -> {Tree, LeafsSize} = couch_key_tree:mapfold( fun(_RevId, {IsDeleted, BodyPointer, UpdateSeq}, leaf, _Acc) -> % pre 1.2 format, will be upgraded on compaction {{IsDeleted == 1, BodyPointer, UpdateSeq, nil}, nil}; (_RevId, {IsDeleted, BodyPointer, UpdateSeq}, branch, Acc) -> {{IsDeleted == 1, BodyPointer, UpdateSeq, nil}, Acc}; (_RevId, {IsDeleted, BodyPointer, UpdateSeq, Size}, leaf, Acc) -> Acc2 = sum_leaf_sizes(Acc, Size), {{IsDeleted == 1, BodyPointer, UpdateSeq, Size}, Acc2}; (_RevId, {IsDeleted, BodyPointer, UpdateSeq, Size}, branch, Acc) -> {{IsDeleted == 1, BodyPointer, UpdateSeq, Size}, Acc}; (_RevId, ?REV_MISSING, _Type, Acc) -> {?REV_MISSING, Acc} end, 0, DiskTree), #full_doc_info{ id = Id, update_seq = HighSeq, deleted = (Deleted == 1), rev_tree = Tree, leafs_size = LeafsSize }. btree_by_id_reduce(reduce, FullDocInfos) -> lists:foldl( fun(Info, {NotDeleted, Deleted, Size}) -> Size2 = sum_leaf_sizes(Size, Info#full_doc_info.leafs_size), case Info#full_doc_info.deleted of true -> {NotDeleted, Deleted + 1, Size2}; false -> {NotDeleted + 1, Deleted, Size2} end end, {0, 0, 0}, FullDocInfos); btree_by_id_reduce(rereduce, Reds) -> lists:foldl( fun({NotDeleted, Deleted}, {AccNotDeleted, AccDeleted, _AccSize}) -> % pre 1.2 format, will be upgraded on compaction {AccNotDeleted + NotDeleted, AccDeleted + Deleted, nil}; ({NotDeleted, Deleted, Size}, {AccNotDeleted, AccDeleted, AccSize}) -> AccSize2 = sum_leaf_sizes(AccSize, Size), {AccNotDeleted + NotDeleted, AccDeleted + Deleted, AccSize2} end, {0, 0, 0}, Reds). sum_leaf_sizes(nil, _) -> nil; sum_leaf_sizes(_, nil) -> nil; sum_leaf_sizes(Size1, Size2) -> Size1 + Size2. btree_by_seq_reduce(reduce, DocInfos) -> % count the number of documents length(DocInfos); btree_by_seq_reduce(rereduce, Reds) -> lists:sum(Reds). simple_upgrade_record(Old, New) when tuple_size(Old) < tuple_size(New) -> OldSz = tuple_size(Old), NewValuesTail = lists:sublist(tuple_to_list(New), OldSz + 1, tuple_size(New) - OldSz), list_to_tuple(tuple_to_list(Old) ++ NewValuesTail); simple_upgrade_record(Old, _New) -> Old. -define(OLD_DISK_VERSION_ERROR, "Database files from versions smaller than 0.10.0 are no longer supported"). init_db(DbName, Filepath, Fd, ReaderFd, Header0, Options) -> Header1 = simple_upgrade_record(Header0, #db_header{}), Header = case element(2, Header1) of 1 -> throw({database_disk_version_error, ?OLD_DISK_VERSION_ERROR}); 2 -> throw({database_disk_version_error, ?OLD_DISK_VERSION_ERROR}); 3 -> throw({database_disk_version_error, ?OLD_DISK_VERSION_ERROR}); 4 -> Header1#db_header{security_ptr = nil}; % 0.10 and pre 0.11 5 -> Header1; % pre 1.2 ?LATEST_DISK_VERSION -> Header1; _ -> throw({database_disk_version_error, "Incorrect disk header version"}) end, {ok, FsyncOptions} = couch_util:parse_term( couch_config:get("couchdb", "fsync_options", "[before_header, after_header, on_file_open]")), case lists:member(on_file_open, FsyncOptions) of true -> ok = couch_file:sync(Fd); _ -> ok end, Compression = couch_compress:get_compression_method(), {ok, IdBtree} = couch_btree:open(Header#db_header.fulldocinfo_by_id_btree_state, Fd, [{split, fun(X) -> btree_by_id_split(X) end}, {join, fun(X,Y) -> btree_by_id_join(X,Y) end}, {reduce, fun(X,Y) -> btree_by_id_reduce(X,Y) end}, {compression, Compression}]), {ok, SeqBtree} = couch_btree:open(Header#db_header.docinfo_by_seq_btree_state, Fd, [{split, fun(X) -> btree_by_seq_split(X) end}, {join, fun(X,Y) -> btree_by_seq_join(X,Y) end}, {reduce, fun(X,Y) -> btree_by_seq_reduce(X,Y) end}, {compression, Compression}]), {ok, LocalDocsBtree} = couch_btree:open(Header#db_header.local_docs_btree_state, Fd, [{compression, Compression}]), case Header#db_header.security_ptr of nil -> Security = [], SecurityPtr = nil; SecurityPtr -> {ok, Security} = couch_file:pread_term(Fd, SecurityPtr) end, % convert start time tuple to microsecs and store as a binary string {MegaSecs, Secs, MicroSecs} = now(), StartTime = ?l2b(io_lib:format("~p", [(MegaSecs*1000000*1000000) + (Secs*1000000) + MicroSecs])), {ok, RefCntr} = couch_ref_counter:start([Fd, ReaderFd]), #db{ update_pid=self(), fd = ReaderFd, updater_fd = Fd, fd_ref_counter = RefCntr, header=Header, fulldocinfo_by_id_btree = IdBtree, docinfo_by_seq_btree = SeqBtree, local_docs_btree = LocalDocsBtree, committed_update_seq = Header#db_header.update_seq, update_seq = Header#db_header.update_seq, name = DbName, filepath = Filepath, security = Security, security_ptr = SecurityPtr, instance_start_time = StartTime, revs_limit = Header#db_header.revs_limit, fsync_options = FsyncOptions, options = Options, compression = Compression, before_doc_update = couch_util:get_value(before_doc_update, Options, nil), after_doc_read = couch_util:get_value(after_doc_read, Options, nil) }. open_reader_fd(Filepath, Options) -> {ok, Fd} = case lists:member(sys_db, Options) of true -> couch_file:open(Filepath, [read_only, sys_db]); false -> couch_file:open(Filepath, [read_only]) end, unlink(Fd), Fd. close_db(#db{fd_ref_counter = RefCntr}) -> couch_ref_counter:drop(RefCntr). refresh_validate_doc_funs(Db0) -> Db = Db0#db{user_ctx = #user_ctx{roles=[<<"_admin">>]}}, DesignDocs = couch_db:get_design_docs(Db), ProcessDocFuns = lists:flatmap( fun(DesignDocInfo) -> {ok, DesignDoc} = couch_db:open_doc_int( Db, DesignDocInfo, [ejson_body]), case couch_doc:get_validate_doc_fun(DesignDoc) of nil -> []; Fun -> [Fun] end end, DesignDocs), Db0#db{validate_doc_funs=ProcessDocFuns}. % rev tree functions flush_trees(_Db, [], AccFlushedTrees) -> {ok, lists:reverse(AccFlushedTrees)}; flush_trees(#db{updater_fd = Fd} = Db, [InfoUnflushed | RestUnflushed], AccFlushed) -> #full_doc_info{update_seq=UpdateSeq, rev_tree=Unflushed} = InfoUnflushed, {Flushed, LeafsSize} = couch_key_tree:mapfold( fun(_Rev, Value, Type, Acc) -> case Value of #doc{deleted = IsDeleted, body = {summary, Summary, AttsFd}} -> % this node value is actually an unwritten document summary, % write to disk. % make sure the Fd in the written bins is the same Fd we are % and convert bins, removing the FD. % All bins should have been written to disk already. case {AttsFd, Fd} of {nil, _} -> ok; {SameFd, SameFd} -> ok; _ -> % Fd where the attachments were written to is not the same % as our Fd. This can happen when a database is being % switched out during a compaction. ?LOG_DEBUG("File where the attachments are written has" " changed. Possibly retrying.", []), throw(retry) end, {ok, NewSummaryPointer, SummarySize} = couch_file:append_raw_chunk(Fd, Summary), TotalSize = lists:foldl( fun(#att{att_len = L}, A) -> A + L end, SummarySize, Value#doc.atts), NewValue = {IsDeleted, NewSummaryPointer, UpdateSeq, TotalSize}, case Type of leaf -> {NewValue, Acc + TotalSize}; branch -> {NewValue, Acc} end; {_, _, _, LeafSize} when Type =:= leaf, LeafSize =/= nil -> {Value, Acc + LeafSize}; _ -> {Value, Acc} end end, 0, Unflushed), InfoFlushed = InfoUnflushed#full_doc_info{ rev_tree = Flushed, leafs_size = LeafsSize }, flush_trees(Db, RestUnflushed, [InfoFlushed | AccFlushed]). send_result(Client, Ref, NewResult) -> % used to send a result to the client catch(Client ! {result, self(), {Ref, NewResult}}). merge_rev_trees(_Limit, _Merge, [], [], AccNewInfos, AccRemoveSeqs, AccSeq) -> {ok, lists:reverse(AccNewInfos), AccRemoveSeqs, AccSeq}; merge_rev_trees(Limit, MergeConflicts, [NewDocs|RestDocsList], [OldDocInfo|RestOldInfo], AccNewInfos, AccRemoveSeqs, AccSeq) -> #full_doc_info{id=Id,rev_tree=OldTree,deleted=OldDeleted0,update_seq=OldSeq} = OldDocInfo, {NewRevTree, _} = lists:foldl( fun({Client, {#doc{revs={Pos,[_Rev|PrevRevs]}}=NewDoc, Ref}}, {AccTree, OldDeleted}) -> if not MergeConflicts -> case couch_key_tree:merge(AccTree, couch_doc:to_path(NewDoc), Limit) of {_NewTree, conflicts} when (not OldDeleted) -> send_result(Client, Ref, conflict), {AccTree, OldDeleted}; {NewTree, conflicts} when PrevRevs /= [] -> % Check to be sure if prev revision was specified, it's % a leaf node in the tree Leafs = couch_key_tree:get_all_leafs(AccTree), IsPrevLeaf = lists:any(fun({_, {LeafPos, [LeafRevId|_]}}) -> {LeafPos, LeafRevId} == {Pos-1, hd(PrevRevs)} end, Leafs), if IsPrevLeaf -> {NewTree, OldDeleted}; true -> send_result(Client, Ref, conflict), {AccTree, OldDeleted} end; {NewTree, no_conflicts} when AccTree == NewTree -> % the tree didn't change at all % meaning we are saving a rev that's already % been editted again. if (Pos == 1) and OldDeleted -> % this means we are recreating a brand new document % into a state that already existed before. % put the rev into a subsequent edit of the deletion #doc_info{revs=[#rev_info{rev={OldPos,OldRev}}|_]} = couch_doc:to_doc_info(OldDocInfo), NewRevId = couch_db:new_revid( NewDoc#doc{revs={OldPos, [OldRev]}}), NewDoc2 = NewDoc#doc{revs={OldPos + 1, [NewRevId, OldRev]}}, {NewTree2, _} = couch_key_tree:merge(AccTree, couch_doc:to_path(NewDoc2), Limit), % we changed the rev id, this tells the caller we did send_result(Client, Ref, {ok, {OldPos + 1, NewRevId}}), {NewTree2, OldDeleted}; true -> send_result(Client, Ref, conflict), {AccTree, OldDeleted} end; {NewTree, _} -> {NewTree, NewDoc#doc.deleted} end; true -> {NewTree, _} = couch_key_tree:merge(AccTree, couch_doc:to_path(NewDoc), Limit), {NewTree, OldDeleted} end end, {OldTree, OldDeleted0}, NewDocs), if NewRevTree == OldTree -> % nothing changed merge_rev_trees(Limit, MergeConflicts, RestDocsList, RestOldInfo, AccNewInfos, AccRemoveSeqs, AccSeq); true -> % we have updated the document, give it a new seq # NewInfo = #full_doc_info{id=Id,update_seq=AccSeq+1,rev_tree=NewRevTree}, RemoveSeqs = case OldSeq of 0 -> AccRemoveSeqs; _ -> [OldSeq | AccRemoveSeqs] end, merge_rev_trees(Limit, MergeConflicts, RestDocsList, RestOldInfo, [NewInfo|AccNewInfos], RemoveSeqs, AccSeq+1) end. new_index_entries([], AccById, AccBySeq, AccDDocIds) -> {AccById, AccBySeq, AccDDocIds}; new_index_entries([FullDocInfo|RestInfos], AccById, AccBySeq, AccDDocIds) -> #doc_info{revs=[#rev_info{deleted=Deleted}|_], id=Id} = DocInfo = couch_doc:to_doc_info(FullDocInfo), AccDDocIds2 = case Id of <> -> [Id | AccDDocIds]; _ -> AccDDocIds end, new_index_entries(RestInfos, [FullDocInfo#full_doc_info{deleted=Deleted}|AccById], [DocInfo|AccBySeq], AccDDocIds2). stem_full_doc_infos(#db{revs_limit=Limit}, DocInfos) -> [Info#full_doc_info{rev_tree=couch_key_tree:stem(Tree, Limit)} || #full_doc_info{rev_tree=Tree}=Info <- DocInfos]. update_docs_int(Db, DocsList, NonRepDocs, MergeConflicts, FullCommit) -> #db{ fulldocinfo_by_id_btree = DocInfoByIdBTree, docinfo_by_seq_btree = DocInfoBySeqBTree, update_seq = LastSeq, revs_limit = RevsLimit } = Db, Ids = [Id || [{_Client, {#doc{id=Id}, _Ref}}|_] <- DocsList], % lookup up the old documents, if they exist. OldDocLookups = couch_btree:lookup(DocInfoByIdBTree, Ids), OldDocInfos = lists:zipwith( fun(_Id, {ok, FullDocInfo}) -> FullDocInfo; (Id, not_found) -> #full_doc_info{id=Id} end, Ids, OldDocLookups), % Merge the new docs into the revision trees. {ok, NewFullDocInfos, RemoveSeqs, NewSeq} = merge_rev_trees(RevsLimit, MergeConflicts, DocsList, OldDocInfos, [], [], LastSeq), % All documents are now ready to write. {ok, Db2} = update_local_docs(Db, NonRepDocs), % Write out the document summaries (the bodies are stored in the nodes of % the trees, the attachments are already written to disk) {ok, FlushedFullDocInfos} = flush_trees(Db2, NewFullDocInfos, []), {IndexFullDocInfos, IndexDocInfos, UpdatedDDocIds} = new_index_entries(FlushedFullDocInfos, [], [], []), % and the indexes {ok, DocInfoByIdBTree2} = couch_btree:add_remove(DocInfoByIdBTree, IndexFullDocInfos, []), {ok, DocInfoBySeqBTree2} = couch_btree:add_remove(DocInfoBySeqBTree, IndexDocInfos, RemoveSeqs), Db3 = Db2#db{ fulldocinfo_by_id_btree = DocInfoByIdBTree2, docinfo_by_seq_btree = DocInfoBySeqBTree2, update_seq = NewSeq}, % Check if we just updated any design documents, and update the validation % funs if we did. Db4 = case UpdatedDDocIds of [] -> Db3; _ -> refresh_validate_doc_funs(Db3) end, {ok, commit_data(Db4, not FullCommit), UpdatedDDocIds}. update_local_docs(Db, []) -> {ok, Db}; update_local_docs(#db{local_docs_btree=Btree}=Db, Docs) -> Ids = [Id || {_Client, {#doc{id=Id}, _Ref}} <- Docs], OldDocLookups = couch_btree:lookup(Btree, Ids), BtreeEntries = lists:zipwith( fun({Client, {#doc{id=Id,deleted=Delete,revs={0,PrevRevs},body=Body}, Ref}}, OldDocLookup) -> case PrevRevs of [RevStr|_] -> PrevRev = list_to_integer(?b2l(RevStr)); [] -> PrevRev = 0 end, OldRev = case OldDocLookup of {ok, {_, {OldRev0, _}}} -> OldRev0; not_found -> 0 end, case OldRev == PrevRev of true -> case Delete of false -> send_result(Client, Ref, {ok, {0, ?l2b(integer_to_list(PrevRev + 1))}}), {update, {Id, {PrevRev + 1, Body}}}; true -> send_result(Client, Ref, {ok, {0, <<"0">>}}), {remove, Id} end; false -> send_result(Client, Ref, conflict), ignore end end, Docs, OldDocLookups), BtreeIdsRemove = [Id || {remove, Id} <- BtreeEntries], BtreeIdsUpdate = [{Key, Val} || {update, {Key, Val}} <- BtreeEntries], {ok, Btree2} = couch_btree:add_remove(Btree, BtreeIdsUpdate, BtreeIdsRemove), {ok, Db#db{local_docs_btree = Btree2}}. commit_data(Db) -> commit_data(Db, false). db_to_header(Db, Header) -> Header#db_header{ update_seq = Db#db.update_seq, docinfo_by_seq_btree_state = couch_btree:get_state(Db#db.docinfo_by_seq_btree), fulldocinfo_by_id_btree_state = couch_btree:get_state(Db#db.fulldocinfo_by_id_btree), local_docs_btree_state = couch_btree:get_state(Db#db.local_docs_btree), security_ptr = Db#db.security_ptr, revs_limit = Db#db.revs_limit}. commit_data(#db{waiting_delayed_commit=nil} = Db, true) -> Db#db{waiting_delayed_commit=erlang:send_after(1000,self(),delayed_commit)}; commit_data(Db, true) -> Db; commit_data(Db, _) -> #db{ updater_fd = Fd, filepath = Filepath, header = OldHeader, fsync_options = FsyncOptions, waiting_delayed_commit = Timer } = Db, if is_reference(Timer) -> erlang:cancel_timer(Timer); true -> ok end, case db_to_header(Db, OldHeader) of OldHeader -> Db#db{waiting_delayed_commit=nil}; Header -> case lists:member(before_header, FsyncOptions) of true -> ok = couch_file:sync(Filepath); _ -> ok end, ok = couch_file:write_header(Fd, Header), case lists:member(after_header, FsyncOptions) of true -> ok = couch_file:sync(Filepath); _ -> ok end, Db#db{waiting_delayed_commit=nil, header=Header, committed_update_seq=Db#db.update_seq} end. copy_doc_attachments(#db{updater_fd = SrcFd} = SrcDb, SrcSp, DestFd) -> {ok, {BodyData, BinInfos0}} = couch_db:read_doc(SrcDb, SrcSp), BinInfos = case BinInfos0 of _ when is_binary(BinInfos0) -> couch_compress:decompress(BinInfos0); _ when is_list(BinInfos0) -> % pre 1.2 file format BinInfos0 end, % copy the bin values NewBinInfos = lists:map( fun({Name, Type, BinSp, AttLen, RevPos, Md5}) -> % 010 UPGRADE CODE {NewBinSp, AttLen, AttLen, Md5, _IdentityMd5} = couch_stream:copy_to_new_stream(SrcFd, BinSp, DestFd), {Name, Type, NewBinSp, AttLen, AttLen, RevPos, Md5, identity}; ({Name, Type, BinSp, AttLen, DiskLen, RevPos, Md5, Enc1}) -> {NewBinSp, AttLen, _, Md5, _IdentityMd5} = couch_stream:copy_to_new_stream(SrcFd, BinSp, DestFd), Enc = case Enc1 of true -> % 0110 UPGRADE CODE gzip; false -> % 0110 UPGRADE CODE identity; _ -> Enc1 end, {Name, Type, NewBinSp, AttLen, DiskLen, RevPos, Md5, Enc} end, BinInfos), {BodyData, NewBinInfos}. copy_docs(Db, #db{updater_fd = DestFd} = NewDb, InfoBySeq0, Retry) -> % COUCHDB-968, make sure we prune duplicates during compaction InfoBySeq = lists:usort(fun(#doc_info{id=A}, #doc_info{id=B}) -> A =< B end, InfoBySeq0), Ids = [Id || #doc_info{id=Id} <- InfoBySeq], LookupResults = couch_btree:lookup(Db#db.fulldocinfo_by_id_btree, Ids), NewFullDocInfos1 = lists:map( fun({ok, #full_doc_info{rev_tree=RevTree}=Info}) -> Info#full_doc_info{rev_tree=couch_key_tree:map( fun(_, _, branch) -> ?REV_MISSING; (_Rev, LeafVal, leaf) -> IsDel = element(1, LeafVal), Sp = element(2, LeafVal), Seq = element(3, LeafVal), {_Body, AttsInfo} = Summary = copy_doc_attachments( Db, Sp, DestFd), SummaryChunk = make_doc_summary(NewDb, Summary), {ok, Pos, SummarySize} = couch_file:append_raw_chunk( DestFd, SummaryChunk), TotalLeafSize = lists:foldl( fun({_, _, _, AttLen, _, _, _, _}, S) -> S + AttLen end, SummarySize, AttsInfo), {IsDel, Pos, Seq, TotalLeafSize} end, RevTree)} end, LookupResults), NewFullDocInfos = stem_full_doc_infos(Db, NewFullDocInfos1), NewDocInfos = [couch_doc:to_doc_info(Info) || Info <- NewFullDocInfos], RemoveSeqs = case Retry of false -> []; true -> % We are retrying a compaction, meaning the documents we are copying may % already exist in our file and must be removed from the by_seq index. Existing = couch_btree:lookup(NewDb#db.fulldocinfo_by_id_btree, Ids), [Seq || {ok, #full_doc_info{update_seq=Seq}} <- Existing] end, {ok, DocInfoBTree} = couch_btree:add_remove( NewDb#db.docinfo_by_seq_btree, NewDocInfos, RemoveSeqs), {ok, FullDocInfoBTree} = couch_btree:add_remove( NewDb#db.fulldocinfo_by_id_btree, NewFullDocInfos, []), update_compact_task(length(NewFullDocInfos)), NewDb#db{ fulldocinfo_by_id_btree=FullDocInfoBTree, docinfo_by_seq_btree=DocInfoBTree}. copy_compact(Db, NewDb0, Retry) -> FsyncOptions = [Op || Op <- NewDb0#db.fsync_options, Op == before_header], Compression = couch_compress:get_compression_method(), NewDb = NewDb0#db{fsync_options=FsyncOptions, compression=Compression}, TotalChanges = couch_db:count_changes_since(Db, NewDb#db.update_seq), BufferSize = list_to_integer( couch_config:get("database_compaction", "doc_buffer_size", "524288")), CheckpointAfter = couch_util:to_integer( couch_config:get("database_compaction", "checkpoint_after", BufferSize * 10)), EnumBySeqFun = fun(#doc_info{high_seq=Seq}=DocInfo, _Offset, {AccNewDb, AccUncopied, AccUncopiedSize, AccCopiedSize}) -> AccUncopiedSize2 = AccUncopiedSize + ?term_size(DocInfo), if AccUncopiedSize2 >= BufferSize -> NewDb2 = copy_docs( Db, AccNewDb, lists:reverse([DocInfo | AccUncopied]), Retry), AccCopiedSize2 = AccCopiedSize + AccUncopiedSize2, if AccCopiedSize2 >= CheckpointAfter -> {ok, {commit_data(NewDb2#db{update_seq = Seq}), [], 0, 0}}; true -> {ok, {NewDb2#db{update_seq = Seq}, [], 0, AccCopiedSize2}} end; true -> {ok, {AccNewDb, [DocInfo | AccUncopied], AccUncopiedSize2, AccCopiedSize}} end end, TaskProps0 = [ {type, database_compaction}, {database, Db#db.name}, {progress, 0}, {changes_done, 0}, {total_changes, TotalChanges} ], case Retry and couch_task_status:is_task_added() of true -> couch_task_status:update([ {retry, true}, {progress, 0}, {changes_done, 0}, {total_changes, TotalChanges} ]); false -> couch_task_status:add_task(TaskProps0), couch_task_status:set_update_frequency(500) end, {ok, _, {NewDb2, Uncopied, _, _}} = couch_btree:foldl(Db#db.docinfo_by_seq_btree, EnumBySeqFun, {NewDb, [], 0, 0}, [{start_key, NewDb#db.update_seq + 1}]), NewDb3 = copy_docs(Db, NewDb2, lists:reverse(Uncopied), Retry), % copy misc header values if NewDb3#db.security /= Db#db.security -> {ok, Ptr, _} = couch_file:append_term( NewDb3#db.updater_fd, Db#db.security, [{compression, NewDb3#db.compression}]), NewDb4 = NewDb3#db{security=Db#db.security, security_ptr=Ptr}; true -> NewDb4 = NewDb3 end, commit_data(NewDb4#db{update_seq=Db#db.update_seq}). start_copy_compact(#db{name=Name,filepath=Filepath,header=#db_header{purge_seq=PurgeSeq}}=Db) -> CompactFile = Filepath ++ ".compact", ?LOG_DEBUG("Compaction process spawned for db \"~s\"", [Name]), case couch_file:open(CompactFile, [nologifmissing]) of {ok, Fd} -> Retry = true, case couch_file:read_header(Fd) of {ok, Header} -> ok; no_valid_header -> ok = couch_file:write_header(Fd, Header=#db_header{}) end; {error, enoent} -> {ok, Fd} = couch_file:open(CompactFile, [create]), Retry = false, ok = couch_file:write_header(Fd, Header=#db_header{}) end, ReaderFd = open_reader_fd(CompactFile, Db#db.options), NewDb = init_db(Name, CompactFile, Fd, ReaderFd, Header, Db#db.options), NewDb2 = if PurgeSeq > 0 -> {ok, PurgedIdsRevs} = couch_db:get_last_purged(Db), {ok, Pointer, _} = couch_file:append_term( Fd, PurgedIdsRevs, [{compression, NewDb#db.compression}]), NewDb#db{header=Header#db_header{purge_seq=PurgeSeq, purged_docs=Pointer}}; true -> NewDb end, unlink(Fd), NewDb3 = copy_compact(Db, NewDb2, Retry), close_db(NewDb3), case gen_server:call( Db#db.update_pid, {compact_done, CompactFile}, infinity) of ok -> ok; {retry, CurrentDb} -> start_copy_compact(CurrentDb) end. update_compact_task(NumChanges) -> [Changes, Total] = couch_task_status:get([changes_done, total_changes]), Changes2 = Changes + NumChanges, Progress = case Total of 0 -> 0; _ -> (Changes2 * 100) div Total end, couch_task_status:update([{changes_done, Changes2}, {progress, Progress}]). make_doc_summary(#db{compression = Comp}, {Body0, Atts0}) -> Body = case couch_compress:is_compressed(Body0, Comp) of true -> Body0; false -> % pre 1.2 database file format couch_compress:compress(Body0, Comp) end, Atts = case couch_compress:is_compressed(Atts0, Comp) of true -> Atts0; false -> couch_compress:compress(Atts0, Comp) end, SummaryBin = ?term_to_bin({Body, Atts}), couch_file:assemble_file_chunk(SummaryBin, couch_util:md5(SummaryBin)). apache-couchdb-1.5.0/src/couchdb/couch_httpd_vhost.erl0000644000175000001440000002772012230722213017713 00000000000000% 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. -module(couch_httpd_vhost). -behaviour(gen_server). -export([start_link/0, config_change/2, reload/0, get_state/0, dispatch_host/1]). -export([urlsplit_netloc/2, redirect_to_vhost/2]). -export([host/1, split_host_port/1]). -export([init/1, handle_call/3, handle_cast/2, handle_info/2, terminate/2, code_change/3]). -include("couch_db.hrl"). -define(SEPARATOR, $\/). -define(MATCH_ALL, {bind, '*'}). -record(vhosts_state, { vhosts, vhost_globals, vhosts_fun}). %% doc the vhost manager. %% This gen_server keep state of vhosts added to the ini and try to %% match the Host header (or forwarded) against rules built against %% vhost list. %% %% Declaration of vhosts take place in the configuration file : %% %% [vhosts] %% example.com = /example %% *.example.com = /example %% %% The first line will rewrite the rquest to display the content of the %% example database. This rule works only if the Host header is %% 'example.com' and won't work for CNAMEs. Second rule on the other hand %% match all CNAMES to example db. So www.example.com or db.example.com %% will work. %% %% The wildcard ('*') should always be the last in the cnames: %% %% "*.db.example.com = /" will match all cname on top of db %% examples to the root of the machine. %% %% %% Rewriting Hosts to path %% ----------------------- %% %% Like in the _rewrite handler you could match some variable and use %them to create the target path. Some examples: %% %% [vhosts] %% *.example.com = /* %% :dbname.example.com = /:dbname %% :ddocname.:dbname.example.com = /:dbname/_design/:ddocname/_rewrite %% %% First rule pass wildcard as dbname, second do the same but use a %% variable name and the third one allows you to use any app with %% @ddocname in any db with @dbname . %% %% You could also change the default function to handle request by %% changing the setting `redirect_vhost_handler` in `httpd` section of %% the Ini: %% %% [httpd] %% redirect_vhost_handler = {Module, Fun} %% %% The function take 2 args : the mochiweb request object and the target %%% path. start_link() -> gen_server:start_link({local, ?MODULE}, ?MODULE, [], []). %% @doc reload vhosts rules reload() -> gen_server:call(?MODULE, reload). get_state() -> gen_server:call(?MODULE, get_state). %% @doc Try to find a rule matching current Host heade. some rule is %% found it rewrite the Mochiweb Request else it return current Request. dispatch_host(MochiReq) -> #vhosts_state{ vhost_globals = VHostGlobals, vhosts = VHosts, vhosts_fun=Fun} = get_state(), {"/" ++ VPath, Query, Fragment} = mochiweb_util:urlsplit_path(MochiReq:get(raw_path)), VPathParts = string:tokens(VPath, "/"), VHost = host(MochiReq), {VHostParts, VhostPort} = split_host_port(VHost), FinalMochiReq = case try_bind_vhost(VHosts, lists:reverse(VHostParts), VhostPort, VPathParts) of no_vhost_matched -> MochiReq; {VhostTarget, NewPath} -> case vhost_global(VHostGlobals, MochiReq) of true -> MochiReq; _Else -> NewPath1 = mochiweb_util:urlunsplit_path({NewPath, Query, Fragment}), MochiReq1 = mochiweb_request:new(MochiReq:get(socket), MochiReq:get(method), NewPath1, MochiReq:get(version), MochiReq:get(headers)), Fun(MochiReq1, VhostTarget) end end, FinalMochiReq. append_path("/"=_Target, "/"=_Path) -> "/"; append_path(Target, Path) -> Target ++ Path. % default redirect vhost handler redirect_to_vhost(MochiReq, VhostTarget) -> Path = MochiReq:get(raw_path), Target = append_path(VhostTarget, Path), ?LOG_DEBUG("Vhost Target: '~p'~n", [Target]), Headers = mochiweb_headers:enter("x-couchdb-vhost-path", Path, MochiReq:get(headers)), % build a new mochiweb request MochiReq1 = mochiweb_request:new(MochiReq:get(socket), MochiReq:get(method), Target, MochiReq:get(version), Headers), % cleanup, It force mochiweb to reparse raw uri. MochiReq1:cleanup(), MochiReq1. %% if so, then it will not be rewritten, but will run as a normal couchdb request. %* normally you'd use this for _uuids _utils and a few of the others you want to %% keep available on vhosts. You can also use it to make databases 'global'. vhost_global( VhostGlobals, MochiReq) -> RawUri = MochiReq:get(raw_path), {"/" ++ Path, _, _} = mochiweb_util:urlsplit_path(RawUri), Front = case couch_httpd:partition(Path) of {"", "", ""} -> "/"; % Special case the root url handler {FirstPart, _, _} -> FirstPart end, [true] == [true||V <- VhostGlobals, V == Front]. %% bind host %% first it try to bind the port then the hostname. try_bind_vhost([], _HostParts, _Port, _PathParts) -> no_vhost_matched; try_bind_vhost([VhostSpec|Rest], HostParts, Port, PathParts) -> {{VHostParts, VPort, VPath}, Path} = VhostSpec, case bind_port(VPort, Port) of ok -> case bind_vhost(lists:reverse(VHostParts), HostParts, []) of {ok, Bindings, Remainings} -> case bind_path(VPath, PathParts) of {ok, PathParts1} -> Path1 = make_target(Path, Bindings, Remainings, []), {make_path(Path1), make_path(PathParts1)}; fail -> try_bind_vhost(Rest, HostParts, Port, PathParts) end; fail -> try_bind_vhost(Rest, HostParts, Port, PathParts) end; fail -> try_bind_vhost(Rest, HostParts, Port, PathParts) end. %% doc: build new patch from bindings. bindings are query args %% (+ dynamic query rewritten if needed) and bindings found in %% bind_path step. %% TODO: merge code with rewrite. But we need to make sure we are %% in string here. make_target([], _Bindings, _Remaining, Acc) -> lists:reverse(Acc); make_target([?MATCH_ALL], _Bindings, Remaining, Acc) -> Acc1 = lists:reverse(Acc) ++ Remaining, Acc1; make_target([?MATCH_ALL|_Rest], _Bindings, Remaining, Acc) -> Acc1 = lists:reverse(Acc) ++ Remaining, Acc1; make_target([{bind, P}|Rest], Bindings, Remaining, Acc) -> P2 = case couch_util:get_value({bind, P}, Bindings) of undefined -> "undefined"; P1 -> P1 end, make_target(Rest, Bindings, Remaining, [P2|Acc]); make_target([P|Rest], Bindings, Remaining, Acc) -> make_target(Rest, Bindings, Remaining, [P|Acc]). %% bind port bind_port(Port, Port) -> ok; bind_port('*', _) -> ok; bind_port(_,_) -> fail. %% bind bhost bind_vhost([],[], Bindings) -> {ok, Bindings, []}; bind_vhost([?MATCH_ALL], [], _Bindings) -> fail; bind_vhost([?MATCH_ALL], Rest, Bindings) -> {ok, Bindings, Rest}; bind_vhost([], _HostParts, _Bindings) -> fail; bind_vhost([{bind, Token}|Rest], [Match|RestHost], Bindings) -> bind_vhost(Rest, RestHost, [{{bind, Token}, Match}|Bindings]); bind_vhost([Cname|Rest], [Cname|RestHost], Bindings) -> bind_vhost(Rest, RestHost, Bindings); bind_vhost(_, _, _) -> fail. %% bind path bind_path([], PathParts) -> {ok, PathParts}; bind_path(_VPathParts, []) -> fail; bind_path([Path|VRest],[Path|Rest]) -> bind_path(VRest, Rest); bind_path(_, _) -> fail. % utilities %% create vhost list from ini host(MochiReq) -> XHost = couch_config:get("httpd", "x_forwarded_host", "X-Forwarded-Host"), case MochiReq:get_header_value(XHost) of undefined -> case MochiReq:get_header_value("Host") of undefined -> []; Value1 -> Value1 end; Value -> Value end. make_vhosts() -> Vhosts = lists:foldl(fun ({_, ""}, Acc) -> Acc; ({Vhost, Path}, Acc) -> [{parse_vhost(Vhost), split_path(Path)}|Acc] end, [], couch_config:get("vhosts")), lists:reverse(lists:usort(Vhosts)). parse_vhost(Vhost) -> case urlsplit_netloc(Vhost, []) of {[], Path} -> {make_spec("*", []), '*', Path}; {HostPort, []} -> {H, P} = split_host_port(HostPort), H1 = make_spec(H, []), {H1, P, []}; {HostPort, Path} -> {H, P} = split_host_port(HostPort), H1 = make_spec(H, []), {H1, P, string:tokens(Path, "/")} end. split_host_port(HostAsString) -> case string:rchr(HostAsString, $:) of 0 -> {split_host(HostAsString), '*'}; N -> HostPart = string:substr(HostAsString, 1, N-1), case (catch erlang:list_to_integer(string:substr(HostAsString, N+1, length(HostAsString)))) of {'EXIT', _} -> {split_host(HostAsString), '*'}; Port -> {split_host(HostPart), Port} end end. split_host(HostAsString) -> string:tokens(HostAsString, "\."). split_path(Path) -> make_spec(string:tokens(Path, "/"), []). make_spec([], Acc) -> lists:reverse(Acc); make_spec([""|R], Acc) -> make_spec(R, Acc); make_spec(["*"|R], Acc) -> make_spec(R, [?MATCH_ALL|Acc]); make_spec([P|R], Acc) -> P1 = parse_var(P), make_spec(R, [P1|Acc]). parse_var(P) -> case P of ":" ++ Var -> {bind, Var}; _ -> P end. % mochiweb doesn't export it. urlsplit_netloc("", Acc) -> {lists:reverse(Acc), ""}; urlsplit_netloc(Rest=[C | _], Acc) when C =:= $/; C =:= $?; C =:= $# -> {lists:reverse(Acc), Rest}; urlsplit_netloc([C | Rest], Acc) -> urlsplit_netloc(Rest, [C | Acc]). make_path(Parts) -> "/" ++ string:join(Parts,[?SEPARATOR]). init(_) -> ok = couch_config:register(fun ?MODULE:config_change/2), %% load configuration {VHostGlobals, VHosts, Fun} = load_conf(), State = #vhosts_state{ vhost_globals=VHostGlobals, vhosts=VHosts, vhosts_fun=Fun}, {ok, State}. handle_call(reload, _From, _State) -> {VHostGlobals, VHosts, Fun} = load_conf(), {reply, ok, #vhosts_state{ vhost_globals=VHostGlobals, vhosts=VHosts, vhosts_fun=Fun}}; handle_call(get_state, _From, State) -> {reply, State, State}; handle_call(_Msg, _From, State) -> {noreply, State}. handle_cast(_Msg, State) -> {noreply, State}. handle_info(_Info, State) -> {noreply, State}. terminate(_Reason, _State) -> ok. code_change(_OldVsn, State, _Extra) -> {ok, State}. config_change("httpd", "vhost_global_handlers") -> ?MODULE:reload(); config_change("httpd", "redirect_vhost_handler") -> ?MODULE:reload(); config_change("vhosts", _) -> ?MODULE:reload(). load_conf() -> %% get vhost globals VHostGlobals = re:split(couch_config:get("httpd", "vhost_global_handlers",""), "\\s*,\\s*",[{return, list}]), %% build vhosts matching rules VHosts = make_vhosts(), %% build vhosts handler fun DefaultVHostFun = "{couch_httpd_vhost, redirect_to_vhost}", Fun = couch_httpd:make_arity_2_fun(couch_config:get("httpd", "redirect_vhost_handler", DefaultVHostFun)), {VHostGlobals, VHosts, Fun}. apache-couchdb-1.5.0/src/couchdb/couch_app.erl0000644000175000001440000000277512230722213016130 00000000000000% 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. -module(couch_app). -behaviour(application). -include("couch_db.hrl"). -export([start/2, stop/1]). start(_Type, DefaultIniFiles) -> IniFiles = get_ini_files(DefaultIniFiles), case start_apps([crypto, asn1, public_key, sasl, inets, oauth, ssl, ibrowse, syntax_tools, compiler, xmerl, mochiweb, os_mon]) of ok -> couch_server_sup:start_link(IniFiles); {error, Reason} -> {error, Reason} end. stop(_) -> ok. get_ini_files(Default) -> case init:get_argument(couch_ini) of error -> Default; {ok, [[]]} -> Default; {ok, [Values]} -> Values end. start_apps([]) -> ok; start_apps([App|Rest]) -> case application:start(App) of ok -> start_apps(Rest); {error, {already_started, App}} -> start_apps(Rest); {error, _Reason} when App =:= public_key -> % ignore on R12B5 start_apps(Rest); {error, _Reason} -> {error, {app_would_not_start, App}} end. apache-couchdb-1.5.0/src/couchdb/couch_event_sup.erl0000644000175000001440000000452612230722213017354 00000000000000% 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. %% The purpose of this module is to allow event handlers to particpate in Erlang %% supervisor trees. It provide a monitorable process that crashes if the event %% handler fails. The process, when shutdown, deregisters the event handler. -module(couch_event_sup). -behaviour(gen_server). -include("couch_db.hrl"). -export([start_link/3,start_link/4, stop/1]). -export([init/1, terminate/2, handle_call/3, handle_cast/2, handle_info/2,code_change/3]). % % Instead calling the % ok = gen_event:add_sup_handler(error_logger, my_log, Args) % % do this: % {ok, LinkedPid} = couch_event_sup:start_link(error_logger, my_log, Args) % % The benefit is the event is now part of the process tree, and can be % started, restarted and shutdown consistently like the rest of the server % components. % % And now if the "event" crashes, the supervisor is notified and can restart % the event handler. % % Use this form to named process: % {ok, LinkedPid} = couch_event_sup:start_link({local, my_log}, error_logger, my_log, Args) % start_link(EventMgr, EventHandler, Args) -> gen_server:start_link(couch_event_sup, {EventMgr, EventHandler, Args}, []). start_link(ServerName, EventMgr, EventHandler, Args) -> gen_server:start_link(ServerName, couch_event_sup, {EventMgr, EventHandler, Args}, []). stop(Pid) -> gen_server:cast(Pid, stop). init({EventMgr, EventHandler, Args}) -> case gen_event:add_sup_handler(EventMgr, EventHandler, Args) of ok -> {ok, {EventMgr, EventHandler}}; {stop, Error} -> {stop, Error} end. terminate(_Reason, _State) -> ok. handle_call(_Whatever, _From, State) -> {ok, State}. handle_cast(stop, State) -> {stop, normal, State}. handle_info({gen_event_EXIT, _Handler, Reason}, State) -> {stop, Reason, State}. code_change(_OldVsn, State, _Extra) -> {ok, State}. apache-couchdb-1.5.0/src/couchdb/couch_key_tree.erl0000644000175000001440000004176012230722213017154 00000000000000% 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. %% @doc Data structure used to represent document edit histories. %% A key tree is used to represent the edit history of a document. Each node of %% the tree represents a particular version. Relations between nodes represent %% the order that these edits were applied. For instance, a set of three edits %% would produce a tree of versions A->B->C indicating that edit C was based on %% version B which was in turn based on A. In a world without replication (and %% no ability to disable MVCC checks), all histories would be forced to be %% linear lists of edits due to constraints imposed by MVCC (ie, new edits must %% be based on the current version). However, we have replication, so we must %% deal with not so easy cases, which lead to trees. %% %% Consider a document in state A. This doc is replicated to a second node. We %% then edit the document on each node leaving it in two different states, B %% and C. We now have two key trees, A->B and A->C. When we go to replicate a %% second time, the key tree must combine these two trees which gives us %% A->(B|C). This is how conflicts are introduced. In terms of the key tree, we %% say that we have two leaves (B and C) that are not deleted. The presense of %% the multiple leaves indicate conflict. To remove a conflict, one of the %% edits (B or C) can be deleted, which results in, A->(B|C->D) where D is an %% edit that is specially marked with the a deleted=true flag. %% %% What makes this a bit more complicated is that there is a limit to the %% number of revisions kept, specified in couch_db.hrl (default is 1000). When %% this limit is exceeded only the last 1000 are kept. This comes in to play %% when branches are merged. The comparison has to begin at the same place in %% the branches. A revision id is of the form N-XXXXXXX where N is the current %% revision. So each path will have a start number, calculated in %% couch_doc:to_path using the formula N - length(RevIds) + 1 So, .eg. if a doc %% was edit 1003 times this start number would be 4, indicating that 3 %% revisions were truncated. %% %% This comes into play in @see merge_at/3 which recursively walks down one %% tree or the other until they begin at the same revision. -module(couch_key_tree). -export([merge/3, find_missing/2, get_key_leafs/2, get_full_key_paths/2, get/2]). -export([get_all_leafs/1, count_leafs/1, remove_leafs/2, get_all_leafs_full/1, stem/2]). -export([map/2, mapfold/3, map_leafs/2, fold/3]). -include("couch_db.hrl"). %% @doc Merge a path with a list of paths and stem to the given length. -spec merge([path()], path(), pos_integer()) -> {[path()], conflicts | no_conflicts}. merge(Paths, Path, Depth) -> {Merged, Conflicts} = merge(Paths, Path), {stem(Merged, Depth), Conflicts}. %% @doc Merge a path with an existing list of paths, returning a new list of %% paths. A return of conflicts indicates a new conflict was discovered in this %% merge. Conflicts may already exist in the original list of paths. -spec merge([path()], path()) -> {[path()], conflicts | no_conflicts}. merge(Paths, Path) -> {ok, Merged, HasConflicts} = merge_one(Paths, Path, [], false), if HasConflicts -> Conflicts = conflicts; (length(Merged) =/= length(Paths)) and (length(Merged) =/= 1) -> Conflicts = conflicts; true -> Conflicts = no_conflicts end, {lists:sort(Merged), Conflicts}. -spec merge_one(Original::[path()], Inserted::path(), [path()], boolean()) -> {ok, Merged::[path()], NewConflicts::boolean()}. merge_one([], Insert, OutAcc, ConflictsAcc) -> {ok, [Insert | OutAcc], ConflictsAcc}; merge_one([{Start, Tree}|Rest], {StartInsert, TreeInsert}, Acc, HasConflicts) -> case merge_at([Tree], StartInsert - Start, [TreeInsert]) of {ok, [Merged], Conflicts} -> MergedStart = lists:min([Start, StartInsert]), {ok, Rest ++ [{MergedStart, Merged} | Acc], Conflicts or HasConflicts}; no -> AccOut = [{Start, Tree} | Acc], merge_one(Rest, {StartInsert, TreeInsert}, AccOut, HasConflicts) end. -spec merge_at(tree(), Place::integer(), tree()) -> {ok, Merged::tree(), HasConflicts::boolean()} | no. merge_at(_Ours, _Place, []) -> no; merge_at([], _Place, _Insert) -> no; merge_at([{Key, Value, SubTree}|Sibs], Place, InsertTree) when Place > 0 -> % inserted starts later than committed, need to drill into committed subtree case merge_at(SubTree, Place - 1, InsertTree) of {ok, Merged, Conflicts} -> {ok, [{Key, Value, Merged} | Sibs], Conflicts}; no -> % first branch didn't merge, move to next branch case merge_at(Sibs, Place, InsertTree) of {ok, Merged, Conflicts} -> {ok, [{Key, Value, SubTree} | Merged], Conflicts}; no -> no end end; merge_at(OurTree, Place, [{Key, Value, SubTree}]) when Place < 0 -> % inserted starts earlier than committed, need to drill into insert subtree case merge_at(OurTree, Place + 1, SubTree) of {ok, Merged, Conflicts} -> {ok, [{Key, Value, Merged}], Conflicts}; no -> no end; merge_at([{Key, V1, SubTree}|Sibs], 0, [{Key, V2, InsertSubTree}]) -> {Merged, Conflicts} = merge_simple(SubTree, InsertSubTree), {ok, [{Key, value_pref(V1, V2), Merged} | Sibs], Conflicts}; merge_at([{OurKey, _, _} | _], 0, [{Key, _, _}]) when OurKey > Key -> % siblings keys are ordered, no point in continuing no; merge_at([Tree | Sibs], 0, InsertTree) -> case merge_at(Sibs, 0, InsertTree) of {ok, Merged, Conflicts} -> {ok, [Tree | Merged], Conflicts}; no -> no end. % key tree functions -spec merge_simple(tree(), tree()) -> {Merged::tree(), NewConflicts::boolean()}. merge_simple([], B) -> {B, false}; merge_simple(A, []) -> {A, false}; merge_simple([{Key, V1, SubA} | NextA], [{Key, V2, SubB} | NextB]) -> {MergedSubTree, Conflict1} = merge_simple(SubA, SubB), {MergedNextTree, Conflict2} = merge_simple(NextA, NextB), Value = value_pref(V1, V2), {[{Key, Value, MergedSubTree} | MergedNextTree], Conflict1 or Conflict2}; merge_simple([{A, _, _} = Tree | Next], [{B, _, _} | _] = Insert) when A < B -> {Merged, Conflict} = merge_simple(Next, Insert), % if Merged has more branches than the input we added a new conflict {[Tree | Merged], Conflict orelse (length(Merged) > length(Next))}; merge_simple(Ours, [Tree | Next]) -> {Merged, Conflict} = merge_simple(Ours, Next), {[Tree | Merged], Conflict orelse (length(Merged) > length(Next))}. find_missing(_Tree, []) -> []; find_missing([], SeachKeys) -> SeachKeys; find_missing([{Start, {Key, Value, SubTree}} | RestTree], SeachKeys) -> PossibleKeys = [{KeyPos, KeyValue} || {KeyPos, KeyValue} <- SeachKeys, KeyPos >= Start], ImpossibleKeys = [{KeyPos, KeyValue} || {KeyPos, KeyValue} <- SeachKeys, KeyPos < Start], Missing = find_missing_simple(Start, [{Key, Value, SubTree}], PossibleKeys), find_missing(RestTree, ImpossibleKeys ++ Missing). find_missing_simple(_Pos, _Tree, []) -> []; find_missing_simple(_Pos, [], SeachKeys) -> SeachKeys; find_missing_simple(Pos, [{Key, _, SubTree} | RestTree], SeachKeys) -> PossibleKeys = [{KeyPos, KeyValue} || {KeyPos, KeyValue} <- SeachKeys, KeyPos >= Pos], ImpossibleKeys = [{KeyPos, KeyValue} || {KeyPos, KeyValue} <- SeachKeys, KeyPos < Pos], SrcKeys2 = PossibleKeys -- [{Pos, Key}], SrcKeys3 = find_missing_simple(Pos + 1, SubTree, SrcKeys2), ImpossibleKeys ++ find_missing_simple(Pos, RestTree, SrcKeys3). filter_leafs([], _Keys, FilteredAcc, RemovedKeysAcc) -> {FilteredAcc, RemovedKeysAcc}; filter_leafs([{Pos, [{LeafKey, _}|_]} = Path |Rest], Keys, FilteredAcc, RemovedKeysAcc) -> FilteredKeys = lists:delete({Pos, LeafKey}, Keys), if FilteredKeys == Keys -> % this leaf is not a key we are looking to remove filter_leafs(Rest, Keys, [Path | FilteredAcc], RemovedKeysAcc); true -> % this did match a key, remove both the node and the input key filter_leafs(Rest, FilteredKeys, FilteredAcc, [{Pos, LeafKey} | RemovedKeysAcc]) end. % Removes any branches from the tree whose leaf node(s) are in the Keys remove_leafs(Trees, Keys) -> % flatten each branch in a tree into a tree path Paths = get_all_leafs_full(Trees), % filter out any that are in the keys list. {FilteredPaths, RemovedKeys} = filter_leafs(Paths, Keys, [], []), SortedPaths = lists:sort( [{Pos + 1 - length(Path), Path} || {Pos, Path} <- FilteredPaths] ), % convert paths back to trees NewTree = lists:foldl( fun({StartPos, Path},TreeAcc) -> [SingleTree] = lists:foldl( fun({K,V},NewTreeAcc) -> [{K,V,NewTreeAcc}] end, [], Path), {NewTrees, _} = merge(TreeAcc, {StartPos, SingleTree}), NewTrees end, [], SortedPaths), {NewTree, RemovedKeys}. % get the leafs in the tree matching the keys. The matching key nodes can be % leafs or an inner nodes. If an inner node, then the leafs for that node % are returned. get_key_leafs(Tree, Keys) -> get_key_leafs(Tree, Keys, []). get_key_leafs(_, [], Acc) -> {Acc, []}; get_key_leafs([], Keys, Acc) -> {Acc, Keys}; get_key_leafs([{Pos, Tree}|Rest], Keys, Acc) -> {Gotten, RemainingKeys} = get_key_leafs_simple(Pos, [Tree], Keys, []), get_key_leafs(Rest, RemainingKeys, Gotten ++ Acc). get_key_leafs_simple(_Pos, _Tree, [], _KeyPathAcc) -> {[], []}; get_key_leafs_simple(_Pos, [], KeysToGet, _KeyPathAcc) -> {[], KeysToGet}; get_key_leafs_simple(Pos, [{Key, _Value, SubTree}=Tree | RestTree], KeysToGet, KeyPathAcc) -> case lists:delete({Pos, Key}, KeysToGet) of KeysToGet -> % same list, key not found {LeafsFound, KeysToGet2} = get_key_leafs_simple(Pos + 1, SubTree, KeysToGet, [Key | KeyPathAcc]), {RestLeafsFound, KeysRemaining} = get_key_leafs_simple(Pos, RestTree, KeysToGet2, KeyPathAcc), {LeafsFound ++ RestLeafsFound, KeysRemaining}; KeysToGet2 -> LeafsFound = get_all_leafs_simple(Pos, [Tree], KeyPathAcc), LeafKeysFound = [{LeafPos, LeafRev} || {_, {LeafPos, [LeafRev|_]}} <- LeafsFound], KeysToGet3 = KeysToGet2 -- LeafKeysFound, {RestLeafsFound, KeysRemaining} = get_key_leafs_simple(Pos, RestTree, KeysToGet3, KeyPathAcc), {LeafsFound ++ RestLeafsFound, KeysRemaining} end. get(Tree, KeysToGet) -> {KeyPaths, KeysNotFound} = get_full_key_paths(Tree, KeysToGet), FixedResults = [ {Value, {Pos, [Key0 || {Key0, _} <- Path]}} || {Pos, [{_Key, Value}|_]=Path} <- KeyPaths], {FixedResults, KeysNotFound}. get_full_key_paths(Tree, Keys) -> get_full_key_paths(Tree, Keys, []). get_full_key_paths(_, [], Acc) -> {Acc, []}; get_full_key_paths([], Keys, Acc) -> {Acc, Keys}; get_full_key_paths([{Pos, Tree}|Rest], Keys, Acc) -> {Gotten, RemainingKeys} = get_full_key_paths(Pos, [Tree], Keys, []), get_full_key_paths(Rest, RemainingKeys, Gotten ++ Acc). get_full_key_paths(_Pos, _Tree, [], _KeyPathAcc) -> {[], []}; get_full_key_paths(_Pos, [], KeysToGet, _KeyPathAcc) -> {[], KeysToGet}; get_full_key_paths(Pos, [{KeyId, Value, SubTree} | RestTree], KeysToGet, KeyPathAcc) -> KeysToGet2 = KeysToGet -- [{Pos, KeyId}], CurrentNodeResult = case length(KeysToGet2) =:= length(KeysToGet) of true -> % not in the key list. []; false -> % this node is the key list. return it [{Pos, [{KeyId, Value} | KeyPathAcc]}] end, {KeysGotten, KeysRemaining} = get_full_key_paths(Pos + 1, SubTree, KeysToGet2, [{KeyId, Value} | KeyPathAcc]), {KeysGotten2, KeysRemaining2} = get_full_key_paths(Pos, RestTree, KeysRemaining, KeyPathAcc), {CurrentNodeResult ++ KeysGotten ++ KeysGotten2, KeysRemaining2}. get_all_leafs_full(Tree) -> get_all_leafs_full(Tree, []). get_all_leafs_full([], Acc) -> Acc; get_all_leafs_full([{Pos, Tree} | Rest], Acc) -> get_all_leafs_full(Rest, get_all_leafs_full_simple(Pos, [Tree], []) ++ Acc). get_all_leafs_full_simple(_Pos, [], _KeyPathAcc) -> []; get_all_leafs_full_simple(Pos, [{KeyId, Value, []} | RestTree], KeyPathAcc) -> [{Pos, [{KeyId, Value} | KeyPathAcc]} | get_all_leafs_full_simple(Pos, RestTree, KeyPathAcc)]; get_all_leafs_full_simple(Pos, [{KeyId, Value, SubTree} | RestTree], KeyPathAcc) -> get_all_leafs_full_simple(Pos + 1, SubTree, [{KeyId, Value} | KeyPathAcc]) ++ get_all_leafs_full_simple(Pos, RestTree, KeyPathAcc). get_all_leafs(Trees) -> get_all_leafs(Trees, []). get_all_leafs([], Acc) -> Acc; get_all_leafs([{Pos, Tree}|Rest], Acc) -> get_all_leafs(Rest, get_all_leafs_simple(Pos, [Tree], []) ++ Acc). get_all_leafs_simple(_Pos, [], _KeyPathAcc) -> []; get_all_leafs_simple(Pos, [{KeyId, Value, []} | RestTree], KeyPathAcc) -> [{Value, {Pos, [KeyId | KeyPathAcc]}} | get_all_leafs_simple(Pos, RestTree, KeyPathAcc)]; get_all_leafs_simple(Pos, [{KeyId, _Value, SubTree} | RestTree], KeyPathAcc) -> get_all_leafs_simple(Pos + 1, SubTree, [KeyId | KeyPathAcc]) ++ get_all_leafs_simple(Pos, RestTree, KeyPathAcc). count_leafs([]) -> 0; count_leafs([{_Pos,Tree}|Rest]) -> count_leafs_simple([Tree]) + count_leafs(Rest). count_leafs_simple([]) -> 0; count_leafs_simple([{_Key, _Value, []} | RestTree]) -> 1 + count_leafs_simple(RestTree); count_leafs_simple([{_Key, _Value, SubTree} | RestTree]) -> count_leafs_simple(SubTree) + count_leafs_simple(RestTree). fold(_Fun, Acc, []) -> Acc; fold(Fun, Acc0, [{Pos, Tree}|Rest]) -> Acc1 = fold_simple(Fun, Acc0, Pos, [Tree]), fold(Fun, Acc1, Rest). fold_simple(_Fun, Acc, _Pos, []) -> Acc; fold_simple(Fun, Acc0, Pos, [{Key, Value, SubTree} | RestTree]) -> Type = if SubTree == [] -> leaf; true -> branch end, Acc1 = Fun({Pos, Key}, Value, Type, Acc0), Acc2 = fold_simple(Fun, Acc1, Pos+1, SubTree), fold_simple(Fun, Acc2, Pos, RestTree). map(_Fun, []) -> []; map(Fun, [{Pos, Tree}|Rest]) -> case erlang:fun_info(Fun, arity) of {arity, 2} -> [NewTree] = map_simple(fun(A,B,_C) -> Fun(A,B) end, Pos, [Tree]), [{Pos, NewTree} | map(Fun, Rest)]; {arity, 3} -> [NewTree] = map_simple(Fun, Pos, [Tree]), [{Pos, NewTree} | map(Fun, Rest)] end. map_simple(_Fun, _Pos, []) -> []; map_simple(Fun, Pos, [{Key, Value, SubTree} | RestTree]) -> Value2 = Fun({Pos, Key}, Value, if SubTree == [] -> leaf; true -> branch end), [{Key, Value2, map_simple(Fun, Pos + 1, SubTree)} | map_simple(Fun, Pos, RestTree)]. mapfold(_Fun, Acc, []) -> {[], Acc}; mapfold(Fun, Acc, [{Pos, Tree} | Rest]) -> {[NewTree], Acc2} = mapfold_simple(Fun, Acc, Pos, [Tree]), {Rest2, Acc3} = mapfold(Fun, Acc2, Rest), {[{Pos, NewTree} | Rest2], Acc3}. mapfold_simple(_Fun, Acc, _Pos, []) -> {[], Acc}; mapfold_simple(Fun, Acc, Pos, [{Key, Value, SubTree} | RestTree]) -> {Value2, Acc2} = Fun({Pos, Key}, Value, if SubTree == [] -> leaf; true -> branch end, Acc), {SubTree2, Acc3} = mapfold_simple(Fun, Acc2, Pos + 1, SubTree), {RestTree2, Acc4} = mapfold_simple(Fun, Acc3, Pos, RestTree), {[{Key, Value2, SubTree2} | RestTree2], Acc4}. map_leafs(_Fun, []) -> []; map_leafs(Fun, [{Pos, Tree}|Rest]) -> [NewTree] = map_leafs_simple(Fun, Pos, [Tree]), [{Pos, NewTree} | map_leafs(Fun, Rest)]. map_leafs_simple(_Fun, _Pos, []) -> []; map_leafs_simple(Fun, Pos, [{Key, Value, []} | RestTree]) -> Value2 = Fun({Pos, Key}, Value), [{Key, Value2, []} | map_leafs_simple(Fun, Pos, RestTree)]; map_leafs_simple(Fun, Pos, [{Key, Value, SubTree} | RestTree]) -> [{Key, Value, map_leafs_simple(Fun, Pos + 1, SubTree)} | map_leafs_simple(Fun, Pos, RestTree)]. stem(Trees, Limit) -> % flatten each branch in a tree into a tree path, sort by starting rev # Paths = lists:sort(lists:map(fun({Pos, Path}) -> StemmedPath = lists:sublist(Path, Limit), {Pos + 1 - length(StemmedPath), StemmedPath} end, get_all_leafs_full(Trees))), % convert paths back to trees lists:foldl( fun({StartPos, Path},TreeAcc) -> [SingleTree] = lists:foldl( fun({K,V},NewTreeAcc) -> [{K,V,NewTreeAcc}] end, [], Path), {NewTrees, _} = merge(TreeAcc, {StartPos, SingleTree}), NewTrees end, [], Paths). value_pref(Tuple, _) when is_tuple(Tuple), (tuple_size(Tuple) == 3 orelse tuple_size(Tuple) == 4) -> Tuple; value_pref(_, Tuple) when is_tuple(Tuple), (tuple_size(Tuple) == 3 orelse tuple_size(Tuple) == 4) -> Tuple; value_pref(?REV_MISSING, Other) -> Other; value_pref(Other, ?REV_MISSING) -> Other; value_pref(Last, _) -> Last. % Tests moved to test/etap/06?-*.t apache-couchdb-1.5.0/src/couchdb/couch_db.erl0000644000175000001440000014021412230722213015724 00000000000000% 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. -module(couch_db). -behaviour(gen_server). -export([open/2,open_int/2,close/1,create/2,get_db_info/1,get_design_docs/1]). -export([start_compact/1, cancel_compact/1]). -export([open_ref_counted/2,is_idle/1,monitor/1,count_changes_since/2]). -export([update_doc/3,update_doc/4,update_docs/4,update_docs/2,update_docs/3,delete_doc/3]). -export([get_doc_info/2,get_full_doc_info/2,get_full_doc_infos/2]). -export([open_doc/2,open_doc/3,open_doc_revs/4]). -export([set_revs_limit/2,get_revs_limit/1]). -export([get_missing_revs/2,name/1,get_update_seq/1,get_committed_update_seq/1]). -export([enum_docs/4,enum_docs_since/5]). -export([enum_docs_since_reduce_to_count/1,enum_docs_reduce_to_count/1]). -export([increment_update_seq/1,get_purge_seq/1,purge_docs/2,get_last_purged/1]). -export([start_link/3,open_doc_int/3,ensure_full_commit/1]). -export([set_security/2,get_security/1]). -export([init/1,terminate/2,handle_call/3,handle_cast/2,code_change/3,handle_info/2]). -export([changes_since/4,changes_since/5,read_doc/2,new_revid/1]). -export([check_is_admin/1, check_is_member/1]). -export([reopen/1, is_system_db/1, compression/1]). -include("couch_db.hrl"). start_link(DbName, Filepath, Options) -> case open_db_file(Filepath, Options) of {ok, Fd} -> StartResult = gen_server:start_link(couch_db, {DbName, Filepath, Fd, Options}, []), unlink(Fd), StartResult; Else -> Else end. open_db_file(Filepath, Options) -> case couch_file:open(Filepath, Options) of {ok, Fd} -> {ok, Fd}; {error, enoent} -> % couldn't find file. is there a compact version? This can happen if % crashed during the file switch. case couch_file:open(Filepath ++ ".compact", [nologifmissing]) of {ok, Fd} -> ?LOG_INFO("Found ~s~s compaction file, using as primary storage.", [Filepath, ".compact"]), ok = file:rename(Filepath ++ ".compact", Filepath), ok = couch_file:sync(Fd), {ok, Fd}; {error, enoent} -> {not_found, no_db_file} end; Error -> Error end. create(DbName, Options) -> couch_server:create(DbName, Options). % this is for opening a database for internal purposes like the replicator % or the view indexer. it never throws a reader error. open_int(DbName, Options) -> couch_server:open(DbName, Options). % this should be called anytime an http request opens the database. % it ensures that the http userCtx is a valid reader open(DbName, Options) -> case couch_server:open(DbName, Options) of {ok, Db} -> try check_is_member(Db), {ok, Db} catch throw:Error -> close(Db), throw(Error) end; Else -> Else end. reopen(#db{main_pid = Pid, fd_ref_counter = OldRefCntr, user_ctx = UserCtx}) -> {ok, #db{fd_ref_counter = NewRefCntr} = NewDb} = gen_server:call(Pid, get_db, infinity), case NewRefCntr =:= OldRefCntr of true -> ok; false -> couch_ref_counter:add(NewRefCntr), catch couch_ref_counter:drop(OldRefCntr) end, {ok, NewDb#db{user_ctx = UserCtx}}. is_system_db(#db{options = Options}) -> lists:member(sys_db, Options). ensure_full_commit(#db{update_pid=UpdatePid,instance_start_time=StartTime}) -> ok = gen_server:call(UpdatePid, full_commit, infinity), {ok, StartTime}. close(#db{fd_ref_counter=RefCntr}) -> couch_ref_counter:drop(RefCntr). open_ref_counted(MainPid, OpenedPid) -> gen_server:call(MainPid, {open_ref_count, OpenedPid}). is_idle(#db{main_pid = MainPid}) -> is_idle(MainPid); is_idle(MainPid) -> gen_server:call(MainPid, is_idle). monitor(#db{main_pid=MainPid}) -> erlang:monitor(process, MainPid). start_compact(#db{update_pid=Pid}) -> gen_server:call(Pid, start_compact). cancel_compact(#db{update_pid=Pid}) -> gen_server:call(Pid, cancel_compact). delete_doc(Db, Id, Revisions) -> DeletedDocs = [#doc{id=Id, revs=[Rev], deleted=true} || Rev <- Revisions], {ok, [Result]} = update_docs(Db, DeletedDocs, []), {ok, Result}. open_doc(Db, IdOrDocInfo) -> open_doc(Db, IdOrDocInfo, []). open_doc(Db, Id, Options) -> increment_stat(Db, {couchdb, database_reads}), case open_doc_int(Db, Id, Options) of {ok, #doc{deleted=true}=Doc} -> case lists:member(deleted, Options) of true -> apply_open_options({ok, Doc},Options); false -> {not_found, deleted} end; Else -> apply_open_options(Else,Options) end. apply_open_options({ok, Doc},Options) -> apply_open_options2(Doc,Options); apply_open_options(Else,_Options) -> Else. apply_open_options2(Doc,[]) -> {ok, Doc}; apply_open_options2(#doc{atts=Atts,revs=Revs}=Doc, [{atts_since, PossibleAncestors}|Rest]) -> RevPos = find_ancestor_rev_pos(Revs, PossibleAncestors), apply_open_options2(Doc#doc{atts=[A#att{data= if AttPos>RevPos -> Data; true -> stub end} || #att{revpos=AttPos,data=Data}=A <- Atts]}, Rest); apply_open_options2(Doc, [ejson_body | Rest]) -> apply_open_options2(couch_doc:with_ejson_body(Doc), Rest); apply_open_options2(Doc,[_|Rest]) -> apply_open_options2(Doc,Rest). find_ancestor_rev_pos({_, []}, _AttsSinceRevs) -> 0; find_ancestor_rev_pos(_DocRevs, []) -> 0; find_ancestor_rev_pos({RevPos, [RevId|Rest]}, AttsSinceRevs) -> case lists:member({RevPos, RevId}, AttsSinceRevs) of true -> RevPos; false -> find_ancestor_rev_pos({RevPos - 1, Rest}, AttsSinceRevs) end. open_doc_revs(Db, Id, Revs, Options) -> increment_stat(Db, {couchdb, database_reads}), [{ok, Results}] = open_doc_revs_int(Db, [{Id, Revs}], Options), {ok, [apply_open_options(Result, Options) || Result <- Results]}. % Each returned result is a list of tuples: % {Id, MissingRevs, PossibleAncestors} % if no revs are missing, it's omitted from the results. get_missing_revs(Db, IdRevsList) -> Results = get_full_doc_infos(Db, [Id1 || {Id1, _Revs} <- IdRevsList]), {ok, find_missing(IdRevsList, Results)}. find_missing([], []) -> []; find_missing([{Id, Revs}|RestIdRevs], [{ok, FullInfo} | RestLookupInfo]) -> case couch_key_tree:find_missing(FullInfo#full_doc_info.rev_tree, Revs) of [] -> find_missing(RestIdRevs, RestLookupInfo); MissingRevs -> #doc_info{revs=RevsInfo} = couch_doc:to_doc_info(FullInfo), LeafRevs = [Rev || #rev_info{rev=Rev} <- RevsInfo], % Find the revs that are possible parents of this rev PossibleAncestors = lists:foldl(fun({LeafPos, LeafRevId}, Acc) -> % this leaf is a "possible ancenstor" of the missing % revs if this LeafPos lessthan any of the missing revs case lists:any(fun({MissingPos, _}) -> LeafPos < MissingPos end, MissingRevs) of true -> [{LeafPos, LeafRevId} | Acc]; false -> Acc end end, [], LeafRevs), [{Id, MissingRevs, PossibleAncestors} | find_missing(RestIdRevs, RestLookupInfo)] end; find_missing([{Id, Revs}|RestIdRevs], [not_found | RestLookupInfo]) -> [{Id, Revs, []} | find_missing(RestIdRevs, RestLookupInfo)]. get_doc_info(Db, Id) -> case get_full_doc_info(Db, Id) of {ok, DocInfo} -> {ok, couch_doc:to_doc_info(DocInfo)}; Else -> Else end. % returns {ok, DocInfo} or not_found get_full_doc_info(Db, Id) -> [Result] = get_full_doc_infos(Db, [Id]), Result. get_full_doc_infos(Db, Ids) -> couch_btree:lookup(by_id_btree(Db), Ids). increment_update_seq(#db{update_pid=UpdatePid}) -> gen_server:call(UpdatePid, increment_update_seq). purge_docs(#db{update_pid=UpdatePid}, IdsRevs) -> gen_server:call(UpdatePid, {purge_docs, IdsRevs}). get_committed_update_seq(#db{committed_update_seq=Seq}) -> Seq. get_update_seq(#db{update_seq=Seq})-> Seq. get_purge_seq(#db{header=#db_header{purge_seq=PurgeSeq}})-> PurgeSeq. get_last_purged(#db{header=#db_header{purged_docs=nil}}) -> {ok, []}; get_last_purged(#db{fd=Fd, header=#db_header{purged_docs=PurgedPointer}}) -> couch_file:pread_term(Fd, PurgedPointer). get_db_info(Db) -> #db{fd=Fd, header=#db_header{disk_version=DiskVersion}, compactor_pid=Compactor, update_seq=SeqNum, name=Name, instance_start_time=StartTime, committed_update_seq=CommittedUpdateSeq, fulldocinfo_by_id_btree = IdBtree, docinfo_by_seq_btree = SeqBtree, local_docs_btree = LocalBtree } = Db, {ok, Size} = couch_file:bytes(Fd), {ok, DbReduction} = couch_btree:full_reduce(by_id_btree(Db)), InfoList = [ {db_name, Name}, {doc_count, element(1, DbReduction)}, {doc_del_count, element(2, DbReduction)}, {update_seq, SeqNum}, {purge_seq, couch_db:get_purge_seq(Db)}, {compact_running, Compactor/=nil}, {disk_size, Size}, {data_size, db_data_size(DbReduction, [SeqBtree, IdBtree, LocalBtree])}, {instance_start_time, StartTime}, {disk_format_version, DiskVersion}, {committed_update_seq, CommittedUpdateSeq} ], {ok, InfoList}. db_data_size({_Count, _DelCount}, _Trees) -> % pre 1.2 format, upgraded on compaction null; db_data_size({_Count, _DelCount, nil}, _Trees) -> null; db_data_size({_Count, _DelCount, DocAndAttsSize}, Trees) -> sum_tree_sizes(DocAndAttsSize, Trees). sum_tree_sizes(Acc, []) -> Acc; sum_tree_sizes(Acc, [T | Rest]) -> case couch_btree:size(T) of nil -> null; Sz -> sum_tree_sizes(Acc + Sz, Rest) end. get_design_docs(Db) -> FoldFun = skip_deleted(fun (#full_doc_info{deleted = true}, _Reds, Acc) -> {ok, Acc}; (#full_doc_info{id= <<"_design/",_/binary>>}=FullDocInfo, _Reds, Acc) -> {ok, [FullDocInfo | Acc]}; (_, _Reds, Acc) -> {stop, Acc} end), KeyOpts = [{start_key, <<"_design/">>}, {end_key_gt, <<"_design0">>}], {ok, _, Docs} = couch_btree:fold(by_id_btree(Db), FoldFun, [], KeyOpts), Docs. check_is_admin(#db{user_ctx=#user_ctx{name=Name,roles=Roles}}=Db) -> {Admins} = get_admins(Db), AdminRoles = [<<"_admin">> | couch_util:get_value(<<"roles">>, Admins, [])], AdminNames = couch_util:get_value(<<"names">>, Admins,[]), case AdminRoles -- Roles of AdminRoles -> % same list, not an admin role case AdminNames -- [Name] of AdminNames -> % same names, not an admin throw({unauthorized, <<"You are not a db or server admin.">>}); _ -> ok end; _ -> ok end. check_is_member(#db{user_ctx=#user_ctx{name=Name,roles=Roles}=UserCtx}=Db) -> case (catch check_is_admin(Db)) of ok -> ok; _ -> {Members} = get_members(Db), ReaderRoles = couch_util:get_value(<<"roles">>, Members,[]), WithAdminRoles = [<<"_admin">> | ReaderRoles], ReaderNames = couch_util:get_value(<<"names">>, Members,[]), case ReaderRoles ++ ReaderNames of [] -> ok; % no readers == public access _Else -> case WithAdminRoles -- Roles of WithAdminRoles -> % same list, not an reader role case ReaderNames -- [Name] of ReaderNames -> % same names, not a reader ?LOG_DEBUG("Not a reader: UserCtx ~p vs Names ~p Roles ~p",[UserCtx, ReaderNames, WithAdminRoles]), throw({unauthorized, <<"You are not authorized to access this db.">>}); _ -> ok end; _ -> ok end end end. get_admins(#db{security=SecProps}) -> couch_util:get_value(<<"admins">>, SecProps, {[]}). get_members(#db{security=SecProps}) -> % we fallback to readers here for backwards compatibility couch_util:get_value(<<"members">>, SecProps, couch_util:get_value(<<"readers">>, SecProps, {[]})). get_security(#db{security=SecProps}) -> {SecProps}. set_security(#db{update_pid=Pid}=Db, {NewSecProps}) when is_list(NewSecProps) -> check_is_admin(Db), ok = validate_security_object(NewSecProps), ok = gen_server:call(Pid, {set_security, NewSecProps}, infinity), {ok, _} = ensure_full_commit(Db), ok; set_security(_, _) -> throw(bad_request). validate_security_object(SecProps) -> Admins = couch_util:get_value(<<"admins">>, SecProps, {[]}), % we fallback to readers here for backwards compatibility Members = couch_util:get_value(<<"members">>, SecProps, couch_util:get_value(<<"readers">>, SecProps, {[]})), ok = validate_names_and_roles(Admins), ok = validate_names_and_roles(Members), ok. % validate user input validate_names_and_roles({Props}) when is_list(Props) -> case couch_util:get_value(<<"names">>,Props,[]) of Ns when is_list(Ns) -> [throw("names must be a JSON list of strings") ||N <- Ns, not is_binary(N)], Ns; _ -> throw("names must be a JSON list of strings") end, case couch_util:get_value(<<"roles">>,Props,[]) of Rs when is_list(Rs) -> [throw("roles must be a JSON list of strings") ||R <- Rs, not is_binary(R)], Rs; _ -> throw("roles must be a JSON list of strings") end, ok. get_revs_limit(#db{revs_limit=Limit}) -> Limit. set_revs_limit(#db{update_pid=Pid}=Db, Limit) when Limit > 0 -> check_is_admin(Db), gen_server:call(Pid, {set_revs_limit, Limit}, infinity); set_revs_limit(_Db, _Limit) -> throw(invalid_revs_limit). name(#db{name=Name}) -> Name. compression(#db{compression=Compression}) -> Compression. update_doc(Db, Doc, Options) -> update_doc(Db, Doc, Options, interactive_edit). update_doc(Db, Doc, Options, UpdateType) -> case update_docs(Db, [Doc], Options, UpdateType) of {ok, [{ok, NewRev}]} -> {ok, NewRev}; {ok, [{{_Id, _Rev}, Error}]} -> throw(Error); {ok, [Error]} -> throw(Error); {ok, []} -> % replication success {Pos, [RevId | _]} = Doc#doc.revs, {ok, {Pos, RevId}} end. update_docs(Db, Docs) -> update_docs(Db, Docs, []). % group_alike_docs groups the sorted documents into sublist buckets, by id. % ([DocA, DocA, DocB, DocC], []) -> [[DocA, DocA], [DocB], [DocC]] group_alike_docs(Docs) -> Sorted = lists:sort(fun({#doc{id=A},_},{#doc{id=B},_})-> A < B end, Docs), group_alike_docs(Sorted, []). group_alike_docs([], Buckets) -> lists:reverse(lists:map(fun lists:reverse/1, Buckets)); group_alike_docs([Doc|Rest], []) -> group_alike_docs(Rest, [[Doc]]); group_alike_docs([{Doc,Ref}|Rest], [Bucket|RestBuckets]) -> [{#doc{id=BucketId},_Ref}|_] = Bucket, case Doc#doc.id == BucketId of true -> % add to existing bucket group_alike_docs(Rest, [[{Doc,Ref}|Bucket]|RestBuckets]); false -> % add to new bucket group_alike_docs(Rest, [[{Doc,Ref}]|[Bucket|RestBuckets]]) end. validate_doc_update(#db{}=Db, #doc{id= <<"_design/",_/binary>>}, _GetDiskDocFun) -> catch check_is_admin(Db); validate_doc_update(#db{validate_doc_funs=[]}, _Doc, _GetDiskDocFun) -> ok; validate_doc_update(_Db, #doc{id= <<"_local/",_/binary>>}, _GetDiskDocFun) -> ok; validate_doc_update(Db, Doc, GetDiskDocFun) -> DiskDoc = GetDiskDocFun(), JsonCtx = couch_util:json_user_ctx(Db), SecObj = get_security(Db), try [case Fun(Doc, DiskDoc, JsonCtx, SecObj) of ok -> ok; Error -> throw(Error) end || Fun <- Db#db.validate_doc_funs], ok catch throw:Error -> Error end. prep_and_validate_update(Db, #doc{id=Id,revs={RevStart, Revs}}=Doc, OldFullDocInfo, LeafRevsDict, AllowConflict) -> case Revs of [PrevRev|_] -> case dict:find({RevStart, PrevRev}, LeafRevsDict) of {ok, {Deleted, DiskSp, DiskRevs}} -> case couch_doc:has_stubs(Doc) of true -> DiskDoc = make_doc(Db, Id, Deleted, DiskSp, DiskRevs), Doc2 = couch_doc:merge_stubs(Doc, DiskDoc), {validate_doc_update(Db, Doc2, fun() -> DiskDoc end), Doc2}; false -> LoadDiskDoc = fun() -> make_doc(Db,Id,Deleted,DiskSp,DiskRevs) end, {validate_doc_update(Db, Doc, LoadDiskDoc), Doc} end; error when AllowConflict -> couch_doc:merge_stubs(Doc, #doc{}), % will generate error if % there are stubs {validate_doc_update(Db, Doc, fun() -> nil end), Doc}; error -> {conflict, Doc} end; [] -> % new doc, and we have existing revs. % reuse existing deleted doc if OldFullDocInfo#full_doc_info.deleted orelse AllowConflict -> {validate_doc_update(Db, Doc, fun() -> nil end), Doc}; true -> {conflict, Doc} end end. prep_and_validate_updates(_Db, [], [], _AllowConflict, AccPrepped, AccFatalErrors) -> {AccPrepped, AccFatalErrors}; prep_and_validate_updates(Db, [DocBucket|RestBuckets], [not_found|RestLookups], AllowConflict, AccPrepped, AccErrors) -> {PreppedBucket, AccErrors3} = lists:foldl( fun({#doc{revs=Revs}=Doc,Ref}, {AccBucket, AccErrors2}) -> case couch_doc:has_stubs(Doc) of true -> couch_doc:merge_stubs(Doc, #doc{}); % will throw exception false -> ok end, case Revs of {0, []} -> case validate_doc_update(Db, Doc, fun() -> nil end) of ok -> {[{Doc, Ref} | AccBucket], AccErrors2}; Error -> {AccBucket, [{Ref, Error} | AccErrors2]} end; _ -> % old revs specified but none exist, a conflict {AccBucket, [{Ref, conflict} | AccErrors2]} end end, {[], AccErrors}, DocBucket), prep_and_validate_updates(Db, RestBuckets, RestLookups, AllowConflict, [lists:reverse(PreppedBucket) | AccPrepped], AccErrors3); prep_and_validate_updates(Db, [DocBucket|RestBuckets], [{ok, #full_doc_info{rev_tree=OldRevTree}=OldFullDocInfo}|RestLookups], AllowConflict, AccPrepped, AccErrors) -> Leafs = couch_key_tree:get_all_leafs(OldRevTree), LeafRevsDict = dict:from_list([ begin Deleted = element(1, LeafVal), Sp = element(2, LeafVal), {{Start, RevId}, {Deleted, Sp, Revs}} end || {LeafVal, {Start, [RevId | _]} = Revs} <- Leafs ]), {PreppedBucket, AccErrors3} = lists:foldl( fun({Doc, Ref}, {Docs2Acc, AccErrors2}) -> case prep_and_validate_update(Db, Doc, OldFullDocInfo, LeafRevsDict, AllowConflict) of {ok, Doc2} -> {[{Doc2, Ref} | Docs2Acc], AccErrors2}; {Error, #doc{}} -> % Record the error {Docs2Acc, [{Ref, Error} |AccErrors2]} end end, {[], AccErrors}, DocBucket), prep_and_validate_updates(Db, RestBuckets, RestLookups, AllowConflict, [PreppedBucket | AccPrepped], AccErrors3). update_docs(Db, Docs, Options) -> update_docs(Db, Docs, Options, interactive_edit). prep_and_validate_replicated_updates(_Db, [], [], AccPrepped, AccErrors) -> Errors2 = [{{Id, {Pos, Rev}}, Error} || {#doc{id=Id,revs={Pos,[Rev|_]}}, Error} <- AccErrors], {lists:reverse(AccPrepped), lists:reverse(Errors2)}; prep_and_validate_replicated_updates(Db, [Bucket|RestBuckets], [OldInfo|RestOldInfo], AccPrepped, AccErrors) -> case OldInfo of not_found -> {ValidatedBucket, AccErrors3} = lists:foldl( fun({Doc, Ref}, {AccPrepped2, AccErrors2}) -> case couch_doc:has_stubs(Doc) of true -> couch_doc:merge_stubs(Doc, #doc{}); % will throw exception false -> ok end, case validate_doc_update(Db, Doc, fun() -> nil end) of ok -> {[{Doc, Ref} | AccPrepped2], AccErrors2}; Error -> {AccPrepped2, [{Doc, Error} | AccErrors2]} end end, {[], AccErrors}, Bucket), prep_and_validate_replicated_updates(Db, RestBuckets, RestOldInfo, [ValidatedBucket | AccPrepped], AccErrors3); {ok, #full_doc_info{rev_tree=OldTree}} -> NewRevTree = lists:foldl( fun({NewDoc, _Ref}, AccTree) -> {NewTree, _} = couch_key_tree:merge(AccTree, couch_doc:to_path(NewDoc), Db#db.revs_limit), NewTree end, OldTree, Bucket), Leafs = couch_key_tree:get_all_leafs_full(NewRevTree), LeafRevsFullDict = dict:from_list( [{{Start, RevId}, FullPath} || {Start, [{RevId, _}|_]}=FullPath <- Leafs]), {ValidatedBucket, AccErrors3} = lists:foldl( fun({#doc{id=Id,revs={Pos, [RevId|_]}}=Doc, Ref}, {AccValidated, AccErrors2}) -> case dict:find({Pos, RevId}, LeafRevsFullDict) of {ok, {Start, Path}} -> % our unflushed doc is a leaf node. Go back on the path % to find the previous rev that's on disk. LoadPrevRevFun = fun() -> make_first_doc_on_disk(Db,Id,Start-1, tl(Path)) end, case couch_doc:has_stubs(Doc) of true -> DiskDoc = LoadPrevRevFun(), Doc2 = couch_doc:merge_stubs(Doc, DiskDoc), GetDiskDocFun = fun() -> DiskDoc end; false -> Doc2 = Doc, GetDiskDocFun = LoadPrevRevFun end, case validate_doc_update(Db, Doc2, GetDiskDocFun) of ok -> {[{Doc2, Ref} | AccValidated], AccErrors2}; Error -> {AccValidated, [{Doc, Error} | AccErrors2]} end; _ -> % this doc isn't a leaf or already exists in the tree. % ignore but consider it a success. {AccValidated, AccErrors2} end end, {[], AccErrors}, Bucket), prep_and_validate_replicated_updates(Db, RestBuckets, RestOldInfo, [ValidatedBucket | AccPrepped], AccErrors3) end. new_revid(#doc{body=Body,revs={OldStart,OldRevs}, atts=Atts,deleted=Deleted}) -> case [{N, T, M} || #att{name=N,type=T,md5=M} <- Atts, M =/= <<>>] of Atts2 when length(Atts) =/= length(Atts2) -> % We must have old style non-md5 attachments ?l2b(integer_to_list(couch_util:rand32())); Atts2 -> OldRev = case OldRevs of [] -> 0; [OldRev0|_] -> OldRev0 end, couch_util:md5(term_to_binary([Deleted, OldStart, OldRev, Body, Atts2])) end. new_revs([], OutBuckets, IdRevsAcc) -> {lists:reverse(OutBuckets), IdRevsAcc}; new_revs([Bucket|RestBuckets], OutBuckets, IdRevsAcc) -> {NewBucket, IdRevsAcc3} = lists:mapfoldl( fun({#doc{revs={Start, RevIds}}=Doc, Ref}, IdRevsAcc2)-> NewRevId = new_revid(Doc), {{Doc#doc{revs={Start+1, [NewRevId | RevIds]}}, Ref}, [{Ref, {ok, {Start+1, NewRevId}}} | IdRevsAcc2]} end, IdRevsAcc, Bucket), new_revs(RestBuckets, [NewBucket|OutBuckets], IdRevsAcc3). check_dup_atts(#doc{atts=Atts}=Doc) -> Atts2 = lists:sort(fun(#att{name=N1}, #att{name=N2}) -> N1 < N2 end, Atts), check_dup_atts2(Atts2), Doc. check_dup_atts2([#att{name=N}, #att{name=N} | _]) -> throw({bad_request, <<"Duplicate attachments">>}); check_dup_atts2([_ | Rest]) -> check_dup_atts2(Rest); check_dup_atts2(_) -> ok. update_docs(Db, Docs, Options, replicated_changes) -> increment_stat(Db, {couchdb, database_writes}), % associate reference with each doc in order to track duplicates Docs2 = lists:map(fun(Doc) -> {Doc, make_ref()} end, Docs), DocBuckets = before_docs_update(Db, group_alike_docs(Docs2)), case (Db#db.validate_doc_funs /= []) orelse lists:any( fun({#doc{id= <>}, _Ref}) -> true; ({#doc{atts=Atts}, _Ref}) -> Atts /= [] end, Docs2) of true -> Ids = [Id || [{#doc{id=Id}, _Ref}|_] <- DocBuckets], ExistingDocs = get_full_doc_infos(Db, Ids), {DocBuckets2, DocErrors} = prep_and_validate_replicated_updates(Db, DocBuckets, ExistingDocs, [], []), DocBuckets3 = [Bucket || [_|_]=Bucket <- DocBuckets2]; % remove empty buckets false -> DocErrors = [], DocBuckets3 = DocBuckets end, DocBuckets4 = [[{doc_flush_atts(check_dup_atts(Doc), Db#db.updater_fd), Ref} || {Doc, Ref} <- Bucket] || Bucket <- DocBuckets3], {ok, []} = write_and_commit(Db, DocBuckets4, [], [merge_conflicts | Options]), {ok, DocErrors}; update_docs(Db, Docs, Options, interactive_edit) -> increment_stat(Db, {couchdb, database_writes}), AllOrNothing = lists:member(all_or_nothing, Options), % go ahead and generate the new revision ids for the documents. % separate out the NonRep documents from the rest of the documents % associate reference with each doc in order to track duplicates Docs2 = lists:map(fun(Doc) -> {Doc, make_ref()} end,Docs), {Docs3, NonRepDocs} = lists:foldl( fun({#doc{id=Id},_Ref}=Doc, {DocsAcc, NonRepDocsAcc}) -> case Id of <> -> {DocsAcc, [Doc | NonRepDocsAcc]}; Id-> {[Doc | DocsAcc], NonRepDocsAcc} end end, {[], []}, Docs2), DocBuckets = before_docs_update(Db, group_alike_docs(Docs3)), case (Db#db.validate_doc_funs /= []) orelse lists:any( fun({#doc{id= <>}, _Ref}) -> true; ({#doc{atts=Atts}, _Ref}) -> Atts /= [] end, Docs3) of true -> % lookup the doc by id and get the most recent Ids = [Id || [{#doc{id=Id}, _Ref}|_] <- DocBuckets], ExistingDocInfos = get_full_doc_infos(Db, Ids), {DocBucketsPrepped, PreCommitFailures} = prep_and_validate_updates(Db, DocBuckets, ExistingDocInfos, AllOrNothing, [], []), % strip out any empty buckets DocBuckets2 = [Bucket || [_|_] = Bucket <- DocBucketsPrepped]; false -> PreCommitFailures = [], DocBuckets2 = DocBuckets end, if (AllOrNothing) and (PreCommitFailures /= []) -> {aborted, lists:foldl(fun({#doc{id=Id,revs=Revs}, Ref},Acc) -> case lists:keyfind(Ref,1,PreCommitFailures) of {Ref, Error} -> case Revs of {Pos, [RevId|_]} -> [{{Id,{Pos, RevId}}, Error} | Acc]; {0, []} -> [{{Id,{0, <<>>}}, Error} | Acc] end; false -> Acc end end,[],Docs3)}; true -> Options2 = if AllOrNothing -> [merge_conflicts]; true -> [] end ++ Options, DocBuckets3 = [[ {doc_flush_atts(set_new_att_revpos( check_dup_atts(Doc)), Db#db.updater_fd), Ref} || {Doc, Ref} <- B] || B <- DocBuckets2], {DocBuckets4, IdRevs} = new_revs(DocBuckets3, [], []), {ok, CommitResults} = write_and_commit(Db, DocBuckets4, NonRepDocs, Options2), ResultsDict = dict:from_list(IdRevs ++ CommitResults ++ PreCommitFailures), {ok, lists:map( fun({#doc{}, Ref}) -> {ok, Result} = dict:find(Ref, ResultsDict), Result end, Docs2)} end. % Returns the first available document on disk. Input list is a full rev path % for the doc. make_first_doc_on_disk(_Db, _Id, _Pos, []) -> nil; make_first_doc_on_disk(Db, Id, Pos, [{_Rev, #doc{}} | RestPath]) -> make_first_doc_on_disk(Db, Id, Pos-1, RestPath); make_first_doc_on_disk(Db, Id, Pos, [{_Rev, ?REV_MISSING}|RestPath]) -> make_first_doc_on_disk(Db, Id, Pos - 1, RestPath); make_first_doc_on_disk(Db, Id, Pos, [{_Rev, RevValue} |_]=DocPath) -> IsDel = element(1, RevValue), Sp = element(2, RevValue), Revs = [Rev || {Rev, _} <- DocPath], make_doc(Db, Id, IsDel, Sp, {Pos, Revs}). set_commit_option(Options) -> CommitSettings = { [true || O <- Options, O==full_commit orelse O==delay_commit], couch_config:get("couchdb", "delayed_commits", "false") }, case CommitSettings of {[true], _} -> Options; % user requested explicit commit setting, do not change it {_, "true"} -> Options; % delayed commits are enabled, do nothing {_, "false"} -> [full_commit|Options]; {_, Else} -> ?LOG_ERROR("[couchdb] delayed_commits setting must be true/false, not ~p", [Else]), [full_commit|Options] end. collect_results(UpdatePid, MRef, ResultsAcc) -> receive {result, UpdatePid, Result} -> collect_results(UpdatePid, MRef, [Result | ResultsAcc]); {done, UpdatePid} -> {ok, ResultsAcc}; {retry, UpdatePid} -> retry; {'DOWN', MRef, _, _, Reason} -> exit(Reason) end. write_and_commit(#db{update_pid=UpdatePid}=Db, DocBuckets1, NonRepDocs, Options0) -> DocBuckets = prepare_doc_summaries(Db, DocBuckets1), Options = set_commit_option(Options0), MergeConflicts = lists:member(merge_conflicts, Options), FullCommit = lists:member(full_commit, Options), MRef = erlang:monitor(process, UpdatePid), try UpdatePid ! {update_docs, self(), DocBuckets, NonRepDocs, MergeConflicts, FullCommit}, case collect_results(UpdatePid, MRef, []) of {ok, Results} -> {ok, Results}; retry -> % This can happen if the db file we wrote to was swapped out by % compaction. Retry by reopening the db and writing to the current file {ok, Db2} = open_ref_counted(Db#db.main_pid, self()), DocBuckets2 = [ [{doc_flush_atts(Doc, Db2#db.updater_fd), Ref} || {Doc, Ref} <- Bucket] || Bucket <- DocBuckets1 ], % We only retry once DocBuckets3 = prepare_doc_summaries(Db2, DocBuckets2), close(Db2), UpdatePid ! {update_docs, self(), DocBuckets3, NonRepDocs, MergeConflicts, FullCommit}, case collect_results(UpdatePid, MRef, []) of {ok, Results} -> {ok, Results}; retry -> throw({update_error, compaction_retry}) end end after erlang:demonitor(MRef, [flush]) end. prepare_doc_summaries(Db, BucketList) -> [lists:map( fun({#doc{body = Body, atts = Atts} = Doc, Ref}) -> DiskAtts = [{N, T, P, AL, DL, R, M, E} || #att{name = N, type = T, data = {_, P}, md5 = M, revpos = R, att_len = AL, disk_len = DL, encoding = E} <- Atts], AttsFd = case Atts of [#att{data = {Fd, _}} | _] -> Fd; [] -> nil end, SummaryChunk = couch_db_updater:make_doc_summary(Db, {Body, DiskAtts}), {Doc#doc{body = {summary, SummaryChunk, AttsFd}}, Ref} end, Bucket) || Bucket <- BucketList]. before_docs_update(#db{before_doc_update = nil}, BucketList) -> BucketList; before_docs_update(#db{before_doc_update = Fun} = Db, BucketList) -> [lists:map( fun({Doc, Ref}) -> NewDoc = Fun(couch_doc:with_ejson_body(Doc), Db), {NewDoc, Ref} end, Bucket) || Bucket <- BucketList]. set_new_att_revpos(#doc{revs={RevPos,_Revs},atts=Atts}=Doc) -> Doc#doc{atts= lists:map(fun(#att{data={_Fd,_Sp}}=Att) -> % already commited to disk, do not set new rev Att; (Att) -> Att#att{revpos=RevPos+1} end, Atts)}. doc_flush_atts(Doc, Fd) -> Doc#doc{atts=[flush_att(Fd, Att) || Att <- Doc#doc.atts]}. check_md5(_NewSig, <<>>) -> ok; check_md5(Sig, Sig) -> ok; check_md5(_, _) -> throw(md5_mismatch). flush_att(Fd, #att{data={Fd0, _}}=Att) when Fd0 == Fd -> % already written to our file, nothing to write Att; flush_att(Fd, #att{data={OtherFd,StreamPointer}, md5=InMd5, disk_len=InDiskLen} = Att) -> {NewStreamData, Len, _IdentityLen, Md5, IdentityMd5} = couch_stream:copy_to_new_stream(OtherFd, StreamPointer, Fd), check_md5(IdentityMd5, InMd5), Att#att{data={Fd, NewStreamData}, md5=Md5, att_len=Len, disk_len=InDiskLen}; flush_att(Fd, #att{data=Data}=Att) when is_binary(Data) -> with_stream(Fd, Att, fun(OutputStream) -> couch_stream:write(OutputStream, Data) end); flush_att(Fd, #att{data=Fun,att_len=undefined}=Att) when is_function(Fun) -> MaxChunkSize = list_to_integer( couch_config:get("couchdb", "attachment_stream_buffer_size", "4096")), with_stream(Fd, Att, fun(OutputStream) -> % Fun(MaxChunkSize, WriterFun) must call WriterFun % once for each chunk of the attachment, Fun(MaxChunkSize, % WriterFun({Length, Binary}, State) % WriterFun({0, _Footers}, State) % Called with Length == 0 on the last time. % WriterFun returns NewState. fun({0, Footers}, _) -> F = mochiweb_headers:from_binary(Footers), case mochiweb_headers:get_value("Content-MD5", F) of undefined -> ok; Md5 -> {md5, base64:decode(Md5)} end; ({_Length, Chunk}, _) -> couch_stream:write(OutputStream, Chunk) end, ok) end); flush_att(Fd, #att{data=Fun,att_len=AttLen}=Att) when is_function(Fun) -> with_stream(Fd, Att, fun(OutputStream) -> write_streamed_attachment(OutputStream, Fun, AttLen) end). compressible_att_type(MimeType) when is_binary(MimeType) -> compressible_att_type(?b2l(MimeType)); compressible_att_type(MimeType) -> TypeExpList = re:split( couch_config:get("attachments", "compressible_types", ""), "\\s*,\\s*", [{return, list}] ), lists:any( fun(TypeExp) -> Regexp = ["^\\s*", re:replace(TypeExp, "\\*", ".*"), "(?:\\s*;.*?)?\\s*", $$], re:run(MimeType, Regexp, [caseless]) =/= nomatch end, [T || T <- TypeExpList, T /= []] ). % From RFC 2616 3.6.1 - Chunked Transfer Coding % % In other words, the origin server is willing to accept % the possibility that the trailer fields might be silently % discarded along the path to the client. % % I take this to mean that if "Trailers: Content-MD5\r\n" % is present in the request, but there is no Content-MD5 % trailer, we're free to ignore this inconsistency and % pretend that no Content-MD5 exists. with_stream(Fd, #att{md5=InMd5,type=Type,encoding=Enc}=Att, Fun) -> BufferSize = list_to_integer( couch_config:get("couchdb", "attachment_stream_buffer_size", "4096")), {ok, OutputStream} = case (Enc =:= identity) andalso compressible_att_type(Type) of true -> CompLevel = list_to_integer( couch_config:get("attachments", "compression_level", "0") ), couch_stream:open(Fd, [{buffer_size, BufferSize}, {encoding, gzip}, {compression_level, CompLevel}]); _ -> couch_stream:open(Fd, [{buffer_size, BufferSize}]) end, ReqMd5 = case Fun(OutputStream) of {md5, FooterMd5} -> case InMd5 of md5_in_footer -> FooterMd5; _ -> InMd5 end; _ -> InMd5 end, {StreamInfo, Len, IdentityLen, Md5, IdentityMd5} = couch_stream:close(OutputStream), check_md5(IdentityMd5, ReqMd5), {AttLen, DiskLen, NewEnc} = case Enc of identity -> case {Md5, IdentityMd5} of {Same, Same} -> {Len, IdentityLen, identity}; _ -> {Len, IdentityLen, gzip} end; gzip -> case {Att#att.att_len, Att#att.disk_len} of {AL, DL} when AL =:= undefined orelse DL =:= undefined -> % Compressed attachment uploaded through the standalone API. {Len, Len, gzip}; {AL, DL} -> % This case is used for efficient push-replication, where a % compressed attachment is located in the body of multipart % content-type request. {AL, DL, gzip} end end, Att#att{ data={Fd,StreamInfo}, att_len=AttLen, disk_len=DiskLen, md5=Md5, encoding=NewEnc }. write_streamed_attachment(_Stream, _F, 0) -> ok; write_streamed_attachment(Stream, F, LenLeft) when LenLeft > 0 -> Bin = read_next_chunk(F, LenLeft), ok = couch_stream:write(Stream, Bin), write_streamed_attachment(Stream, F, LenLeft - size(Bin)). read_next_chunk(F, _) when is_function(F, 0) -> F(); read_next_chunk(F, LenLeft) when is_function(F, 1) -> F(lists:min([LenLeft, 16#2000])). enum_docs_since_reduce_to_count(Reds) -> couch_btree:final_reduce( fun couch_db_updater:btree_by_seq_reduce/2, Reds). enum_docs_reduce_to_count(Reds) -> FinalRed = couch_btree:final_reduce( fun couch_db_updater:btree_by_id_reduce/2, Reds), element(1, FinalRed). changes_since(Db, StartSeq, Fun, Acc) -> changes_since(Db, StartSeq, Fun, [], Acc). changes_since(Db, StartSeq, Fun, Options, Acc) -> Wrapper = fun(DocInfo, _Offset, Acc2) -> Fun(DocInfo, Acc2) end, {ok, _LastReduction, AccOut} = couch_btree:fold(by_seq_btree(Db), Wrapper, Acc, [{start_key, StartSeq + 1}] ++ Options), {ok, AccOut}. count_changes_since(Db, SinceSeq) -> BTree = by_seq_btree(Db), {ok, Changes} = couch_btree:fold_reduce(BTree, fun(_SeqStart, PartialReds, 0) -> {ok, couch_btree:final_reduce(BTree, PartialReds)} end, 0, [{start_key, SinceSeq + 1}]), Changes. enum_docs_since(Db, SinceSeq, InFun, Acc, Options) -> {ok, LastReduction, AccOut} = couch_btree:fold( by_seq_btree(Db), InFun, Acc, [{start_key, SinceSeq + 1} | Options]), {ok, enum_docs_since_reduce_to_count(LastReduction), AccOut}. enum_docs(Db, InFun, InAcc, Options) -> FoldFun = skip_deleted(InFun), {ok, LastReduce, OutAcc} = couch_btree:fold( by_id_btree(Db), FoldFun, InAcc, Options), {ok, enum_docs_reduce_to_count(LastReduce), OutAcc}. % server functions init({DbName, Filepath, Fd, Options}) -> {ok, UpdaterPid} = gen_server:start_link(couch_db_updater, {self(), DbName, Filepath, Fd, Options}, []), {ok, #db{fd_ref_counter=RefCntr}=Db} = gen_server:call(UpdaterPid, get_db), couch_ref_counter:add(RefCntr), case lists:member(sys_db, Options) of true -> ok; false -> couch_stats_collector:track_process_count({couchdb, open_databases}) end, process_flag(trap_exit, true), {ok, Db}. terminate(_Reason, Db) -> couch_util:shutdown_sync(Db#db.update_pid), ok. handle_call({open_ref_count, OpenerPid}, _, #db{fd_ref_counter=RefCntr}=Db) -> ok = couch_ref_counter:add(RefCntr, OpenerPid), {reply, {ok, Db}, Db}; handle_call(is_idle, _From, #db{fd_ref_counter=RefCntr, compactor_pid=Compact, waiting_delayed_commit=Delay}=Db) -> % Idle means no referrers. Unless in the middle of a compaction file switch, % there are always at least 2 referrers, couch_db_updater and us. {reply, (Delay == nil) andalso (Compact == nil) andalso (couch_ref_counter:count(RefCntr) == 2), Db}; handle_call({db_updated, NewDb}, _From, #db{fd_ref_counter=OldRefCntr}) -> #db{fd_ref_counter=NewRefCntr}=NewDb, case NewRefCntr =:= OldRefCntr of true -> ok; false -> couch_ref_counter:add(NewRefCntr), couch_ref_counter:drop(OldRefCntr) end, {reply, ok, NewDb}; handle_call(get_db, _From, Db) -> {reply, {ok, Db}, Db}. handle_cast(Msg, Db) -> ?LOG_ERROR("Bad cast message received for db ~s: ~p", [Db#db.name, Msg]), exit({error, Msg}). code_change(_OldVsn, State, _Extra) -> {ok, State}. handle_info({'EXIT', _Pid, normal}, Db) -> {noreply, Db}; handle_info({'EXIT', _Pid, Reason}, Server) -> {stop, Reason, Server}; handle_info(Msg, Db) -> ?LOG_ERROR("Bad message received for db ~s: ~p", [Db#db.name, Msg]), exit({error, Msg}). %%% Internal function %%% open_doc_revs_int(Db, IdRevs, Options) -> Ids = [Id || {Id, _Revs} <- IdRevs], LookupResults = get_full_doc_infos(Db, Ids), lists:zipwith( fun({Id, Revs}, Lookup) -> case Lookup of {ok, #full_doc_info{rev_tree=RevTree}} -> {FoundRevs, MissingRevs} = case Revs of all -> {couch_key_tree:get_all_leafs(RevTree), []}; _ -> case lists:member(latest, Options) of true -> couch_key_tree:get_key_leafs(RevTree, Revs); false -> couch_key_tree:get(RevTree, Revs) end end, FoundResults = lists:map(fun({Value, {Pos, [Rev|_]}=FoundRevPath}) -> case Value of ?REV_MISSING -> % we have the rev in our list but know nothing about it {{not_found, missing}, {Pos, Rev}}; RevValue -> IsDeleted = element(1, RevValue), SummaryPtr = element(2, RevValue), {ok, make_doc(Db, Id, IsDeleted, SummaryPtr, FoundRevPath)} end end, FoundRevs), Results = FoundResults ++ [{{not_found, missing}, MissingRev} || MissingRev <- MissingRevs], {ok, Results}; not_found when Revs == all -> {ok, []}; not_found -> {ok, [{{not_found, missing}, Rev} || Rev <- Revs]} end end, IdRevs, LookupResults). open_doc_int(Db, <> = Id, Options) -> case couch_btree:lookup(local_btree(Db), [Id]) of [{ok, {_, {Rev, BodyData}}}] -> Doc = #doc{id=Id, revs={0, [?l2b(integer_to_list(Rev))]}, body=BodyData}, apply_open_options({ok, Doc}, Options); [not_found] -> {not_found, missing} end; open_doc_int(Db, #doc_info{id=Id,revs=[RevInfo|_]}=DocInfo, Options) -> #rev_info{deleted=IsDeleted,rev={Pos,RevId},body_sp=Bp} = RevInfo, Doc = make_doc(Db, Id, IsDeleted, Bp, {Pos,[RevId]}), apply_open_options( {ok, Doc#doc{meta=doc_meta_info(DocInfo, [], Options)}}, Options); open_doc_int(Db, #full_doc_info{id=Id,rev_tree=RevTree}=FullDocInfo, Options) -> #doc_info{revs=[#rev_info{deleted=IsDeleted,rev=Rev,body_sp=Bp}|_]} = DocInfo = couch_doc:to_doc_info(FullDocInfo), {[{_, RevPath}], []} = couch_key_tree:get(RevTree, [Rev]), Doc = make_doc(Db, Id, IsDeleted, Bp, RevPath), apply_open_options( {ok, Doc#doc{meta=doc_meta_info(DocInfo, RevTree, Options)}}, Options); open_doc_int(Db, Id, Options) -> case get_full_doc_info(Db, Id) of {ok, FullDocInfo} -> open_doc_int(Db, FullDocInfo, Options); not_found -> {not_found, missing} end. doc_meta_info(#doc_info{high_seq=Seq,revs=[#rev_info{rev=Rev}|RestInfo]}, RevTree, Options) -> case lists:member(revs_info, Options) of false -> []; true -> {[{Pos, RevPath}],[]} = couch_key_tree:get_full_key_paths(RevTree, [Rev]), [{revs_info, Pos, lists:map( fun({Rev1, ?REV_MISSING}) -> {Rev1, missing}; ({Rev1, RevValue}) -> case element(1, RevValue) of true -> {Rev1, deleted}; false -> {Rev1, available} end end, RevPath)}] end ++ case lists:member(conflicts, Options) of false -> []; true -> case [Rev1 || #rev_info{rev=Rev1,deleted=false} <- RestInfo] of [] -> []; ConflictRevs -> [{conflicts, ConflictRevs}] end end ++ case lists:member(deleted_conflicts, Options) of false -> []; true -> case [Rev1 || #rev_info{rev=Rev1,deleted=true} <- RestInfo] of [] -> []; DelConflictRevs -> [{deleted_conflicts, DelConflictRevs}] end end ++ case lists:member(local_seq, Options) of false -> []; true -> [{local_seq, Seq}] end. read_doc(#db{fd=Fd}, Pos) -> couch_file:pread_term(Fd, Pos). make_doc(#db{updater_fd = Fd} = Db, Id, Deleted, Bp, RevisionPath) -> {BodyData, Atts} = case Bp of nil -> {[], []}; _ -> {ok, {BodyData0, Atts00}} = read_doc(Db, Bp), Atts0 = case Atts00 of _ when is_binary(Atts00) -> couch_compress:decompress(Atts00); _ when is_list(Atts00) -> % pre 1.2 format Atts00 end, {BodyData0, lists:map( fun({Name,Type,Sp,AttLen,DiskLen,RevPos,Md5,Enc}) -> #att{name=Name, type=Type, att_len=AttLen, disk_len=DiskLen, md5=Md5, revpos=RevPos, data={Fd,Sp}, encoding= case Enc of true -> % 0110 UPGRADE CODE gzip; false -> % 0110 UPGRADE CODE identity; _ -> Enc end }; ({Name,Type,Sp,AttLen,RevPos,Md5}) -> #att{name=Name, type=Type, att_len=AttLen, disk_len=AttLen, md5=Md5, revpos=RevPos, data={Fd,Sp}}; ({Name,{Type,Sp,AttLen}}) -> #att{name=Name, type=Type, att_len=AttLen, disk_len=AttLen, md5= <<>>, revpos=0, data={Fd,Sp}} end, Atts0)} end, Doc = #doc{ id = Id, revs = RevisionPath, body = BodyData, atts = Atts, deleted = Deleted }, after_doc_read(Db, Doc). after_doc_read(#db{after_doc_read = nil}, Doc) -> Doc; after_doc_read(#db{after_doc_read = Fun} = Db, Doc) -> Fun(couch_doc:with_ejson_body(Doc), Db). increment_stat(#db{options = Options}, Stat) -> case lists:member(sys_db, Options) of true -> ok; false -> couch_stats_collector:increment(Stat) end. local_btree(#db{local_docs_btree = BTree, fd = ReaderFd}) -> BTree#btree{fd = ReaderFd}. by_seq_btree(#db{docinfo_by_seq_btree = BTree, fd = ReaderFd}) -> BTree#btree{fd = ReaderFd}. by_id_btree(#db{fulldocinfo_by_id_btree = BTree, fd = ReaderFd}) -> BTree#btree{fd = ReaderFd}. skip_deleted(FoldFun) -> fun (visit, KV, Reds, Acc) -> FoldFun(KV, Reds, Acc); (traverse, _LK, {Undeleted, _Del, _Size}, Acc) when Undeleted == 0 -> {skip, Acc}; (traverse, _, _, Acc) -> {ok, Acc} end. apache-couchdb-1.5.0/src/couchdb/couch_db.hrl0000644000175000001440000001455612230722213015740 00000000000000% 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. -define(LOCAL_DOC_PREFIX, "_local/"). -define(DESIGN_DOC_PREFIX0, "_design"). -define(DESIGN_DOC_PREFIX, "_design/"). -define(DEFAULT_COMPRESSION, snappy). -define(MIN_STR, <<"">>). -define(MAX_STR, <<255>>). % illegal utf string % the lowest possible database sequence number -define(LOWEST_SEQ, 0). -define(REWRITE_COUNT, couch_rewrite_count). -define(JSON_ENCODE(V), ejson:encode(V)). -define(JSON_DECODE(V), ejson:decode(V)). -define(b2l(V), binary_to_list(V)). -define(l2b(V), list_to_binary(V)). -define(term_to_bin(T), term_to_binary(T, [{minor_version, 1}])). -define(term_size(T), try erlang:external_size(T) catch _:_ -> byte_size(?term_to_bin(T)) end). -define(DEFAULT_ATTACHMENT_CONTENT_TYPE, <<"application/octet-stream">>). -define(LOG_DEBUG(Format, Args), case couch_log:debug_on(?MODULE) of true -> couch_log:debug(Format, Args); false -> ok end). -define(LOG_INFO(Format, Args), case couch_log:info_on(?MODULE) of true -> couch_log:info(Format, Args); false -> ok end). -define(LOG_WARN(Format, Args), case couch_log:warn_on(?MODULE) of true -> couch_log:warn(Format, Args); false -> ok end). -define(LOG_ERROR(Format, Args), couch_log:error(Format, Args)). % Tree::term() is really a tree(), but we don't want to require R13B04 yet -type branch() :: {Key::term(), Value::term(), Tree::term()}. -type path() :: {Start::pos_integer(), branch()}. -type tree() :: [branch()]. % sorted by key -record(rev_info, { rev, seq = 0, deleted = false, body_sp = nil % stream pointer }). -record(doc_info, { id = <<"">>, high_seq = 0, revs = [] % rev_info }). -record(full_doc_info, {id = <<"">>, update_seq = 0, deleted = false, rev_tree = [], leafs_size = 0 }). -record(httpd, {mochi_req, peer, method, requested_path_parts, path_parts, db_url_handlers, user_ctx, req_body = undefined, design_url_handlers, auth, default_fun, url_handlers }). -record(doc, { id = <<"">>, revs = {0, []}, % the json body object. body = {[]}, atts = [], % attachments deleted = false, % key/value tuple of meta information, provided when using special options: % couch_db:open_doc(Db, Id, Options). meta = [] }). -record(att, { name, type, att_len, disk_len, % length of the attachment in its identity form % (that is, without a content encoding applied to it) % differs from att_len when encoding /= identity md5= <<>>, revpos=0, data, encoding=identity % currently supported values are: % identity, gzip % additional values to support in the future: % deflate, compress }). -record(user_ctx, { name=null, roles=[], handler }). % This should be updated anytime a header change happens that requires more % than filling in new defaults. % % As long the changes are limited to new header fields (with inline % defaults) added to the end of the record, then there is no need to increment % the disk revision number. % % if the disk revision is incremented, then new upgrade logic will need to be % added to couch_db_updater:init_db. -define(LATEST_DISK_VERSION, 6). -record(db_header, {disk_version = ?LATEST_DISK_VERSION, update_seq = 0, unused = 0, fulldocinfo_by_id_btree_state = nil, docinfo_by_seq_btree_state = nil, local_docs_btree_state = nil, purge_seq = 0, purged_docs = nil, security_ptr = nil, revs_limit = 1000 }). -record(db, {main_pid = nil, update_pid = nil, compactor_pid = nil, instance_start_time, % number of microsecs since jan 1 1970 as a binary string fd, updater_fd, fd_ref_counter, header = #db_header{}, committed_update_seq, fulldocinfo_by_id_btree, docinfo_by_seq_btree, local_docs_btree, update_seq, name, filepath, validate_doc_funs = [], security = [], security_ptr = nil, user_ctx = #user_ctx{}, waiting_delayed_commit = nil, revs_limit = 1000, fsync_options = [], options = [], compression, before_doc_update = nil, % nil | fun(Doc, Db) -> NewDoc after_doc_read = nil % nil | fun(Doc, Db) -> NewDoc }). -record(view_query_args, { start_key, end_key, start_docid = ?MIN_STR, end_docid = ?MAX_STR, direction = fwd, inclusive_end=true, % aka a closed-interval limit = 10000000000, % Huge number to simplify logic skip = 0, group_level = 0, view_type = nil, include_docs = false, conflicts = false, stale = false, multi_get = false, callback = nil, list = nil }). -record(view_fold_helper_funs, { reduce_count, passed_end, start_response, send_row }). -record(reduce_fold_helper_funs, { start_response, send_row }). -record(extern_resp_args, { code = 200, stop = false, data = <<>>, ctype = "application/json", headers = [], json = nil }). -record(index_header, {seq=0, purge_seq=0, id_btree_state=nil, view_states=nil }). % small value used in revision trees to indicate the revision isn't stored -define(REV_MISSING, []). -record(changes_args, { feed = "normal", dir = fwd, since = 0, limit = 1000000000000000, style = main_only, heartbeat, timeout, filter = "", filter_fun, filter_args = [], include_docs = false, conflicts = false, db_open_options = [] }). -record(btree, { fd, root, extract_kv = fun({_Key, _Value} = KV) -> KV end, assemble_kv = fun(Key, Value) -> {Key, Value} end, less = fun(A, B) -> A < B end, reduce = nil, compression = ?DEFAULT_COMPRESSION }). apache-couchdb-1.5.0/src/couchdb/couch_work_queue.erl0000644000175000001440000001151712230722213017530 00000000000000% 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. -module(couch_work_queue). -behaviour(gen_server). -include("couch_db.hrl"). % public API -export([new/1, queue/2, dequeue/1, dequeue/2, close/1, item_count/1, size/1]). % gen_server callbacks -export([init/1, terminate/2]). -export([handle_call/3, handle_cast/2, code_change/3, handle_info/2]). -record(q, { queue = queue:new(), blocked = [], max_size, max_items, items = 0, size = 0, work_waiters = [], close_on_dequeue = false, multi_workers = false }). new(Options) -> gen_server:start_link(couch_work_queue, Options, []). queue(Wq, Item) when is_binary(Item) -> gen_server:call(Wq, {queue, Item, byte_size(Item)}, infinity); queue(Wq, Item) -> gen_server:call(Wq, {queue, Item, ?term_size(Item)}, infinity). dequeue(Wq) -> dequeue(Wq, all). dequeue(Wq, MaxItems) -> try gen_server:call(Wq, {dequeue, MaxItems}, infinity) catch _:_ -> closed end. item_count(Wq) -> try gen_server:call(Wq, item_count, infinity) catch _:_ -> closed end. size(Wq) -> try gen_server:call(Wq, size, infinity) catch _:_ -> closed end. close(Wq) -> gen_server:cast(Wq, close). init(Options) -> Q = #q{ max_size = couch_util:get_value(max_size, Options, nil), max_items = couch_util:get_value(max_items, Options, nil), multi_workers = couch_util:get_value(multi_workers, Options, false) }, {ok, Q}. terminate(_Reason, #q{work_waiters=Workers}) -> lists:foreach(fun({W, _}) -> gen_server:reply(W, closed) end, Workers). handle_call({queue, Item, Size}, From, #q{work_waiters = []} = Q0) -> Q = Q0#q{size = Q0#q.size + Size, items = Q0#q.items + 1, queue = queue:in({Item, Size}, Q0#q.queue)}, case (Q#q.size >= Q#q.max_size) orelse (Q#q.items >= Q#q.max_items) of true -> {noreply, Q#q{blocked = [From | Q#q.blocked]}}; false -> {reply, ok, Q} end; handle_call({queue, Item, _}, _From, #q{work_waiters = [{W, _Max} | Rest]} = Q) -> gen_server:reply(W, {ok, [Item]}), {reply, ok, Q#q{work_waiters = Rest}}; handle_call({dequeue, Max}, From, Q) -> #q{work_waiters = Workers, multi_workers = Multi, items = Count} = Q, case {Workers, Multi} of {[_ | _], false} -> exit("Only one caller allowed to wait for this work at a time"); {[_ | _], true} -> {noreply, Q#q{work_waiters=Workers ++ [{From, Max}]}}; _ -> case Count of 0 -> {noreply, Q#q{work_waiters=Workers ++ [{From, Max}]}}; C when C > 0 -> deliver_queue_items(Max, Q) end end; handle_call(item_count, _From, Q) -> {reply, Q#q.items, Q}; handle_call(size, _From, Q) -> {reply, Q#q.size, Q}. deliver_queue_items(Max, Q) -> #q{ queue = Queue, items = Count, size = Size, close_on_dequeue = Close, blocked = Blocked } = Q, case (Max =:= all) orelse (Max >= Count) of false -> {Items, Size2, Queue2, Blocked2} = dequeue_items( Max, Size, Queue, Blocked, []), Q2 = Q#q{ items = Count - Max, size = Size2, blocked = Blocked2, queue = Queue2 }, {reply, {ok, Items}, Q2}; true -> lists:foreach(fun(F) -> gen_server:reply(F, ok) end, Blocked), Q2 = Q#q{items = 0, size = 0, blocked = [], queue = queue:new()}, Items = [Item || {Item, _} <- queue:to_list(Queue)], case Close of false -> {reply, {ok, Items}, Q2}; true -> {stop, normal, {ok, Items}, Q2} end end. dequeue_items(0, Size, Queue, Blocked, DequeuedAcc) -> {lists:reverse(DequeuedAcc), Size, Queue, Blocked}; dequeue_items(NumItems, Size, Queue, Blocked, DequeuedAcc) -> {{value, {Item, ItemSize}}, Queue2} = queue:out(Queue), case Blocked of [] -> Blocked2 = Blocked; [From | Blocked2] -> gen_server:reply(From, ok) end, dequeue_items( NumItems - 1, Size - ItemSize, Queue2, Blocked2, [Item | DequeuedAcc]). handle_cast(close, #q{items = 0} = Q) -> {stop, normal, Q}; handle_cast(close, Q) -> {noreply, Q#q{close_on_dequeue = true}}. code_change(_OldVsn, State, _Extra) -> {ok, State}. handle_info(X, Q) -> {stop, X, Q}. apache-couchdb-1.5.0/src/couchdb/couch_ref_counter.erl0000644000175000001440000000616212230722213017655 00000000000000% 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. -module(couch_ref_counter). -behaviour(gen_server). -export([start/1, init/1, terminate/2, handle_call/3, handle_cast/2, code_change/3, handle_info/2]). -export([drop/1,drop/2,add/1,add/2,count/1]). start(ChildProcs) -> gen_server:start(couch_ref_counter, {self(), ChildProcs}, []). drop(RefCounterPid) -> drop(RefCounterPid, self()). drop(RefCounterPid, Pid) -> gen_server:call(RefCounterPid, {drop, Pid}, infinity). add(RefCounterPid) -> add(RefCounterPid, self()). add(RefCounterPid, Pid) -> gen_server:call(RefCounterPid, {add, Pid}, infinity). count(RefCounterPid) -> gen_server:call(RefCounterPid, count). % server functions -record(srv, { referrers=dict:new(), % a dict of each ref counting proc. child_procs=[] }). init({Pid, ChildProcs}) -> [link(ChildProc) || ChildProc <- ChildProcs], Referrers = dict:from_list([{Pid, {erlang:monitor(process, Pid), 1}}]), {ok, #srv{referrers=Referrers, child_procs=ChildProcs}}. terminate(_Reason, #srv{child_procs=ChildProcs}) -> [couch_util:shutdown_sync(Pid) || Pid <- ChildProcs], ok. handle_call({add, Pid},_From, #srv{referrers=Referrers}=Srv) -> Referrers2 = case dict:find(Pid, Referrers) of error -> dict:store(Pid, {erlang:monitor(process, Pid), 1}, Referrers); {ok, {MonRef, RefCnt}} -> dict:store(Pid, {MonRef, RefCnt + 1}, Referrers) end, {reply, ok, Srv#srv{referrers=Referrers2}}; handle_call(count, _From, Srv) -> {monitors, Monitors} = process_info(self(), monitors), {reply, length(Monitors), Srv}; handle_call({drop, Pid}, _From, #srv{referrers=Referrers}=Srv) -> Referrers2 = case dict:find(Pid, Referrers) of {ok, {MonRef, 1}} -> erlang:demonitor(MonRef, [flush]), dict:erase(Pid, Referrers); {ok, {MonRef, Num}} -> dict:store(Pid, {MonRef, Num-1}, Referrers); error -> Referrers end, Srv2 = Srv#srv{referrers=Referrers2}, case should_close() of true -> {stop,normal,ok,Srv2}; false -> {reply, ok, Srv2} end. handle_cast(Msg, _Srv)-> exit({unknown_msg,Msg}). code_change(_OldVsn, State, _Extra) -> {ok, State}. handle_info({'DOWN', MonRef, _, Pid, _}, #srv{referrers=Referrers}=Srv) -> {ok, {MonRef, _RefCount}} = dict:find(Pid, Referrers), Srv2 = Srv#srv{referrers=dict:erase(Pid, Referrers)}, case should_close() of true -> {stop,normal,Srv2}; false -> {noreply,Srv2} end. should_close() -> case process_info(self(), monitors) of {monitors, []} -> true; _ -> false end. apache-couchdb-1.5.0/src/couchdb/couch_config_writer.erl0000644000175000001440000000665612230722213020213 00000000000000% 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. %% @doc Saves a Key/Value pair to a ini file. The Key consists of a Section %% and Option combination. If that combination is found in the ini file %% the new value replaces the old value. If only the Section is found the %% Option and value combination is appended to the Section. If the Section %% does not yet exist in the ini file, it is added and the Option/Value %% pair is appended. %% @see couch_config -module(couch_config_writer). -export([save_to_file/2]). -include("couch_db.hrl"). %% @spec save_to_file( %% Config::{{Section::string(), Option::string()}, Value::string()}, %% File::filename()) -> ok %% @doc Saves a Section/Key/Value triple to the ini file File::filename() save_to_file({{Section, Key}, Value}, File) -> {ok, OldFileContents} = file:read_file(File), Lines = re:split(OldFileContents, "\r\n|\n|\r|\032", [{return, list}]), SectionLine = "[" ++ Section ++ "]", {ok, Pattern} = re:compile(["^(", Key, "\\s*=)|\\[[a-zA-Z0-9\_-]*\\]"]), NewLines = process_file_lines(Lines, [], SectionLine, Pattern, Key, Value), NewFileContents = reverse_and_add_newline(strip_empty_lines(NewLines), []), case file:write_file(File, NewFileContents) of ok -> ok; {error, Reason} = Error -> ?LOG_ERROR("Could not write config file ~s: ~s", [File, file:format_error(Reason)]), Error end. process_file_lines([Section|Rest], SeenLines, Section, Pattern, Key, Value) -> process_section_lines(Rest, [Section|SeenLines], Pattern, Key, Value); process_file_lines([Line|Rest], SeenLines, Section, Pattern, Key, Value) -> process_file_lines(Rest, [Line|SeenLines], Section, Pattern, Key, Value); process_file_lines([], SeenLines, Section, _Pattern, Key, Value) -> % Section wasn't found. Append it with the option here. [Key ++ " = " ++ Value, Section, "" | strip_empty_lines(SeenLines)]. process_section_lines([Line|Rest], SeenLines, Pattern, Key, Value) -> case re:run(Line, Pattern, [{capture, all_but_first}]) of nomatch -> % Found nothing interesting. Move on. process_section_lines(Rest, [Line|SeenLines], Pattern, Key, Value); {match, []} -> % Found another section. Append the option here. lists:reverse(Rest) ++ [Line, "", Key ++ " = " ++ Value | strip_empty_lines(SeenLines)]; {match, _} -> % Found the option itself. Replace it. lists:reverse(Rest) ++ [Key ++ " = " ++ Value | SeenLines] end; process_section_lines([], SeenLines, _Pattern, Key, Value) -> % Found end of file within the section. Append the option here. [Key ++ " = " ++ Value | strip_empty_lines(SeenLines)]. reverse_and_add_newline([Line|Rest], Content) -> reverse_and_add_newline(Rest, [Line, "\n", Content]); reverse_and_add_newline([], Content) -> Content. strip_empty_lines(["" | Rest]) -> strip_empty_lines(Rest); strip_empty_lines(All) -> All. apache-couchdb-1.5.0/src/couchdb/Makefile.am0000644000175000001440000001275612230722213015517 00000000000000## 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. SUBDIRS = priv # devdocdir = $(localdocdir)/developer/couchdb couchlibdir = $(localerlanglibdir)/couch-$(version) couchincludedir = $(couchlibdir)/include couchebindir = $(couchlibdir)/ebin couchinclude_DATA = couch_db.hrl couch_js_functions.hrl couchebin_DATA = $(compiled_files) # dist_devdoc_DATA = $(doc_base) $(doc_modules) CLEANFILES = $(compiled_files) $(doc_base) # CLEANFILES = $(doc_modules) edoc-info source_files = \ couch.erl \ couch_app.erl \ couch_auth_cache.erl \ couch_btree.erl \ couch_changes.erl \ couch_compaction_daemon.erl \ couch_compress.erl \ couch_config.erl \ couch_config_writer.erl \ couch_db.erl \ couch_db_update_notifier.erl \ couch_db_update_notifier_sup.erl \ couch_doc.erl \ couch_drv.erl \ couch_ejson_compare.erl \ couch_event_sup.erl \ couch_external_manager.erl \ couch_external_server.erl \ couch_file.erl \ couch_httpd.erl \ couch_httpd_db.erl \ couch_httpd_auth.erl \ couch_httpd_cors.erl \ couch_httpd_oauth.erl \ couch_httpd_external.erl \ couch_httpd_misc_handlers.erl \ couch_httpd_proxy.erl \ couch_httpd_rewrite.erl \ couch_httpd_stats_handlers.erl \ couch_httpd_vhost.erl \ couch_key_tree.erl \ couch_log.erl \ couch_native_process.erl \ couch_os_daemons.erl \ couch_os_process.erl \ couch_passwords.erl \ couch_primary_sup.erl \ couch_query_servers.erl \ couch_ref_counter.erl \ couch_secondary_sup.erl \ couch_server.erl \ couch_server_sup.erl \ couch_stats_aggregator.erl \ couch_stats_collector.erl \ couch_stream.erl \ couch_task_status.erl \ couch_users_db.erl \ couch_util.erl \ couch_uuids.erl \ couch_db_updater.erl \ couch_work_queue.erl \ json_stream_parse.erl EXTRA_DIST = $(source_files) couch_db.hrl couch_js_functions.hrl compiled_files = \ couch.app \ couch.beam \ couch_app.beam \ couch_auth_cache.beam \ couch_btree.beam \ couch_changes.beam \ couch_compaction_daemon.beam \ couch_compress.beam \ couch_config.beam \ couch_config_writer.beam \ couch_db.beam \ couch_db_update_notifier.beam \ couch_db_update_notifier_sup.beam \ couch_doc.beam \ couch_drv.beam \ couch_ejson_compare.beam \ couch_event_sup.beam \ couch_external_manager.beam \ couch_external_server.beam \ couch_file.beam \ couch_httpd.beam \ couch_httpd_db.beam \ couch_httpd_auth.beam \ couch_httpd_oauth.beam \ couch_httpd_cors.beam \ couch_httpd_proxy.beam \ couch_httpd_external.beam \ couch_httpd_misc_handlers.beam \ couch_httpd_rewrite.beam \ couch_httpd_stats_handlers.beam \ couch_httpd_vhost.beam \ couch_key_tree.beam \ couch_log.beam \ couch_native_process.beam \ couch_os_daemons.beam \ couch_os_process.beam \ couch_passwords.beam \ couch_primary_sup.beam \ couch_query_servers.beam \ couch_ref_counter.beam \ couch_secondary_sup.beam \ couch_server.beam \ couch_server_sup.beam \ couch_stats_aggregator.beam \ couch_stats_collector.beam \ couch_stream.beam \ couch_task_status.beam \ couch_users_db.beam \ couch_util.beam \ couch_uuids.beam \ couch_db_updater.beam \ couch_work_queue.beam \ json_stream_parse.beam # doc_base = \ # erlang.png \ # index.html \ # modules-frame.html \ # overview-summary.html \ # packages-frame.html \ # stylesheet.css # doc_modules = \ # couch_btree.html \ # couch_config.html \ # couch_config_writer.html \ # couch_db.html \ # couch_db_update_notifier.html \ # couch_db_update_notifier_sup.html \ # couch_doc.html \ # couch_event_sup.html \ # couch_file.html \ # couch_httpd.html \ # couch_key_tree.html \ # couch_log.html \ # couch_query_servers.html \ # couch_rep.html \ # couch_rep_sup.html \ # couch_server.html \ # couch_server_sup.html \ # couch_stream.html \ # couch_util.html if WINDOWS couch.app: couch.app.tpl modules=`find . -name "*.erl" \! -name ".*" -exec basename {} .erl \; | tr '\n' ',' | sed "s/,$$//"`; \ sed -e "s|%package_name%|@package_name@|g" \ -e "s|%version%|@version@|g" \ -e "s|@modules@|$$modules|g" \ -e "s|%localconfdir%|../etc/couchdb|g" \ -e "s|@defaultini@|default.ini|g" \ -e "s|@localini@|local.ini|g" > \ $@ < $< else couch.app: couch.app.tpl modules=`{ find . -name "*.erl" \! -name ".*" -exec basename {} .erl \; | tr '\n' ','; echo ''; } | sed "s/,$$//"`; \ sed -e "s|%package_name%|@package_name@|g" \ -e "s|%version%|@version@|g" \ -e "s|@modules@|$$modules|g" \ -e "s|%localconfdir%|@localconfdir@|g" \ -e "s|@defaultini@|default.ini|g" \ -e "s|@localini@|local.ini|g" > \ $@ < $< chmod +x $@ endif # $(dist_devdoc_DATA): edoc-info # $(ERL) -noshell -run edoc_run files [\"$<\"] %.beam: %.erl couch_db.hrl couch_js_functions.hrl $(ERLC) $(ERLC_FLAGS) ${TEST} $<; apache-couchdb-1.5.0/src/couchdb/Makefile.in0000644000175000001440000006734612230722243015540 00000000000000# Makefile.in generated by automake 1.11.6 from Makefile.am. # @configure_input@ # Copyright (C) 1994, 1995, 1996, 1997, 1998, 1999, 2000, 2001, 2002, # 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011 Free Software # Foundation, Inc. # This Makefile.in is free software; the Free Software Foundation # gives unlimited permission to copy and/or distribute it, # with or without modifications, as long as this notice is preserved. # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY, to the extent permitted by law; without # even the implied warranty of MERCHANTABILITY or FITNESS FOR A # PARTICULAR PURPOSE. @SET_MAKE@ VPATH = @srcdir@ am__make_dryrun = \ { \ am__dry=no; \ case $$MAKEFLAGS in \ *\\[\ \ ]*) \ echo 'am--echo: ; @echo "AM" OK' | $(MAKE) -f - 2>/dev/null \ | grep '^AM OK$$' >/dev/null || am__dry=yes;; \ *) \ for am__flg in $$MAKEFLAGS; do \ case $$am__flg in \ *=*|--*) ;; \ *n*) am__dry=yes; break;; \ esac; \ done;; \ esac; \ test $$am__dry = yes; \ } pkgdatadir = $(datadir)/@PACKAGE@ pkgincludedir = $(includedir)/@PACKAGE@ pkglibdir = $(libdir)/@PACKAGE@ pkglibexecdir = $(libexecdir)/@PACKAGE@ am__cd = CDPATH="$${ZSH_VERSION+.}$(PATH_SEPARATOR)" && cd install_sh_DATA = $(install_sh) -c -m 644 install_sh_PROGRAM = $(install_sh) -c install_sh_SCRIPT = $(install_sh) -c INSTALL_HEADER = $(INSTALL_DATA) transform = $(program_transform_name) NORMAL_INSTALL = : PRE_INSTALL = : POST_INSTALL = : NORMAL_UNINSTALL = : PRE_UNINSTALL = : POST_UNINSTALL = : build_triplet = @build@ host_triplet = @host@ subdir = src/couchdb DIST_COMMON = $(srcdir)/Makefile.am $(srcdir)/Makefile.in \ $(srcdir)/couch.app.tpl.in ACLOCAL_M4 = $(top_srcdir)/aclocal.m4 am__aclocal_m4_deps = $(top_srcdir)/m4/libtool.m4 \ $(top_srcdir)/m4/ltoptions.m4 $(top_srcdir)/m4/ltsugar.m4 \ $(top_srcdir)/m4/ltversion.m4 $(top_srcdir)/m4/lt~obsolete.m4 \ $(top_srcdir)/acinclude.m4 $(top_srcdir)/configure.ac am__configure_deps = $(am__aclocal_m4_deps) $(CONFIGURE_DEPENDENCIES) \ $(ACLOCAL_M4) mkinstalldirs = $(install_sh) -d CONFIG_HEADER = $(top_builddir)/config.h \ $(top_builddir)/src/snappy/google-snappy/config.h CONFIG_CLEAN_FILES = couch.app.tpl CONFIG_CLEAN_VPATH_FILES = SOURCES = DIST_SOURCES = RECURSIVE_TARGETS = all-recursive check-recursive dvi-recursive \ html-recursive info-recursive install-data-recursive \ install-dvi-recursive install-exec-recursive \ install-html-recursive install-info-recursive \ install-pdf-recursive install-ps-recursive install-recursive \ installcheck-recursive installdirs-recursive pdf-recursive \ ps-recursive uninstall-recursive am__can_run_installinfo = \ case $$AM_UPDATE_INFO_DIR in \ n|no|NO) false;; \ *) (install-info --version) >/dev/null 2>&1;; \ esac am__vpath_adj_setup = srcdirstrip=`echo "$(srcdir)" | sed 's|.|.|g'`; am__vpath_adj = case $$p in \ $(srcdir)/*) f=`echo "$$p" | sed "s|^$$srcdirstrip/||"`;; \ *) f=$$p;; \ esac; am__strip_dir = f=`echo $$p | sed -e 's|^.*/||'`; am__install_max = 40 am__nobase_strip_setup = \ srcdirstrip=`echo "$(srcdir)" | sed 's/[].[^$$\\*|]/\\\\&/g'` am__nobase_strip = \ for p in $$list; do echo "$$p"; done | sed -e "s|$$srcdirstrip/||" am__nobase_list = $(am__nobase_strip_setup); \ for p in $$list; do echo "$$p $$p"; done | \ sed "s| $$srcdirstrip/| |;"' / .*\//!s/ .*/ ./; s,\( .*\)/[^/]*$$,\1,' | \ $(AWK) 'BEGIN { files["."] = "" } { files[$$2] = files[$$2] " " $$1; \ if (++n[$$2] == $(am__install_max)) \ { print $$2, files[$$2]; n[$$2] = 0; files[$$2] = "" } } \ END { for (dir in files) print dir, files[dir] }' am__base_list = \ sed '$$!N;$$!N;$$!N;$$!N;$$!N;$$!N;$$!N;s/\n/ /g' | \ sed '$$!N;$$!N;$$!N;$$!N;s/\n/ /g' am__uninstall_files_from_dir = { \ test -z "$$files" \ || { test ! -d "$$dir" && test ! -f "$$dir" && test ! -r "$$dir"; } \ || { echo " ( cd '$$dir' && rm -f" $$files ")"; \ $(am__cd) "$$dir" && rm -f $$files; }; \ } am__installdirs = "$(DESTDIR)$(couchebindir)" \ "$(DESTDIR)$(couchincludedir)" DATA = $(couchebin_DATA) $(couchinclude_DATA) RECURSIVE_CLEAN_TARGETS = mostlyclean-recursive clean-recursive \ distclean-recursive maintainer-clean-recursive AM_RECURSIVE_TARGETS = $(RECURSIVE_TARGETS:-recursive=) \ $(RECURSIVE_CLEAN_TARGETS:-recursive=) tags TAGS ctags CTAGS \ distdir ETAGS = etags CTAGS = ctags DIST_SUBDIRS = $(SUBDIRS) DISTFILES = $(DIST_COMMON) $(DIST_SOURCES) $(TEXINFOS) $(EXTRA_DIST) am__relativize = \ dir0=`pwd`; \ sed_first='s,^\([^/]*\)/.*$$,\1,'; \ sed_rest='s,^[^/]*/*,,'; \ sed_last='s,^.*/\([^/]*\)$$,\1,'; \ sed_butlast='s,/*[^/]*$$,,'; \ while test -n "$$dir1"; do \ first=`echo "$$dir1" | sed -e "$$sed_first"`; \ if test "$$first" != "."; then \ if test "$$first" = ".."; then \ dir2=`echo "$$dir0" | sed -e "$$sed_last"`/"$$dir2"; \ dir0=`echo "$$dir0" | sed -e "$$sed_butlast"`; \ else \ first2=`echo "$$dir2" | sed -e "$$sed_first"`; \ if test "$$first2" = "$$first"; then \ dir2=`echo "$$dir2" | sed -e "$$sed_rest"`; \ else \ dir2="../$$dir2"; \ fi; \ dir0="$$dir0"/"$$first"; \ fi; \ fi; \ dir1=`echo "$$dir1" | sed -e "$$sed_rest"`; \ done; \ reldir="$$dir2" ACLOCAL = @ACLOCAL@ AMTAR = @AMTAR@ AR = @AR@ AS = @AS@ AUTOCONF = @AUTOCONF@ AUTOHEADER = @AUTOHEADER@ AUTOMAKE = @AUTOMAKE@ AWK = @AWK@ CC = @CC@ CCDEPMODE = @CCDEPMODE@ CFLAGS = @CFLAGS@ CPP = @CPP@ CPPFLAGS = @CPPFLAGS@ CURL_CFLAGS = @CURL_CFLAGS@ CURL_CONFIG = @CURL_CONFIG@ CURL_LIBS = @CURL_LIBS@ CXX = @CXX@ CXXCPP = @CXXCPP@ CXXDEPMODE = @CXXDEPMODE@ CXXFLAGS = @CXXFLAGS@ CYGPATH_W = @CYGPATH_W@ DEFS = @DEFS@ DEPDIR = @DEPDIR@ DLLTOOL = @DLLTOOL@ DSYMUTIL = @DSYMUTIL@ DUMPBIN = @DUMPBIN@ ECHO_C = @ECHO_C@ ECHO_N = @ECHO_N@ ECHO_T = @ECHO_T@ EGREP = @EGREP@ ERL = @ERL@ ERLANG_FLAGS = @ERLANG_FLAGS@ ERLC = @ERLC@ ERLC_FLAGS = @ERLC_FLAGS@ ESCRIPT = @ESCRIPT@ EXEEXT = @EXEEXT@ FGREP = @FGREP@ FLAGS = @FLAGS@ GREP = @GREP@ HAS_HELP2MAN = @HAS_HELP2MAN@ HAS_INSTALLINFO = @HAS_INSTALLINFO@ HAS_MAKEINFO = @HAS_MAKEINFO@ HAS_PDFLATEX = @HAS_PDFLATEX@ HAS_SPHINX_BUILD = @HAS_SPHINX_BUILD@ ICU_BIN = @ICU_BIN@ ICU_CFLAGS = @ICU_CFLAGS@ ICU_CONFIG = @ICU_CONFIG@ ICU_CPPFLAGS = @ICU_CPPFLAGS@ ICU_CXXFLAGS = @ICU_CXXFLAGS@ ICU_LIBS = @ICU_LIBS@ INNO_COMPILER_EXECUTABLE = @INNO_COMPILER_EXECUTABLE@ INSTALL = @INSTALL@ INSTALL_DATA = @INSTALL_DATA@ INSTALL_PROGRAM = @INSTALL_PROGRAM@ INSTALL_SCRIPT = @INSTALL_SCRIPT@ INSTALL_STRIP_PROGRAM = @INSTALL_STRIP_PROGRAM@ JS_CFLAGS = @JS_CFLAGS@ JS_LIBS = @JS_LIBS@ JS_LIB_BINARY = @JS_LIB_BINARY@ LD = @LD@ LDFLAGS = @LDFLAGS@ LIBOBJS = @LIBOBJS@ LIBS = @LIBS@ LIBTOOL = @LIBTOOL@ LIPO = @LIPO@ LN_S = @LN_S@ LTLIBOBJS = @LTLIBOBJS@ MAKEINFO = @MAKEINFO@ MANIFEST_TOOL = @MANIFEST_TOOL@ MKDIR_P = @MKDIR_P@ NM = @NM@ NMEDIT = @NMEDIT@ OBJDUMP = @OBJDUMP@ OBJEXT = @OBJEXT@ OTOOL = @OTOOL@ OTOOL64 = @OTOOL64@ PACKAGE = @PACKAGE@ PACKAGE_BUGREPORT = @PACKAGE_BUGREPORT@ PACKAGE_NAME = @PACKAGE_NAME@ PACKAGE_STRING = @PACKAGE_STRING@ PACKAGE_TARNAME = @PACKAGE_TARNAME@ PACKAGE_URL = @PACKAGE_URL@ PACKAGE_VERSION = @PACKAGE_VERSION@ PATH_SEPARATOR = @PATH_SEPARATOR@ PKG_CONFIG = @PKG_CONFIG@ PKG_CONFIG_LIBDIR = @PKG_CONFIG_LIBDIR@ PKG_CONFIG_PATH = @PKG_CONFIG_PATH@ RANLIB = @RANLIB@ SED = @SED@ SET_MAKE = @SET_MAKE@ SHELL = @SHELL@ SNAPPY_MAJOR = @SNAPPY_MAJOR@ SNAPPY_MINOR = @SNAPPY_MINOR@ SNAPPY_PATCHLEVEL = @SNAPPY_PATCHLEVEL@ STRIP = @STRIP@ VERSION = @VERSION@ abs_builddir = @abs_builddir@ abs_srcdir = @abs_srcdir@ abs_top_builddir = @abs_top_builddir@ abs_top_srcdir = @abs_top_srcdir@ ac_ct_AR = @ac_ct_AR@ ac_ct_CC = @ac_ct_CC@ ac_ct_CXX = @ac_ct_CXX@ ac_ct_DUMPBIN = @ac_ct_DUMPBIN@ ac_cv_have_stddef_h = @ac_cv_have_stddef_h@ ac_cv_have_stdint_h = @ac_cv_have_stdint_h@ am__include = @am__include@ am__leading_dot = @am__leading_dot@ am__quote = @am__quote@ am__tar = @am__tar@ am__untar = @am__untar@ bindir = @bindir@ bug_uri = @bug_uri@ build = @build@ build_alias = @build_alias@ build_cpu = @build_cpu@ build_os = @build_os@ build_vendor = @build_vendor@ builddir = @builddir@ datadir = @datadir@ datarootdir = @datarootdir@ docdir = @docdir@ dvidir = @dvidir@ erlangbin = @erlangbin@ erlangversion = @erlangversion@ exec_prefix = @exec_prefix@ host = @host@ host_alias = @host_alias@ host_cpu = @host_cpu@ host_os = @host_os@ host_vendor = @host_vendor@ htmldir = @htmldir@ includedir = @includedir@ infodir = @infodir@ initdir = @initdir@ install_sh = @install_sh@ launchddir = @launchddir@ libdir = @libdir@ libexecdir = @libexecdir@ localconfdir = @localconfdir@ localdatadir = @localdatadir@ localdocdir = @localdocdir@ localedir = @localedir@ localerlanglibdir = @localerlanglibdir@ locallibbindir = @locallibbindir@ locallibdir = @locallibdir@ localstatedir = @localstatedir@ localstatelibdir = @localstatelibdir@ localstatelogdir = @localstatelogdir@ localstaterundir = @localstaterundir@ mandir = @mandir@ mkdir_p = @mkdir_p@ msvc_redist_dir = @msvc_redist_dir@ msvc_redist_name = @msvc_redist_name@ oldincludedir = @oldincludedir@ openssl_bin_dir = @openssl_bin_dir@ otp_release = @otp_release@ package_author_address = @package_author_address@ package_author_name = @package_author_name@ package_identifier = @package_identifier@ package_name = @package_name@ package_tarname = @package_tarname@ pdfdir = @pdfdir@ prefix = @prefix@ program_transform_name = @program_transform_name@ psdir = @psdir@ sbindir = @sbindir@ sharedstatedir = @sharedstatedir@ srcdir = @srcdir@ sysconfdir = @sysconfdir@ target_alias = @target_alias@ top_build_prefix = @top_build_prefix@ top_builddir = @top_builddir@ top_srcdir = @top_srcdir@ version = @version@ version_major = @version_major@ version_minor = @version_minor@ version_release = @version_release@ version_revision = @version_revision@ version_stage = @version_stage@ SUBDIRS = priv # devdocdir = $(localdocdir)/developer/couchdb couchlibdir = $(localerlanglibdir)/couch-$(version) couchincludedir = $(couchlibdir)/include couchebindir = $(couchlibdir)/ebin couchinclude_DATA = couch_db.hrl couch_js_functions.hrl couchebin_DATA = $(compiled_files) # dist_devdoc_DATA = $(doc_base) $(doc_modules) CLEANFILES = $(compiled_files) $(doc_base) # CLEANFILES = $(doc_modules) edoc-info source_files = \ couch.erl \ couch_app.erl \ couch_auth_cache.erl \ couch_btree.erl \ couch_changes.erl \ couch_compaction_daemon.erl \ couch_compress.erl \ couch_config.erl \ couch_config_writer.erl \ couch_db.erl \ couch_db_update_notifier.erl \ couch_db_update_notifier_sup.erl \ couch_doc.erl \ couch_drv.erl \ couch_ejson_compare.erl \ couch_event_sup.erl \ couch_external_manager.erl \ couch_external_server.erl \ couch_file.erl \ couch_httpd.erl \ couch_httpd_db.erl \ couch_httpd_auth.erl \ couch_httpd_cors.erl \ couch_httpd_oauth.erl \ couch_httpd_external.erl \ couch_httpd_misc_handlers.erl \ couch_httpd_proxy.erl \ couch_httpd_rewrite.erl \ couch_httpd_stats_handlers.erl \ couch_httpd_vhost.erl \ couch_key_tree.erl \ couch_log.erl \ couch_native_process.erl \ couch_os_daemons.erl \ couch_os_process.erl \ couch_passwords.erl \ couch_primary_sup.erl \ couch_query_servers.erl \ couch_ref_counter.erl \ couch_secondary_sup.erl \ couch_server.erl \ couch_server_sup.erl \ couch_stats_aggregator.erl \ couch_stats_collector.erl \ couch_stream.erl \ couch_task_status.erl \ couch_users_db.erl \ couch_util.erl \ couch_uuids.erl \ couch_db_updater.erl \ couch_work_queue.erl \ json_stream_parse.erl EXTRA_DIST = $(source_files) couch_db.hrl couch_js_functions.hrl compiled_files = \ couch.app \ couch.beam \ couch_app.beam \ couch_auth_cache.beam \ couch_btree.beam \ couch_changes.beam \ couch_compaction_daemon.beam \ couch_compress.beam \ couch_config.beam \ couch_config_writer.beam \ couch_db.beam \ couch_db_update_notifier.beam \ couch_db_update_notifier_sup.beam \ couch_doc.beam \ couch_drv.beam \ couch_ejson_compare.beam \ couch_event_sup.beam \ couch_external_manager.beam \ couch_external_server.beam \ couch_file.beam \ couch_httpd.beam \ couch_httpd_db.beam \ couch_httpd_auth.beam \ couch_httpd_oauth.beam \ couch_httpd_cors.beam \ couch_httpd_proxy.beam \ couch_httpd_external.beam \ couch_httpd_misc_handlers.beam \ couch_httpd_rewrite.beam \ couch_httpd_stats_handlers.beam \ couch_httpd_vhost.beam \ couch_key_tree.beam \ couch_log.beam \ couch_native_process.beam \ couch_os_daemons.beam \ couch_os_process.beam \ couch_passwords.beam \ couch_primary_sup.beam \ couch_query_servers.beam \ couch_ref_counter.beam \ couch_secondary_sup.beam \ couch_server.beam \ couch_server_sup.beam \ couch_stats_aggregator.beam \ couch_stats_collector.beam \ couch_stream.beam \ couch_task_status.beam \ couch_users_db.beam \ couch_util.beam \ couch_uuids.beam \ couch_db_updater.beam \ couch_work_queue.beam \ json_stream_parse.beam all: all-recursive .SUFFIXES: $(srcdir)/Makefile.in: $(srcdir)/Makefile.am $(am__configure_deps) @for dep in $?; do \ case '$(am__configure_deps)' in \ *$$dep*) \ ( cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh ) \ && { if test -f $@; then exit 0; else break; fi; }; \ exit 1;; \ esac; \ done; \ echo ' cd $(top_srcdir) && $(AUTOMAKE) --foreign src/couchdb/Makefile'; \ $(am__cd) $(top_srcdir) && \ $(AUTOMAKE) --foreign src/couchdb/Makefile .PRECIOUS: Makefile Makefile: $(srcdir)/Makefile.in $(top_builddir)/config.status @case '$?' in \ *config.status*) \ cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh;; \ *) \ echo ' cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ $(am__depfiles_maybe)'; \ cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ $(am__depfiles_maybe);; \ esac; $(top_builddir)/config.status: $(top_srcdir)/configure $(CONFIG_STATUS_DEPENDENCIES) cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh $(top_srcdir)/configure: $(am__configure_deps) cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh $(ACLOCAL_M4): $(am__aclocal_m4_deps) cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh $(am__aclocal_m4_deps): couch.app.tpl: $(top_builddir)/config.status $(srcdir)/couch.app.tpl.in cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ mostlyclean-libtool: -rm -f *.lo clean-libtool: -rm -rf .libs _libs install-couchebinDATA: $(couchebin_DATA) @$(NORMAL_INSTALL) @list='$(couchebin_DATA)'; test -n "$(couchebindir)" || list=; \ if test -n "$$list"; then \ echo " $(MKDIR_P) '$(DESTDIR)$(couchebindir)'"; \ $(MKDIR_P) "$(DESTDIR)$(couchebindir)" || exit 1; \ fi; \ for p in $$list; do \ if test -f "$$p"; then d=; else d="$(srcdir)/"; fi; \ echo "$$d$$p"; \ done | $(am__base_list) | \ while read files; do \ echo " $(INSTALL_DATA) $$files '$(DESTDIR)$(couchebindir)'"; \ $(INSTALL_DATA) $$files "$(DESTDIR)$(couchebindir)" || exit $$?; \ done uninstall-couchebinDATA: @$(NORMAL_UNINSTALL) @list='$(couchebin_DATA)'; test -n "$(couchebindir)" || list=; \ files=`for p in $$list; do echo $$p; done | sed -e 's|^.*/||'`; \ dir='$(DESTDIR)$(couchebindir)'; $(am__uninstall_files_from_dir) install-couchincludeDATA: $(couchinclude_DATA) @$(NORMAL_INSTALL) @list='$(couchinclude_DATA)'; test -n "$(couchincludedir)" || list=; \ if test -n "$$list"; then \ echo " $(MKDIR_P) '$(DESTDIR)$(couchincludedir)'"; \ $(MKDIR_P) "$(DESTDIR)$(couchincludedir)" || exit 1; \ fi; \ for p in $$list; do \ if test -f "$$p"; then d=; else d="$(srcdir)/"; fi; \ echo "$$d$$p"; \ done | $(am__base_list) | \ while read files; do \ echo " $(INSTALL_DATA) $$files '$(DESTDIR)$(couchincludedir)'"; \ $(INSTALL_DATA) $$files "$(DESTDIR)$(couchincludedir)" || exit $$?; \ done uninstall-couchincludeDATA: @$(NORMAL_UNINSTALL) @list='$(couchinclude_DATA)'; test -n "$(couchincludedir)" || list=; \ files=`for p in $$list; do echo $$p; done | sed -e 's|^.*/||'`; \ dir='$(DESTDIR)$(couchincludedir)'; $(am__uninstall_files_from_dir) # This directory's subdirectories are mostly independent; you can cd # into them and run `make' without going through this Makefile. # To change the values of `make' variables: instead of editing Makefiles, # (1) if the variable is set in `config.status', edit `config.status' # (which will cause the Makefiles to be regenerated when you run `make'); # (2) otherwise, pass the desired values on the `make' command line. $(RECURSIVE_TARGETS): @fail= failcom='exit 1'; \ for f in x $$MAKEFLAGS; do \ case $$f in \ *=* | --[!k]*);; \ *k*) failcom='fail=yes';; \ esac; \ done; \ dot_seen=no; \ target=`echo $@ | sed s/-recursive//`; \ list='$(SUBDIRS)'; for subdir in $$list; do \ echo "Making $$target in $$subdir"; \ if test "$$subdir" = "."; then \ dot_seen=yes; \ local_target="$$target-am"; \ else \ local_target="$$target"; \ fi; \ ($(am__cd) $$subdir && $(MAKE) $(AM_MAKEFLAGS) $$local_target) \ || eval $$failcom; \ done; \ if test "$$dot_seen" = "no"; then \ $(MAKE) $(AM_MAKEFLAGS) "$$target-am" || exit 1; \ fi; test -z "$$fail" $(RECURSIVE_CLEAN_TARGETS): @fail= failcom='exit 1'; \ for f in x $$MAKEFLAGS; do \ case $$f in \ *=* | --[!k]*);; \ *k*) failcom='fail=yes';; \ esac; \ done; \ dot_seen=no; \ case "$@" in \ distclean-* | maintainer-clean-*) list='$(DIST_SUBDIRS)' ;; \ *) list='$(SUBDIRS)' ;; \ esac; \ rev=''; for subdir in $$list; do \ if test "$$subdir" = "."; then :; else \ rev="$$subdir $$rev"; \ fi; \ done; \ rev="$$rev ."; \ target=`echo $@ | sed s/-recursive//`; \ for subdir in $$rev; do \ echo "Making $$target in $$subdir"; \ if test "$$subdir" = "."; then \ local_target="$$target-am"; \ else \ local_target="$$target"; \ fi; \ ($(am__cd) $$subdir && $(MAKE) $(AM_MAKEFLAGS) $$local_target) \ || eval $$failcom; \ done && test -z "$$fail" tags-recursive: list='$(SUBDIRS)'; for subdir in $$list; do \ test "$$subdir" = . || ($(am__cd) $$subdir && $(MAKE) $(AM_MAKEFLAGS) tags); \ done ctags-recursive: list='$(SUBDIRS)'; for subdir in $$list; do \ test "$$subdir" = . || ($(am__cd) $$subdir && $(MAKE) $(AM_MAKEFLAGS) ctags); \ done ID: $(HEADERS) $(SOURCES) $(LISP) $(TAGS_FILES) list='$(SOURCES) $(HEADERS) $(LISP) $(TAGS_FILES)'; \ unique=`for i in $$list; do \ if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \ done | \ $(AWK) '{ files[$$0] = 1; nonempty = 1; } \ END { if (nonempty) { for (i in files) print i; }; }'`; \ mkid -fID $$unique tags: TAGS TAGS: tags-recursive $(HEADERS) $(SOURCES) $(TAGS_DEPENDENCIES) \ $(TAGS_FILES) $(LISP) set x; \ here=`pwd`; \ if ($(ETAGS) --etags-include --version) >/dev/null 2>&1; then \ include_option=--etags-include; \ empty_fix=.; \ else \ include_option=--include; \ empty_fix=; \ fi; \ list='$(SUBDIRS)'; for subdir in $$list; do \ if test "$$subdir" = .; then :; else \ test ! -f $$subdir/TAGS || \ set "$$@" "$$include_option=$$here/$$subdir/TAGS"; \ fi; \ done; \ list='$(SOURCES) $(HEADERS) $(LISP) $(TAGS_FILES)'; \ unique=`for i in $$list; do \ if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \ done | \ $(AWK) '{ files[$$0] = 1; nonempty = 1; } \ END { if (nonempty) { for (i in files) print i; }; }'`; \ shift; \ if test -z "$(ETAGS_ARGS)$$*$$unique"; then :; else \ test -n "$$unique" || unique=$$empty_fix; \ if test $$# -gt 0; then \ $(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \ "$$@" $$unique; \ else \ $(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \ $$unique; \ fi; \ fi ctags: CTAGS CTAGS: ctags-recursive $(HEADERS) $(SOURCES) $(TAGS_DEPENDENCIES) \ $(TAGS_FILES) $(LISP) list='$(SOURCES) $(HEADERS) $(LISP) $(TAGS_FILES)'; \ unique=`for i in $$list; do \ if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \ done | \ $(AWK) '{ files[$$0] = 1; nonempty = 1; } \ END { if (nonempty) { for (i in files) print i; }; }'`; \ test -z "$(CTAGS_ARGS)$$unique" \ || $(CTAGS) $(CTAGSFLAGS) $(AM_CTAGSFLAGS) $(CTAGS_ARGS) \ $$unique GTAGS: here=`$(am__cd) $(top_builddir) && pwd` \ && $(am__cd) $(top_srcdir) \ && gtags -i $(GTAGS_ARGS) "$$here" distclean-tags: -rm -f TAGS ID GTAGS GRTAGS GSYMS GPATH tags distdir: $(DISTFILES) @srcdirstrip=`echo "$(srcdir)" | sed 's/[].[^$$\\*]/\\\\&/g'`; \ topsrcdirstrip=`echo "$(top_srcdir)" | sed 's/[].[^$$\\*]/\\\\&/g'`; \ list='$(DISTFILES)'; \ dist_files=`for file in $$list; do echo $$file; done | \ sed -e "s|^$$srcdirstrip/||;t" \ -e "s|^$$topsrcdirstrip/|$(top_builddir)/|;t"`; \ case $$dist_files in \ */*) $(MKDIR_P) `echo "$$dist_files" | \ sed '/\//!d;s|^|$(distdir)/|;s,/[^/]*$$,,' | \ sort -u` ;; \ esac; \ for file in $$dist_files; do \ if test -f $$file || test -d $$file; then d=.; else d=$(srcdir); fi; \ if test -d $$d/$$file; then \ dir=`echo "/$$file" | sed -e 's,/[^/]*$$,,'`; \ if test -d "$(distdir)/$$file"; then \ find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} \;; \ fi; \ if test -d $(srcdir)/$$file && test $$d != $(srcdir); then \ cp -fpR $(srcdir)/$$file "$(distdir)$$dir" || exit 1; \ find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} \;; \ fi; \ cp -fpR $$d/$$file "$(distdir)$$dir" || exit 1; \ else \ test -f "$(distdir)/$$file" \ || cp -p $$d/$$file "$(distdir)/$$file" \ || exit 1; \ fi; \ done @list='$(DIST_SUBDIRS)'; for subdir in $$list; do \ if test "$$subdir" = .; then :; else \ $(am__make_dryrun) \ || test -d "$(distdir)/$$subdir" \ || $(MKDIR_P) "$(distdir)/$$subdir" \ || exit 1; \ dir1=$$subdir; dir2="$(distdir)/$$subdir"; \ $(am__relativize); \ new_distdir=$$reldir; \ dir1=$$subdir; dir2="$(top_distdir)"; \ $(am__relativize); \ new_top_distdir=$$reldir; \ echo " (cd $$subdir && $(MAKE) $(AM_MAKEFLAGS) top_distdir="$$new_top_distdir" distdir="$$new_distdir" \\"; \ echo " am__remove_distdir=: am__skip_length_check=: am__skip_mode_fix=: distdir)"; \ ($(am__cd) $$subdir && \ $(MAKE) $(AM_MAKEFLAGS) \ top_distdir="$$new_top_distdir" \ distdir="$$new_distdir" \ am__remove_distdir=: \ am__skip_length_check=: \ am__skip_mode_fix=: \ distdir) \ || exit 1; \ fi; \ done check-am: all-am check: check-recursive all-am: Makefile $(DATA) installdirs: installdirs-recursive installdirs-am: for dir in "$(DESTDIR)$(couchebindir)" "$(DESTDIR)$(couchincludedir)"; do \ test -z "$$dir" || $(MKDIR_P) "$$dir"; \ done install: install-recursive install-exec: install-exec-recursive install-data: install-data-recursive uninstall: uninstall-recursive install-am: all-am @$(MAKE) $(AM_MAKEFLAGS) install-exec-am install-data-am installcheck: installcheck-recursive install-strip: if test -z '$(STRIP)'; then \ $(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(INSTALL_STRIP_PROGRAM)" \ install_sh_PROGRAM="$(INSTALL_STRIP_PROGRAM)" INSTALL_STRIP_FLAG=-s \ install; \ else \ $(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(INSTALL_STRIP_PROGRAM)" \ install_sh_PROGRAM="$(INSTALL_STRIP_PROGRAM)" INSTALL_STRIP_FLAG=-s \ "INSTALL_PROGRAM_ENV=STRIPPROG='$(STRIP)'" install; \ fi mostlyclean-generic: clean-generic: -test -z "$(CLEANFILES)" || rm -f $(CLEANFILES) distclean-generic: -test -z "$(CONFIG_CLEAN_FILES)" || rm -f $(CONFIG_CLEAN_FILES) -test . = "$(srcdir)" || test -z "$(CONFIG_CLEAN_VPATH_FILES)" || rm -f $(CONFIG_CLEAN_VPATH_FILES) maintainer-clean-generic: @echo "This command is intended for maintainers to use" @echo "it deletes files that may require special tools to rebuild." clean: clean-recursive clean-am: clean-generic clean-libtool mostlyclean-am distclean: distclean-recursive -rm -f Makefile distclean-am: clean-am distclean-generic distclean-tags dvi: dvi-recursive dvi-am: html: html-recursive html-am: info: info-recursive info-am: install-data-am: install-couchebinDATA install-couchincludeDATA install-dvi: install-dvi-recursive install-dvi-am: install-exec-am: install-html: install-html-recursive install-html-am: install-info: install-info-recursive install-info-am: install-man: install-pdf: install-pdf-recursive install-pdf-am: install-ps: install-ps-recursive install-ps-am: installcheck-am: maintainer-clean: maintainer-clean-recursive -rm -f Makefile maintainer-clean-am: distclean-am maintainer-clean-generic mostlyclean: mostlyclean-recursive mostlyclean-am: mostlyclean-generic mostlyclean-libtool pdf: pdf-recursive pdf-am: ps: ps-recursive ps-am: uninstall-am: uninstall-couchebinDATA uninstall-couchincludeDATA .MAKE: $(RECURSIVE_CLEAN_TARGETS) $(RECURSIVE_TARGETS) ctags-recursive \ install-am install-strip tags-recursive .PHONY: $(RECURSIVE_CLEAN_TARGETS) $(RECURSIVE_TARGETS) CTAGS GTAGS \ all all-am check check-am clean clean-generic clean-libtool \ ctags ctags-recursive distclean distclean-generic \ distclean-libtool distclean-tags distdir dvi dvi-am html \ html-am info info-am install install-am install-couchebinDATA \ install-couchincludeDATA install-data install-data-am \ install-dvi install-dvi-am install-exec install-exec-am \ install-html install-html-am install-info install-info-am \ install-man install-pdf install-pdf-am install-ps \ install-ps-am install-strip installcheck installcheck-am \ installdirs installdirs-am maintainer-clean \ maintainer-clean-generic mostlyclean mostlyclean-generic \ mostlyclean-libtool pdf pdf-am ps ps-am tags tags-recursive \ uninstall uninstall-am uninstall-couchebinDATA \ uninstall-couchincludeDATA # doc_base = \ # erlang.png \ # index.html \ # modules-frame.html \ # overview-summary.html \ # packages-frame.html \ # stylesheet.css # doc_modules = \ # couch_btree.html \ # couch_config.html \ # couch_config_writer.html \ # couch_db.html \ # couch_db_update_notifier.html \ # couch_db_update_notifier_sup.html \ # couch_doc.html \ # couch_event_sup.html \ # couch_file.html \ # couch_httpd.html \ # couch_key_tree.html \ # couch_log.html \ # couch_query_servers.html \ # couch_rep.html \ # couch_rep_sup.html \ # couch_server.html \ # couch_server_sup.html \ # couch_stream.html \ # couch_util.html @WINDOWS_TRUE@couch.app: couch.app.tpl @WINDOWS_TRUE@ modules=`find . -name "*.erl" \! -name ".*" -exec basename {} .erl \; | tr '\n' ',' | sed "s/,$$//"`; \ @WINDOWS_TRUE@ sed -e "s|%package_name%|@package_name@|g" \ @WINDOWS_TRUE@ -e "s|%version%|@version@|g" \ @WINDOWS_TRUE@ -e "s|@modules@|$$modules|g" \ @WINDOWS_TRUE@ -e "s|%localconfdir%|../etc/couchdb|g" \ @WINDOWS_TRUE@ -e "s|@defaultini@|default.ini|g" \ @WINDOWS_TRUE@ -e "s|@localini@|local.ini|g" > \ @WINDOWS_TRUE@ $@ < $< @WINDOWS_FALSE@couch.app: couch.app.tpl @WINDOWS_FALSE@ modules=`{ find . -name "*.erl" \! -name ".*" -exec basename {} .erl \; | tr '\n' ','; echo ''; } | sed "s/,$$//"`; \ @WINDOWS_FALSE@ sed -e "s|%package_name%|@package_name@|g" \ @WINDOWS_FALSE@ -e "s|%version%|@version@|g" \ @WINDOWS_FALSE@ -e "s|@modules@|$$modules|g" \ @WINDOWS_FALSE@ -e "s|%localconfdir%|@localconfdir@|g" \ @WINDOWS_FALSE@ -e "s|@defaultini@|default.ini|g" \ @WINDOWS_FALSE@ -e "s|@localini@|local.ini|g" > \ @WINDOWS_FALSE@ $@ < $< @WINDOWS_FALSE@ chmod +x $@ # $(dist_devdoc_DATA): edoc-info # $(ERL) -noshell -run edoc_run files [\"$<\"] %.beam: %.erl couch_db.hrl couch_js_functions.hrl $(ERLC) $(ERLC_FLAGS) ${TEST} $<; # Tell versions [3.59,3.63) of GNU make to not export all variables. # Otherwise a system limit (for SysV at least) may be exceeded. .NOEXPORT: apache-couchdb-1.5.0/src/couchdb/couch_os_daemons.erl0000644000175000001440000003266612230722213017501 00000000000000% 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. -module(couch_os_daemons). -behaviour(gen_server). -export([start_link/0, info/0, info/1, config_change/2]). -export([init/1, terminate/2, code_change/3]). -export([handle_call/3, handle_cast/2, handle_info/2]). -include("couch_db.hrl"). -record(daemon, { port, name, cmd, kill, status=running, cfg_patterns=[], errors=[], buf=[] }). -define(PORT_OPTIONS, [stream, {line, 1024}, binary, exit_status, hide]). -define(TIMEOUT, 5000). start_link() -> gen_server:start_link({local, ?MODULE}, ?MODULE, [], []). info() -> info([]). info(Options) -> gen_server:call(?MODULE, {daemon_info, Options}). config_change(Section, Key) -> gen_server:cast(?MODULE, {config_change, Section, Key}). init(_) -> process_flag(trap_exit, true), ok = couch_config:register(fun ?MODULE:config_change/2), Table = ets:new(?MODULE, [protected, set, {keypos, #daemon.port}]), reload_daemons(Table), {ok, Table}. terminate(_Reason, Table) -> [stop_port(D) || D <- ets:tab2list(Table)], ok. handle_call({daemon_info, Options}, _From, Table) when is_list(Options) -> case lists:member(table, Options) of true -> {reply, {ok, ets:tab2list(Table)}, Table}; _ -> {reply, {ok, Table}, Table} end; handle_call(Msg, From, Table) -> ?LOG_ERROR("Unknown call message to ~p from ~p: ~p", [?MODULE, From, Msg]), {stop, error, Table}. handle_cast({config_change, Sect, Key}, Table) -> restart_daemons(Table, Sect, Key), case Sect of "os_daemons" -> reload_daemons(Table); _ -> ok end, {noreply, Table}; handle_cast(stop, Table) -> {stop, normal, Table}; handle_cast(Msg, Table) -> ?LOG_ERROR("Unknown cast message to ~p: ~p", [?MODULE, Msg]), {stop, error, Table}. handle_info({'EXIT', Port, Reason}, Table) -> case ets:lookup(Table, Port) of [] -> ?LOG_INFO("Port ~p exited after stopping: ~p~n", [Port, Reason]); [#daemon{status=stopping}] -> true = ets:delete(Table, Port); [#daemon{name=Name, status=restarting}=D] -> ?LOG_INFO("Daemon ~P restarting after config change.", [Name]), true = ets:delete(Table, Port), {ok, Port2} = start_port(D#daemon.cmd), true = ets:insert(Table, D#daemon{ port=Port2, status=running, kill=undefined, buf=[] }); [#daemon{name=Name, status=halted}] -> ?LOG_ERROR("Halted daemon process: ~p", [Name]); [D] -> ?LOG_ERROR("Invalid port state at exit: ~p", [D]) end, {noreply, Table}; handle_info({Port, closed}, Table) -> handle_info({Port, {exit_status, closed}}, Table); handle_info({Port, {exit_status, Status}}, Table) -> case ets:lookup(Table, Port) of [] -> ?LOG_ERROR("Unknown port ~p exiting ~p", [Port, Status]), {stop, {error, unknown_port_died, Status}, Table}; [#daemon{name=Name, status=restarting}=D] -> ?LOG_INFO("Daemon ~P restarting after config change.", [Name]), true = ets:delete(Table, Port), {ok, Port2} = start_port(D#daemon.cmd), true = ets:insert(Table, D#daemon{ port=Port2, status=running, kill=undefined, buf=[] }), {noreply, Table}; [#daemon{status=stopping}=D] -> % The configuration changed and this daemon is no % longer needed. ?LOG_DEBUG("Port ~p shut down.", [D#daemon.name]), true = ets:delete(Table, Port), {noreply, Table}; [D] -> % Port died for unknown reason. Check to see if it's % died too many times or if we should boot it back up. case should_halt([now() | D#daemon.errors]) of {true, _} -> % Halting the process. We won't try and reboot % until the configuration changes. Fmt = "Daemon ~p halted with exit_status ~p", ?LOG_ERROR(Fmt, [D#daemon.name, Status]), D2 = D#daemon{status=halted, errors=nil, buf=nil}, true = ets:insert(Table, D2), {noreply, Table}; {false, Errors} -> % We're guessing it was a random error, this daemon % has behaved so we'll give it another chance. Fmt = "Daemon ~p is being rebooted after exit_status ~p", ?LOG_INFO(Fmt, [D#daemon.name, Status]), true = ets:delete(Table, Port), {ok, Port2} = start_port(D#daemon.cmd), true = ets:insert(Table, D#daemon{ port=Port2, status=running, kill=undefined, errors=Errors, buf=[] }), {noreply, Table} end; _Else -> throw(error) end; handle_info({Port, {data, {noeol, Data}}}, Table) -> [#daemon{buf=Buf}=D] = ets:lookup(Table, Port), true = ets:insert(Table, D#daemon{buf=[Data | Buf]}), {noreply, Table}; handle_info({Port, {data, {eol, Data}}}, Table) -> [#daemon{buf=Buf}=D] = ets:lookup(Table, Port), Line = lists:reverse(Buf, Data), % The first line echoed back is the kill command % for when we go to get rid of the port. Lines after % that are considered part of the stdio API. case D#daemon.kill of undefined -> true = ets:insert(Table, D#daemon{kill=?b2l(Line), buf=[]}); _Else -> D2 = case (catch ?JSON_DECODE(Line)) of {invalid_json, Rejected} -> ?LOG_ERROR("Ignoring OS daemon request: ~p", [Rejected]), D; JSON -> {ok, D3} = handle_port_message(D, JSON), D3 end, true = ets:insert(Table, D2#daemon{buf=[]}) end, {noreply, Table}; handle_info({Port, Error}, Table) -> ?LOG_ERROR("Unexpectd message from port ~p: ~p", [Port, Error]), stop_port(Port), [D] = ets:lookup(Table, Port), true = ets:insert(Table, D#daemon{status=restarting, buf=nil}), {noreply, Table}; handle_info(Msg, Table) -> ?LOG_ERROR("Unexpected info message to ~p: ~p", [?MODULE, Msg]), {stop, error, Table}. code_change(_OldVsn, State, _Extra) -> {ok, State}. % Internal API % % Port management helpers % start_port(Command) -> start_port(Command, []). start_port(Command, EnvPairs) -> PrivDir = couch_util:priv_dir(), Spawnkiller = filename:join(PrivDir, "couchspawnkillable"), Opts = case lists:keytake(env, 1, ?PORT_OPTIONS) of false -> ?PORT_OPTIONS ++ [ {env,EnvPairs} ]; {value, {env,OldPairs}, SubOpts} -> AllPairs = lists:keymerge(1, EnvPairs, OldPairs), SubOpts ++ [ {env,AllPairs} ] end, Port = open_port({spawn, Spawnkiller ++ " " ++ Command}, Opts), {ok, Port}. stop_port(#daemon{port=Port, kill=undefined}=D) -> ?LOG_ERROR("Stopping daemon without a kill command: ~p", [D#daemon.name]), catch port_close(Port); stop_port(#daemon{port=Port}=D) -> ?LOG_DEBUG("Stopping daemon: ~p", [D#daemon.name]), os:cmd(D#daemon.kill), catch port_close(Port). handle_port_message(#daemon{port=Port}=Daemon, [<<"get">>, Section]) -> KVs = couch_config:get(Section), Data = lists:map(fun({K, V}) -> {?l2b(K), ?l2b(V)} end, KVs), Json = iolist_to_binary(?JSON_ENCODE({Data})), port_command(Port, <>), {ok, Daemon}; handle_port_message(#daemon{port=Port}=Daemon, [<<"get">>, Section, Key]) -> Value = case couch_config:get(Section, Key, null) of null -> null; String -> ?l2b(String) end, Json = iolist_to_binary(?JSON_ENCODE(Value)), port_command(Port, <>), {ok, Daemon}; handle_port_message(Daemon, [<<"register">>, Sec]) when is_binary(Sec) -> Patterns = lists:usort(Daemon#daemon.cfg_patterns ++ [{?b2l(Sec)}]), {ok, Daemon#daemon{cfg_patterns=Patterns}}; handle_port_message(Daemon, [<<"register">>, Sec, Key]) when is_binary(Sec) andalso is_binary(Key) -> Pattern = {?b2l(Sec), ?b2l(Key)}, Patterns = lists:usort(Daemon#daemon.cfg_patterns ++ [Pattern]), {ok, Daemon#daemon{cfg_patterns=Patterns}}; handle_port_message(#daemon{name=Name}=Daemon, [<<"log">>, Msg]) -> handle_log_message(Name, Msg, <<"info">>), {ok, Daemon}; handle_port_message(#daemon{name=Name}=Daemon, [<<"log">>, Msg, {Opts}]) -> Level = couch_util:get_value(<<"level">>, Opts, <<"info">>), handle_log_message(Name, Msg, Level), {ok, Daemon}; handle_port_message(#daemon{name=Name}=Daemon, Else) -> ?LOG_ERROR("Daemon ~p made invalid request: ~p", [Name, Else]), {ok, Daemon}. handle_log_message(Name, Msg, _Level) when not is_binary(Msg) -> ?LOG_ERROR("Invalid log message from daemon ~p: ~p", [Name, Msg]); handle_log_message(Name, Msg, <<"debug">>) -> ?LOG_DEBUG("Daemon ~p :: ~s", [Name, ?b2l(Msg)]); handle_log_message(Name, Msg, <<"info">>) -> ?LOG_INFO("Daemon ~p :: ~s", [Name, ?b2l(Msg)]); handle_log_message(Name, Msg, <<"error">>) -> ?LOG_ERROR("Daemon: ~p :: ~s", [Name, ?b2l(Msg)]); handle_log_message(Name, Msg, Level) -> ?LOG_ERROR("Invalid log level from daemon: ~p", [Level]), ?LOG_INFO("Daemon: ~p :: ~s", [Name, ?b2l(Msg)]). % % Daemon management helpers % reload_daemons(Table) -> % List of daemons we want to have running. Configured = lists:sort(couch_config:get("os_daemons")), % Remove records for daemons that were halted. MSpecHalted = #daemon{name='$1', cmd='$2', status=halted, _='_'}, Halted = lists:sort([{N, C} || [N, C] <- ets:match(Table, MSpecHalted)]), ok = stop_os_daemons(Table, find_to_stop(Configured, Halted, [])), % Stop daemons that are running % Start newly configured daemons MSpecRunning = #daemon{name='$1', cmd='$2', status=running, _='_'}, Running = lists:sort([{N, C} || [N, C] <- ets:match(Table, MSpecRunning)]), ok = stop_os_daemons(Table, find_to_stop(Configured, Running, [])), ok = boot_os_daemons(Table, find_to_boot(Configured, Running, [])), ok. restart_daemons(Table, Sect, Key) -> restart_daemons(Table, Sect, Key, ets:first(Table)). restart_daemons(_, _, _, '$end_of_table') -> ok; restart_daemons(Table, Sect, Key, Port) -> [D] = ets:lookup(Table, Port), HasSect = lists:member({Sect}, D#daemon.cfg_patterns), HasKey = lists:member({Sect, Key}, D#daemon.cfg_patterns), case HasSect or HasKey of true -> stop_port(D), D2 = D#daemon{status=restarting, buf=nil}, true = ets:insert(Table, D2); _ -> ok end, restart_daemons(Table, Sect, Key, ets:next(Table, Port)). stop_os_daemons(_Table, []) -> ok; stop_os_daemons(Table, [{Name, Cmd} | Rest]) -> [[Port]] = ets:match(Table, #daemon{port='$1', name=Name, cmd=Cmd, _='_'}), [D] = ets:lookup(Table, Port), case D#daemon.status of halted -> ets:delete(Table, Port); _ -> stop_port(D), D2 = D#daemon{status=stopping, errors=nil, buf=nil}, true = ets:insert(Table, D2) end, stop_os_daemons(Table, Rest). boot_os_daemons(_Table, []) -> ok; boot_os_daemons(Table, [{Name, Cmd} | Rest]) -> {ok, Port} = start_port(Cmd), true = ets:insert(Table, #daemon{port=Port, name=Name, cmd=Cmd}), boot_os_daemons(Table, Rest). % Elements unique to the configured set need to be booted. find_to_boot([], _Rest, Acc) -> % Nothing else configured. Acc; find_to_boot([D | R1], [D | R2], Acc) -> % Elements are equal, daemon already running. find_to_boot(R1, R2, Acc); find_to_boot([D1 | R1], [D2 | _]=A2, Acc) when D1 < D2 -> find_to_boot(R1, A2, [D1 | Acc]); find_to_boot(A1, [_ | R2], Acc) -> find_to_boot(A1, R2, Acc); find_to_boot(Rest, [], Acc) -> % No more candidates for already running. Boot all. Rest ++ Acc. % Elements unique to the running set need to be killed. find_to_stop([], Rest, Acc) -> % The rest haven't been found, so they must all % be ready to die. Rest ++ Acc; find_to_stop([D | R1], [D | R2], Acc) -> % Elements are equal, daemon already running. find_to_stop(R1, R2, Acc); find_to_stop([D1 | R1], [D2 | _]=A2, Acc) when D1 < D2 -> find_to_stop(R1, A2, Acc); find_to_stop(A1, [D2 | R2], Acc) -> find_to_stop(A1, R2, [D2 | Acc]); find_to_stop(_, [], Acc) -> % No more running daemons to worry about. Acc. should_halt(Errors) -> RetryTimeCfg = couch_config:get("os_daemon_settings", "retry_time", "5"), RetryTime = list_to_integer(RetryTimeCfg), Now = now(), RecentErrors = lists:filter(fun(Time) -> timer:now_diff(Now, Time) =< RetryTime * 1000000 end, Errors), RetryCfg = couch_config:get("os_daemon_settings", "max_retries", "3"), Retries = list_to_integer(RetryCfg), {length(RecentErrors) >= Retries, RecentErrors}. apache-couchdb-1.5.0/src/couchdb/couch_db_update_notifier.erl0000644000175000001440000000510512230722213021164 00000000000000% 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. % % This causes an OS process to spawned and it is notified every time a database % is updated. % % The notifications are in the form of a the database name sent as a line of % text to the OS processes stdout. % -module(couch_db_update_notifier). -behaviour(gen_event). -export([start_link/1, notify/1]). -export([init/1, terminate/2, handle_event/2, handle_call/2, handle_info/2, code_change/3,stop/1]). -include("couch_db.hrl"). start_link(Exec) -> couch_event_sup:start_link(couch_db_update, {couch_db_update_notifier, make_ref()}, Exec). notify(Event) -> gen_event:notify(couch_db_update, Event). stop(Pid) -> couch_event_sup:stop(Pid). init(Exec) when is_list(Exec) -> % an exe couch_os_process:start_link(Exec, []); init(Else) -> {ok, Else}. terminate(_Reason, Pid) when is_pid(Pid) -> couch_os_process:stop(Pid), ok; terminate(_Reason, _State) -> ok. handle_event(Event, Fun) when is_function(Fun, 1) -> Fun(Event), {ok, Fun}; handle_event(Event, {Fun, FunAcc}) -> FunAcc2 = Fun(Event, FunAcc), {ok, {Fun, FunAcc2}}; handle_event({EventType, EventDesc}, Pid) -> Obj = encode_event(EventType, EventDesc), ok = couch_os_process:send(Pid, Obj), {ok, Pid}. handle_call(_Request, State) -> {reply, ok, State}. handle_info({'EXIT', Pid, Reason}, Pid) -> ?LOG_ERROR("Update notification process ~p died: ~p", [Pid, Reason]), remove_handler; handle_info({'EXIT', _, _}, Pid) -> %% the db_update event manager traps exits and forwards this message to all %% its handlers. Just ignore as it wasn't our os_process that exited. {ok, Pid}. code_change(_OldVsn, State, _Extra) -> {ok, State}. encode_event(EventType, EventDesc) when is_atom(EventType) -> encode_event(atom_to_list(EventType), EventDesc); encode_event(EventType, EventDesc) when is_list(EventType) -> encode_event(?l2b(EventType), EventDesc); encode_event(EventType, {DbName, DocId}) -> {[{type, EventType}, {db, DbName}, {id, DocId}]}; encode_event(EventType, DbName) -> {[{type, EventType}, {db, DbName}]}. apache-couchdb-1.5.0/src/couchdb/couch_httpd_rewrite.erl0000644000175000001440000004234512230722213020231 00000000000000% 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. % % bind_path is based on bind method from Webmachine %% @doc Module for URL rewriting by pattern matching. -module(couch_httpd_rewrite). -export([handle_rewrite_req/3]). -include("couch_db.hrl"). -define(SEPARATOR, $\/). -define(MATCH_ALL, {bind, <<"*">>}). %% doc The http rewrite handler. All rewriting is done from %% /dbname/_design/ddocname/_rewrite by default. %% %% each rules should be in rewrites member of the design doc. %% Ex of a complete rule : %% %% { %% .... %% "rewrites": [ %% { %% "from": "", %% "to": "index.html", %% "method": "GET", %% "query": {} %% } %% ] %% } %% %% from: is the path rule used to bind current uri to the rule. It %% use pattern matching for that. %% %% to: rule to rewrite an url. It can contain variables depending on binding %% variables discovered during pattern matching and query args (url args and from %% the query member.) %% %% method: method to bind the request method to the rule. by default "*" %% query: query args you want to define they can contain dynamic variable %% by binding the key to the bindings %% %% %% to and from are path with patterns. pattern can be string starting with ":" or %% "*". ex: %% /somepath/:var/* %% %% This path is converted in erlang list by splitting "/". Each var are %% converted in atom. "*" is converted to '*' atom. The pattern matching is done %% by splitting "/" in request url in a list of token. A string pattern will %% match equal token. The star atom ('*' in single quotes) will match any number %% of tokens, but may only be present as the last pathtern in a pathspec. If all %% tokens are matched and all pathterms are used, then the pathspec matches. It works %% like webmachine. Each identified token will be reused in to rule and in query %% %% The pattern matching is done by first matching the request method to a rule. by %% default all methods match a rule. (method is equal to "*" by default). Then %% It will try to match the path to one rule. If no rule match, then a 404 error %% is displayed. %% %% Once a rule is found we rewrite the request url using the "to" and %% "query" members. The identified token are matched to the rule and %% will replace var. if '*' is found in the rule it will contain the remaining %% part if it exists. %% %% Examples: %% %% Dispatch rule URL TO Tokens %% %% {"from": "/a/b", /a/b?k=v /some/b?k=v var =:= b %% "to": "/some/"} k = v %% %% {"from": "/a/b", /a/b /some/b?var=b var =:= b %% "to": "/some/:var"} %% %% {"from": "/a", /a /some %% "to": "/some/*"} %% %% {"from": "/a/*", /a/b/c /some/b/c %% "to": "/some/*"} %% %% {"from": "/a", /a /some %% "to": "/some/*"} %% %% {"from": "/a/:foo/*", /a/b/c /some/b/c?foo=b foo =:= b %% "to": "/some/:foo/*"} %% %% {"from": "/a/:foo", /a/b /some/?k=b&foo=b foo =:= b %% "to": "/some", %% "query": { %% "k": ":foo" %% }} %% %% {"from": "/a", /a?foo=b /some/b foo =:= b %% "to": "/some/:foo", %% }} handle_rewrite_req(#httpd{ path_parts=[DbName, <<"_design">>, DesignName, _Rewrite|PathParts], method=Method, mochi_req=MochiReq}=Req, _Db, DDoc) -> % we are in a design handler DesignId = <<"_design/", DesignName/binary>>, Prefix = <<"/", (?l2b(couch_util:url_encode(DbName)))/binary, "/", DesignId/binary>>, QueryList = lists:map(fun decode_query_value/1, couch_httpd:qs(Req)), RewritesSoFar = erlang:get(?REWRITE_COUNT), MaxRewrites = list_to_integer(couch_config:get("httpd", "rewrite_limit", "100")), case RewritesSoFar >= MaxRewrites of true -> throw({bad_request, <<"Exceeded rewrite recursion limit">>}); false -> erlang:put(?REWRITE_COUNT, RewritesSoFar + 1) end, #doc{body={Props}} = DDoc, % get rules from ddoc case couch_util:get_value(<<"rewrites">>, Props) of undefined -> couch_httpd:send_error(Req, 404, <<"rewrite_error">>, <<"Invalid path.">>); Bin when is_binary(Bin) -> couch_httpd:send_error(Req, 400, <<"rewrite_error">>, <<"Rewrite rules are a String. They must be a JSON Array.">>); Rules -> % create dispatch list from rules DispatchList = [make_rule(Rule) || {Rule} <- Rules], Method1 = couch_util:to_binary(Method), %% get raw path by matching url to a rule. RawPath = case try_bind_path(DispatchList, Method1, PathParts, QueryList) of no_dispatch_path -> throw(not_found); {NewPathParts, Bindings} -> Parts = [quote_plus(X) || X <- NewPathParts], % build new path, reencode query args, eventually convert % them to json Bindings1 = maybe_encode_bindings(Bindings), Path = binary_to_list( iolist_to_binary([ string:join(Parts, [?SEPARATOR]), [["?", mochiweb_util:urlencode(Bindings1)] || Bindings1 =/= [] ] ])), % if path is relative detect it and rewrite path case mochiweb_util:safe_relative_path(Path) of undefined -> ?b2l(Prefix) ++ "/" ++ Path; P1 -> ?b2l(Prefix) ++ "/" ++ P1 end end, % normalize final path (fix levels "." and "..") RawPath1 = ?b2l(iolist_to_binary(normalize_path(RawPath))), % In order to do OAuth correctly, we have to save the % requested path. We use default so chained rewriting % wont replace the original header. Headers = mochiweb_headers:default("x-couchdb-requested-path", MochiReq:get(raw_path), MochiReq:get(headers)), ?LOG_DEBUG("rewrite to ~p ~n", [RawPath1]), % build a new mochiweb request MochiReq1 = mochiweb_request:new(MochiReq:get(socket), MochiReq:get(method), RawPath1, MochiReq:get(version), Headers), % cleanup, It force mochiweb to reparse raw uri. MochiReq1:cleanup(), #httpd{ db_url_handlers = DbUrlHandlers, design_url_handlers = DesignUrlHandlers, default_fun = DefaultFun, url_handlers = UrlHandlers, user_ctx = UserCtx, auth = Auth } = Req, erlang:put(pre_rewrite_auth, Auth), erlang:put(pre_rewrite_user_ctx, UserCtx), couch_httpd:handle_request_int(MochiReq1, DefaultFun, UrlHandlers, DbUrlHandlers, DesignUrlHandlers) end. quote_plus({bind, X}) -> mochiweb_util:quote_plus(X); quote_plus(X) -> mochiweb_util:quote_plus(X). %% @doc Try to find a rule matching current url. If none is found %% 404 error not_found is raised try_bind_path([], _Method, _PathParts, _QueryList) -> no_dispatch_path; try_bind_path([Dispatch|Rest], Method, PathParts, QueryList) -> [{PathParts1, Method1}, RedirectPath, QueryArgs, Formats] = Dispatch, case bind_method(Method1, Method) of true -> case bind_path(PathParts1, PathParts, []) of {ok, Remaining, Bindings} -> Bindings1 = Bindings ++ QueryList, % we parse query args from the rule and fill % it eventually with bindings vars QueryArgs1 = make_query_list(QueryArgs, Bindings1, Formats, []), % remove params in QueryLists1 that are already in % QueryArgs1 Bindings2 = lists:foldl(fun({K, V}, Acc) -> K1 = to_binding(K), KV = case couch_util:get_value(K1, QueryArgs1) of undefined -> [{K1, V}]; _V1 -> [] end, Acc ++ KV end, [], Bindings1), FinalBindings = Bindings2 ++ QueryArgs1, NewPathParts = make_new_path(RedirectPath, FinalBindings, Remaining, []), {NewPathParts, FinalBindings}; fail -> try_bind_path(Rest, Method, PathParts, QueryList) end; false -> try_bind_path(Rest, Method, PathParts, QueryList) end. %% rewriting dynamically the quey list given as query member in %% rewrites. Each value is replaced by one binding or an argument %% passed in url. make_query_list([], _Bindings, _Formats, Acc) -> Acc; make_query_list([{Key, {Value}}|Rest], Bindings, Formats, Acc) -> Value1 = {Value}, make_query_list(Rest, Bindings, Formats, [{to_binding(Key), Value1}|Acc]); make_query_list([{Key, Value}|Rest], Bindings, Formats, Acc) when is_binary(Value) -> Value1 = replace_var(Value, Bindings, Formats), make_query_list(Rest, Bindings, Formats, [{to_binding(Key), Value1}|Acc]); make_query_list([{Key, Value}|Rest], Bindings, Formats, Acc) when is_list(Value) -> Value1 = replace_var(Value, Bindings, Formats), make_query_list(Rest, Bindings, Formats, [{to_binding(Key), Value1}|Acc]); make_query_list([{Key, Value}|Rest], Bindings, Formats, Acc) -> make_query_list(Rest, Bindings, Formats, [{to_binding(Key), Value}|Acc]). replace_var(<<"*">>=Value, Bindings, Formats) -> get_var(Value, Bindings, Value, Formats); replace_var(<<":", Var/binary>> = Value, Bindings, Formats) -> get_var(Var, Bindings, Value, Formats); replace_var(Value, _Bindings, _Formats) when is_binary(Value) -> Value; replace_var(Value, Bindings, Formats) when is_list(Value) -> lists:reverse(lists:foldl(fun (<<":", Var/binary>>=Value1, Acc) -> [get_var(Var, Bindings, Value1, Formats)|Acc]; (Value1, Acc) -> [Value1|Acc] end, [], Value)); replace_var(Value, _Bindings, _Formats) -> Value. maybe_json(Key, Value) -> case lists:member(Key, [<<"key">>, <<"startkey">>, <<"start_key">>, <<"endkey">>, <<"end_key">>, <<"keys">>]) of true -> ?JSON_ENCODE(Value); false -> Value end. get_var(VarName, Props, Default, Formats) -> VarName1 = to_binding(VarName), Val = couch_util:get_value(VarName1, Props, Default), maybe_format(VarName, Val, Formats). maybe_format(VarName, Value, Formats) -> case couch_util:get_value(VarName, Formats) of undefined -> Value; Format -> format(Format, Value) end. format(<<"int">>, Value) when is_integer(Value) -> Value; format(<<"int">>, Value) when is_binary(Value) -> format(<<"int">>, ?b2l(Value)); format(<<"int">>, Value) when is_list(Value) -> case (catch list_to_integer(Value)) of IntVal when is_integer(IntVal) -> IntVal; _ -> Value end; format(<<"bool">>, Value) when is_binary(Value) -> format(<<"bool">>, ?b2l(Value)); format(<<"bool">>, Value) when is_list(Value) -> case string:to_lower(Value) of "true" -> true; "false" -> false; _ -> Value end; format(_Format, Value) -> Value. %% doc: build new patch from bindings. bindings are query args %% (+ dynamic query rewritten if needed) and bindings found in %% bind_path step. make_new_path([], _Bindings, _Remaining, Acc) -> lists:reverse(Acc); make_new_path([?MATCH_ALL], _Bindings, Remaining, Acc) -> Acc1 = lists:reverse(Acc) ++ Remaining, Acc1; make_new_path([?MATCH_ALL|_Rest], _Bindings, Remaining, Acc) -> Acc1 = lists:reverse(Acc) ++ Remaining, Acc1; make_new_path([{bind, P}|Rest], Bindings, Remaining, Acc) -> P2 = case couch_util:get_value({bind, P}, Bindings) of undefined -> << "undefined">>; P1 -> iolist_to_binary(P1) end, make_new_path(Rest, Bindings, Remaining, [P2|Acc]); make_new_path([P|Rest], Bindings, Remaining, Acc) -> make_new_path(Rest, Bindings, Remaining, [P|Acc]). %% @doc If method of the query fith the rule method. If the %% method rule is '*', which is the default, all %% request method will bind. It allows us to make rules %% depending on HTTP method. bind_method(?MATCH_ALL, _Method ) -> true; bind_method({bind, Method}, Method) -> true; bind_method(_, _) -> false. %% @doc bind path. Using the rule from we try to bind variables given %% to the current url by pattern matching bind_path([], [], Bindings) -> {ok, [], Bindings}; bind_path([?MATCH_ALL], [Match|_RestMatch]=Rest, Bindings) -> {ok, Rest, [{?MATCH_ALL, Match}|Bindings]}; bind_path(_, [], _) -> fail; bind_path([{bind, Token}|RestToken],[Match|RestMatch],Bindings) -> bind_path(RestToken, RestMatch, [{{bind, Token}, Match}|Bindings]); bind_path([Token|RestToken], [Token|RestMatch], Bindings) -> bind_path(RestToken, RestMatch, Bindings); bind_path(_, _, _) -> fail. %% normalize path. normalize_path(Path) -> "/" ++ string:join(normalize_path1(string:tokens(Path, "/"), []), [?SEPARATOR]). normalize_path1([], Acc) -> lists:reverse(Acc); normalize_path1([".."|Rest], Acc) -> Acc1 = case Acc of [] -> [".."|Acc]; [T|_] when T =:= ".." -> [".."|Acc]; [_|R] -> R end, normalize_path1(Rest, Acc1); normalize_path1(["."|Rest], Acc) -> normalize_path1(Rest, Acc); normalize_path1([Path|Rest], Acc) -> normalize_path1(Rest, [Path|Acc]). %% @doc transform json rule in erlang for pattern matching make_rule(Rule) -> Method = case couch_util:get_value(<<"method">>, Rule) of undefined -> ?MATCH_ALL; M -> to_binding(M) end, QueryArgs = case couch_util:get_value(<<"query">>, Rule) of undefined -> []; {Args} -> Args end, FromParts = case couch_util:get_value(<<"from">>, Rule) of undefined -> [?MATCH_ALL]; From -> parse_path(From) end, ToParts = case couch_util:get_value(<<"to">>, Rule) of undefined -> throw({error, invalid_rewrite_target}); To -> parse_path(To) end, Formats = case couch_util:get_value(<<"formats">>, Rule) of undefined -> []; {Fmts} -> Fmts end, [{FromParts, Method}, ToParts, QueryArgs, Formats]. parse_path(Path) -> {ok, SlashRE} = re:compile(<<"\\/">>), path_to_list(re:split(Path, SlashRE), [], 0). %% @doc convert a path rule (from or to) to an erlang list %% * and path variable starting by ":" are converted %% in erlang atom. path_to_list([], Acc, _DotDotCount) -> lists:reverse(Acc); path_to_list([<<>>|R], Acc, DotDotCount) -> path_to_list(R, Acc, DotDotCount); path_to_list([<<"*">>|R], Acc, DotDotCount) -> path_to_list(R, [?MATCH_ALL|Acc], DotDotCount); path_to_list([<<"..">>|R], Acc, DotDotCount) when DotDotCount == 2 -> case couch_config:get("httpd", "secure_rewrites", "true") of "false" -> path_to_list(R, [<<"..">>|Acc], DotDotCount+1); _Else -> ?LOG_INFO("insecure_rewrite_rule ~p blocked", [lists:reverse(Acc) ++ [<<"..">>] ++ R]), throw({insecure_rewrite_rule, "too many ../.. segments"}) end; path_to_list([<<"..">>|R], Acc, DotDotCount) -> path_to_list(R, [<<"..">>|Acc], DotDotCount+1); path_to_list([P|R], Acc, DotDotCount) -> P1 = case P of <<":", Var/binary>> -> to_binding(Var); _ -> P end, path_to_list(R, [P1|Acc], DotDotCount). maybe_encode_bindings([]) -> []; maybe_encode_bindings(Props) -> lists:foldl(fun ({{bind, <<"*">>}, _V}, Acc) -> Acc; ({{bind, K}, V}, Acc) -> V1 = iolist_to_binary(maybe_json(K, V)), [{K, V1}|Acc] end, [], Props). decode_query_value({K,V}) -> case lists:member(K, ["key", "startkey", "start_key", "endkey", "end_key", "keys"]) of true -> {to_binding(K), ?JSON_DECODE(V)}; false -> {to_binding(K), ?l2b(V)} end. to_binding({bind, V}) -> {bind, V}; to_binding(V) when is_list(V) -> to_binding(?l2b(V)); to_binding(V) -> {bind, V}. apache-couchdb-1.5.0/src/couchdb/couch_util.erl0000644000175000001440000003443712230722213016325 00000000000000% 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. -module(couch_util). -export([priv_dir/0, normpath/1]). -export([should_flush/0, should_flush/1, to_existing_atom/1]). -export([rand32/0, implode/2, collate/2, collate/3]). -export([abs_pathname/1,abs_pathname/2, trim/1]). -export([encodeBase64Url/1, decodeBase64Url/1]). -export([validate_utf8/1, to_hex/1, parse_term/1, dict_find/3]). -export([get_nested_json_value/2, json_user_ctx/1]). -export([proplist_apply_field/2, json_apply_field/2]). -export([to_binary/1, to_integer/1, to_list/1, url_encode/1]). -export([verify/2,simple_call/2,shutdown_sync/1]). -export([get_value/2, get_value/3]). -export([md5/1, md5_init/0, md5_update/2, md5_final/1]). -export([reorder_results/2]). -export([url_strip_password/1]). -export([encode_doc_id/1]). -export([with_db/2]). -export([rfc1123_date/0, rfc1123_date/1]). -include("couch_db.hrl"). % arbitrarily chosen amount of memory to use before flushing to disk -define(FLUSH_MAX_MEM, 10000000). priv_dir() -> case code:priv_dir(couch) of {error, bad_name} -> % small hack, in dev mode "app" is couchdb. Fixing requires % renaming src/couch to src/couch. Not really worth the hassle. % -Damien code:priv_dir(couchdb); Dir -> Dir end. % Normalize a pathname by removing .. and . components. normpath(Path) -> normparts(filename:split(Path), []). normparts([], Acc) -> filename:join(lists:reverse(Acc)); normparts([".." | RestParts], [_Drop | RestAcc]) -> normparts(RestParts, RestAcc); normparts(["." | RestParts], Acc) -> normparts(RestParts, Acc); normparts([Part | RestParts], Acc) -> normparts(RestParts, [Part | Acc]). % works like list_to_existing_atom, except can be list or binary and it % gives you the original value instead of an error if no existing atom. to_existing_atom(V) when is_list(V) -> try list_to_existing_atom(V) catch _:_ -> V end; to_existing_atom(V) when is_binary(V) -> try list_to_existing_atom(?b2l(V)) catch _:_ -> V end; to_existing_atom(V) when is_atom(V) -> V. shutdown_sync(Pid) when not is_pid(Pid)-> ok; shutdown_sync(Pid) -> MRef = erlang:monitor(process, Pid), try catch unlink(Pid), catch exit(Pid, shutdown), receive {'DOWN', MRef, _, _, _} -> ok end after erlang:demonitor(MRef, [flush]) end. simple_call(Pid, Message) -> MRef = erlang:monitor(process, Pid), try Pid ! {self(), Message}, receive {Pid, Result} -> Result; {'DOWN', MRef, _, _, Reason} -> exit(Reason) end after erlang:demonitor(MRef, [flush]) end. validate_utf8(Data) when is_list(Data) -> validate_utf8(?l2b(Data)); validate_utf8(Bin) when is_binary(Bin) -> validate_utf8_fast(Bin, 0). validate_utf8_fast(B, O) -> case B of <<_:O/binary>> -> true; <<_:O/binary, C1, _/binary>> when C1 < 128 -> validate_utf8_fast(B, 1 + O); <<_:O/binary, C1, C2, _/binary>> when C1 >= 194, C1 =< 223, C2 >= 128, C2 =< 191 -> validate_utf8_fast(B, 2 + O); <<_:O/binary, C1, C2, C3, _/binary>> when C1 >= 224, C1 =< 239, C2 >= 128, C2 =< 191, C3 >= 128, C3 =< 191 -> validate_utf8_fast(B, 3 + O); <<_:O/binary, C1, C2, C3, C4, _/binary>> when C1 >= 240, C1 =< 244, C2 >= 128, C2 =< 191, C3 >= 128, C3 =< 191, C4 >= 128, C4 =< 191 -> validate_utf8_fast(B, 4 + O); _ -> false end. to_hex([]) -> []; to_hex(Bin) when is_binary(Bin) -> to_hex(binary_to_list(Bin)); to_hex([H|T]) -> [to_digit(H div 16), to_digit(H rem 16) | to_hex(T)]. to_digit(N) when N < 10 -> $0 + N; to_digit(N) -> $a + N-10. parse_term(Bin) when is_binary(Bin) -> parse_term(binary_to_list(Bin)); parse_term(List) -> {ok, Tokens, _} = erl_scan:string(List ++ "."), erl_parse:parse_term(Tokens). get_value(Key, List) -> get_value(Key, List, undefined). get_value(Key, List, Default) -> case lists:keysearch(Key, 1, List) of {value, {Key,Value}} -> Value; false -> Default end. get_nested_json_value({Props}, [Key|Keys]) -> case couch_util:get_value(Key, Props, nil) of nil -> throw({not_found, <<"missing json key: ", Key/binary>>}); Value -> get_nested_json_value(Value, Keys) end; get_nested_json_value(Value, []) -> Value; get_nested_json_value(_NotJSONObj, _) -> throw({not_found, json_mismatch}). proplist_apply_field(H, L) -> {R} = json_apply_field(H, {L}), R. json_apply_field(H, {L}) -> json_apply_field(H, L, []). json_apply_field({Key, NewValue}, [{Key, _OldVal} | Headers], Acc) -> json_apply_field({Key, NewValue}, Headers, Acc); json_apply_field({Key, NewValue}, [{OtherKey, OtherVal} | Headers], Acc) -> json_apply_field({Key, NewValue}, Headers, [{OtherKey, OtherVal} | Acc]); json_apply_field({Key, NewValue}, [], Acc) -> {[{Key, NewValue}|Acc]}. json_user_ctx(#db{name=DbName, user_ctx=Ctx}) -> {[{<<"db">>, DbName}, {<<"name">>,Ctx#user_ctx.name}, {<<"roles">>,Ctx#user_ctx.roles}]}. % returns a random integer rand32() -> crypto:rand_uniform(0, 16#100000000). % given a pathname "../foo/bar/" it gives back the fully qualified % absolute pathname. abs_pathname(" " ++ Filename) -> % strip leading whitspace abs_pathname(Filename); abs_pathname([$/ |_]=Filename) -> Filename; abs_pathname(Filename) -> {ok, Cwd} = file:get_cwd(), {Filename2, Args} = separate_cmd_args(Filename, ""), abs_pathname(Filename2, Cwd) ++ Args. abs_pathname(Filename, Dir) -> Name = filename:absname(Filename, Dir ++ "/"), OutFilename = filename:join(fix_path_list(filename:split(Name), [])), % If the filename is a dir (last char slash, put back end slash case string:right(Filename,1) of "/" -> OutFilename ++ "/"; "\\" -> OutFilename ++ "/"; _Else-> OutFilename end. % if this as an executable with arguments, seperate out the arguments % ""./foo\ bar.sh -baz=blah" -> {"./foo\ bar.sh", " -baz=blah"} separate_cmd_args("", CmdAcc) -> {lists:reverse(CmdAcc), ""}; separate_cmd_args("\\ " ++ Rest, CmdAcc) -> % handle skipped value separate_cmd_args(Rest, " \\" ++ CmdAcc); separate_cmd_args(" " ++ Rest, CmdAcc) -> {lists:reverse(CmdAcc), " " ++ Rest}; separate_cmd_args([Char|Rest], CmdAcc) -> separate_cmd_args(Rest, [Char | CmdAcc]). % Is a character whitespace? is_whitespace($\s) -> true; is_whitespace($\t) -> true; is_whitespace($\n) -> true; is_whitespace($\r) -> true; is_whitespace(_Else) -> false. % removes leading and trailing whitespace from a string trim(String) -> String2 = lists:dropwhile(fun is_whitespace/1, String), lists:reverse(lists:dropwhile(fun is_whitespace/1, lists:reverse(String2))). % takes a heirarchical list of dirs and removes the dots ".", double dots % ".." and the corresponding parent dirs. fix_path_list([], Acc) -> lists:reverse(Acc); fix_path_list([".."|Rest], [_PrevAcc|RestAcc]) -> fix_path_list(Rest, RestAcc); fix_path_list(["."|Rest], Acc) -> fix_path_list(Rest, Acc); fix_path_list([Dir | Rest], Acc) -> fix_path_list(Rest, [Dir | Acc]). implode(List, Sep) -> implode(List, Sep, []). implode([], _Sep, Acc) -> lists:flatten(lists:reverse(Acc)); implode([H], Sep, Acc) -> implode([], Sep, [H|Acc]); implode([H|T], Sep, Acc) -> implode(T, Sep, [Sep,H|Acc]). drv_port() -> case get(couch_drv_port) of undefined -> Port = open_port({spawn, "couch_icu_driver"}, []), put(couch_drv_port, Port), Port; Port -> Port end. collate(A, B) -> collate(A, B, []). collate(A, B, Options) when is_binary(A), is_binary(B) -> Operation = case lists:member(nocase, Options) of true -> 1; % Case insensitive false -> 0 % Case sensitive end, SizeA = byte_size(A), SizeB = byte_size(B), Bin = <>, [Result] = erlang:port_control(drv_port(), Operation, Bin), % Result is 0 for lt, 1 for eq and 2 for gt. Subtract 1 to return the % expected typical -1, 0, 1 Result - 1. should_flush() -> should_flush(?FLUSH_MAX_MEM). should_flush(MemThreshHold) -> {memory, ProcMem} = process_info(self(), memory), BinMem = lists:foldl(fun({_Id, Size, _NRefs}, Acc) -> Size+Acc end, 0, element(2,process_info(self(), binary))), if ProcMem+BinMem > 2*MemThreshHold -> garbage_collect(), {memory, ProcMem2} = process_info(self(), memory), BinMem2 = lists:foldl(fun({_Id, Size, _NRefs}, Acc) -> Size+Acc end, 0, element(2,process_info(self(), binary))), ProcMem2+BinMem2 > MemThreshHold; true -> false end. encodeBase64Url(Url) -> Url1 = re:replace(base64:encode(Url), ["=+", $$], ""), Url2 = re:replace(Url1, "/", "_", [global]), re:replace(Url2, "\\+", "-", [global, {return, binary}]). decodeBase64Url(Url64) -> Url1 = re:replace(Url64, "-", "+", [global]), Url2 = re:replace(Url1, "_", "/", [global]), Padding = lists:duplicate((4 - iolist_size(Url2) rem 4) rem 4, $=), base64:decode(iolist_to_binary([Url2, Padding])). dict_find(Key, Dict, DefaultValue) -> case dict:find(Key, Dict) of {ok, Value} -> Value; error -> DefaultValue end. to_binary(V) when is_binary(V) -> V; to_binary(V) when is_list(V) -> try list_to_binary(V) catch _:_ -> list_to_binary(io_lib:format("~p", [V])) end; to_binary(V) when is_atom(V) -> list_to_binary(atom_to_list(V)); to_binary(V) -> list_to_binary(io_lib:format("~p", [V])). to_integer(V) when is_integer(V) -> V; to_integer(V) when is_list(V) -> erlang:list_to_integer(V); to_integer(V) when is_binary(V) -> erlang:list_to_integer(binary_to_list(V)). to_list(V) when is_list(V) -> V; to_list(V) when is_binary(V) -> binary_to_list(V); to_list(V) when is_atom(V) -> atom_to_list(V); to_list(V) -> lists:flatten(io_lib:format("~p", [V])). url_encode(Bin) when is_binary(Bin) -> url_encode(binary_to_list(Bin)); url_encode([H|T]) -> if H >= $a, $z >= H -> [H|url_encode(T)]; H >= $A, $Z >= H -> [H|url_encode(T)]; H >= $0, $9 >= H -> [H|url_encode(T)]; H == $_; H == $.; H == $-; H == $: -> [H|url_encode(T)]; true -> case lists:flatten(io_lib:format("~.16.0B", [H])) of [X, Y] -> [$%, X, Y | url_encode(T)]; [X] -> [$%, $0, X | url_encode(T)] end end; url_encode([]) -> []. verify([X|RestX], [Y|RestY], Result) -> verify(RestX, RestY, (X bxor Y) bor Result); verify([], [], Result) -> Result == 0. verify(<>, <>) -> verify(?b2l(X), ?b2l(Y)); verify(X, Y) when is_list(X) and is_list(Y) -> case length(X) == length(Y) of true -> verify(X, Y, 0); false -> false end; verify(_X, _Y) -> false. -spec md5(Data::(iolist() | binary())) -> Digest::binary(). md5(Data) -> try crypto:md5(Data) catch error:_ -> erlang:md5(Data) end. -spec md5_init() -> Context::binary(). md5_init() -> try crypto:md5_init() catch error:_ -> erlang:md5_init() end. -spec md5_update(Context::binary(), Data::(iolist() | binary())) -> NewContext::binary(). md5_update(Ctx, D) -> try crypto:md5_update(Ctx,D) catch error:_ -> erlang:md5_update(Ctx,D) end. -spec md5_final(Context::binary()) -> Digest::binary(). md5_final(Ctx) -> try crypto:md5_final(Ctx) catch error:_ -> erlang:md5_final(Ctx) end. % linear search is faster for small lists, length() is 0.5 ms for 100k list reorder_results(Keys, SortedResults) when length(Keys) < 100 -> [couch_util:get_value(Key, SortedResults) || Key <- Keys]; reorder_results(Keys, SortedResults) -> KeyDict = dict:from_list(SortedResults), [dict:fetch(Key, KeyDict) || Key <- Keys]. url_strip_password(Url) -> re:replace(Url, "http(s)?://([^:]+):[^@]+@(.*)$", "http\\1://\\2:*****@\\3", [{return, list}]). encode_doc_id(#doc{id = Id}) -> encode_doc_id(Id); encode_doc_id(Id) when is_list(Id) -> encode_doc_id(?l2b(Id)); encode_doc_id(<<"_design/", Rest/binary>>) -> "_design/" ++ url_encode(Rest); encode_doc_id(<<"_local/", Rest/binary>>) -> "_local/" ++ url_encode(Rest); encode_doc_id(Id) -> url_encode(Id). with_db(Db, Fun) when is_record(Db, db) -> Fun(Db); with_db(DbName, Fun) -> case couch_db:open_int(DbName, [{user_ctx, #user_ctx{roles=[<<"_admin">>]}}]) of {ok, Db} -> try Fun(Db) after catch couch_db:close(Db) end; Else -> throw(Else) end. rfc1123_date() -> {{YYYY,MM,DD},{Hour,Min,Sec}} = calendar:universal_time(), DayNumber = calendar:day_of_the_week({YYYY,MM,DD}), lists:flatten( io_lib:format("~s, ~2.2.0w ~3.s ~4.4.0w ~2.2.0w:~2.2.0w:~2.2.0w GMT", [day(DayNumber),DD,month(MM),YYYY,Hour,Min,Sec])). rfc1123_date(undefined) -> undefined; rfc1123_date(UniversalTime) -> {{YYYY,MM,DD},{Hour,Min,Sec}} = UniversalTime, DayNumber = calendar:day_of_the_week({YYYY,MM,DD}), lists:flatten( io_lib:format("~s, ~2.2.0w ~3.s ~4.4.0w ~2.2.0w:~2.2.0w:~2.2.0w GMT", [day(DayNumber),DD,month(MM),YYYY,Hour,Min,Sec])). %% day day(1) -> "Mon"; day(2) -> "Tue"; day(3) -> "Wed"; day(4) -> "Thu"; day(5) -> "Fri"; day(6) -> "Sat"; day(7) -> "Sun". %% month month(1) -> "Jan"; month(2) -> "Feb"; month(3) -> "Mar"; month(4) -> "Apr"; month(5) -> "May"; month(6) -> "Jun"; month(7) -> "Jul"; month(8) -> "Aug"; month(9) -> "Sep"; month(10) -> "Oct"; month(11) -> "Nov"; month(12) -> "Dec". apache-couchdb-1.5.0/src/couchdb/couch.app.tpl.in0000644000175000001440000000137312230722213016462 00000000000000{application, couch, [ {description, "@package_name@"}, {vsn, "@version@"}, {modules, [@modules@]}, {registered, [ couch_config, couch_db_update, couch_db_update_notifier_sup, couch_external_manager, couch_httpd, couch_log, couch_primary_services, couch_query_servers, couch_secondary_services, couch_server, couch_server_sup, couch_stats_aggregator, couch_stats_collector, couch_task_status ]}, {mod, {couch_app, [ "%localconfdir%/@defaultini@", "%localconfdir%/@localini@" ]}}, {applications, [kernel, stdlib]}, {included_applications, [crypto, sasl, inets, oauth, ibrowse, mochiweb, os_mon]} ]}. apache-couchdb-1.5.0/src/couchdb/couch_httpd_auth.erl0000644000175000001440000003660412230722213017512 00000000000000% 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. -module(couch_httpd_auth). -include("couch_db.hrl"). -export([default_authentication_handler/1,special_test_authentication_handler/1]). -export([cookie_authentication_handler/1]). -export([null_authentication_handler/1]). -export([proxy_authentification_handler/1]). -export([cookie_auth_header/2]). -export([handle_session_req/1]). -import(couch_httpd, [header_value/2, send_json/2,send_json/4, send_method_not_allowed/2]). special_test_authentication_handler(Req) -> case header_value(Req, "WWW-Authenticate") of "X-Couch-Test-Auth " ++ NamePass -> % NamePass is a colon separated string: "joe schmoe:a password". [Name, Pass] = re:split(NamePass, ":", [{return, list}, {parts, 2}]), case {Name, Pass} of {"Jan Lehnardt", "apple"} -> ok; {"Christopher Lenz", "dog food"} -> ok; {"Noah Slater", "biggiesmalls endian"} -> ok; {"Chris Anderson", "mp3"} -> ok; {"Damien Katz", "pecan pie"} -> ok; {_, _} -> throw({unauthorized, <<"Name or password is incorrect.">>}) end, Req#httpd{user_ctx=#user_ctx{name=?l2b(Name)}}; _ -> % No X-Couch-Test-Auth credentials sent, give admin access so the % previous authentication can be restored after the test Req#httpd{user_ctx=#user_ctx{roles=[<<"_admin">>]}} end. basic_name_pw(Req) -> AuthorizationHeader = header_value(Req, "Authorization"), case AuthorizationHeader of "Basic " ++ Base64Value -> case re:split(base64:decode(Base64Value), ":", [{return, list}, {parts, 2}]) of ["_", "_"] -> % special name and pass to be logged out nil; [User, Pass] -> {User, Pass}; _ -> nil end; _ -> nil end. default_authentication_handler(Req) -> case basic_name_pw(Req) of {User, Pass} -> case couch_auth_cache:get_user_creds(User) of nil -> throw({unauthorized, <<"Name or password is incorrect.">>}); UserProps -> case authenticate(?l2b(Pass), UserProps) of true -> Req#httpd{user_ctx=#user_ctx{ name=?l2b(User), roles=couch_util:get_value(<<"roles">>, UserProps, []) }}; _Else -> throw({unauthorized, <<"Name or password is incorrect.">>}) end end; nil -> case couch_server:has_admins() of true -> Req; false -> case couch_config:get("couch_httpd_auth", "require_valid_user", "false") of "true" -> Req; % If no admins, and no user required, then everyone is admin! % Yay, admin party! _ -> Req#httpd{user_ctx=#user_ctx{roles=[<<"_admin">>]}} end end end. null_authentication_handler(Req) -> Req#httpd{user_ctx=#user_ctx{roles=[<<"_admin">>]}}. %% @doc proxy auth handler. % % This handler allows creation of a userCtx object from a user authenticated remotly. % The client just pass specific headers to CouchDB and the handler create the userCtx. % Headers name can be defined in local.ini. By thefault they are : % % * X-Auth-CouchDB-UserName : contain the username, (x_auth_username in % couch_httpd_auth section) % * X-Auth-CouchDB-Roles : contain the user roles, list of roles separated by a % comma (x_auth_roles in couch_httpd_auth section) % * X-Auth-CouchDB-Token : token to authenticate the authorization (x_auth_token % in couch_httpd_auth section). This token is an hmac-sha1 created from secret key % and username. The secret key should be the same in the client and couchdb node. s % ecret key is the secret key in couch_httpd_auth section of ini. This token is optional % if value of proxy_use_secret key in couch_httpd_auth section of ini isn't true. % proxy_authentification_handler(Req) -> case proxy_auth_user(Req) of nil -> Req; Req2 -> Req2 end. proxy_auth_user(Req) -> XHeaderUserName = couch_config:get("couch_httpd_auth", "x_auth_username", "X-Auth-CouchDB-UserName"), XHeaderRoles = couch_config:get("couch_httpd_auth", "x_auth_roles", "X-Auth-CouchDB-Roles"), XHeaderToken = couch_config:get("couch_httpd_auth", "x_auth_token", "X-Auth-CouchDB-Token"), case header_value(Req, XHeaderUserName) of undefined -> nil; UserName -> Roles = case header_value(Req, XHeaderRoles) of undefined -> []; Else -> [?l2b(R) || R <- string:tokens(Else, ",")] end, case couch_config:get("couch_httpd_auth", "proxy_use_secret", "false") of "true" -> case couch_config:get("couch_httpd_auth", "secret", nil) of nil -> Req#httpd{user_ctx=#user_ctx{name=?l2b(UserName), roles=Roles}}; Secret -> ExpectedToken = couch_util:to_hex(crypto:sha_mac(Secret, UserName)), case header_value(Req, XHeaderToken) of Token when Token == ExpectedToken -> Req#httpd{user_ctx=#user_ctx{name=?l2b(UserName), roles=Roles}}; _ -> nil end end; _ -> Req#httpd{user_ctx=#user_ctx{name=?l2b(UserName), roles=Roles}} end end. cookie_authentication_handler(#httpd{mochi_req=MochiReq}=Req) -> case MochiReq:get_cookie_value("AuthSession") of undefined -> Req; [] -> Req; Cookie -> [User, TimeStr, HashStr] = try AuthSession = couch_util:decodeBase64Url(Cookie), [_A, _B, _Cs] = re:split(?b2l(AuthSession), ":", [{return, list}, {parts, 3}]) catch _:_Error -> Reason = <<"Malformed AuthSession cookie. Please clear your cookies.">>, throw({bad_request, Reason}) end, % Verify expiry and hash CurrentTime = make_cookie_time(), case couch_config:get("couch_httpd_auth", "secret", nil) of nil -> ?LOG_DEBUG("cookie auth secret is not set",[]), Req; SecretStr -> Secret = ?l2b(SecretStr), case couch_auth_cache:get_user_creds(User) of nil -> Req; UserProps -> UserSalt = couch_util:get_value(<<"salt">>, UserProps, <<"">>), FullSecret = <>, ExpectedHash = crypto:sha_mac(FullSecret, User ++ ":" ++ TimeStr), Hash = ?l2b(HashStr), Timeout = list_to_integer( couch_config:get("couch_httpd_auth", "timeout", "600")), ?LOG_DEBUG("timeout ~p", [Timeout]), case (catch erlang:list_to_integer(TimeStr, 16)) of TimeStamp when CurrentTime < TimeStamp + Timeout -> case couch_passwords:verify(ExpectedHash, Hash) of true -> TimeLeft = TimeStamp + Timeout - CurrentTime, ?LOG_DEBUG("Successful cookie auth as: ~p", [User]), Req#httpd{user_ctx=#user_ctx{ name=?l2b(User), roles=couch_util:get_value(<<"roles">>, UserProps, []) }, auth={FullSecret, TimeLeft < Timeout*0.9}}; _Else -> Req end; _Else -> Req end end end end. cookie_auth_header(#httpd{user_ctx=#user_ctx{name=null}}, _Headers) -> []; cookie_auth_header(#httpd{user_ctx=#user_ctx{name=User}, auth={Secret, true}}=Req, Headers) -> % Note: we only set the AuthSession cookie if: % * a valid AuthSession cookie has been received % * we are outside a 10% timeout window % * and if an AuthSession cookie hasn't already been set e.g. by a login % or logout handler. % The login and logout handlers need to set the AuthSession cookie % themselves. CookieHeader = couch_util:get_value("Set-Cookie", Headers, ""), Cookies = mochiweb_cookies:parse_cookie(CookieHeader), AuthSession = couch_util:get_value("AuthSession", Cookies), if AuthSession == undefined -> TimeStamp = make_cookie_time(), [cookie_auth_cookie(Req, ?b2l(User), Secret, TimeStamp)]; true -> [] end; cookie_auth_header(_Req, _Headers) -> []. cookie_auth_cookie(Req, User, Secret, TimeStamp) -> SessionData = User ++ ":" ++ erlang:integer_to_list(TimeStamp, 16), Hash = crypto:sha_mac(Secret, SessionData), mochiweb_cookies:cookie("AuthSession", couch_util:encodeBase64Url(SessionData ++ ":" ++ ?b2l(Hash)), [{path, "/"}] ++ cookie_scheme(Req) ++ max_age()). ensure_cookie_auth_secret() -> case couch_config:get("couch_httpd_auth", "secret", nil) of nil -> NewSecret = ?b2l(couch_uuids:random()), couch_config:set("couch_httpd_auth", "secret", NewSecret), NewSecret; Secret -> Secret end. % session handlers % Login handler with user db handle_session_req(#httpd{method='POST', mochi_req=MochiReq}=Req) -> ReqBody = MochiReq:recv_body(), Form = case MochiReq:get_primary_header_value("content-type") of % content type should be json "application/x-www-form-urlencoded" ++ _ -> mochiweb_util:parse_qs(ReqBody); "application/json" ++ _ -> {Pairs} = ?JSON_DECODE(ReqBody), lists:map(fun({Key, Value}) -> {?b2l(Key), ?b2l(Value)} end, Pairs); _ -> [] end, UserName = ?l2b(couch_util:get_value("name", Form, "")), Password = ?l2b(couch_util:get_value("password", Form, "")), ?LOG_DEBUG("Attempt Login: ~s",[UserName]), User = case couch_auth_cache:get_user_creds(UserName) of nil -> []; Result -> Result end, UserSalt = couch_util:get_value(<<"salt">>, User, <<>>), case authenticate(Password, User) of true -> % setup the session cookie Secret = ?l2b(ensure_cookie_auth_secret()), CurrentTime = make_cookie_time(), Cookie = cookie_auth_cookie(Req, ?b2l(UserName), <>, CurrentTime), % TODO document the "next" feature in Futon {Code, Headers} = case couch_httpd:qs_value(Req, "next", nil) of nil -> {200, [Cookie]}; Redirect -> {302, [Cookie, {"Location", couch_httpd:absolute_uri(Req, Redirect)}]} end, send_json(Req#httpd{req_body=ReqBody}, Code, Headers, {[ {ok, true}, {name, couch_util:get_value(<<"name">>, User, null)}, {roles, couch_util:get_value(<<"roles">>, User, [])} ]}); _Else -> % clear the session Cookie = mochiweb_cookies:cookie("AuthSession", "", [{path, "/"}] ++ cookie_scheme(Req)), {Code, Headers} = case couch_httpd:qs_value(Req, "fail", nil) of nil -> {401, [Cookie]}; Redirect -> {302, [Cookie, {"Location", couch_httpd:absolute_uri(Req, Redirect)}]} end, send_json(Req, Code, Headers, {[{error, <<"unauthorized">>},{reason, <<"Name or password is incorrect.">>}]}) end; % get user info % GET /_session handle_session_req(#httpd{method='GET', user_ctx=UserCtx}=Req) -> Name = UserCtx#user_ctx.name, ForceLogin = couch_httpd:qs_value(Req, "basic", "false"), case {Name, ForceLogin} of {null, "true"} -> throw({unauthorized, <<"Please login.">>}); {Name, _} -> send_json(Req, {[ % remove this ok {ok, true}, {<<"userCtx">>, {[ {name, Name}, {roles, UserCtx#user_ctx.roles} ]}}, {info, {[ {authentication_db, ?l2b(couch_config:get("couch_httpd_auth", "authentication_db"))}, {authentication_handlers, [auth_name(H) || H <- couch_httpd:make_fun_spec_strs( couch_config:get("httpd", "authentication_handlers"))]} ] ++ maybe_value(authenticated, UserCtx#user_ctx.handler, fun(Handler) -> auth_name(?b2l(Handler)) end)}} ]}) end; % logout by deleting the session handle_session_req(#httpd{method='DELETE'}=Req) -> Cookie = mochiweb_cookies:cookie("AuthSession", "", [{path, "/"}] ++ cookie_scheme(Req)), {Code, Headers} = case couch_httpd:qs_value(Req, "next", nil) of nil -> {200, [Cookie]}; Redirect -> {302, [Cookie, {"Location", couch_httpd:absolute_uri(Req, Redirect)}]} end, send_json(Req, Code, Headers, {[{ok, true}]}); handle_session_req(Req) -> send_method_not_allowed(Req, "GET,HEAD,POST,DELETE"). maybe_value(_Key, undefined, _Fun) -> []; maybe_value(Key, Else, Fun) -> [{Key, Fun(Else)}]. authenticate(Pass, UserProps) -> UserSalt = couch_util:get_value(<<"salt">>, UserProps, <<>>), {PasswordHash, ExpectedHash} = case couch_util:get_value(<<"password_scheme">>, UserProps, <<"simple">>) of <<"simple">> -> {couch_passwords:simple(Pass, UserSalt), couch_util:get_value(<<"password_sha">>, UserProps, nil)}; <<"pbkdf2">> -> Iterations = couch_util:get_value(<<"iterations">>, UserProps, 10000), {couch_passwords:pbkdf2(Pass, UserSalt, Iterations), couch_util:get_value(<<"derived_key">>, UserProps, nil)} end, couch_passwords:verify(PasswordHash, ExpectedHash). auth_name(String) when is_list(String) -> [_,_,_,_,_,Name|_] = re:split(String, "[\\W_]", [{return, list}]), ?l2b(Name). make_cookie_time() -> {NowMS, NowS, _} = erlang:now(), NowMS * 1000000 + NowS. cookie_scheme(#httpd{mochi_req=MochiReq}) -> [{http_only, true}] ++ case MochiReq:get(scheme) of http -> []; https -> [{secure, true}] end. max_age() -> case couch_config:get("couch_httpd_auth", "allow_persistent_cookies", "false") of "false" -> []; "true" -> Timeout = list_to_integer( couch_config:get("couch_httpd_auth", "timeout", "600")), [{max_age, Timeout}] end. apache-couchdb-1.5.0/src/couchdb/couch_db_update_notifier_sup.erl0000644000175000001440000000405712230722213022060 00000000000000% 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. % % This causes an OS process to spawned and it is notified every time a database % is updated. % % The notifications are in the form of a the database name sent as a line of % text to the OS processes stdout. % -module(couch_db_update_notifier_sup). -behaviour(supervisor). -export([start_link/0, init/1, config_change/3]). start_link() -> supervisor:start_link({local, couch_db_update_notifier_sup}, couch_db_update_notifier_sup, []). init([]) -> ok = couch_config:register(fun ?MODULE:config_change/3), UpdateNotifierExes = couch_config:get("update_notification"), {ok, {{one_for_one, 10, 3600}, lists:map(fun({Name, UpdateNotifierExe}) -> {Name, {couch_db_update_notifier, start_link, [UpdateNotifierExe]}, permanent, 1000, supervisor, [couch_db_update_notifier]} end, UpdateNotifierExes)}}. %% @doc when update_notification configuration changes, terminate the process %% for that notifier and start a new one with the updated config config_change("update_notification", Id, Exe) -> ChildSpec = { Id, {couch_db_update_notifier, start_link, [Exe]}, permanent, 1000, supervisor, [couch_db_update_notifier] }, supervisor:terminate_child(couch_db_update_notifier_sup, Id), supervisor:delete_child(couch_db_update_notifier_sup, Id), supervisor:start_child(couch_db_update_notifier_sup, ChildSpec). apache-couchdb-1.5.0/src/couchdb/couch_passwords.erl0000644000175000001440000001061112230722213017361 00000000000000% 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. -module(couch_passwords). -export([simple/2, pbkdf2/3, pbkdf2/4, verify/2]). -export([hash_admin_password/1, get_unhashed_admins/0]). -include("couch_db.hrl"). -define(MAX_DERIVED_KEY_LENGTH, (1 bsl 32 - 1)). -define(SHA1_OUTPUT_LENGTH, 20). %% legacy scheme, not used for new passwords. -spec simple(binary(), binary()) -> binary(). simple(Password, Salt) -> ?l2b(couch_util:to_hex(crypto:sha(<>))). %% CouchDB utility functions -spec hash_admin_password(binary()) -> binary(). hash_admin_password(ClearPassword) -> Iterations = couch_config:get("couch_httpd_auth", "iterations", "10000"), Salt = couch_uuids:random(), DerivedKey = couch_passwords:pbkdf2(couch_util:to_binary(ClearPassword), Salt ,list_to_integer(Iterations)), ?l2b("-pbkdf2-" ++ ?b2l(DerivedKey) ++ "," ++ ?b2l(Salt) ++ "," ++ Iterations). -spec get_unhashed_admins() -> list(). get_unhashed_admins() -> lists:filter( fun({_User, "-hashed-" ++ _}) -> false; % already hashed ({_User, "-pbkdf2-" ++ _}) -> false; % already hashed ({_User, _ClearPassword}) -> true end, couch_config:get("admins")). %% Current scheme, much stronger. -spec pbkdf2(binary(), binary(), integer()) -> binary(). pbkdf2(Password, Salt, Iterations) -> {ok, Result} = pbkdf2(Password, Salt, Iterations, ?SHA1_OUTPUT_LENGTH), Result. -spec pbkdf2(binary(), binary(), integer(), integer()) -> {ok, binary()} | {error, derived_key_too_long}. pbkdf2(_Password, _Salt, _Iterations, DerivedLength) when DerivedLength > ?MAX_DERIVED_KEY_LENGTH -> {error, derived_key_too_long}; pbkdf2(Password, Salt, Iterations, DerivedLength) -> L = ceiling(DerivedLength / ?SHA1_OUTPUT_LENGTH), <> = iolist_to_binary(pbkdf2(Password, Salt, Iterations, L, 1, [])), {ok, ?l2b(couch_util:to_hex(Bin))}. -spec pbkdf2(binary(), binary(), integer(), integer(), integer(), iolist()) -> iolist(). pbkdf2(_Password, _Salt, _Iterations, BlockCount, BlockIndex, Acc) when BlockIndex > BlockCount -> lists:reverse(Acc); pbkdf2(Password, Salt, Iterations, BlockCount, BlockIndex, Acc) -> Block = pbkdf2(Password, Salt, Iterations, BlockIndex, 1, <<>>, <<>>), pbkdf2(Password, Salt, Iterations, BlockCount, BlockIndex + 1, [Block|Acc]). -spec pbkdf2(binary(), binary(), integer(), integer(), integer(), binary(), binary()) -> binary(). pbkdf2(_Password, _Salt, Iterations, _BlockIndex, Iteration, _Prev, Acc) when Iteration > Iterations -> Acc; pbkdf2(Password, Salt, Iterations, BlockIndex, 1, _Prev, _Acc) -> InitialBlock = crypto:sha_mac(Password, <>), pbkdf2(Password, Salt, Iterations, BlockIndex, 2, InitialBlock, InitialBlock); pbkdf2(Password, Salt, Iterations, BlockIndex, Iteration, Prev, Acc) -> Next = crypto:sha_mac(Password, Prev), pbkdf2(Password, Salt, Iterations, BlockIndex, Iteration + 1, Next, crypto:exor(Next, Acc)). %% verify two lists for equality without short-circuits to avoid timing attacks. -spec verify(string(), string(), integer()) -> boolean(). verify([X|RestX], [Y|RestY], Result) -> verify(RestX, RestY, (X bxor Y) bor Result); verify([], [], Result) -> Result == 0. -spec verify(binary(), binary()) -> boolean(); (list(), list()) -> boolean(). verify(<>, <>) -> verify(?b2l(X), ?b2l(Y)); verify(X, Y) when is_list(X) and is_list(Y) -> case length(X) == length(Y) of true -> verify(X, Y, 0); false -> false end; verify(_X, _Y) -> false. -spec ceiling(number()) -> integer(). ceiling(X) -> T = erlang:trunc(X), case (X - T) of Neg when Neg < 0 -> T; Pos when Pos > 0 -> T + 1; _ -> T end. apache-couchdb-1.5.0/src/couchdb/couch_users_db.erl0000644000175000001440000000772612230722213017157 00000000000000% 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. -module(couch_users_db). -export([before_doc_update/2, after_doc_read/2, strip_non_public_fields/1]). -include("couch_db.hrl"). -define(NAME, <<"name">>). -define(PASSWORD, <<"password">>). -define(DERIVED_KEY, <<"derived_key">>). -define(PASSWORD_SCHEME, <<"password_scheme">>). -define(PBKDF2, <<"pbkdf2">>). -define(ITERATIONS, <<"iterations">>). -define(SALT, <<"salt">>). -define(replace(L, K, V), lists:keystore(K, 1, L, {K, V})). % If the request's userCtx identifies an admin % -> save_doc (see below) % % If the request's userCtx.name is null: % -> save_doc % // this is an anonymous user registering a new document % // in case a user doc with the same id already exists, the anonymous % // user will get a regular doc update conflict. % If the request's userCtx.name doesn't match the doc's name % -> 404 // Not Found % Else % -> save_doc before_doc_update(Doc, #db{user_ctx = UserCtx} = Db) -> #user_ctx{name=Name} = UserCtx, DocName = get_doc_name(Doc), case (catch couch_db:check_is_admin(Db)) of ok -> save_doc(Doc); _ when Name =:= DocName orelse Name =:= null -> save_doc(Doc); _ -> throw(not_found) end. % If newDoc.password == null || newDoc.password == undefined: % -> % noop % Else -> // calculate password hash server side % newDoc.password_sha = hash_pw(newDoc.password + salt) % newDoc.salt = salt % newDoc.password = null save_doc(#doc{body={Body}} = Doc) -> case couch_util:get_value(?PASSWORD, Body) of null -> % server admins don't have a user-db password entry Doc; undefined -> Doc; ClearPassword -> Iterations = list_to_integer(couch_config:get("couch_httpd_auth", "iterations", "1000")), Salt = couch_uuids:random(), DerivedKey = couch_passwords:pbkdf2(ClearPassword, Salt, Iterations), Body0 = [{?PASSWORD_SCHEME, ?PBKDF2}, {?ITERATIONS, Iterations}|Body], Body1 = ?replace(Body0, ?DERIVED_KEY, DerivedKey), Body2 = ?replace(Body1, ?SALT, Salt), Body3 = proplists:delete(?PASSWORD, Body2), Doc#doc{body={Body3}} end. % If the doc is a design doc % If the request's userCtx identifies an admin % -> return doc % Else % -> 403 // Forbidden % If the request's userCtx identifies an admin % -> return doc % If the request's userCtx.name doesn't match the doc's name % -> 404 // Not Found % Else % -> return doc after_doc_read(#doc{id = <>} = Doc, Db) -> case (catch couch_db:check_is_admin(Db)) of ok -> Doc; _ -> throw({forbidden, <<"Only administrators can view design docs in the users database.">>}) end; after_doc_read(Doc, #db{user_ctx = UserCtx} = Db) -> #user_ctx{name=Name} = UserCtx, DocName = get_doc_name(Doc), case (catch couch_db:check_is_admin(Db)) of ok -> Doc; _ when Name =:= DocName -> Doc; _ -> Doc1 = strip_non_public_fields(Doc), case Doc1 of #doc{body={[]}} -> throw(not_found); _ -> Doc1 end end. get_doc_name(#doc{id= <<"org.couchdb.user:", Name/binary>>}) -> Name; get_doc_name(_) -> undefined. strip_non_public_fields(#doc{body={Props}}=Doc) -> Public = re:split(couch_config:get("couch_httpd_auth", "public_fields", ""), "\\s*,\\s*", [{return, binary}]), Doc#doc{body={[{K, V} || {K, V} <- Props, lists:member(K, Public)]}}. apache-couchdb-1.5.0/src/couchdb/couch_secondary_sup.erl0000644000175000001440000000311212230722213020210 00000000000000% 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. -module(couch_secondary_sup). -behaviour(supervisor). -export([init/1, start_link/0]). start_link() -> supervisor:start_link({local,couch_secondary_services}, ?MODULE, []). init([]) -> SecondarySupervisors = [ {couch_db_update_notifier_sup, {couch_db_update_notifier_sup, start_link, []}, permanent, infinity, supervisor, [couch_db_update_notifier_sup]}, {couch_plugin_event, {gen_event, start_link, [{local, couch_plugin}]}, permanent, brutal_kill, worker, dynamic} ], Children = SecondarySupervisors ++ [ begin {ok, {Module, Fun, Args}} = couch_util:parse_term(SpecStr), {list_to_atom(Name), {Module, Fun, Args}, permanent, brutal_kill, worker, [Module]} end || {Name, SpecStr} <- couch_config:get("daemons"), SpecStr /= ""], {ok, {{one_for_one, 10, 3600}, Children}}. apache-couchdb-1.5.0/src/couchdb/json_stream_parse.erl0000644000175000001440000003322312230722213017675 00000000000000% 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. -module(json_stream_parse). -export([events/2, to_ejson/1, collect_object/2]). -define(IS_WS(X), (X == $\ orelse X == $\t orelse X == $\n orelse X == $\r)). -define(IS_DELIM(X), (X == $} orelse X == $] orelse X == $,)). -define(IS_DIGIT(X), (X >= $0 andalso X =< $9)). % Parses the json into events. % % The DataFun param is a function that produces the data for parsing. When % called it must yield a tuple, or the atom done. The first element in the % tuple is the data itself, and the second element is a function to be called % next to get the next chunk of data in the stream. % % The EventFun is called everytime a json element is parsed. It must produce % a new function to be called for the next event. % % Events happen each time a new element in the json string is parsed. % For simple value types, the data itself is returned: % Strings % Integers % Floats % true % false % null % % For arrays, the start of the array is signaled by the event array_start % atom. The end is signaled by array_end. The events before the end are the % values, or nested values. % % For objects, the start of the object is signaled by the event object_start % atom. The end is signaled by object_end. Each key is signaled by % {key, KeyString}, and the following event is the value, or start of the % value (array_start, object_start). % events(Data,EventFun) when is_list(Data)-> events(list_to_binary(Data),EventFun); events(Data,EventFun) when is_binary(Data)-> events(fun() -> {Data, fun() -> done end} end,EventFun); events(DataFun,EventFun) -> parse_one(DataFun, EventFun, <<>>). % converts the JSON directly to the erlang represention of Json to_ejson(DF) -> {_DF2, EF, _Rest} = events(DF, fun(Ev) -> collect_events(Ev, []) end), [[EJson]] = make_ejson(EF(get_results), [[]]), EJson. % This function is used to return complete objects while parsing streams. % % Return this function from inside an event function right after getting an % object_start event. It then collects the remaining events for that object % and converts it to the erlang represention of Json. % % It then calls your ReturnControl function with the erlang object. Your % return control function then should yield another event function. % % This example stream parses an array of objects, calling % fun do_something_with_the_object/1 for each object. % % ev_array(array_start) -> % fun(Ev) -> ev_object_loop(Ev) end. % % ev_object_loop(object_start) -> % fun(Ev) -> % json_stream_parse:collect_object(Ev, % fun(Obj) -> % do_something_with_the_object(Obj), % fun(Ev2) -> ev_object_loop(Ev2) end % end) % end; % ev_object_loop(array_end) -> % ok % end. % % % invoke the parse % main() -> % ... % events(Data, fun(Ev) -> ev_array(Ev) end). collect_object(Ev, ReturnControl) -> collect_object(Ev, 0, ReturnControl, [object_start]). % internal methods parse_one(DF,EF,Acc) -> case toke(DF, Acc) of none -> none; {Token, DF2, Rest} -> case Token of "{" -> EF2 = EF(object_start), {DF3, EF3, Rest2} = parse_object(DF2, EF2, Rest), {DF3, EF3(object_end), Rest2}; "[" -> EF2 = EF(array_start), {DF3, EF3, Rest2} = parse_array(DF2, EF2, Rest), {DF3, EF3(array_end), Rest2}; Int when is_integer(Int)-> {DF2, EF(Int), Rest}; Float when is_float(Float)-> {DF2, EF(Float), Rest}; Atom when is_atom(Atom)-> {DF2, EF(Atom), Rest}; String when is_binary(String)-> {DF2, EF(String), Rest}; _OtherToken -> err(unexpected_token) end end. must_parse_one(DF,EF,Acc,Error)-> case parse_one(DF, EF, Acc) of none -> err(Error); Else -> Else end. must_toke(DF, Data, Error) -> case toke(DF, Data) of none -> err(Error); Result -> Result end. toke(DF, <<>>) -> case DF() of done -> none; {Data, DF2} -> toke(DF2, Data) end; toke(DF, <>) when ?IS_WS(C)-> toke(DF, Rest); toke(DF, <<${,Rest/binary>>) -> {"{", DF, Rest}; toke(DF, <<$},Rest/binary>>) -> {"}", DF, Rest}; toke(DF, <<$[,Rest/binary>>) -> {"[", DF, Rest}; toke(DF, <<$],Rest/binary>>) -> {"]", DF, Rest}; toke(DF, <<$",Rest/binary>>) -> toke_string(DF,Rest,[]); toke(DF, <<$,,Rest/binary>>) -> {",", DF, Rest}; toke(DF, <<$:,Rest/binary>>) -> {":", DF, Rest}; toke(DF, <<$-,Rest/binary>>) -> {<> = Data, DF2} = must_df(DF,1,Rest,expected_number), case ?IS_DIGIT(C) of true -> toke_number_leading(DF2, Data, "-"); false -> err(expected_number) end; toke(DF, <> = Data) when ?IS_DIGIT(C) -> toke_number_leading(DF, Data, []); toke(DF, <<$t,Rest/binary>>) -> {Data, DF2} = must_match(<<"rue">>, DF, Rest), {true, DF2, Data}; toke(DF, <<$f,Rest/binary>>) -> {Data, DF2} = must_match(<<"alse">>, DF, Rest), {false, DF2, Data}; toke(DF, <<$n,Rest/binary>>) -> {Data, DF2} = must_match(<<"ull">>, DF, Rest), {null, DF2, Data}; toke(_, _) -> err(bad_token). must_match(Pattern, DF, Data) -> Size = size(Pattern), case must_df(DF, Size, Data, bad_token) of {<>, DF2} -> {Data2, DF2}; {_, _} -> err(bad_token) end. must_df(DF,Error)-> case DF() of done -> err(Error); {Data, DF2} -> {Data, DF2} end. must_df(DF,NeedLen,Acc,Error)-> if size(Acc) >= NeedLen -> {Acc, DF}; true -> case DF() of done -> err(Error); {Data, DF2} -> must_df(DF2, NeedLen, <>, Error) end end. parse_object(DF,EF,Acc) -> case must_toke(DF, Acc, unterminated_object) of {String, DF2, Rest} when is_binary(String)-> EF2 = EF({key,String}), case must_toke(DF2,Rest,unterminated_object) of {":", DF3, Rest2} -> {DF4, EF3, Rest3} = must_parse_one(DF3, EF2, Rest2, expected_value), case must_toke(DF4,Rest3, unterminated_object) of {",", DF5, Rest4} -> parse_object(DF5, EF3, Rest4); {"}", DF5, Rest4} -> {DF5, EF3, Rest4}; {_, _, _} -> err(unexpected_token) end; _Else -> err(expected_colon) end; {"}", DF2, Rest} -> {DF2, EF, Rest}; {_, _, _} -> err(unexpected_token) end. parse_array0(DF,EF,Acc) -> case toke(DF, Acc) of none -> err(unterminated_array); {",", DF2, Rest} -> parse_array(DF2,EF,Rest); {"]", DF2, Rest} -> {DF2,EF,Rest}; _ -> err(unexpected_token) end. parse_array(DF,EF,Acc) -> case toke(DF, Acc) of none -> err(unterminated_array); {Token, DF2, Rest} -> case Token of "{" -> EF2 = EF(object_start), {DF3, EF3, Rest2} = parse_object(DF2, EF2, Rest), parse_array0(DF3, EF3(object_end), Rest2); "[" -> EF2 = EF(array_start), {DF3, EF3, Rest2} = parse_array(DF2, EF2, Rest), parse_array0(DF3, EF3(array_end), Rest2); Int when is_integer(Int)-> parse_array0(DF2, EF(Int), Rest); Float when is_float(Float)-> parse_array0(DF2, EF(Float), Rest); Atom when is_atom(Atom)-> parse_array0(DF2, EF(Atom), Rest); String when is_binary(String)-> parse_array0(DF2, EF(String), Rest); "]" -> {DF2, EF, Rest}; _ -> err(unexpected_token) end end. toke_string(DF, <<>>, Acc) -> {Data, DF2} = must_df(DF, unterminated_string), toke_string(DF2, Data, Acc); toke_string(DF, <<$\\,$",Rest/binary>>, Acc) -> toke_string(DF, Rest, [$" | Acc]); toke_string(DF, <<$\\,$\\,Rest/binary>>, Acc) -> toke_string(DF, Rest, [$\\ | Acc]); toke_string(DF, <<$\\,$/,Rest/binary>>, Acc) -> toke_string(DF, Rest, [$/ | Acc]); toke_string(DF, <<$\\,$b,Rest/binary>>, Acc) -> toke_string(DF, Rest, [$\b | Acc]); toke_string(DF, <<$\\,$f,Rest/binary>>, Acc) -> toke_string(DF, Rest, [$\f | Acc]); toke_string(DF, <<$\\,$n,Rest/binary>>, Acc) -> toke_string(DF, Rest, [$\n | Acc]); toke_string(DF, <<$\\,$r,Rest/binary>>, Acc) -> toke_string(DF, Rest, [$\r | Acc]); toke_string(DF, <<$\\,$t,Rest/binary>>, Acc) -> toke_string(DF, Rest, [$\t | Acc]); toke_string(DF, <<$\\,$u,Rest/binary>>, Acc) -> {<>, DF2} = must_df(DF,4,Rest,missing_hex), UTFChar = erlang:list_to_integer([A, B, C, D], 16), if UTFChar == 16#FFFF orelse UTFChar == 16#FFFE -> err(invalid_utf_char); true -> ok end, Chars = xmerl_ucs:to_utf8(UTFChar), toke_string(DF2, Data, lists:reverse(Chars) ++ Acc); toke_string(DF, <<$\\>>, Acc) -> {Data, DF2} = must_df(DF, unterminated_string), toke_string(DF2, <<$\\,Data/binary>>, Acc); toke_string(_DF, <<$\\, _/binary>>, _Acc) -> err(bad_escape); toke_string(DF, <<$", Rest/binary>>, Acc) -> {list_to_binary(lists:reverse(Acc)), DF, Rest}; toke_string(DF, <>, Acc) -> toke_string(DF, Rest, [C | Acc]). toke_number_leading(DF, <>, Acc) when ?IS_DIGIT(Digit) -> toke_number_leading(DF, Rest, [Digit | Acc]); toke_number_leading(DF, <>=Rest, Acc) when ?IS_WS(C) orelse ?IS_DELIM(C) -> {list_to_integer(lists:reverse(Acc)), DF, Rest}; toke_number_leading(DF, <<>>, Acc) -> case DF() of done -> {list_to_integer(lists:reverse(Acc)), fun() -> done end, <<>>}; {Data, DF2} -> toke_number_leading(DF2, Data, Acc) end; toke_number_leading(DF, <<$., Rest/binary>>, Acc) -> toke_number_trailing(DF, Rest, [$.|Acc]); toke_number_leading(DF, <<$e, Rest/binary>>, Acc) -> toke_number_exponent(DF, Rest, [$e, $0, $.|Acc]); toke_number_leading(DF, <<$E, Rest/binary>>, Acc) -> toke_number_exponent(DF, Rest, [$e, $0, $.|Acc]); toke_number_leading(_, _, _) -> err(unexpected_character_in_number). toke_number_trailing(DF, <>, Acc) when ?IS_DIGIT(Digit) -> toke_number_trailing(DF, Rest, [Digit | Acc]); toke_number_trailing(DF, <>=Rest, Acc) when ?IS_WS(C) orelse ?IS_DELIM(C) -> {list_to_float(lists:reverse(Acc)), DF, Rest}; toke_number_trailing(DF, <<>>, Acc) -> case DF() of done -> {list_to_float(lists:reverse(Acc)), fun() -> done end, <<>>}; {Data, DF2} -> toke_number_trailing(DF2, Data, Acc) end; toke_number_trailing(DF, <<"e", Rest/binary>>, [C|_]=Acc) when C /= $. -> toke_number_exponent(DF, Rest, [$e|Acc]); toke_number_trailing(DF, <<"E", Rest/binary>>, [C|_]=Acc) when C /= $. -> toke_number_exponent(DF, Rest, [$e|Acc]); toke_number_trailing(_, _, _) -> err(unexpected_character_in_number). toke_number_exponent(DF, <>, Acc) when ?IS_DIGIT(Digit) -> toke_number_exponent(DF, Rest, [Digit | Acc]); toke_number_exponent(DF, <>, [$e|_]=Acc) when Sign == $+ orelse Sign == $- -> toke_number_exponent(DF, Rest, [Sign | Acc]); toke_number_exponent(DF, <>=Rest, Acc) when ?IS_WS(C) orelse ?IS_DELIM(C) -> {list_to_float(lists:reverse(Acc)), DF, Rest}; toke_number_exponent(DF, <<>>, Acc) -> case DF() of done -> {list_to_float(lists:reverse(Acc)), fun() -> done end, <<>>}; {Data, DF2} -> toke_number_exponent(DF2, Data, Acc) end; toke_number_exponent(_, _, _) -> err(unexpected_character_in_number). err(Error)-> throw({parse_error,Error}). make_ejson([], Stack) -> Stack; make_ejson([array_start | RevEvs], [ArrayValues, PrevValues | RestStack]) -> make_ejson(RevEvs, [[ArrayValues | PrevValues] | RestStack]); make_ejson([array_end | RevEvs], Stack) -> make_ejson(RevEvs, [[] | Stack]); make_ejson([object_start | RevEvs], [ObjValues, PrevValues | RestStack]) -> make_ejson(RevEvs, [[{ObjValues} | PrevValues] | RestStack]); make_ejson([object_end | RevEvs], Stack) -> make_ejson(RevEvs, [[] | Stack]); make_ejson([{key, String} | RevEvs], [[PrevValue|RestObject] | RestStack] = _Stack) -> make_ejson(RevEvs, [[{String, PrevValue}|RestObject] | RestStack]); make_ejson([Value | RevEvs], [Vals | RestStack] = _Stack) -> make_ejson(RevEvs, [[Value | Vals] | RestStack]). collect_events(get_results, Acc) -> Acc; collect_events(Ev, Acc) -> fun(NextEv) -> collect_events(NextEv, [Ev | Acc]) end. collect_object(object_end, 0, ReturnControl, Acc) -> [[Obj]] = make_ejson([object_end | Acc], [[]]), ReturnControl(Obj); collect_object(object_end, NestCount, ReturnControl, Acc) -> fun(Ev) -> collect_object(Ev, NestCount - 1, ReturnControl, [object_end | Acc]) end; collect_object(object_start, NestCount, ReturnControl, Acc) -> fun(Ev) -> collect_object(Ev, NestCount + 1, ReturnControl, [object_start | Acc]) end; collect_object(Ev, NestCount, ReturnControl, Acc) -> fun(Ev2) -> collect_object(Ev2, NestCount, ReturnControl, [Ev | Acc]) end. apache-couchdb-1.5.0/src/couchdb/couch_doc.erl0000644000175000001440000005410212230722213016104 00000000000000% 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. -module(couch_doc). -export([to_doc_info/1,to_doc_info_path/1,parse_rev/1,parse_revs/1,rev_to_str/1,revs_to_strs/1]). -export([att_foldl/3,range_att_foldl/5,att_foldl_decode/3,get_validate_doc_fun/1]). -export([from_json_obj/1,to_json_obj/2,has_stubs/1, merge_stubs/2]). -export([validate_docid/1]). -export([doc_from_multi_part_stream/2]). -export([doc_to_multi_part_stream/5, len_doc_to_multi_part_stream/4]). -export([abort_multi_part_stream/1]). -export([to_path/1]). -export([mp_parse_doc/2]). -export([with_ejson_body/1]). -include("couch_db.hrl"). -spec to_path(#doc{}) -> path(). to_path(#doc{revs={Start, RevIds}}=Doc) -> [Branch] = to_branch(Doc, lists:reverse(RevIds)), {Start - length(RevIds) + 1, Branch}. -spec to_branch(#doc{}, [RevId::binary()]) -> [branch()]. to_branch(Doc, [RevId]) -> [{RevId, Doc, []}]; to_branch(Doc, [RevId | Rest]) -> [{RevId, ?REV_MISSING, to_branch(Doc, Rest)}]. % helpers used by to_json_obj to_json_rev(0, []) -> []; to_json_rev(Start, [FirstRevId|_]) -> [{<<"_rev">>, ?l2b([integer_to_list(Start),"-",revid_to_str(FirstRevId)])}]. to_json_body(true, {Body}) -> Body ++ [{<<"_deleted">>, true}]; to_json_body(false, {Body}) -> Body. to_json_revisions(Options, Start, RevIds) -> case lists:member(revs, Options) of false -> []; true -> [{<<"_revisions">>, {[{<<"start">>, Start}, {<<"ids">>, [revid_to_str(R) ||R <- RevIds]}]}}] end. revid_to_str(RevId) when size(RevId) =:= 16 -> ?l2b(couch_util:to_hex(RevId)); revid_to_str(RevId) -> RevId. rev_to_str({Pos, RevId}) -> ?l2b([integer_to_list(Pos),"-",revid_to_str(RevId)]). revs_to_strs([]) -> []; revs_to_strs([{Pos, RevId}| Rest]) -> [rev_to_str({Pos, RevId}) | revs_to_strs(Rest)]. to_json_meta(Meta) -> lists:map( fun({revs_info, Start, RevsInfo}) -> {JsonRevsInfo, _Pos} = lists:mapfoldl( fun({RevId, Status}, PosAcc) -> JsonObj = {[{<<"rev">>, rev_to_str({PosAcc, RevId})}, {<<"status">>, ?l2b(atom_to_list(Status))}]}, {JsonObj, PosAcc - 1} end, Start, RevsInfo), {<<"_revs_info">>, JsonRevsInfo}; ({local_seq, Seq}) -> {<<"_local_seq">>, Seq}; ({conflicts, Conflicts}) -> {<<"_conflicts">>, revs_to_strs(Conflicts)}; ({deleted_conflicts, DConflicts}) -> {<<"_deleted_conflicts">>, revs_to_strs(DConflicts)} end, Meta). to_json_attachments(Attachments, Options) -> to_json_attachments( Attachments, lists:member(attachments, Options), lists:member(follows, Options), lists:member(att_encoding_info, Options) ). to_json_attachments([], _OutputData, _DataToFollow, _ShowEncInfo) -> []; to_json_attachments(Atts, OutputData, DataToFollow, ShowEncInfo) -> AttProps = lists:map( fun(#att{disk_len=DiskLen, att_len=AttLen, encoding=Enc}=Att) -> {Att#att.name, {[ {<<"content_type">>, Att#att.type}, {<<"revpos">>, Att#att.revpos}] ++ case Att#att.md5 of <<>> -> []; Md5 -> EncodedMd5 = base64:encode(Md5), [{<<"digest">>, <<"md5-",EncodedMd5/binary>>}] end ++ if not OutputData orelse Att#att.data == stub -> [{<<"length">>, DiskLen}, {<<"stub">>, true}]; true -> if DataToFollow -> [{<<"length">>, DiskLen}, {<<"follows">>, true}]; true -> AttData = case Enc of gzip -> zlib:gunzip(att_to_bin(Att)); identity -> att_to_bin(Att) end, [{<<"data">>, base64:encode(AttData)}] end end ++ case {ShowEncInfo, Enc} of {false, _} -> []; {true, identity} -> []; {true, _} -> [ {<<"encoding">>, couch_util:to_binary(Enc)}, {<<"encoded_length">>, AttLen} ] end }} end, Atts), [{<<"_attachments">>, {AttProps}}]. to_json_obj(Doc, Options) -> doc_to_json_obj(with_ejson_body(Doc), Options). doc_to_json_obj(#doc{id=Id,deleted=Del,body=Body,revs={Start, RevIds}, meta=Meta}=Doc,Options)-> {[{<<"_id">>, Id}] ++ to_json_rev(Start, RevIds) ++ to_json_body(Del, Body) ++ to_json_revisions(Options, Start, RevIds) ++ to_json_meta(Meta) ++ to_json_attachments(Doc#doc.atts, Options) }. from_json_obj({Props}) -> transfer_fields(Props, #doc{body=[]}); from_json_obj(_Other) -> throw({bad_request, "Document must be a JSON object"}). parse_revid(RevId) when size(RevId) =:= 32 -> RevInt = erlang:list_to_integer(?b2l(RevId), 16), <>; parse_revid(RevId) when length(RevId) =:= 32 -> RevInt = erlang:list_to_integer(RevId, 16), <>; parse_revid(RevId) when is_binary(RevId) -> RevId; parse_revid(RevId) when is_list(RevId) -> ?l2b(RevId). parse_rev(Rev) when is_binary(Rev) -> parse_rev(?b2l(Rev)); parse_rev(Rev) when is_list(Rev) -> SplitRev = lists:splitwith(fun($-) -> false; (_) -> true end, Rev), case SplitRev of {Pos, [$- | RevId]} -> {list_to_integer(Pos), parse_revid(RevId)}; _Else -> throw({bad_request, <<"Invalid rev format">>}) end; parse_rev(_BadRev) -> throw({bad_request, <<"Invalid rev format">>}). parse_revs([]) -> []; parse_revs([Rev | Rest]) -> [parse_rev(Rev) | parse_revs(Rest)]. validate_docid(<<"">>) -> throw({bad_request, <<"Document id must not be empty">>}); validate_docid(Id) when is_binary(Id) -> case couch_util:validate_utf8(Id) of false -> throw({bad_request, <<"Document id must be valid UTF-8">>}); true -> ok end, case Id of <<"_design/", _/binary>> -> ok; <<"_local/", _/binary>> -> ok; <<"_", _/binary>> -> throw({bad_request, <<"Only reserved document ids may start with underscore.">>}); _Else -> ok end; validate_docid(Id) -> ?LOG_DEBUG("Document id is not a string: ~p", [Id]), throw({bad_request, <<"Document id must be a string">>}). transfer_fields([], #doc{body=Fields}=Doc) -> % convert fields back to json object Doc#doc{body={lists:reverse(Fields)}}; transfer_fields([{<<"_id">>, Id} | Rest], Doc) -> validate_docid(Id), transfer_fields(Rest, Doc#doc{id=Id}); transfer_fields([{<<"_rev">>, Rev} | Rest], #doc{revs={0, []}}=Doc) -> {Pos, RevId} = parse_rev(Rev), transfer_fields(Rest, Doc#doc{revs={Pos, [RevId]}}); transfer_fields([{<<"_rev">>, _Rev} | Rest], Doc) -> % we already got the rev from the _revisions transfer_fields(Rest,Doc); transfer_fields([{<<"_attachments">>, {JsonBins}} | Rest], Doc) -> Atts = lists:map(fun({Name, {BinProps}}) -> Md5 = case couch_util:get_value(<<"digest">>, BinProps) of <<"md5-",EncodedMd5/binary>> -> base64:decode(EncodedMd5); _ -> <<>> end, case couch_util:get_value(<<"stub">>, BinProps) of true -> Type = couch_util:get_value(<<"content_type">>, BinProps), RevPos = couch_util:get_value(<<"revpos">>, BinProps, nil), DiskLen = couch_util:get_value(<<"length">>, BinProps), {Enc, EncLen} = att_encoding_info(BinProps), #att{name=Name, data=stub, type=Type, att_len=EncLen, disk_len=DiskLen, encoding=Enc, revpos=RevPos, md5=Md5}; _ -> Type = couch_util:get_value(<<"content_type">>, BinProps, ?DEFAULT_ATTACHMENT_CONTENT_TYPE), RevPos = couch_util:get_value(<<"revpos">>, BinProps, 0), case couch_util:get_value(<<"follows">>, BinProps) of true -> DiskLen = couch_util:get_value(<<"length">>, BinProps), {Enc, EncLen} = att_encoding_info(BinProps), #att{name=Name, data=follows, type=Type, encoding=Enc, att_len=EncLen, disk_len=DiskLen, revpos=RevPos, md5=Md5}; _ -> Value = couch_util:get_value(<<"data">>, BinProps), Bin = base64:decode(Value), LenBin = size(Bin), #att{name=Name, data=Bin, type=Type, att_len=LenBin, disk_len=LenBin, revpos=RevPos} end end end, JsonBins), transfer_fields(Rest, Doc#doc{atts=Atts}); transfer_fields([{<<"_revisions">>, {Props}} | Rest], Doc) -> RevIds = couch_util:get_value(<<"ids">>, Props), Start = couch_util:get_value(<<"start">>, Props), if not is_integer(Start) -> throw({doc_validation, "_revisions.start isn't an integer."}); not is_list(RevIds) -> throw({doc_validation, "_revisions.ids isn't a array."}); true -> ok end, [throw({doc_validation, "RevId isn't a string"}) || RevId <- RevIds, not is_binary(RevId)], RevIds2 = [parse_revid(RevId) || RevId <- RevIds], transfer_fields(Rest, Doc#doc{revs={Start, RevIds2}}); transfer_fields([{<<"_deleted">>, B} | Rest], Doc) when is_boolean(B) -> transfer_fields(Rest, Doc#doc{deleted=B}); % ignored fields transfer_fields([{<<"_revs_info">>, _} | Rest], Doc) -> transfer_fields(Rest, Doc); transfer_fields([{<<"_local_seq">>, _} | Rest], Doc) -> transfer_fields(Rest, Doc); transfer_fields([{<<"_conflicts">>, _} | Rest], Doc) -> transfer_fields(Rest, Doc); transfer_fields([{<<"_deleted_conflicts">>, _} | Rest], Doc) -> transfer_fields(Rest, Doc); % special fields for replication documents transfer_fields([{<<"_replication_state">>, _} = Field | Rest], #doc{body=Fields} = Doc) -> transfer_fields(Rest, Doc#doc{body=[Field|Fields]}); transfer_fields([{<<"_replication_state_time">>, _} = Field | Rest], #doc{body=Fields} = Doc) -> transfer_fields(Rest, Doc#doc{body=[Field|Fields]}); transfer_fields([{<<"_replication_id">>, _} = Field | Rest], #doc{body=Fields} = Doc) -> transfer_fields(Rest, Doc#doc{body=[Field|Fields]}); transfer_fields([{<<"_replication_stats">>, _} = Field | Rest], #doc{body=Fields} = Doc) -> transfer_fields(Rest, Doc#doc{body=[Field|Fields]}); % unknown special field transfer_fields([{<<"_",Name/binary>>, _} | _], _) -> throw({doc_validation, ?l2b(io_lib:format("Bad special document member: _~s", [Name]))}); transfer_fields([Field | Rest], #doc{body=Fields}=Doc) -> transfer_fields(Rest, Doc#doc{body=[Field|Fields]}). att_encoding_info(BinProps) -> DiskLen = couch_util:get_value(<<"length">>, BinProps), case couch_util:get_value(<<"encoding">>, BinProps) of undefined -> {identity, DiskLen}; Enc -> EncodedLen = couch_util:get_value(<<"encoded_length">>, BinProps, DiskLen), {list_to_existing_atom(?b2l(Enc)), EncodedLen} end. to_doc_info(FullDocInfo) -> {DocInfo, _Path} = to_doc_info_path(FullDocInfo), DocInfo. max_seq(Tree, UpdateSeq) -> FoldFun = fun({_Pos, _Key}, Value, _Type, MaxOldSeq) -> case Value of {_Deleted, _DiskPos, OldTreeSeq} -> % Older versions didn't track data sizes. erlang:max(MaxOldSeq, OldTreeSeq); {_Deleted, _DiskPos, OldTreeSeq, _Size} -> erlang:max(MaxOldSeq, OldTreeSeq); _ -> MaxOldSeq end end, couch_key_tree:fold(FoldFun, UpdateSeq, Tree). to_doc_info_path(#full_doc_info{id=Id,rev_tree=Tree,update_seq=Seq}) -> RevInfosAndPath = [ {#rev_info{ deleted = element(1, LeafVal), body_sp = element(2, LeafVal), seq = element(3, LeafVal), rev = {Pos, RevId} }, Path} || {LeafVal, {Pos, [RevId | _]} = Path} <- couch_key_tree:get_all_leafs(Tree) ], SortedRevInfosAndPath = lists:sort( fun({#rev_info{deleted=DeletedA,rev=RevA}, _PathA}, {#rev_info{deleted=DeletedB,rev=RevB}, _PathB}) -> % sort descending by {not deleted, rev} {not DeletedA, RevA} > {not DeletedB, RevB} end, RevInfosAndPath), [{_RevInfo, WinPath}|_] = SortedRevInfosAndPath, RevInfos = [RevInfo || {RevInfo, _Path} <- SortedRevInfosAndPath], {#doc_info{id=Id, high_seq=max_seq(Tree, Seq), revs=RevInfos}, WinPath}. att_foldl(#att{data=Bin}, Fun, Acc) when is_binary(Bin) -> Fun(Bin, Acc); att_foldl(#att{data={Fd,Sp},md5=Md5}, Fun, Acc) -> couch_stream:foldl(Fd, Sp, Md5, Fun, Acc); att_foldl(#att{data=DataFun,att_len=Len}, Fun, Acc) when is_function(DataFun) -> fold_streamed_data(DataFun, Len, Fun, Acc). range_att_foldl(#att{data={Fd,Sp}}, From, To, Fun, Acc) -> couch_stream:range_foldl(Fd, Sp, From, To, Fun, Acc). att_foldl_decode(#att{data={Fd,Sp},md5=Md5,encoding=Enc}, Fun, Acc) -> couch_stream:foldl_decode(Fd, Sp, Md5, Enc, Fun, Acc); att_foldl_decode(#att{data=Fun2,att_len=Len, encoding=identity}, Fun, Acc) -> fold_streamed_data(Fun2, Len, Fun, Acc). att_to_bin(#att{data=Bin}) when is_binary(Bin) -> Bin; att_to_bin(#att{data=Iolist}) when is_list(Iolist) -> iolist_to_binary(Iolist); att_to_bin(#att{data={_Fd,_Sp}}=Att) -> iolist_to_binary( lists:reverse(att_foldl( Att, fun(Bin,Acc) -> [Bin|Acc] end, [] )) ); att_to_bin(#att{data=DataFun, att_len=Len}) when is_function(DataFun)-> iolist_to_binary( lists:reverse(fold_streamed_data( DataFun, Len, fun(Data, Acc) -> [Data | Acc] end, [] )) ). get_validate_doc_fun(#doc{body={Props}}=DDoc) -> case couch_util:get_value(<<"validate_doc_update">>, Props) of undefined -> nil; _Else -> fun(EditDoc, DiskDoc, Ctx, SecObj) -> couch_query_servers:validate_doc_update(DDoc, EditDoc, DiskDoc, Ctx, SecObj) end end. has_stubs(#doc{atts=Atts}) -> has_stubs(Atts); has_stubs([]) -> false; has_stubs([#att{data=stub}|_]) -> true; has_stubs([_Att|Rest]) -> has_stubs(Rest). merge_stubs(#doc{id = Id}, nil) -> throw({missing_stub, <<"Previous revision missing for document ", Id/binary>>}); merge_stubs(#doc{id=Id,atts=MemBins}=StubsDoc, #doc{atts=DiskBins}) -> BinDict = dict:from_list([{Name, Att} || #att{name=Name}=Att <- DiskBins]), MergedBins = lists:map( fun(#att{name=Name, data=stub, revpos=StubRevPos}) -> case dict:find(Name, BinDict) of {ok, #att{revpos=DiskRevPos}=DiskAtt} when DiskRevPos == StubRevPos orelse StubRevPos == nil -> DiskAtt; _ -> throw({missing_stub, <<"id:", Id/binary, ", name:", Name/binary>>}) end; (Att) -> Att end, MemBins), StubsDoc#doc{atts= MergedBins}. fold_streamed_data(_RcvFun, 0, _Fun, Acc) -> Acc; fold_streamed_data(RcvFun, LenLeft, Fun, Acc) when LenLeft > 0-> Bin = RcvFun(), ResultAcc = Fun(Bin, Acc), fold_streamed_data(RcvFun, LenLeft - size(Bin), Fun, ResultAcc). len_doc_to_multi_part_stream(Boundary, JsonBytes, Atts, SendEncodedAtts) -> AttsSize = lists:foldl(fun(Att, AccAttsSize) -> #att{ data=Data, name=Name, att_len=AttLen, disk_len=DiskLen, type=Type, encoding=Encoding } = Att, case Data of stub -> AccAttsSize; _ -> AccAttsSize + 4 + % "\r\n\r\n" case SendEncodedAtts of true -> % header length(integer_to_list(AttLen)) + AttLen; _ -> % header length(integer_to_list(DiskLen)) + DiskLen end + 4 + % "\r\n--" size(Boundary) + % attachment headers % (the length of the Content-Length has already been set) size(Name) + size(Type) + length("\r\nContent-Disposition: attachment; filename=\"\"") + length("\r\nContent-Type: ") + length("\r\nContent-Length: ") + case Encoding of identity -> 0; _ -> length(atom_to_list(Encoding)) + length("\r\nContent-Encoding: ") end end end, 0, Atts), if AttsSize == 0 -> {<<"application/json">>, iolist_size(JsonBytes)}; true -> {<<"multipart/related; boundary=\"", Boundary/binary, "\"">>, 2 + % "--" size(Boundary) + 36 + % "\r\ncontent-type: application/json\r\n\r\n" iolist_size(JsonBytes) + 4 + % "\r\n--" size(Boundary) + + AttsSize + 2 % "--" } end. doc_to_multi_part_stream(Boundary, JsonBytes, Atts, WriteFun, SendEncodedAtts) -> case lists:any(fun(#att{data=Data})-> Data /= stub end, Atts) of true -> WriteFun([<<"--", Boundary/binary, "\r\nContent-Type: application/json\r\n\r\n">>, JsonBytes, <<"\r\n--", Boundary/binary>>]), atts_to_mp(Atts, Boundary, WriteFun, SendEncodedAtts); false -> WriteFun(JsonBytes) end. atts_to_mp([], _Boundary, WriteFun, _SendEncAtts) -> WriteFun(<<"--">>); atts_to_mp([#att{data=stub} | RestAtts], Boundary, WriteFun, SendEncodedAtts) -> atts_to_mp(RestAtts, Boundary, WriteFun, SendEncodedAtts); atts_to_mp([Att | RestAtts], Boundary, WriteFun, SendEncodedAtts) -> #att{ name=Name, att_len=AttLen, disk_len=DiskLen, type=Type, encoding=Encoding } = Att, % write headers LengthBin = case SendEncodedAtts of true -> list_to_binary(integer_to_list(AttLen)); false -> list_to_binary(integer_to_list(DiskLen)) end, WriteFun(<<"\r\nContent-Disposition: attachment; filename=\"", Name/binary, "\"">>), WriteFun(<<"\r\nContent-Type: ", Type/binary>>), WriteFun(<<"\r\nContent-Length: ", LengthBin/binary>>), case Encoding of identity -> ok; _ -> EncodingBin = atom_to_binary(Encoding, latin1), WriteFun(<<"\r\nContent-Encoding: ", EncodingBin/binary>>) end, % write data WriteFun(<<"\r\n\r\n">>), AttFun = case SendEncodedAtts of false -> fun att_foldl_decode/3; true -> fun att_foldl/3 end, AttFun(Att, fun(Data, _) -> WriteFun(Data) end, ok), WriteFun(<<"\r\n--", Boundary/binary>>), atts_to_mp(RestAtts, Boundary, WriteFun, SendEncodedAtts). doc_from_multi_part_stream(ContentType, DataFun) -> Parent = self(), Parser = spawn_link(fun() -> {<<"--",_/binary>>, _, _} = couch_httpd:parse_multipart_request( ContentType, DataFun, fun(Next) -> mp_parse_doc(Next, []) end), unlink(Parent), Parent ! {self(), finished} end), Ref = make_ref(), Parser ! {get_doc_bytes, Ref, self()}, receive {doc_bytes, Ref, DocBytes} -> Doc = from_json_obj(?JSON_DECODE(DocBytes)), % go through the attachments looking for 'follows' in the data, % replace with function that reads the data from MIME stream. ReadAttachmentDataFun = fun() -> Parser ! {get_bytes, Ref, self()}, receive {bytes, Ref, Bytes} -> Bytes end end, Atts2 = lists:map( fun(#att{data=follows}=A) -> A#att{data=ReadAttachmentDataFun}; (A) -> A end, Doc#doc.atts), WaitFun = fun() -> receive {Parser, finished} -> ok end, erlang:put(mochiweb_request_recv, true) end, {ok, Doc#doc{atts=Atts2}, WaitFun, Parser} end. mp_parse_doc({headers, H}, []) -> case couch_util:get_value("content-type", H) of {"application/json", _} -> fun (Next) -> mp_parse_doc(Next, []) end end; mp_parse_doc({body, Bytes}, AccBytes) -> fun (Next) -> mp_parse_doc(Next, [Bytes | AccBytes]) end; mp_parse_doc(body_end, AccBytes) -> receive {get_doc_bytes, Ref, From} -> From ! {doc_bytes, Ref, lists:reverse(AccBytes)} end, fun mp_parse_atts/1. mp_parse_atts(eof) -> ok; mp_parse_atts({headers, _H}) -> fun mp_parse_atts/1; mp_parse_atts({body, Bytes}) -> receive {get_bytes, Ref, From} -> From ! {bytes, Ref, Bytes} end, fun mp_parse_atts/1; mp_parse_atts(body_end) -> fun mp_parse_atts/1. abort_multi_part_stream(Parser) -> abort_multi_part_stream(Parser, erlang:monitor(process, Parser)). abort_multi_part_stream(Parser, MonRef) -> case is_process_alive(Parser) of true -> Parser ! {get_bytes, nil, self()}, receive {bytes, nil, _Bytes} -> abort_multi_part_stream(Parser, MonRef); {'DOWN', MonRef, _, _, _} -> ok end; false -> erlang:demonitor(MonRef, [flush]) end. with_ejson_body(#doc{body = Body} = Doc) when is_binary(Body) -> Doc#doc{body = couch_compress:decompress(Body)}; with_ejson_body(#doc{body = {_}} = Doc) -> Doc. apache-couchdb-1.5.0/src/couchdb/couch_compress.erl0000644000175000001440000000514712230722213017177 00000000000000% 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. -module(couch_compress). -export([compress/2, decompress/1, is_compressed/2]). -export([get_compression_method/0]). -include("couch_db.hrl"). % binaries compressed with snappy have their first byte set to this value -define(SNAPPY_PREFIX, 1). % Term prefixes documented at: % http://www.erlang.org/doc/apps/erts/erl_ext_dist.html -define(TERM_PREFIX, 131). -define(COMPRESSED_TERM_PREFIX, 131, 80). get_compression_method() -> case couch_config:get("couchdb", "file_compression") of undefined -> ?DEFAULT_COMPRESSION; Method1 -> case string:tokens(Method1, "_") of [Method] -> list_to_existing_atom(Method); [Method, Level] -> {list_to_existing_atom(Method), list_to_integer(Level)} end end. compress(<> = Bin, snappy) -> Bin; compress(<> = Bin, Method) -> compress(decompress(Bin), Method); compress(<> = Bin, Method) -> compress(decompress(Bin), Method); compress(Term, none) -> ?term_to_bin(Term); compress(Term, {deflate, Level}) -> term_to_binary(Term, [{minor_version, 1}, {compressed, Level}]); compress(Term, snappy) -> Bin = ?term_to_bin(Term), try {ok, CompressedBin} = snappy:compress(Bin), case byte_size(CompressedBin) < byte_size(Bin) of true -> <>; false -> Bin end catch exit:snappy_nif_not_loaded -> Bin end. decompress(<>) -> {ok, TermBin} = snappy:decompress(Rest), binary_to_term(TermBin); decompress(<> = Bin) -> binary_to_term(Bin). is_compressed(<>, Method) -> Method =:= snappy; is_compressed(<>, {deflate, _Level}) -> true; is_compressed(<>, _Method) -> false; is_compressed(<>, Method) -> Method =:= none; is_compressed(Term, _Method) when not is_binary(Term) -> false. apache-couchdb-1.5.0/src/couchdb/couch_httpd_stats_handlers.erl0000644000175000001440000000367012230722213021564 00000000000000% 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. -module(couch_httpd_stats_handlers). -include("couch_db.hrl"). -export([handle_stats_req/1]). -import(couch_httpd, [ send_json/2, send_json/3, send_json/4, send_method_not_allowed/2, start_json_response/2, send_chunk/2, end_json_response/1, start_chunked_response/3, send_error/4 ]). handle_stats_req(#httpd{method='GET', path_parts=[_]}=Req) -> flush(Req), send_json(Req, couch_stats_aggregator:all(range(Req))); handle_stats_req(#httpd{method='GET', path_parts=[_, _Mod]}) -> throw({bad_request, <<"Stat names must have exactly to parts.">>}); handle_stats_req(#httpd{method='GET', path_parts=[_, Mod, Key]}=Req) -> flush(Req), Stats = couch_stats_aggregator:get_json({list_to_atom(binary_to_list(Mod)), list_to_atom(binary_to_list(Key))}, range(Req)), send_json(Req, {[{Mod, {[{Key, Stats}]}}]}); handle_stats_req(#httpd{method='GET', path_parts=[_, _Mod, _Key | _Extra]}) -> throw({bad_request, <<"Stat names must have exactly two parts.">>}); handle_stats_req(Req) -> send_method_not_allowed(Req, "GET"). range(Req) -> case couch_util:get_value("range", couch_httpd:qs(Req)) of undefined -> 0; Value -> list_to_integer(Value) end. flush(Req) -> case couch_util:get_value("flush", couch_httpd:qs(Req)) of "true" -> couch_stats_aggregator:collect_sample(); _Else -> ok end. apache-couchdb-1.5.0/src/couchdb/couch_server_sup.erl0000644000175000001440000001122512230722213017533 00000000000000% 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. -module(couch_server_sup). -behaviour(supervisor). -export([start_link/1,stop/0, couch_config_start_link_wrapper/2, restart_core_server/0, config_change/2]). -include("couch_db.hrl"). %% supervisor callbacks -export([init/1]). start_link(IniFiles) -> case whereis(couch_server_sup) of undefined -> start_server(IniFiles); _Else -> {error, already_started} end. restart_core_server() -> init:restart(). couch_config_start_link_wrapper(IniFiles, FirstConfigPid) -> case is_process_alive(FirstConfigPid) of true -> link(FirstConfigPid), {ok, FirstConfigPid}; false -> couch_config:start_link(IniFiles) end. start_server(IniFiles) -> case init:get_argument(pidfile) of {ok, [PidFile]} -> case file:write_file(PidFile, os:getpid()) of ok -> ok; {error, Reason} -> io:format("Failed to write PID file ~s: ~s", [PidFile, file:format_error(Reason)]) end; _ -> ok end, {ok, ConfigPid} = couch_config:start_link(IniFiles), LogLevel = couch_config:get("log", "level", "info"), % announce startup io:format("Apache CouchDB ~s (LogLevel=~s) is starting.~n", [ couch_server:get_version(), LogLevel ]), case LogLevel of "debug" -> io:format("Configuration Settings ~p:~n", [IniFiles]), [io:format(" [~s] ~s=~p~n", [Module, Variable, Value]) || {{Module, Variable}, Value} <- couch_config:all()]; _ -> ok end, BaseChildSpecs = {{one_for_all, 10, 3600}, [{couch_config, {couch_server_sup, couch_config_start_link_wrapper, [IniFiles, ConfigPid]}, permanent, brutal_kill, worker, [couch_config]}, {couch_primary_services, {couch_primary_sup, start_link, []}, permanent, infinity, supervisor, [couch_primary_sup]}, {couch_secondary_services, {couch_secondary_sup, start_link, []}, permanent, infinity, supervisor, [couch_secondary_sup]} ]}, % ensure these applications are running application:start(ibrowse), application:start(crypto), {ok, Pid} = supervisor:start_link( {local, couch_server_sup}, couch_server_sup, BaseChildSpecs), % launch the icu bridge % just restart if one of the config settings change. couch_config:register(fun ?MODULE:config_change/2, Pid), unlink(ConfigPid), Ip = couch_config:get("httpd", "bind_address"), io:format("Apache CouchDB has started. Time to relax.~n"), Uris = [get_uri(Name, Ip) || Name <- [couch_httpd, https]], [begin case Uri of undefined -> ok; Uri -> ?LOG_INFO("Apache CouchDB has started on ~s", [Uri]) end end || Uri <- Uris], case couch_config:get("couchdb", "uri_file", null) of null -> ok; UriFile -> Lines = [begin case Uri of undefined -> []; Uri -> io_lib:format("~s~n", [Uri]) end end || Uri <- Uris], case file:write_file(UriFile, Lines) of ok -> ok; {error, Reason2} = Error -> ?LOG_ERROR("Failed to write to URI file ~s: ~s", [UriFile, file:format_error(Reason2)]), throw(Error) end end, {ok, Pid}. stop() -> catch exit(whereis(couch_server_sup), normal). config_change("daemons", _) -> supervisor:terminate_child(couch_server_sup, couch_secondary_services), supervisor:restart_child(couch_server_sup, couch_secondary_services); config_change("couchdb", "util_driver_dir") -> init:restart(). init(ChildSpecs) -> {ok, ChildSpecs}. get_uri(Name, Ip) -> case get_port(Name) of undefined -> undefined; Port -> io_lib:format("~s://~s:~w/", [get_scheme(Name), Ip, Port]) end. get_scheme(couch_httpd) -> "http"; get_scheme(https) -> "https". get_port(Name) -> try mochiweb_socket_server:get(Name, port) catch exit:{noproc, _}-> undefined end. apache-couchdb-1.5.0/src/couchdb/couch_httpd.erl0000644000175000001440000011622512230722213016467 00000000000000% 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. -module(couch_httpd). -include("couch_db.hrl"). -export([start_link/0, start_link/1, stop/0, config_change/2, handle_request/5]). -export([header_value/2,header_value/3,qs_value/2,qs_value/3,qs/1,qs_json_value/3]). -export([path/1,absolute_uri/2,body_length/1]). -export([verify_is_server_admin/1,unquote/1,quote/1,recv/2,recv_chunked/4,error_info/1]). -export([make_fun_spec_strs/1]). -export([make_arity_1_fun/1, make_arity_2_fun/1, make_arity_3_fun/1]). -export([parse_form/1,json_body/1,json_body_obj/1,body/1]). -export([doc_etag/1, make_etag/1, etag_match/2, etag_respond/3, etag_maybe/2]). -export([primary_header_value/2,partition/1,serve_file/3,serve_file/4, server_header/0]). -export([start_chunked_response/3,send_chunk/2,log_request/2]). -export([start_response_length/4, start_response/3, send/2]). -export([start_json_response/2, start_json_response/3, end_json_response/1]). -export([send_response/4,send_method_not_allowed/2,send_error/4, send_redirect/2,send_chunked_error/2]). -export([send_json/2,send_json/3,send_json/4,last_chunk/1,parse_multipart_request/3]). -export([accepted_encodings/1,handle_request_int/5,validate_referer/1,validate_ctype/2]). -export([http_1_0_keep_alive/2]). start_link() -> start_link(http). start_link(http) -> Port = couch_config:get("httpd", "port", "5984"), start_link(?MODULE, [{port, Port}]); start_link(https) -> Port = couch_config:get("ssl", "port", "6984"), CertFile = couch_config:get("ssl", "cert_file", nil), KeyFile = couch_config:get("ssl", "key_file", nil), Options = case CertFile /= nil andalso KeyFile /= nil of true -> SslOpts = [{certfile, CertFile}, {keyfile, KeyFile}], %% set password if one is needed for the cert SslOpts1 = case couch_config:get("ssl", "password", nil) of nil -> SslOpts; Password -> SslOpts ++ [{password, Password}] end, % do we verify certificates ? FinalSslOpts = case couch_config:get("ssl", "verify_ssl_certificates", "false") of "false" -> SslOpts1; "true" -> case couch_config:get("ssl", "cacert_file", nil) of nil -> io:format("Verify SSL certificate " ++"enabled but file containing " ++"PEM encoded CA certificates is " ++"missing", []), throw({error, missing_cacerts}); CaCertFile -> Depth = list_to_integer(couch_config:get("ssl", "ssl_certificate_max_depth", "1")), FinalOpts = [ {cacertfile, CaCertFile}, {depth, Depth}, {verify, verify_peer}], % allows custom verify fun. case couch_config:get("ssl", "verify_fun", nil) of nil -> FinalOpts; SpecStr -> FinalOpts ++ [{verify_fun, make_arity_3_fun(SpecStr)}] end end end, [{port, Port}, {ssl, true}, {ssl_opts, FinalSslOpts}]; false -> io:format("SSL enabled but PEM certificates are missing.", []), throw({error, missing_certs}) end, start_link(https, Options). start_link(Name, Options) -> % read config and register for configuration changes % just stop if one of the config settings change. couch_server_sup % will restart us and then we will pick up the new settings. BindAddress = couch_config:get("httpd", "bind_address", any), validate_bind_address(BindAddress), DefaultSpec = "{couch_httpd_db, handle_request}", DefaultFun = make_arity_1_fun( couch_config:get("httpd", "default_handler", DefaultSpec) ), UrlHandlersList = lists:map( fun({UrlKey, SpecStr}) -> {?l2b(UrlKey), make_arity_1_fun(SpecStr)} end, couch_config:get("httpd_global_handlers")), DbUrlHandlersList = lists:map( fun({UrlKey, SpecStr}) -> {?l2b(UrlKey), make_arity_2_fun(SpecStr)} end, couch_config:get("httpd_db_handlers")), DesignUrlHandlersList = lists:map( fun({UrlKey, SpecStr}) -> {?l2b(UrlKey), make_arity_3_fun(SpecStr)} end, couch_config:get("httpd_design_handlers")), UrlHandlers = dict:from_list(UrlHandlersList), DbUrlHandlers = dict:from_list(DbUrlHandlersList), DesignUrlHandlers = dict:from_list(DesignUrlHandlersList), {ok, ServerOptions} = couch_util:parse_term( couch_config:get("httpd", "server_options", "[]")), {ok, SocketOptions} = couch_util:parse_term( couch_config:get("httpd", "socket_options", "[]")), set_auth_handlers(), % ensure uuid is set so that concurrent replications % get the same value. couch_server:get_uuid(), Loop = fun(Req)-> case SocketOptions of [] -> ok; _ -> ok = mochiweb_socket:setopts(Req:get(socket), SocketOptions) end, apply(?MODULE, handle_request, [ Req, DefaultFun, UrlHandlers, DbUrlHandlers, DesignUrlHandlers ]) end, % set mochiweb options FinalOptions = lists:append([Options, ServerOptions, [ {loop, Loop}, {name, Name}, {ip, BindAddress}]]), % launch mochiweb {ok, Pid} = case mochiweb_http:start(FinalOptions) of {ok, MochiPid} -> {ok, MochiPid}; {error, Reason} -> io:format("Failure to start Mochiweb: ~s~n",[Reason]), throw({error, Reason}) end, ok = couch_config:register(fun ?MODULE:config_change/2, Pid), {ok, Pid}. stop() -> mochiweb_http:stop(couch_httpd), mochiweb_http:stop(https). config_change("httpd", "bind_address") -> ?MODULE:stop(); config_change("httpd", "port") -> ?MODULE:stop(); config_change("httpd", "default_handler") -> ?MODULE:stop(); config_change("httpd", "server_options") -> ?MODULE:stop(); config_change("httpd", "socket_options") -> ?MODULE:stop(); config_change("httpd", "authentication_handlers") -> set_auth_handlers(); config_change("httpd_global_handlers", _) -> ?MODULE:stop(); config_change("httpd_db_handlers", _) -> ?MODULE:stop(); config_change("ssl", _) -> ?MODULE:stop(). set_auth_handlers() -> AuthenticationSrcs = make_fun_spec_strs( couch_config:get("httpd", "authentication_handlers", "")), AuthHandlers = lists:map( fun(A) -> {make_arity_1_fun(A), ?l2b(A)} end, AuthenticationSrcs), ok = application:set_env(couch, auth_handlers, AuthHandlers). % SpecStr is a string like "{my_module, my_fun}" % or "{my_module, my_fun, <<"my_arg">>}" make_arity_1_fun(SpecStr) -> case couch_util:parse_term(SpecStr) of {ok, {Mod, Fun, SpecArg}} -> fun(Arg) -> Mod:Fun(Arg, SpecArg) end; {ok, {Mod, Fun}} -> fun(Arg) -> Mod:Fun(Arg) end end. make_arity_2_fun(SpecStr) -> case couch_util:parse_term(SpecStr) of {ok, {Mod, Fun, SpecArg}} -> fun(Arg1, Arg2) -> Mod:Fun(Arg1, Arg2, SpecArg) end; {ok, {Mod, Fun}} -> fun(Arg1, Arg2) -> Mod:Fun(Arg1, Arg2) end end. make_arity_3_fun(SpecStr) -> case couch_util:parse_term(SpecStr) of {ok, {Mod, Fun, SpecArg}} -> fun(Arg1, Arg2, Arg3) -> Mod:Fun(Arg1, Arg2, Arg3, SpecArg) end; {ok, {Mod, Fun}} -> fun(Arg1, Arg2, Arg3) -> Mod:Fun(Arg1, Arg2, Arg3) end end. % SpecStr is "{my_module, my_fun}, {my_module2, my_fun2}" make_fun_spec_strs(SpecStr) -> re:split(SpecStr, "(?<=})\\s*,\\s*(?={)", [{return, list}]). handle_request(MochiReq, DefaultFun, UrlHandlers, DbUrlHandlers, DesignUrlHandlers) -> %% reset rewrite count for new request erlang:put(?REWRITE_COUNT, 0), MochiReq1 = couch_httpd_vhost:dispatch_host(MochiReq), handle_request_int(MochiReq1, DefaultFun, UrlHandlers, DbUrlHandlers, DesignUrlHandlers). handle_request_int(MochiReq, DefaultFun, UrlHandlers, DbUrlHandlers, DesignUrlHandlers) -> Begin = now(), % for the path, use the raw path with the query string and fragment % removed, but URL quoting left intact RawUri = MochiReq:get(raw_path), {"/" ++ Path, _, _} = mochiweb_util:urlsplit_path(RawUri), Headers = MochiReq:get(headers), % get requested path RequestedPath = case MochiReq:get_header_value("x-couchdb-vhost-path") of undefined -> case MochiReq:get_header_value("x-couchdb-requested-path") of undefined -> RawUri; R -> R end; P -> P end, HandlerKey = case mochiweb_util:partition(Path, "/") of {"", "", ""} -> <<"/">>; % Special case the root url handler {FirstPart, _, _} -> list_to_binary(FirstPart) end, ?LOG_DEBUG("~p ~s ~p from ~p~nHeaders: ~p", [ MochiReq:get(method), RawUri, MochiReq:get(version), MochiReq:get(peer), mochiweb_headers:to_list(MochiReq:get(headers)) ]), Method1 = case MochiReq:get(method) of % already an atom Meth when is_atom(Meth) -> Meth; % Non standard HTTP verbs aren't atoms (COPY, MOVE etc) so convert when % possible (if any module references the atom, then it's existing). Meth -> couch_util:to_existing_atom(Meth) end, increment_method_stats(Method1), % allow broken HTTP clients to fake a full method vocabulary with an X-HTTP-METHOD-OVERRIDE header MethodOverride = MochiReq:get_primary_header_value("X-HTTP-Method-Override"), Method2 = case lists:member(MethodOverride, ["GET", "HEAD", "POST", "PUT", "DELETE", "TRACE", "CONNECT", "COPY"]) of true -> ?LOG_INFO("MethodOverride: ~s (real method was ~s)", [MethodOverride, Method1]), case Method1 of 'POST' -> couch_util:to_existing_atom(MethodOverride); _ -> % Ignore X-HTTP-Method-Override when the original verb isn't POST. % I'd like to send a 406 error to the client, but that'd require a nasty refactor. % throw({not_acceptable, <<"X-HTTP-Method-Override may only be used with POST requests.">>}) Method1 end; _ -> Method1 end, % alias HEAD to GET as mochiweb takes care of stripping the body Method = case Method2 of 'HEAD' -> 'GET'; Other -> Other end, HttpReq = #httpd{ mochi_req = MochiReq, peer = MochiReq:get(peer), method = Method, requested_path_parts = [?l2b(unquote(Part)) || Part <- string:tokens(RequestedPath, "/")], path_parts = [?l2b(unquote(Part)) || Part <- string:tokens(Path, "/")], db_url_handlers = DbUrlHandlers, design_url_handlers = DesignUrlHandlers, default_fun = DefaultFun, url_handlers = UrlHandlers, user_ctx = erlang:erase(pre_rewrite_user_ctx), auth = erlang:erase(pre_rewrite_auth) }, HandlerFun = couch_util:dict_find(HandlerKey, UrlHandlers, DefaultFun), {ok, AuthHandlers} = application:get_env(couch, auth_handlers), {ok, Resp} = try case couch_httpd_cors:is_preflight_request(HttpReq) of #httpd{} -> case authenticate_request(HttpReq, AuthHandlers) of #httpd{} = Req -> HandlerFun(Req); Response -> Response end; Response -> Response end catch throw:{http_head_abort, Resp0} -> {ok, Resp0}; throw:{invalid_json, S} -> ?LOG_ERROR("attempted upload of invalid JSON (set log_level to debug to log it)", []), ?LOG_DEBUG("Invalid JSON: ~p",[S]), send_error(HttpReq, {bad_request, invalid_json}); throw:unacceptable_encoding -> ?LOG_ERROR("unsupported encoding method for the response", []), send_error(HttpReq, {not_acceptable, "unsupported encoding"}); throw:bad_accept_encoding_value -> ?LOG_ERROR("received invalid Accept-Encoding header", []), send_error(HttpReq, bad_request); exit:normal -> exit(normal); exit:snappy_nif_not_loaded -> ErrorReason = "To access the database or view index, Apache CouchDB" " must be built with Erlang OTP R13B04 or higher.", ?LOG_ERROR("~s", [ErrorReason]), send_error(HttpReq, {bad_otp_release, ErrorReason}); exit:{body_too_large, _} -> send_error(HttpReq, request_entity_too_large); throw:Error -> Stack = erlang:get_stacktrace(), ?LOG_DEBUG("Minor error in HTTP request: ~p",[Error]), ?LOG_DEBUG("Stacktrace: ~p",[Stack]), send_error(HttpReq, Error); error:badarg -> Stack = erlang:get_stacktrace(), ?LOG_ERROR("Badarg error in HTTP request",[]), ?LOG_INFO("Stacktrace: ~p",[Stack]), send_error(HttpReq, badarg); error:function_clause -> Stack = erlang:get_stacktrace(), ?LOG_ERROR("function_clause error in HTTP request",[]), ?LOG_INFO("Stacktrace: ~p",[Stack]), send_error(HttpReq, function_clause); Tag:Error -> Stack = erlang:get_stacktrace(), ?LOG_ERROR("Uncaught error in HTTP request: ~p",[{Tag, Error}]), ?LOG_INFO("Stacktrace: ~p",[Stack]), send_error(HttpReq, Error) end, RequestTime = round(timer:now_diff(now(), Begin)/1000), couch_stats_collector:record({couchdb, request_time}, RequestTime), couch_stats_collector:increment({httpd, requests}), {ok, Resp}. % Try authentication handlers in order until one sets a user_ctx % the auth funs also have the option of returning a response % move this to couch_httpd_auth? authenticate_request(#httpd{user_ctx=#user_ctx{}} = Req, _AuthHandlers) -> Req; authenticate_request(#httpd{} = Req, []) -> case couch_config:get("couch_httpd_auth", "require_valid_user", "false") of "true" -> throw({unauthorized, <<"Authentication required.">>}); "false" -> Req#httpd{user_ctx=#user_ctx{}} end; authenticate_request(#httpd{} = Req, [{AuthFun, AuthSrc} | RestAuthHandlers]) -> R = case AuthFun(Req) of #httpd{user_ctx=#user_ctx{}=UserCtx}=Req2 -> Req2#httpd{user_ctx=UserCtx#user_ctx{handler=AuthSrc}}; Else -> Else end, authenticate_request(R, RestAuthHandlers); authenticate_request(Response, _AuthSrcs) -> Response. increment_method_stats(Method) -> couch_stats_collector:increment({httpd_request_methods, Method}). validate_referer(Req) -> Host = host_for_request(Req), Referer = header_value(Req, "Referer", fail), case Referer of fail -> throw({bad_request, <<"Referer header required.">>}); Referer -> {_,RefererHost,_,_,_} = mochiweb_util:urlsplit(Referer), if RefererHost =:= Host -> ok; true -> throw({bad_request, <<"Referer header must match host.">>}) end end. validate_ctype(Req, Ctype) -> case header_value(Req, "Content-Type") of undefined -> throw({bad_ctype, "Content-Type must be "++Ctype}); ReqCtype -> case string:tokens(ReqCtype, ";") of [Ctype] -> ok; [Ctype, _Rest] -> ok; _Else -> throw({bad_ctype, "Content-Type must be "++Ctype}) end end. % Utilities partition(Path) -> mochiweb_util:partition(Path, "/"). header_value(#httpd{mochi_req=MochiReq}, Key) -> MochiReq:get_header_value(Key). header_value(#httpd{mochi_req=MochiReq}, Key, Default) -> case MochiReq:get_header_value(Key) of undefined -> Default; Value -> Value end. primary_header_value(#httpd{mochi_req=MochiReq}, Key) -> MochiReq:get_primary_header_value(Key). accepted_encodings(#httpd{mochi_req=MochiReq}) -> case MochiReq:accepted_encodings(["gzip", "identity"]) of bad_accept_encoding_value -> throw(bad_accept_encoding_value); [] -> throw(unacceptable_encoding); EncList -> EncList end. serve_file(Req, RelativePath, DocumentRoot) -> serve_file(Req, RelativePath, DocumentRoot, []). serve_file(#httpd{mochi_req=MochiReq}=Req, RelativePath, DocumentRoot, ExtraHeaders) -> log_request(Req, 200), ResponseHeaders = server_header() ++ couch_httpd_auth:cookie_auth_header(Req, []) ++ ExtraHeaders, {ok, MochiReq:serve_file(RelativePath, DocumentRoot, couch_httpd_cors:cors_headers(Req, ResponseHeaders))}. qs_value(Req, Key) -> qs_value(Req, Key, undefined). qs_value(Req, Key, Default) -> couch_util:get_value(Key, qs(Req), Default). qs_json_value(Req, Key, Default) -> case qs_value(Req, Key, Default) of Default -> Default; Result -> ?JSON_DECODE(Result) end. qs(#httpd{mochi_req=MochiReq}) -> MochiReq:parse_qs(). path(#httpd{mochi_req=MochiReq}) -> MochiReq:get(path). host_for_request(#httpd{mochi_req=MochiReq}) -> XHost = couch_config:get("httpd", "x_forwarded_host", "X-Forwarded-Host"), case MochiReq:get_header_value(XHost) of undefined -> case MochiReq:get_header_value("Host") of undefined -> {ok, {Address, Port}} = case MochiReq:get(socket) of {ssl, SslSocket} -> ssl:sockname(SslSocket); Socket -> inet:sockname(Socket) end, inet_parse:ntoa(Address) ++ ":" ++ integer_to_list(Port); Value1 -> Value1 end; Value -> Value end. absolute_uri(#httpd{mochi_req=MochiReq}=Req, Path) -> Host = host_for_request(Req), XSsl = couch_config:get("httpd", "x_forwarded_ssl", "X-Forwarded-Ssl"), Scheme = case MochiReq:get_header_value(XSsl) of "on" -> "https"; _ -> XProto = couch_config:get("httpd", "x_forwarded_proto", "X-Forwarded-Proto"), case MochiReq:get_header_value(XProto) of %% Restrict to "https" and "http" schemes only "https" -> "https"; _ -> case MochiReq:get(scheme) of https -> "https"; http -> "http" end end end, Scheme ++ "://" ++ Host ++ Path. unquote(UrlEncodedString) -> mochiweb_util:unquote(UrlEncodedString). quote(UrlDecodedString) -> mochiweb_util:quote_plus(UrlDecodedString). parse_form(#httpd{mochi_req=MochiReq}) -> mochiweb_multipart:parse_form(MochiReq). recv(#httpd{mochi_req=MochiReq}, Len) -> MochiReq:recv(Len). recv_chunked(#httpd{mochi_req=MochiReq}, MaxChunkSize, ChunkFun, InitState) -> % Fun is called once with each chunk % Fun({Length, Binary}, State) % called with Length == 0 on the last time. MochiReq:stream_body(MaxChunkSize, ChunkFun, InitState). body_length(#httpd{mochi_req=MochiReq}) -> MochiReq:get(body_length). body(#httpd{mochi_req=MochiReq, req_body=undefined}) -> MaxSize = list_to_integer( couch_config:get("couchdb", "max_document_size", "4294967296")), MochiReq:recv_body(MaxSize); body(#httpd{req_body=ReqBody}) -> ReqBody. json_body(Httpd) -> ?JSON_DECODE(body(Httpd)). json_body_obj(Httpd) -> case json_body(Httpd) of {Props} -> {Props}; _Else -> throw({bad_request, "Request body must be a JSON object"}) end. doc_etag(#doc{revs={Start, [DiskRev|_]}}) -> "\"" ++ ?b2l(couch_doc:rev_to_str({Start, DiskRev})) ++ "\"". make_etag(Term) -> <> = couch_util:md5(term_to_binary(Term)), iolist_to_binary([$", io_lib:format("~.36B", [SigInt]), $"]). etag_match(Req, CurrentEtag) when is_binary(CurrentEtag) -> etag_match(Req, binary_to_list(CurrentEtag)); etag_match(Req, CurrentEtag) -> EtagsToMatch = string:tokens( header_value(Req, "If-None-Match", ""), ", "), lists:member(CurrentEtag, EtagsToMatch). etag_respond(Req, CurrentEtag, RespFun) -> case etag_match(Req, CurrentEtag) of true -> % the client has this in their cache. send_response(Req, 304, [{"ETag", CurrentEtag}], <<>>); false -> % Run the function. RespFun() end. etag_maybe(Req, RespFun) -> try RespFun() catch throw:{etag_match, ETag} -> send_response(Req, 304, [{"ETag", ETag}], <<>>) end. verify_is_server_admin(#httpd{user_ctx=UserCtx}) -> verify_is_server_admin(UserCtx); verify_is_server_admin(#user_ctx{roles=Roles}) -> case lists:member(<<"_admin">>, Roles) of true -> ok; false -> throw({unauthorized, <<"You are not a server admin.">>}) end. log_request(#httpd{mochi_req=MochiReq,peer=Peer}=Req, Code) -> ?LOG_INFO("~s - - ~s ~s ~B", [ Peer, MochiReq:get(method), MochiReq:get(raw_path), Code ]), gen_event:notify(couch_plugin, {log_request, Req, Code}). start_response_length(#httpd{mochi_req=MochiReq}=Req, Code, Headers, Length) -> log_request(Req, Code), couch_stats_collector:increment({httpd_status_codes, Code}), Headers1 = Headers ++ server_header() ++ couch_httpd_auth:cookie_auth_header(Req, Headers), Headers2 = couch_httpd_cors:cors_headers(Req, Headers1), Resp = MochiReq:start_response_length({Code, Headers2, Length}), case MochiReq:get(method) of 'HEAD' -> throw({http_head_abort, Resp}); _ -> ok end, {ok, Resp}. start_response(#httpd{mochi_req=MochiReq}=Req, Code, Headers) -> log_request(Req, Code), couch_stats_collector:increment({httpd_status_codes, Code}), CookieHeader = couch_httpd_auth:cookie_auth_header(Req, Headers), Headers1 = Headers ++ server_header() ++ CookieHeader, Headers2 = couch_httpd_cors:cors_headers(Req, Headers1), Resp = MochiReq:start_response({Code, Headers2}), case MochiReq:get(method) of 'HEAD' -> throw({http_head_abort, Resp}); _ -> ok end, {ok, Resp}. send(Resp, Data) -> Resp:send(Data), {ok, Resp}. no_resp_conn_header([]) -> true; no_resp_conn_header([{Hdr, _}|Rest]) -> case string:to_lower(Hdr) of "connection" -> false; _ -> no_resp_conn_header(Rest) end. http_1_0_keep_alive(Req, Headers) -> KeepOpen = Req:should_close() == false, IsHttp10 = Req:get(version) == {1, 0}, NoRespHeader = no_resp_conn_header(Headers), case KeepOpen andalso IsHttp10 andalso NoRespHeader of true -> [{"Connection", "Keep-Alive"} | Headers]; false -> Headers end. start_chunked_response(#httpd{mochi_req=MochiReq}=Req, Code, Headers) -> log_request(Req, Code), couch_stats_collector:increment({httpd_status_codes, Code}), Headers1 = http_1_0_keep_alive(MochiReq, Headers), Headers2 = Headers1 ++ server_header() ++ couch_httpd_auth:cookie_auth_header(Req, Headers1), Headers3 = couch_httpd_cors:cors_headers(Req, Headers2), Resp = MochiReq:respond({Code, Headers3, chunked}), case MochiReq:get(method) of 'HEAD' -> throw({http_head_abort, Resp}); _ -> ok end, {ok, Resp}. send_chunk(Resp, Data) -> case iolist_size(Data) of 0 -> ok; % do nothing _ -> Resp:write_chunk(Data) end, {ok, Resp}. last_chunk(Resp) -> Resp:write_chunk([]), {ok, Resp}. send_response(#httpd{mochi_req=MochiReq}=Req, Code, Headers, Body) -> log_request(Req, Code), couch_stats_collector:increment({httpd_status_codes, Code}), Headers1 = http_1_0_keep_alive(MochiReq, Headers), if Code >= 500 -> ?LOG_ERROR("httpd ~p error response:~n ~s", [Code, Body]); Code >= 400 -> ?LOG_DEBUG("httpd ~p error response:~n ~s", [Code, Body]); true -> ok end, Headers2 = Headers1 ++ server_header() ++ couch_httpd_auth:cookie_auth_header(Req, Headers1), Headers3 = couch_httpd_cors:cors_headers(Req, Headers2), {ok, MochiReq:respond({Code, Headers3, Body})}. send_method_not_allowed(Req, Methods) -> send_error(Req, 405, [{"Allow", Methods}], <<"method_not_allowed">>, ?l2b("Only " ++ Methods ++ " allowed")). send_json(Req, Value) -> send_json(Req, 200, Value). send_json(Req, Code, Value) -> send_json(Req, Code, [], Value). send_json(Req, Code, Headers, Value) -> initialize_jsonp(Req), DefaultHeaders = [ {"Content-Type", negotiate_content_type(Req)}, {"Cache-Control", "must-revalidate"} ], Body = [start_jsonp(), ?JSON_ENCODE(Value), end_jsonp(), $\n], send_response(Req, Code, DefaultHeaders ++ Headers, Body). start_json_response(Req, Code) -> start_json_response(Req, Code, []). start_json_response(Req, Code, Headers) -> initialize_jsonp(Req), DefaultHeaders = [ {"Content-Type", negotiate_content_type(Req)}, {"Cache-Control", "must-revalidate"} ], {ok, Resp} = start_chunked_response(Req, Code, DefaultHeaders ++ Headers), case start_jsonp() of [] -> ok; Start -> send_chunk(Resp, Start) end, {ok, Resp}. end_json_response(Resp) -> send_chunk(Resp, end_jsonp() ++ [$\n]), last_chunk(Resp). initialize_jsonp(Req) -> case get(jsonp) of undefined -> put(jsonp, qs_value(Req, "callback", no_jsonp)); _ -> ok end, case get(jsonp) of no_jsonp -> []; [] -> []; CallBack -> try % make sure jsonp is configured on (default off) case couch_config:get("httpd", "allow_jsonp", "false") of "true" -> validate_callback(CallBack); _Else -> put(jsonp, no_jsonp) end catch Error -> put(jsonp, no_jsonp), throw(Error) end end. start_jsonp() -> case get(jsonp) of no_jsonp -> []; [] -> []; CallBack -> ["/* CouchDB */", CallBack, "("] end. end_jsonp() -> case erlang:erase(jsonp) of no_jsonp -> []; [] -> []; _ -> ");" end. validate_callback(CallBack) when is_binary(CallBack) -> validate_callback(binary_to_list(CallBack)); validate_callback([]) -> ok; validate_callback([Char | Rest]) -> case Char of _ when Char >= $a andalso Char =< $z -> ok; _ when Char >= $A andalso Char =< $Z -> ok; _ when Char >= $0 andalso Char =< $9 -> ok; _ when Char == $. -> ok; _ when Char == $_ -> ok; _ when Char == $[ -> ok; _ when Char == $] -> ok; _ -> throw({bad_request, invalid_callback}) end, validate_callback(Rest). error_info({Error, Reason}) when is_list(Reason) -> error_info({Error, ?l2b(Reason)}); error_info(bad_request) -> {400, <<"bad_request">>, <<>>}; error_info({bad_request, Reason}) -> {400, <<"bad_request">>, Reason}; error_info({query_parse_error, Reason}) -> {400, <<"query_parse_error">>, Reason}; % Prior art for md5 mismatch resulting in a 400 is from AWS S3 error_info(md5_mismatch) -> {400, <<"content_md5_mismatch">>, <<"Possible message corruption.">>}; error_info(not_found) -> {404, <<"not_found">>, <<"missing">>}; error_info({not_found, Reason}) -> {404, <<"not_found">>, Reason}; error_info({not_acceptable, Reason}) -> {406, <<"not_acceptable">>, Reason}; error_info(conflict) -> {409, <<"conflict">>, <<"Document update conflict.">>}; error_info({forbidden, Msg}) -> {403, <<"forbidden">>, Msg}; error_info({unauthorized, Msg}) -> {401, <<"unauthorized">>, Msg}; error_info(file_exists) -> {412, <<"file_exists">>, <<"The database could not be " "created, the file already exists.">>}; error_info(request_entity_too_large) -> {413, <<"too_large">>, <<"the request entity is too large">>}; error_info({bad_ctype, Reason}) -> {415, <<"bad_content_type">>, Reason}; error_info(requested_range_not_satisfiable) -> {416, <<"requested_range_not_satisfiable">>, <<"Requested range not satisfiable">>}; error_info({error, illegal_database_name, Name}) -> Message = "Name: '" ++ Name ++ "'. Only lowercase characters (a-z), " ++ "digits (0-9), and any of the characters _, $, (, ), +, -, and / " ++ "are allowed. Must begin with a letter.", {400, <<"illegal_database_name">>, couch_util:to_binary(Message)}; error_info({missing_stub, Reason}) -> {412, <<"missing_stub">>, Reason}; error_info({Error, Reason}) -> {500, couch_util:to_binary(Error), couch_util:to_binary(Reason)}; error_info(Error) -> {500, <<"unknown_error">>, couch_util:to_binary(Error)}. error_headers(#httpd{mochi_req=MochiReq}=Req, Code, ErrorStr, ReasonStr) -> if Code == 401 -> % this is where the basic auth popup is triggered case MochiReq:get_header_value("X-CouchDB-WWW-Authenticate") of undefined -> case couch_config:get("httpd", "WWW-Authenticate", nil) of nil -> % If the client is a browser and the basic auth popup isn't turned on % redirect to the session page. case ErrorStr of <<"unauthorized">> -> case couch_config:get("couch_httpd_auth", "authentication_redirect", nil) of nil -> {Code, []}; AuthRedirect -> case couch_config:get("couch_httpd_auth", "require_valid_user", "false") of "true" -> % send the browser popup header no matter what if we are require_valid_user {Code, [{"WWW-Authenticate", "Basic realm=\"server\""}]}; _False -> case MochiReq:accepts_content_type("application/json") of true -> {Code, []}; false -> case MochiReq:accepts_content_type("text/html") of true -> % Redirect to the path the user requested, not % the one that is used internally. UrlReturnRaw = case MochiReq:get_header_value("x-couchdb-vhost-path") of undefined -> MochiReq:get(path); VHostPath -> VHostPath end, RedirectLocation = lists:flatten([ AuthRedirect, "?return=", couch_util:url_encode(UrlReturnRaw), "&reason=", couch_util:url_encode(ReasonStr) ]), {302, [{"Location", absolute_uri(Req, RedirectLocation)}]}; false -> {Code, []} end end end end; _Else -> {Code, []} end; Type -> {Code, [{"WWW-Authenticate", Type}]} end; Type -> {Code, [{"WWW-Authenticate", Type}]} end; true -> {Code, []} end. send_error(_Req, {already_sent, Resp, _Error}) -> {ok, Resp}; send_error(Req, Error) -> {Code, ErrorStr, ReasonStr} = error_info(Error), {Code1, Headers} = error_headers(Req, Code, ErrorStr, ReasonStr), send_error(Req, Code1, Headers, ErrorStr, ReasonStr). send_error(Req, Code, ErrorStr, ReasonStr) -> send_error(Req, Code, [], ErrorStr, ReasonStr). send_error(Req, Code, Headers, ErrorStr, ReasonStr) -> send_json(Req, Code, Headers, {[{<<"error">>, ErrorStr}, {<<"reason">>, ReasonStr}]}). % give the option for list functions to output html or other raw errors send_chunked_error(Resp, {_Error, {[{<<"body">>, Reason}]}}) -> send_chunk(Resp, Reason), last_chunk(Resp); send_chunked_error(Resp, Error) -> {Code, ErrorStr, ReasonStr} = error_info(Error), JsonError = {[{<<"code">>, Code}, {<<"error">>, ErrorStr}, {<<"reason">>, ReasonStr}]}, send_chunk(Resp, ?l2b([$\n,?JSON_ENCODE(JsonError),$\n])), last_chunk(Resp). send_redirect(Req, Path) -> send_response(Req, 301, [{"Location", absolute_uri(Req, Path)}], <<>>). negotiate_content_type(Req) -> case get(jsonp) of no_jsonp -> negotiate_content_type1(Req); [] -> negotiate_content_type1(Req); _Callback -> "text/javascript" end. negotiate_content_type1(#httpd{mochi_req=MochiReq}) -> %% Determine the appropriate Content-Type header for a JSON response %% depending on the Accept header in the request. A request that explicitly %% lists the correct JSON MIME type will get that type, otherwise the %% response will have the generic MIME type "text/plain" AcceptedTypes = case MochiReq:get_header_value("Accept") of undefined -> []; AcceptHeader -> string:tokens(AcceptHeader, ", ") end, case lists:member("application/json", AcceptedTypes) of true -> "application/json"; false -> "text/plain; charset=utf-8" end. server_header() -> [{"Server", "CouchDB/" ++ couch_server:get_version() ++ " (Erlang OTP/" ++ erlang:system_info(otp_release) ++ ")"}]. -record(mp, {boundary, buffer, data_fun, callback}). parse_multipart_request(ContentType, DataFun, Callback) -> Boundary0 = iolist_to_binary(get_boundary(ContentType)), Boundary = <<"\r\n--", Boundary0/binary>>, Mp = #mp{boundary= Boundary, buffer= <<>>, data_fun=DataFun, callback=Callback}, {Mp2, _NilCallback} = read_until(Mp, <<"--", Boundary0/binary>>, fun nil_callback/1), #mp{buffer=Buffer, data_fun=DataFun2, callback=Callback2} = parse_part_header(Mp2), {Buffer, DataFun2, Callback2}. nil_callback(_Data)-> fun nil_callback/1. get_boundary({"multipart/" ++ _, Opts}) -> case couch_util:get_value("boundary", Opts) of S when is_list(S) -> S end; get_boundary(ContentType) -> {"multipart/" ++ _ , Opts} = mochiweb_util:parse_header(ContentType), get_boundary({"multipart/", Opts}). split_header(<<>>) -> []; split_header(Line) -> {Name, [$: | Value]} = lists:splitwith(fun (C) -> C =/= $: end, binary_to_list(Line)), [{string:to_lower(string:strip(Name)), mochiweb_util:parse_header(Value)}]. read_until(#mp{data_fun=DataFun, buffer=Buffer}=Mp, Pattern, Callback) -> case find_in_binary(Pattern, Buffer) of not_found -> Callback2 = Callback(Buffer), {Buffer2, DataFun2} = DataFun(), Buffer3 = iolist_to_binary(Buffer2), read_until(Mp#mp{data_fun=DataFun2,buffer=Buffer3}, Pattern, Callback2); {partial, 0} -> {NewData, DataFun2} = DataFun(), read_until(Mp#mp{data_fun=DataFun2, buffer= iolist_to_binary([Buffer,NewData])}, Pattern, Callback); {partial, Skip} -> <> = Buffer, Callback2 = Callback(DataChunk), {NewData, DataFun2} = DataFun(), read_until(Mp#mp{data_fun=DataFun2, buffer= iolist_to_binary([Rest | NewData])}, Pattern, Callback2); {exact, 0} -> PatternLen = size(Pattern), <<_:PatternLen/binary, Rest/binary>> = Buffer, {Mp#mp{buffer= Rest}, Callback}; {exact, Skip} -> PatternLen = size(Pattern), <> = Buffer, Callback2 = Callback(DataChunk), {Mp#mp{buffer= Rest}, Callback2} end. parse_part_header(#mp{callback=UserCallBack}=Mp) -> {Mp2, AccCallback} = read_until(Mp, <<"\r\n\r\n">>, fun(Next) -> acc_callback(Next, []) end), HeaderData = AccCallback(get_data), Headers = lists:foldl(fun(Line, Acc) -> split_header(Line) ++ Acc end, [], re:split(HeaderData,<<"\r\n">>, [])), NextCallback = UserCallBack({headers, Headers}), parse_part_body(Mp2#mp{callback=NextCallback}). parse_part_body(#mp{boundary=Prefix, callback=Callback}=Mp) -> {Mp2, WrappedCallback} = read_until(Mp, Prefix, fun(Data) -> body_callback_wrapper(Data, Callback) end), Callback2 = WrappedCallback(get_callback), Callback3 = Callback2(body_end), case check_for_last(Mp2#mp{callback=Callback3}) of {last, #mp{callback=Callback3}=Mp3} -> Mp3#mp{callback=Callback3(eof)}; {more, Mp3} -> parse_part_header(Mp3) end. acc_callback(get_data, Acc)-> iolist_to_binary(lists:reverse(Acc)); acc_callback(Data, Acc)-> fun(Next) -> acc_callback(Next, [Data | Acc]) end. body_callback_wrapper(get_callback, Callback) -> Callback; body_callback_wrapper(Data, Callback) -> Callback2 = Callback({body, Data}), fun(Next) -> body_callback_wrapper(Next, Callback2) end. check_for_last(#mp{buffer=Buffer, data_fun=DataFun}=Mp) -> case Buffer of <<"--",_/binary>> -> {last, Mp}; <<_, _, _/binary>> -> {more, Mp}; _ -> % not long enough {Data, DataFun2} = DataFun(), check_for_last(Mp#mp{buffer= <>, data_fun = DataFun2}) end. find_in_binary(_B, <<>>) -> not_found; find_in_binary(B, Data) -> case binary:match(Data, [B], []) of nomatch -> partial_find(binary:part(B, {0, byte_size(B) - 1}), binary:part(Data, {byte_size(Data), -byte_size(Data) + 1}), 1); {Pos, _Len} -> {exact, Pos} end. partial_find(<<>>, _Data, _Pos) -> not_found; partial_find(B, Data, N) when byte_size(Data) > 0 -> case binary:match(Data, [B], []) of nomatch -> partial_find(binary:part(B, {0, byte_size(B) - 1}), binary:part(Data, {byte_size(Data), -byte_size(Data) + 1}), N + 1); {Pos, _Len} -> {partial, N + Pos} end; partial_find(_B, _Data, _N) -> not_found. validate_bind_address(Address) -> case inet_parse:address(Address) of {ok, _} -> ok; _ -> throw({error, invalid_bind_address}) end. apache-couchdb-1.5.0/src/couchdb/couch_drv.erl0000644000175000001440000000320112230722213016124 00000000000000% 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. -module(couch_drv). -behaviour(gen_server). -export([init/1, handle_call/3, handle_cast/2, handle_info/2, terminate/2, code_change/3]). -export([start_link/0]). -include("couch_db.hrl"). start_link() -> gen_server:start_link({local, ?MODULE}, ?MODULE, [], []). init([]) -> LibDir = util_driver_dir(), case erl_ddll:load(LibDir, "couch_icu_driver") of ok -> {ok, nil}; {error, already_loaded} -> ?LOG_INFO("~p reloading couch_icu_driver", [?MODULE]), ok = erl_ddll:reload(LibDir, "couch_icu_driver"), {ok, nil}; {error, Error} -> {stop, erl_ddll:format_error(Error)} end. handle_call(_Request, _From, State) -> {reply, ok, State}. handle_cast(_Request, State) -> {noreply, State}. handle_info(_Info, State) -> {noreply, State}. terminate(_Reason, _State) -> ok. code_change(_OldVsn, State, _Extra) -> {ok, State}. % private API util_driver_dir() -> case couch_config:get("couchdb", "util_driver_dir", null) of null -> filename:join(couch_util:priv_dir(), "lib"); LibDir0 -> LibDir0 end. apache-couchdb-1.5.0/src/couchdb/couch_httpd_external.erl0000644000175000001440000001472712230722213020375 00000000000000% 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. -module(couch_httpd_external). -export([handle_external_req/2, handle_external_req/3]). -export([send_external_response/2, json_req_obj/2, json_req_obj/3]). -export([default_or_content_type/2, parse_external_response/1]). -import(couch_httpd,[send_error/4]). -include("couch_db.hrl"). % handle_external_req/2 % for the old type of config usage: % _external = {couch_httpd_external, handle_external_req} % with urls like % /db/_external/action/design/name handle_external_req(#httpd{ path_parts=[_DbName, _External, UrlName | _Path] }=HttpReq, Db) -> process_external_req(HttpReq, Db, UrlName); handle_external_req(#httpd{path_parts=[_, _]}=Req, _Db) -> send_error(Req, 404, <<"external_server_error">>, <<"No server name specified.">>); handle_external_req(Req, _) -> send_error(Req, 404, <<"external_server_error">>, <<"Broken assumption">>). % handle_external_req/3 % for this type of config usage: % _action = {couch_httpd_external, handle_external_req, <<"action">>} % with urls like % /db/_action/design/name handle_external_req(HttpReq, Db, Name) -> process_external_req(HttpReq, Db, Name). process_external_req(HttpReq, Db, Name) -> Response = couch_external_manager:execute(binary_to_list(Name), json_req_obj(HttpReq, Db)), case Response of {unknown_external_server, Msg} -> send_error(HttpReq, 404, <<"external_server_error">>, Msg); _ -> send_external_response(HttpReq, Response) end. json_req_obj(Req, Db) -> json_req_obj(Req, Db, null). json_req_obj(#httpd{mochi_req=Req, method=Method, requested_path_parts=RequestedPath, path_parts=Path, req_body=ReqBody }, Db, DocId) -> Body = case ReqBody of undefined -> MaxSize = list_to_integer( couch_config:get("couchdb", "max_document_size", "4294967296")), Req:recv_body(MaxSize); Else -> Else end, ParsedForm = case Req:get_primary_header_value("content-type") of "application/x-www-form-urlencoded" ++ _ -> case Body of undefined -> []; _ -> mochiweb_util:parse_qs(Body) end; _ -> [] end, Headers = Req:get(headers), Hlist = mochiweb_headers:to_list(Headers), {ok, Info} = couch_db:get_db_info(Db), % add headers... {[{<<"info">>, {Info}}, {<<"id">>, DocId}, {<<"uuid">>, couch_uuids:new()}, {<<"method">>, Method}, {<<"requested_path">>, RequestedPath}, {<<"path">>, Path}, {<<"raw_path">>, ?l2b(Req:get(raw_path))}, {<<"query">>, json_query_keys(to_json_terms(Req:parse_qs()))}, {<<"headers">>, to_json_terms(Hlist)}, {<<"body">>, Body}, {<<"peer">>, ?l2b(Req:get(peer))}, {<<"form">>, to_json_terms(ParsedForm)}, {<<"cookie">>, to_json_terms(Req:parse_cookie())}, {<<"userCtx">>, couch_util:json_user_ctx(Db)}, {<<"secObj">>, couch_db:get_security(Db)}]}. to_json_terms(Data) -> to_json_terms(Data, []). to_json_terms([], Acc) -> {lists:reverse(Acc)}; to_json_terms([{Key, Value} | Rest], Acc) when is_atom(Key) -> to_json_terms(Rest, [{list_to_binary(atom_to_list(Key)), list_to_binary(Value)} | Acc]); to_json_terms([{Key, Value} | Rest], Acc) -> to_json_terms(Rest, [{list_to_binary(Key), list_to_binary(Value)} | Acc]). json_query_keys({Json}) -> json_query_keys(Json, []). json_query_keys([], Acc) -> {lists:reverse(Acc)}; json_query_keys([{<<"startkey">>, Value} | Rest], Acc) -> json_query_keys(Rest, [{<<"startkey">>, ?JSON_DECODE(Value)}|Acc]); json_query_keys([{<<"endkey">>, Value} | Rest], Acc) -> json_query_keys(Rest, [{<<"endkey">>, ?JSON_DECODE(Value)}|Acc]); json_query_keys([{<<"key">>, Value} | Rest], Acc) -> json_query_keys(Rest, [{<<"key">>, ?JSON_DECODE(Value)}|Acc]); json_query_keys([Term | Rest], Acc) -> json_query_keys(Rest, [Term|Acc]). send_external_response(Req, Response) -> #extern_resp_args{ code = Code, data = Data, ctype = CType, headers = Headers, json = Json } = parse_external_response(Response), Headers1 = default_or_content_type(CType, Headers), case Json of nil -> couch_httpd:send_response(Req, Code, Headers1, Data); Json -> couch_httpd:send_json(Req, Code, Headers1, Json) end. parse_external_response({Response}) -> lists:foldl(fun({Key,Value}, Args) -> case {Key, Value} of {"", _} -> Args; {<<"code">>, Value} -> Args#extern_resp_args{code=Value}; {<<"stop">>, true} -> Args#extern_resp_args{stop=true}; {<<"json">>, Value} -> Args#extern_resp_args{ json=Value, ctype="application/json"}; {<<"body">>, Value} -> Args#extern_resp_args{data=Value, ctype="text/html; charset=utf-8"}; {<<"base64">>, Value} -> Args#extern_resp_args{ data=base64:decode(Value), ctype="application/binary" }; {<<"headers">>, {Headers}} -> NewHeaders = lists:map(fun({Header, HVal}) -> {binary_to_list(Header), binary_to_list(HVal)} end, Headers), Args#extern_resp_args{headers=NewHeaders}; _ -> % unknown key Msg = lists:flatten(io_lib:format("Invalid data from external server: ~p", [{Key, Value}])), throw({external_response_error, Msg}) end end, #extern_resp_args{}, Response). default_or_content_type(DefaultContentType, Headers) -> IsContentType = fun({X, _}) -> string:to_lower(X) == "content-type" end, case lists:any(IsContentType, Headers) of false -> [{"Content-Type", DefaultContentType} | Headers]; true -> Headers end. apache-couchdb-1.5.0/src/couchdb/couch_config.erl0000644000175000001440000002075712230722213016615 00000000000000% 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. % Reads CouchDB's ini file and gets queried for configuration parameters. % This module is initialized with a list of ini files that it consecutively % reads Key/Value pairs from and saves them in an ets table. If more than one % ini file is specified, the last one is used to write changes that are made % with store/2 back to that ini file. -module(couch_config). -behaviour(gen_server). -include("couch_db.hrl"). -export([start_link/1, stop/0]). -export([all/0, get/1, get/2, get/3, set/3, set/4, delete/2, delete/3]). -export([register/1, register/2]). -export([parse_ini_file/1]). -export([init/1, terminate/2, code_change/3]). -export([handle_call/3, handle_cast/2, handle_info/2]). -record(config, { notify_funs=[], write_filename=undefined }). start_link(IniFiles) -> gen_server:start_link({local, ?MODULE}, ?MODULE, IniFiles, []). stop() -> gen_server:cast(?MODULE, stop). all() -> lists:sort(gen_server:call(?MODULE, all, infinity)). get(Section) when is_binary(Section) -> ?MODULE:get(?b2l(Section)); get(Section) -> Matches = ets:match(?MODULE, {{Section, '$1'}, '$2'}), [{Key, Value} || [Key, Value] <- Matches]. get(Section, Key) -> ?MODULE:get(Section, Key, undefined). get(Section, Key, Default) when is_binary(Section) and is_binary(Key) -> ?MODULE:get(?b2l(Section), ?b2l(Key), Default); get(Section, Key, Default) -> case ets:lookup(?MODULE, {Section, Key}) of [] -> Default; [{_, Match}] -> Match end. set(Section, Key, Value) -> ?MODULE:set(Section, Key, Value, true). set(Section, Key, Value, Persist) when is_binary(Section) and is_binary(Key) -> ?MODULE:set(?b2l(Section), ?b2l(Key), Value, Persist); set(Section, Key, Value, Persist) -> gen_server:call(?MODULE, {set, Section, Key, Value, Persist}). delete(Section, Key) when is_binary(Section) and is_binary(Key) -> delete(?b2l(Section), ?b2l(Key)); delete(Section, Key) -> delete(Section, Key, true). delete(Section, Key, Persist) when is_binary(Section) and is_binary(Key) -> delete(?b2l(Section), ?b2l(Key), Persist); delete(Section, Key, Persist) -> gen_server:call(?MODULE, {delete, Section, Key, Persist}). register(Fun) -> ?MODULE:register(Fun, self()). register(Fun, Pid) -> gen_server:call(?MODULE, {register, Fun, Pid}). init(IniFiles) -> ets:new(?MODULE, [named_table, set, protected]), try lists:foreach(fun(IniFile) -> {ok, ParsedIniValues} = parse_ini_file(IniFile), ets:insert(?MODULE, ParsedIniValues) end, IniFiles), WriteFile = case IniFiles of [_|_] -> lists:last(IniFiles); _ -> undefined end, {ok, #config{write_filename = WriteFile}} catch _Tag:Error -> {stop, Error} end. terminate(_Reason, _State) -> ok. handle_call(all, _From, Config) -> Resp = lists:sort((ets:tab2list(?MODULE))), {reply, Resp, Config}; handle_call({set, Sec, Key, Val, Persist}, From, Config) -> Result = case {Persist, Config#config.write_filename} of {true, undefined} -> ok; {true, FileName} -> couch_config_writer:save_to_file({{Sec, Key}, Val}, FileName); _ -> ok end, case Result of ok -> true = ets:insert(?MODULE, {{Sec, Key}, Val}), spawn_link(fun() -> [catch F(Sec, Key, Val, Persist) || {_Pid, F} <- Config#config.notify_funs], gen_server:reply(From, ok) end), {noreply, Config}; _Error -> {reply, Result, Config} end; handle_call({delete, Sec, Key, Persist}, From, Config) -> true = ets:delete(?MODULE, {Sec,Key}), case {Persist, Config#config.write_filename} of {true, undefined} -> ok; {true, FileName} -> couch_config_writer:save_to_file({{Sec, Key}, ""}, FileName); _ -> ok end, spawn_link(fun() -> [catch F(Sec, Key, deleted, Persist) || {_Pid, F} <- Config#config.notify_funs], gen_server:reply(From, ok) end), {noreply, Config}; handle_call({register, Fun, Pid}, _From, #config{notify_funs=PidFuns}=Config) -> erlang:monitor(process, Pid), % convert 1 and 2 arity to 3 arity Fun2 = case Fun of _ when is_function(Fun, 1) -> fun(Section, _Key, _Value, _Persist) -> Fun(Section) end; _ when is_function(Fun, 2) -> fun(Section, Key, _Value, _Persist) -> Fun(Section, Key) end; _ when is_function(Fun, 3) -> fun(Section, Key, Value, _Persist) -> Fun(Section, Key, Value) end; _ when is_function(Fun, 4) -> Fun end, {reply, ok, Config#config{notify_funs=[{Pid, Fun2} | PidFuns]}}. handle_cast(stop, State) -> {stop, normal, State}; handle_cast(_Msg, State) -> {noreply, State}. handle_info({'DOWN', _, _, DownPid, _}, #config{notify_funs=PidFuns}=Config) -> % remove any funs registered by the downed process FilteredPidFuns = [{Pid,Fun} || {Pid,Fun} <- PidFuns, Pid /= DownPid], {noreply, Config#config{notify_funs=FilteredPidFuns}}. code_change(_OldVsn, State, _Extra) -> {ok, State}. parse_ini_file(IniFile) -> IniFilename = couch_util:abs_pathname(IniFile), IniBin = case file:read_file(IniFilename) of {ok, IniBin0} -> IniBin0; {error, Reason} = Error -> ?LOG_ERROR("Could not read server configuration file ~s: ~s", [IniFilename, file:format_error(Reason)]), throw(Error) end, Lines = re:split(IniBin, "\r\n|\n|\r|\032", [{return, list}]), {_, ParsedIniValues} = lists:foldl(fun(Line, {AccSectionName, AccValues}) -> case string:strip(Line) of "[" ++ Rest -> case re:split(Rest, "\\]", [{return, list}]) of [NewSectionName, ""] -> {NewSectionName, AccValues}; _Else -> % end bracket not at end, ignore this line {AccSectionName, AccValues} end; ";" ++ _Comment -> {AccSectionName, AccValues}; Line2 -> case re:split(Line2, "\s*=\s*", [{return, list}]) of [Value] -> MultiLineValuePart = case re:run(Line, "^ \\S", []) of {match, _} -> true; _ -> false end, case {MultiLineValuePart, AccValues} of {true, [{{_, ValueName}, PrevValue} | AccValuesRest]} -> % remove comment case re:split(Value, " ;|\t;", [{return, list}]) of [[]] -> % empty line {AccSectionName, AccValues}; [LineValue | _Rest] -> E = {{AccSectionName, ValueName}, PrevValue ++ " " ++ LineValue}, {AccSectionName, [E | AccValuesRest]} end; _ -> {AccSectionName, AccValues} end; [""|_LineValues] -> % line begins with "=", ignore {AccSectionName, AccValues}; [ValueName|LineValues] -> % yeehaw, got a line! RemainingLine = couch_util:implode(LineValues, "="), % removes comments case re:split(RemainingLine, " ;|\t;", [{return, list}]) of [[]] -> % empty line means delete this key ets:delete(?MODULE, {AccSectionName, ValueName}), {AccSectionName, AccValues}; [LineValue | _Rest] -> {AccSectionName, [{{AccSectionName, ValueName}, LineValue} | AccValues]} end end end end, {"", []}, Lines), {ok, ParsedIniValues}. apache-couchdb-1.5.0/src/couchdb/couch_changes.erl0000644000175000001440000004562412230722213016760 00000000000000% 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. -module(couch_changes). -include("couch_db.hrl"). -export([handle_changes/3]). % For the builtin filter _docs_ids, this is the maximum number % of documents for which we trigger the optimized code path. -define(MAX_DOC_IDS, 100). -record(changes_acc, { db, seq, prepend, filter, callback, user_acc, resp_type, limit, include_docs, conflicts, timeout, timeout_fun }). %% @type Req -> #httpd{} | {json_req, JsonObj()} handle_changes(Args1, Req, Db0) -> #changes_args{ style = Style, filter = FilterName, feed = Feed, dir = Dir, since = Since } = Args1, {FilterFun, FilterArgs} = make_filter_fun(FilterName, Style, Req, Db0), Args = Args1#changes_args{filter_fun = FilterFun, filter_args = FilterArgs}, Start = fun() -> {ok, Db} = couch_db:reopen(Db0), StartSeq = case Dir of rev -> couch_db:get_update_seq(Db); fwd -> Since end, {Db, StartSeq} end, % begin timer to deal with heartbeat when filter function fails case Args#changes_args.heartbeat of undefined -> erlang:erase(last_changes_heartbeat); Val when is_integer(Val); Val =:= true -> put(last_changes_heartbeat, now()) end, case lists:member(Feed, ["continuous", "longpoll", "eventsource"]) of true -> fun(CallbackAcc) -> {Callback, UserAcc} = get_callback_acc(CallbackAcc), Self = self(), {ok, Notify} = couch_db_update_notifier:start_link( fun({_, DbName}) when Db0#db.name == DbName -> Self ! db_updated; (_) -> ok end ), {Db, StartSeq} = Start(), UserAcc2 = start_sending_changes(Callback, UserAcc, Feed), {Timeout, TimeoutFun} = get_changes_timeout(Args, Callback), Acc0 = build_acc(Args, Callback, UserAcc2, Db, StartSeq, <<"">>, Timeout, TimeoutFun), try keep_sending_changes( Args#changes_args{dir=fwd}, Acc0, true) after couch_db_update_notifier:stop(Notify), get_rest_db_updated(ok) % clean out any remaining update messages end end; false -> fun(CallbackAcc) -> {Callback, UserAcc} = get_callback_acc(CallbackAcc), UserAcc2 = start_sending_changes(Callback, UserAcc, Feed), {Timeout, TimeoutFun} = get_changes_timeout(Args, Callback), {Db, StartSeq} = Start(), Acc0 = build_acc(Args#changes_args{feed="normal"}, Callback, UserAcc2, Db, StartSeq, <<>>, Timeout, TimeoutFun), {ok, #changes_acc{seq = LastSeq, user_acc = UserAcc3}} = send_changes( Args#changes_args{feed="normal"}, Acc0, true), end_sending_changes(Callback, UserAcc3, LastSeq, Feed) end end. get_callback_acc({Callback, _UserAcc} = Pair) when is_function(Callback, 3) -> Pair; get_callback_acc(Callback) when is_function(Callback, 2) -> {fun(Ev, Data, _) -> Callback(Ev, Data) end, ok}. %% @type Req -> #httpd{} | {json_req, JsonObj()} make_filter_fun([$_ | _] = FilterName, Style, Req, Db) -> builtin_filter_fun(FilterName, Style, Req, Db); make_filter_fun(FilterName, Style, Req, Db) -> {os_filter_fun(FilterName, Style, Req, Db), []}. os_filter_fun(FilterName, Style, Req, Db) -> case [list_to_binary(couch_httpd:unquote(Part)) || Part <- string:tokens(FilterName, "/")] of [] -> fun(_Db2, #doc_info{revs=Revs}) -> builtin_results(Style, Revs) end; [DName, FName] -> DesignId = <<"_design/", DName/binary>>, DDoc = couch_httpd_db:couch_doc_open(Db, DesignId, nil, [ejson_body]), % validate that the ddoc has the filter fun #doc{body={Props}} = DDoc, couch_util:get_nested_json_value({Props}, [<<"filters">>, FName]), fun(Db2, DocInfo) -> DocInfos = case Style of main_only -> [DocInfo]; all_docs -> [DocInfo#doc_info{revs=[Rev]}|| Rev <- DocInfo#doc_info.revs] end, Docs = [Doc || {ok, Doc} <- [ couch_db:open_doc(Db2, DocInfo2, [deleted, conflicts]) || DocInfo2 <- DocInfos]], {ok, Passes} = couch_query_servers:filter_docs( Req, Db2, DDoc, FName, Docs ), [{[{<<"rev">>, couch_doc:rev_to_str({RevPos,RevId})}]} || {Pass, #doc{revs={RevPos,[RevId|_]}}} <- lists:zip(Passes, Docs), Pass == true] end; _Else -> throw({bad_request, "filter parameter must be of the form `designname/filtername`"}) end. builtin_filter_fun("_doc_ids", Style, {json_req, {Props}}, _Db) -> DocIds = couch_util:get_value(<<"doc_ids">>, Props), {filter_docids(DocIds, Style), DocIds}; builtin_filter_fun("_doc_ids", Style, #httpd{method='POST'}=Req, _Db) -> {Props} = couch_httpd:json_body_obj(Req), DocIds = couch_util:get_value(<<"doc_ids">>, Props, nil), {filter_docids(DocIds, Style), DocIds}; builtin_filter_fun("_doc_ids", Style, #httpd{method='GET'}=Req, _Db) -> DocIds = ?JSON_DECODE(couch_httpd:qs_value(Req, "doc_ids", "null")), {filter_docids(DocIds, Style), DocIds}; builtin_filter_fun("_design", Style, _Req, _Db) -> {filter_designdoc(Style), []}; builtin_filter_fun("_view", Style, Req, Db) -> ViewName = couch_httpd:qs_value(Req, "view", ""), {filter_view(ViewName, Style, Db), []}; builtin_filter_fun(_FilterName, _Style, _Req, _Db) -> throw({bad_request, "unknown builtin filter name"}). filter_docids(DocIds, Style) when is_list(DocIds)-> fun(_Db, #doc_info{id=DocId, revs=Revs}) -> case lists:member(DocId, DocIds) of true -> builtin_results(Style, Revs); _ -> [] end end; filter_docids(_, _) -> throw({bad_request, "`doc_ids` filter parameter is not a list."}). filter_designdoc(Style) -> fun(_Db, #doc_info{id=DocId, revs=Revs}) -> case DocId of <<"_design", _/binary>> -> builtin_results(Style, Revs); _ -> [] end end. filter_view("", _Style, _Db) -> throw({bad_request, "`view` filter parameter is not provided."}); filter_view(ViewName, Style, Db) -> case [list_to_binary(couch_httpd:unquote(Part)) || Part <- string:tokens(ViewName, "/")] of [] -> throw({bad_request, "Invalid `view` parameter."}); [DName, VName] -> DesignId = <<"_design/", DName/binary>>, DDoc = couch_httpd_db:couch_doc_open(Db, DesignId, nil, [ejson_body]), % validate that the ddoc has the filter fun #doc{body={Props}} = DDoc, couch_util:get_nested_json_value({Props}, [<<"views">>, VName]), fun(Db2, DocInfo) -> DocInfos = case Style of main_only -> [DocInfo]; all_docs -> [DocInfo#doc_info{revs=[Rev]}|| Rev <- DocInfo#doc_info.revs] end, Docs = [Doc || {ok, Doc} <- [ couch_db:open_doc(Db2, DocInfo2, [deleted, conflicts]) || DocInfo2 <- DocInfos]], {ok, Passes} = couch_query_servers:filter_view( DDoc, VName, Docs ), [{[{<<"rev">>, couch_doc:rev_to_str({RevPos,RevId})}]} || {Pass, #doc{revs={RevPos,[RevId|_]}}} <- lists:zip(Passes, Docs), Pass == true] end end. builtin_results(Style, [#rev_info{rev=Rev}|_]=Revs) -> case Style of main_only -> [{[{<<"rev">>, couch_doc:rev_to_str(Rev)}]}]; all_docs -> [{[{<<"rev">>, couch_doc:rev_to_str(R)}]} || #rev_info{rev=R} <- Revs] end. get_changes_timeout(Args, Callback) -> #changes_args{ heartbeat = Heartbeat, timeout = Timeout, feed = ResponseType } = Args, DefaultTimeout = list_to_integer( couch_config:get("httpd", "changes_timeout", "60000") ), case Heartbeat of undefined -> case Timeout of undefined -> {DefaultTimeout, fun(UserAcc) -> {stop, UserAcc} end}; infinity -> {infinity, fun(UserAcc) -> {stop, UserAcc} end}; _ -> {lists:min([DefaultTimeout, Timeout]), fun(UserAcc) -> {stop, UserAcc} end} end; true -> {DefaultTimeout, fun(UserAcc) -> {ok, Callback(timeout, ResponseType, UserAcc)} end}; _ -> {lists:min([DefaultTimeout, Heartbeat]), fun(UserAcc) -> {ok, Callback(timeout, ResponseType, UserAcc)} end} end. start_sending_changes(_Callback, UserAcc, ResponseType) when ResponseType =:= "continuous" orelse ResponseType =:= "eventsource" -> UserAcc; start_sending_changes(Callback, UserAcc, ResponseType) -> Callback(start, ResponseType, UserAcc). build_acc(Args, Callback, UserAcc, Db, StartSeq, Prepend, Timeout, TimeoutFun) -> #changes_args{ include_docs = IncludeDocs, conflicts = Conflicts, limit = Limit, feed = ResponseType, filter_fun = FilterFun } = Args, #changes_acc{ db = Db, seq = StartSeq, prepend = Prepend, filter = FilterFun, callback = Callback, user_acc = UserAcc, resp_type = ResponseType, limit = Limit, include_docs = IncludeDocs, conflicts = Conflicts, timeout = Timeout, timeout_fun = TimeoutFun }. send_changes(Args, Acc0, FirstRound) -> #changes_args{ dir = Dir, filter = FilterName, filter_args = FilterArgs } = Args, #changes_acc{ db = Db, seq = StartSeq } = Acc0, case FirstRound of true -> case FilterName of "_doc_ids" when length(FilterArgs) =< ?MAX_DOC_IDS -> send_changes_doc_ids( FilterArgs, Db, StartSeq, Dir, fun changes_enumerator/2, Acc0); "_design" -> send_changes_design_docs( Db, StartSeq, Dir, fun changes_enumerator/2, Acc0); _ -> couch_db:changes_since( Db, StartSeq, fun changes_enumerator/2, [{dir, Dir}], Acc0) end; false -> couch_db:changes_since( Db, StartSeq, fun changes_enumerator/2, [{dir, Dir}], Acc0) end. send_changes_doc_ids(DocIds, Db, StartSeq, Dir, Fun, Acc0) -> Lookups = couch_btree:lookup(Db#db.fulldocinfo_by_id_btree, DocIds), FullDocInfos = lists:foldl( fun({ok, FDI}, Acc) -> [FDI | Acc]; (not_found, Acc) -> Acc end, [], Lookups), send_lookup_changes(FullDocInfos, StartSeq, Dir, Db, Fun, Acc0). send_changes_design_docs(Db, StartSeq, Dir, Fun, Acc0) -> FoldFun = fun(FullDocInfo, _, Acc) -> {ok, [FullDocInfo | Acc]} end, KeyOpts = [{start_key, <<"_design/">>}, {end_key_gt, <<"_design0">>}], {ok, _, FullDocInfos} = couch_btree:fold( Db#db.fulldocinfo_by_id_btree, FoldFun, [], KeyOpts), send_lookup_changes(FullDocInfos, StartSeq, Dir, Db, Fun, Acc0). send_lookup_changes(FullDocInfos, StartSeq, Dir, Db, Fun, Acc0) -> FoldFun = case Dir of fwd -> fun lists:foldl/3; rev -> fun lists:foldr/3 end, GreaterFun = case Dir of fwd -> fun(A, B) -> A > B end; rev -> fun(A, B) -> A =< B end end, DocInfos = lists:foldl( fun(FDI, Acc) -> DI = couch_doc:to_doc_info(FDI), case GreaterFun(DI#doc_info.high_seq, StartSeq) of true -> [DI | Acc]; false -> Acc end end, [], FullDocInfos), SortedDocInfos = lists:keysort(#doc_info.high_seq, DocInfos), FinalAcc = try FoldFun( fun(DocInfo, Acc) -> case Fun(DocInfo, Acc) of {ok, NewAcc} -> NewAcc; {stop, NewAcc} -> throw({stop, NewAcc}) end end, Acc0, SortedDocInfos) catch throw:{stop, Acc} -> Acc end, case Dir of fwd -> {ok, FinalAcc#changes_acc{seq = couch_db:get_update_seq(Db)}}; rev -> {ok, FinalAcc} end. keep_sending_changes(Args, Acc0, FirstRound) -> #changes_args{ feed = ResponseType, limit = Limit, db_open_options = DbOptions } = Args, {ok, ChangesAcc} = send_changes( Args#changes_args{dir=fwd}, Acc0, FirstRound), #changes_acc{ db = Db, callback = Callback, timeout = Timeout, timeout_fun = TimeoutFun, seq = EndSeq, prepend = Prepend2, user_acc = UserAcc2, limit = NewLimit } = ChangesAcc, couch_db:close(Db), if Limit > NewLimit, ResponseType == "longpoll" -> end_sending_changes(Callback, UserAcc2, EndSeq, ResponseType); true -> case wait_db_updated(Timeout, TimeoutFun, UserAcc2) of {updated, UserAcc4} -> DbOptions1 = [{user_ctx, Db#db.user_ctx} | DbOptions], case couch_db:open(Db#db.name, DbOptions1) of {ok, Db2} -> keep_sending_changes( Args#changes_args{limit=NewLimit}, ChangesAcc#changes_acc{ db = Db2, user_acc = UserAcc4, seq = EndSeq, prepend = Prepend2, timeout = Timeout, timeout_fun = TimeoutFun}, false); _Else -> end_sending_changes(Callback, UserAcc2, EndSeq, ResponseType) end; {stop, UserAcc4} -> end_sending_changes(Callback, UserAcc4, EndSeq, ResponseType) end end. end_sending_changes(Callback, UserAcc, EndSeq, ResponseType) -> Callback({stop, EndSeq}, ResponseType, UserAcc). changes_enumerator(DocInfo, #changes_acc{resp_type = ResponseType} = Acc) when ResponseType =:= "continuous" orelse ResponseType =:= "eventsource" -> #changes_acc{ filter = FilterFun, callback = Callback, user_acc = UserAcc, limit = Limit, db = Db, timeout = Timeout, timeout_fun = TimeoutFun } = Acc, #doc_info{high_seq = Seq} = DocInfo, Results0 = FilterFun(Db, DocInfo), Results = [Result || Result <- Results0, Result /= null], %% TODO: I'm thinking this should be < 1 and not =< 1 Go = if Limit =< 1 -> stop; true -> ok end, case Results of [] -> {Done, UserAcc2} = maybe_heartbeat(Timeout, TimeoutFun, UserAcc), case Done of stop -> {stop, Acc#changes_acc{seq = Seq, user_acc = UserAcc2}}; ok -> {Go, Acc#changes_acc{seq = Seq, user_acc = UserAcc2}} end; _ -> ChangesRow = changes_row(Results, DocInfo, Acc), UserAcc2 = Callback({change, ChangesRow, <<>>}, ResponseType, UserAcc), reset_heartbeat(), {Go, Acc#changes_acc{seq = Seq, user_acc = UserAcc2, limit = Limit - 1}} end; changes_enumerator(DocInfo, Acc) -> #changes_acc{ filter = FilterFun, callback = Callback, prepend = Prepend, user_acc = UserAcc, limit = Limit, resp_type = ResponseType, db = Db, timeout = Timeout, timeout_fun = TimeoutFun } = Acc, #doc_info{high_seq = Seq} = DocInfo, Results0 = FilterFun(Db, DocInfo), Results = [Result || Result <- Results0, Result /= null], Go = if (Limit =< 1) andalso Results =/= [] -> stop; true -> ok end, case Results of [] -> {Done, UserAcc2} = maybe_heartbeat(Timeout, TimeoutFun, UserAcc), case Done of stop -> {stop, Acc#changes_acc{seq = Seq, user_acc = UserAcc2}}; ok -> {Go, Acc#changes_acc{seq = Seq, user_acc = UserAcc2}} end; _ -> ChangesRow = changes_row(Results, DocInfo, Acc), UserAcc2 = Callback({change, ChangesRow, Prepend}, ResponseType, UserAcc), reset_heartbeat(), {Go, Acc#changes_acc{ seq = Seq, prepend = <<",\n">>, user_acc = UserAcc2, limit = Limit - 1}} end. changes_row(Results, DocInfo, Acc) -> #doc_info{ id = Id, high_seq = Seq, revs = [#rev_info{deleted = Del} | _] } = DocInfo, #changes_acc{db = Db, include_docs = IncDoc, conflicts = Conflicts} = Acc, {[{<<"seq">>, Seq}, {<<"id">>, Id}, {<<"changes">>, Results}] ++ deleted_item(Del) ++ case IncDoc of true -> Opts = case Conflicts of true -> [deleted, conflicts]; false -> [deleted] end, Doc = couch_index_util:load_doc(Db, DocInfo, Opts), case Doc of null -> [{doc, null}]; _ -> [{doc, couch_doc:to_json_obj(Doc, [])}] end; false -> [] end}. deleted_item(true) -> [{<<"deleted">>, true}]; deleted_item(_) -> []. % waits for a db_updated msg, if there are multiple msgs, collects them. wait_db_updated(Timeout, TimeoutFun, UserAcc) -> receive db_updated -> get_rest_db_updated(UserAcc) after Timeout -> {Go, UserAcc2} = TimeoutFun(UserAcc), case Go of ok -> wait_db_updated(Timeout, TimeoutFun, UserAcc2); stop -> {stop, UserAcc2} end end. get_rest_db_updated(UserAcc) -> receive db_updated -> get_rest_db_updated(UserAcc) after 0 -> {updated, UserAcc} end. reset_heartbeat() -> case get(last_changes_heartbeat) of undefined -> ok; _ -> put(last_changes_heartbeat, now()) end. maybe_heartbeat(Timeout, TimeoutFun, Acc) -> Before = get(last_changes_heartbeat), case Before of undefined -> {ok, Acc}; _ -> Now = now(), case timer:now_diff(Now, Before) div 1000 >= Timeout of true -> Acc2 = TimeoutFun(Acc), put(last_changes_heartbeat, Now), Acc2; false -> {ok, Acc} end end. apache-couchdb-1.5.0/src/couchdb/couch_os_process.erl0000644000175000001440000001605512230722213017523 00000000000000% 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. -module(couch_os_process). -behaviour(gen_server). -export([start_link/1, start_link/2, start_link/3, stop/1]). -export([set_timeout/2, prompt/2]). -export([send/2, writeline/2, readline/1, writejson/2, readjson/1]). -export([init/1, terminate/2, handle_call/3, handle_cast/2, handle_info/2, code_change/3]). -include("couch_db.hrl"). -define(PORT_OPTIONS, [stream, {line, 4096}, binary, exit_status, hide]). -record(os_proc, {command, port, writer, reader, timeout=5000 }). start_link(Command) -> start_link(Command, []). start_link(Command, Options) -> start_link(Command, Options, ?PORT_OPTIONS). start_link(Command, Options, PortOptions) -> gen_server:start_link(couch_os_process, [Command, Options, PortOptions], []). stop(Pid) -> gen_server:cast(Pid, stop). % Read/Write API set_timeout(Pid, TimeOut) when is_integer(TimeOut) -> ok = gen_server:call(Pid, {set_timeout, TimeOut}, infinity). % Used by couch_db_update_notifier.erl send(Pid, Data) -> gen_server:cast(Pid, {send, Data}). prompt(Pid, Data) -> case gen_server:call(Pid, {prompt, Data}, infinity) of {ok, Result} -> Result; Error -> ?LOG_ERROR("OS Process Error ~p :: ~p",[Pid,Error]), throw(Error) end. % Utility functions for reading and writing % in custom functions writeline(OsProc, Data) when is_record(OsProc, os_proc) -> port_command(OsProc#os_proc.port, [Data, $\n]). readline(#os_proc{} = OsProc) -> readline(OsProc, []). readline(#os_proc{port = Port} = OsProc, Acc) -> receive {Port, {data, {noeol, Data}}} when is_binary(Acc) -> readline(OsProc, <>); {Port, {data, {noeol, Data}}} when is_binary(Data) -> readline(OsProc, Data); {Port, {data, {noeol, Data}}} -> readline(OsProc, [Data|Acc]); {Port, {data, {eol, <>}}} when is_binary(Acc) -> [<>]; {Port, {data, {eol, Data}}} when is_binary(Data) -> [Data]; {Port, {data, {eol, Data}}} -> lists:reverse(Acc, Data); {Port, Err} -> catch port_close(Port), throw({os_process_error, Err}) after OsProc#os_proc.timeout -> catch port_close(Port), throw({os_process_error, "OS process timed out."}) end. % Standard JSON functions writejson(OsProc, Data) when is_record(OsProc, os_proc) -> JsonData = ?JSON_ENCODE(Data), ?LOG_DEBUG("OS Process ~p Input :: ~s", [OsProc#os_proc.port, JsonData]), true = writeline(OsProc, JsonData). readjson(OsProc) when is_record(OsProc, os_proc) -> Line = iolist_to_binary(readline(OsProc)), ?LOG_DEBUG("OS Process ~p Output :: ~s", [OsProc#os_proc.port, Line]), try % Don't actually parse the whole JSON. Just try to see if it's % a command or a doc map/reduce/filter/show/list/update output. % If it's a command then parse the whole JSON and execute the % command, otherwise return the raw JSON line to the caller. pick_command(Line) catch throw:abort -> {json, Line}; throw:{cmd, _Cmd} -> case ?JSON_DECODE(Line) of [<<"log">>, Msg] when is_binary(Msg) -> % we got a message to log. Log it and continue ?LOG_INFO("OS Process ~p Log :: ~s", [OsProc#os_proc.port, Msg]), readjson(OsProc); [<<"error">>, Id, Reason] -> throw({error, {couch_util:to_existing_atom(Id),Reason}}); [<<"fatal">>, Id, Reason] -> ?LOG_INFO("OS Process ~p Fatal Error :: ~s ~p", [OsProc#os_proc.port, Id, Reason]), throw({couch_util:to_existing_atom(Id),Reason}); _Result -> {json, Line} end end. pick_command(Line) -> json_stream_parse:events(Line, fun pick_command0/1). pick_command0(array_start) -> fun pick_command1/1; pick_command0(_) -> throw(abort). pick_command1(<<"log">> = Cmd) -> throw({cmd, Cmd}); pick_command1(<<"error">> = Cmd) -> throw({cmd, Cmd}); pick_command1(<<"fatal">> = Cmd) -> throw({cmd, Cmd}); pick_command1(_) -> throw(abort). % gen_server API init([Command, Options, PortOptions]) -> PrivDir = couch_util:priv_dir(), Spawnkiller = filename:join(PrivDir, "couchspawnkillable"), BaseProc = #os_proc{ command=Command, port=open_port({spawn, Spawnkiller ++ " " ++ Command}, PortOptions), writer=fun writejson/2, reader=fun readjson/1 }, KillCmd = iolist_to_binary(readline(BaseProc)), Pid = self(), ?LOG_DEBUG("OS Process Start :: ~p", [BaseProc#os_proc.port]), spawn(fun() -> % this ensure the real os process is killed when this process dies. erlang:monitor(process, Pid), receive _ -> ok end, os:cmd(?b2l(iolist_to_binary(KillCmd))) end), OsProc = lists:foldl(fun(Opt, Proc) -> case Opt of {writer, Writer} when is_function(Writer) -> Proc#os_proc{writer=Writer}; {reader, Reader} when is_function(Reader) -> Proc#os_proc{reader=Reader}; {timeout, TimeOut} when is_integer(TimeOut) -> Proc#os_proc{timeout=TimeOut} end end, BaseProc, Options), {ok, OsProc}. terminate(_Reason, #os_proc{port=Port}) -> catch port_close(Port), ok. handle_call({set_timeout, TimeOut}, _From, OsProc) -> {reply, ok, OsProc#os_proc{timeout=TimeOut}}; handle_call({prompt, Data}, _From, OsProc) -> #os_proc{writer=Writer, reader=Reader} = OsProc, try Writer(OsProc, Data), {reply, {ok, Reader(OsProc)}, OsProc} catch throw:{error, OsError} -> {reply, OsError, OsProc}; throw:OtherError -> {stop, normal, OtherError, OsProc} end. handle_cast({send, Data}, #os_proc{writer=Writer}=OsProc) -> try Writer(OsProc, Data), {noreply, OsProc} catch throw:OsError -> ?LOG_ERROR("Failed sending data: ~p -> ~p", [Data, OsError]), {stop, normal, OsProc} end; handle_cast(stop, OsProc) -> {stop, normal, OsProc}; handle_cast(Msg, OsProc) -> ?LOG_DEBUG("OS Proc: Unknown cast: ~p", [Msg]), {noreply, OsProc}. handle_info({Port, {exit_status, 0}}, #os_proc{port=Port}=OsProc) -> ?LOG_INFO("OS Process terminated normally", []), {stop, normal, OsProc}; handle_info({Port, {exit_status, Status}}, #os_proc{port=Port}=OsProc) -> ?LOG_ERROR("OS Process died with status: ~p", [Status]), {stop, {exit_status, Status}, OsProc}. code_change(_OldVsn, State, _Extra) -> {ok, State}. apache-couchdb-1.5.0/src/couchdb/couch_httpd_cors.erl0000644000175000001440000002710512230722213017513 00000000000000% 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. %% @doc module to handle Cross-Origin Resource Sharing %% %% This module handles CORS requests and preflight request for %% CouchDB. The configuration is done in the ini file. %% %% This implements http://www.w3.org/TR/cors/ -module(couch_httpd_cors). -include("couch_db.hrl"). -export([is_preflight_request/1, cors_headers/2]). -define(SUPPORTED_HEADERS, "Accept, Accept-Language, Content-Type," ++ "Expires, Last-Modified, Pragma, Origin, Content-Length," ++ "If-Match, Destination, X-Requested-With, " ++ "X-Http-Method-Override, Content-Range"). -define(SUPPORTED_METHODS, "GET, HEAD, POST, PUT, DELETE," ++ "TRACE, CONNECT, COPY, OPTIONS"). % as defined in http://www.w3.org/TR/cors/#terminology -define(SIMPLE_HEADERS, ["Cache-Control", "Content-Language", "Content-Type", "Expires", "Last-Modified", "Pragma"]). -define(SIMPLE_CONTENT_TYPE_VALUES, ["application/x-www-form-urlencoded", "multipart/form-data", "text/plain"]). % TODO: - pick a sane default -define(CORS_DEFAULT_MAX_AGE, 12345). %% is_preflight_request/1 % http://www.w3.org/TR/cors/#resource-preflight-requests is_preflight_request(#httpd{method=Method}=Req) when Method /= 'OPTIONS' -> Req; is_preflight_request(Req) -> EnableCors = enable_cors(), is_preflight_request(Req, EnableCors). is_preflight_request(Req, false) -> Req; is_preflight_request(#httpd{mochi_req=MochiReq}=Req, true) -> case preflight_request(MochiReq) of {ok, PreflightHeaders} -> send_preflight_response(Req, PreflightHeaders); _ -> Req end. preflight_request(MochiReq) -> Origin = MochiReq:get_header_value("Origin"), preflight_request(MochiReq, Origin). preflight_request(MochiReq, undefined) -> % If the Origin header is not present terminate this set of % steps. The request is outside the scope of this specification. % http://www.w3.org/TR/cors/#resource-preflight-requests MochiReq; preflight_request(MochiReq, Origin) -> Host = couch_httpd_vhost:host(MochiReq), AcceptedOrigins = get_accepted_origins(Host), AcceptAll = lists:member("*", AcceptedOrigins), HandlerFun = fun() -> OriginList = couch_util:to_list(Origin), handle_preflight_request(OriginList, Host, MochiReq) end, case AcceptAll of true -> % Always matching is acceptable since the list of % origins can be unbounded. % http://www.w3.org/TR/cors/#resource-preflight-requests HandlerFun(); false -> case lists:member(Origin, AcceptedOrigins) of % The Origin header can only contain a single origin as % the user agent will not follow redirects. % http://www.w3.org/TR/cors/#resource-preflight-requests % TODO: Square against multi origin thinger in Security Considerations true -> HandlerFun(); false -> % If the value of the Origin header is not a % case-sensitive match for any of the values % in list of origins do not set any additional % headers and terminate this set of steps. % http://www.w3.org/TR/cors/#resource-preflight-requests false end end. handle_preflight_request(Origin, Host, MochiReq) -> %% get supported methods SupportedMethods = split_list(cors_config(Host, "methods", ?SUPPORTED_METHODS)), % get supported headers AllSupportedHeaders = split_list(cors_config(Host, "headers", ?SUPPORTED_HEADERS)), SupportedHeaders = [string:to_lower(H) || H <- AllSupportedHeaders], % get max age MaxAge = cors_config(Host, "max_age", ?CORS_DEFAULT_MAX_AGE), PreflightHeaders0 = maybe_add_credentials(Origin, Host, [ {"Access-Control-Allow-Origin", Origin}, {"Access-Control-Max-Age", MaxAge}, {"Access-Control-Allow-Methods", string:join(SupportedMethods, ", ")}]), case MochiReq:get_header_value("Access-Control-Request-Method") of undefined -> % If there is no Access-Control-Request-Method header % or if parsing failed, do not set any additional headers % and terminate this set of steps. The request is outside % the scope of this specification. % http://www.w3.org/TR/cors/#resource-preflight-requests {ok, PreflightHeaders0}; Method -> case lists:member(Method, SupportedMethods) of true -> % method ok , check headers AccessHeaders = MochiReq:get_header_value( "Access-Control-Request-Headers"), {FinalReqHeaders, ReqHeaders} = case AccessHeaders of undefined -> {"", []}; Headers -> % transform header list in something we % could check. make sure everything is a % list RH = [string:to_lower(H) || H <- split_headers(Headers)], {Headers, RH} end, % check if headers are supported case ReqHeaders -- SupportedHeaders of [] -> PreflightHeaders = PreflightHeaders0 ++ [{"Access-Control-Allow-Headers", FinalReqHeaders}], {ok, PreflightHeaders}; _ -> false end; false -> % If method is not a case-sensitive match for any of % the values in list of methods do not set any additional % headers and terminate this set of steps. % http://www.w3.org/TR/cors/#resource-preflight-requests false end end. send_preflight_response(#httpd{mochi_req=MochiReq}=Req, Headers) -> couch_httpd:log_request(Req, 204), couch_stats_collector:increment({httpd_status_codes, 204}), Headers1 = couch_httpd:http_1_0_keep_alive(MochiReq, Headers), Headers2 = Headers1 ++ couch_httpd:server_header() ++ couch_httpd_auth:cookie_auth_header(Req, Headers1), {ok, MochiReq:respond({204, Headers2, <<>>})}. % cors_headers/1 cors_headers(MochiReq, RequestHeaders) -> EnableCors = enable_cors(), CorsHeaders = do_cors_headers(MochiReq, EnableCors), maybe_apply_cors_headers(CorsHeaders, RequestHeaders). do_cors_headers(#httpd{mochi_req=MochiReq}, true) -> Host = couch_httpd_vhost:host(MochiReq), AcceptedOrigins = get_accepted_origins(Host), case MochiReq:get_header_value("Origin") of undefined -> % If the Origin header is not present terminate % this set of steps. The request is outside the scope % of this specification. % http://www.w3.org/TR/cors/#resource-processing-model []; Origin -> handle_cors_headers(couch_util:to_list(Origin), Host, AcceptedOrigins) end; do_cors_headers(_MochiReq, false) -> []. maybe_apply_cors_headers([], RequestHeaders) -> RequestHeaders; maybe_apply_cors_headers(CorsHeaders, RequestHeaders0) -> % for each RequestHeader that isn't in SimpleHeaders, % (or Content-Type with SIMPLE_CONTENT_TYPE_VALUES) % append to Access-Control-Expose-Headers % return: RequestHeaders ++ CorsHeaders ++ ACEH RequestHeaders = [K || {K,_V} <- RequestHeaders0], ExposedHeaders0 = reduce_headers(RequestHeaders, ?SIMPLE_HEADERS), % here we may have not moved Content-Type into ExposedHeaders, % now we need to check whether the Content-Type valus is % in ?SIMPLE_CONTENT_TYPE_VALUES and if it isn’t add Content- % Type to to ExposedHeaders ContentType = proplists:get_value("Content-Type", RequestHeaders0), IncludeContentType = case ContentType of undefined -> false; _ -> ContentType_ = string:to_lower(ContentType), lists:member(ContentType_, ?SIMPLE_CONTENT_TYPE_VALUES) end, ExposedHeaders = case IncludeContentType of false -> lists:umerge(ExposedHeaders0, ["Content-Type"]); true -> ExposedHeaders0 end, CorsHeaders ++ RequestHeaders0 ++ [{"Access-Control-Expose-Headers", string:join(ExposedHeaders, ", ")}]. reduce_headers(A, B) -> reduce_headers0(A, B, []). reduce_headers0([], _B, Result) -> Result; reduce_headers0([ElmA|RestA], B, Result) -> R = case member_nocase(ElmA, B) of true -> Result; _Else -> [ElmA | Result] end, reduce_headers0(RestA, B, R). member_nocase(ElmA, List) -> lists:any(fun(ElmB) -> string:to_lower(ElmA) =:= string:to_lower(ElmB) end, List). handle_cors_headers(_Origin, _Host, []) -> []; handle_cors_headers(Origin, Host, AcceptedOrigins) -> AcceptAll = lists:member("*", AcceptedOrigins), case {AcceptAll, lists:member(Origin, AcceptedOrigins)} of {true, _} -> make_cors_header(Origin, Host); {false, true} -> make_cors_header(Origin, Host); _ -> % If the value of the Origin header is not a % case-sensitive match for any of the values % in list of origins, do not set any additional % headers and terminate this set of steps. % http://www.w3.org/TR/cors/#resource-requests [] end. make_cors_header(Origin, Host) -> Headers = [{"Access-Control-Allow-Origin", Origin}], maybe_add_credentials(Origin, Host, Headers). %% util maybe_add_credentials(Origin, Host, Headers) -> maybe_add_credentials(Headers, allow_credentials(Origin, Host)). maybe_add_credentials(Headers, false) -> Headers; maybe_add_credentials(Headers, true) -> Headers ++ [{"Access-Control-Allow-Credentials", "true"}]. allow_credentials("*", _Host) -> false; allow_credentials(_Origin, Host) -> Default = get_bool_config("cors", "credentials", false), get_bool_config(cors_section(Host), "credentials", Default). cors_config(Host, Key, Default) -> couch_config:get(cors_section(Host), Key, couch_config:get("cors", Key, Default)). cors_section(Host0) -> {Host, _Port} = split_host_port(Host0), "cors:" ++ Host. enable_cors() -> get_bool_config("httpd", "enable_cors", false). get_bool_config(Section, Key, Default) -> case couch_config:get(Section, Key) of undefined -> Default; "true" -> true; "false" -> false end. get_accepted_origins(Host) -> split_list(cors_config(Host, "origins", [])). split_list(S) -> re:split(S, "\\s*,\\s*", [trim, {return, list}]). split_headers(H) -> re:split(H, ",\\s*", [{return,list}, trim]). split_host_port(HostAsString) -> % split at semicolon ":" Split = string:rchr(HostAsString, $:), split_host_port(HostAsString, Split). split_host_port(HostAsString, 0) -> % no semicolon {HostAsString, '*'}; split_host_port(HostAsString, N) -> HostPart = string:substr(HostAsString, 1, N-1), % parse out port % is there a nicer way? case (catch erlang:list_to_integer(string:substr(HostAsString, N+1, length(HostAsString)))) of {'EXIT', _} -> {HostAsString, '*'}; Port -> {HostPart, Port} end. apache-couchdb-1.5.0/src/couchdb/couch_task_status.erl0000644000175000001440000001075512230722213017712 00000000000000% 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. -module(couch_task_status). -behaviour(gen_server). % This module is used to track the status of long running tasks. % Long running tasks register themselves, via a call to add_task/1, and then % update their status properties via update/1. The status of a task is a % list of properties. Each property is a tuple, with the first element being % either an atom or a binary and the second element must be an EJSON value. When % a task updates its status, it can override some or all of its properties. % The properties {started_on, UnitTimestamp}, {updated_on, UnixTimestamp} and % {pid, ErlangPid} are automatically added by this module. % When a tracked task dies, its status will be automatically removed from % memory. To get the tasks list, call the all/0 function. -export([start_link/0, stop/0]). -export([all/0, add_task/1, update/1, get/1, set_update_frequency/1]). -export([is_task_added/0]). -export([init/1, terminate/2, code_change/3]). -export([handle_call/3, handle_cast/2, handle_info/2]). -include("couch_db.hrl"). -define(set(L, K, V), lists:keystore(K, 1, L, {K, V})). start_link() -> gen_server:start_link({local, ?MODULE}, ?MODULE, [], []). stop() -> gen_server:cast(?MODULE, stop). all() -> gen_server:call(?MODULE, all). add_task(Props) -> put(task_status_update, {{0, 0, 0}, 0}), Ts = timestamp(), TaskProps = lists:ukeysort( 1, [{started_on, Ts}, {updated_on, Ts} | Props]), put(task_status_props, TaskProps), gen_server:call(?MODULE, {add_task, TaskProps}). is_task_added() -> is_list(erlang:get(task_status_props)). set_update_frequency(Msecs) -> put(task_status_update, {{0, 0, 0}, Msecs * 1000}). update(Props) -> MergeProps = lists:ukeysort(1, Props), TaskProps = lists:ukeymerge(1, MergeProps, erlang:get(task_status_props)), put(task_status_props, TaskProps), maybe_persist(TaskProps). get(Props) when is_list(Props) -> TaskProps = erlang:get(task_status_props), [couch_util:get_value(P, TaskProps) || P <- Props]; get(Prop) -> TaskProps = erlang:get(task_status_props), couch_util:get_value(Prop, TaskProps). maybe_persist(TaskProps0) -> {LastUpdateTime, Frequency} = erlang:get(task_status_update), case timer:now_diff(Now = now(), LastUpdateTime) >= Frequency of true -> put(task_status_update, {Now, Frequency}), TaskProps = ?set(TaskProps0, updated_on, timestamp(Now)), gen_server:cast(?MODULE, {update_status, self(), TaskProps}); false -> ok end. init([]) -> % read configuration settings and register for configuration changes ets:new(?MODULE, [ordered_set, protected, named_table]), {ok, nil}. terminate(_Reason,_State) -> ok. handle_call({add_task, TaskProps}, {From, _}, Server) -> case ets:lookup(?MODULE, From) of [] -> true = ets:insert(?MODULE, {From, TaskProps}), erlang:monitor(process, From), {reply, ok, Server}; [_] -> {reply, {add_task_error, already_registered}, Server} end; handle_call(all, _, Server) -> All = [ [{pid, ?l2b(pid_to_list(Pid))} | TaskProps] || {Pid, TaskProps} <- ets:tab2list(?MODULE) ], {reply, All, Server}. handle_cast({update_status, Pid, NewProps}, Server) -> case ets:lookup(?MODULE, Pid) of [{Pid, _CurProps}] -> ?LOG_DEBUG("New task status for ~p: ~p", [Pid, NewProps]), true = ets:insert(?MODULE, {Pid, NewProps}); _ -> % Task finished/died in the meanwhile and we must have received % a monitor message before this call - ignore. ok end, {noreply, Server}; handle_cast(stop, State) -> {stop, normal, State}. handle_info({'DOWN', _MonitorRef, _Type, Pid, _Info}, Server) -> %% should we also erlang:demonitor(_MonitorRef), ? ets:delete(?MODULE, Pid), {noreply, Server}. code_change(_OldVsn, State, _Extra) -> {ok, State}. timestamp() -> timestamp(now()). timestamp({Mega, Secs, _}) -> Mega * 1000000 + Secs. apache-couchdb-1.5.0/src/couchdb/couch_log.erl0000644000175000001440000001716412230722213016127 00000000000000% 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. -module(couch_log). -behaviour(gen_event). % public API -export([start_link/0, stop/0]). -export([debug/2, info/2, warn/2, error/2]). -export([debug_on/0, info_on/0, warn_on/0, get_level/0, get_level_integer/0, set_level/1]). -export([debug_on/1, info_on/1, warn_on/1, get_level/1, get_level_integer/1, set_level/2]). -export([read/2]). % gen_event callbacks -export([init/1, handle_event/2, terminate/2, code_change/3]). -export([handle_info/2, handle_call/2]). -define(LEVEL_ERROR, 4). -define(LEVEL_WARN, 3). -define(LEVEL_INFO, 2). -define(LEVEL_DEBUG, 1). -record(state, { fd, level, sasl }). debug(Format, Args) -> {ConsoleMsg, FileMsg} = get_log_messages(self(), debug, Format, Args), gen_event:sync_notify(error_logger, {couch_debug, ConsoleMsg, FileMsg}). info(Format, Args) -> {ConsoleMsg, FileMsg} = get_log_messages(self(), info, Format, Args), gen_event:sync_notify(error_logger, {couch_info, ConsoleMsg, FileMsg}). warn(Format, Args) -> {ConsoleMsg, FileMsg} = get_log_messages(self(), warn, Format, Args), gen_event:sync_notify(error_logger, {couch_warn, ConsoleMsg, FileMsg}). error(Format, Args) -> {ConsoleMsg, FileMsg} = get_log_messages(self(), error, Format, Args), gen_event:sync_notify(error_logger, {couch_error, ConsoleMsg, FileMsg}). level_integer(error) -> ?LEVEL_ERROR; level_integer(warn) -> ?LEVEL_WARN; level_integer(info) -> ?LEVEL_INFO; level_integer(debug) -> ?LEVEL_DEBUG; level_integer(_Else) -> ?LEVEL_ERROR. % anything else default to ERROR level level_atom(?LEVEL_ERROR) -> error; level_atom(?LEVEL_WARN) -> warn; level_atom(?LEVEL_INFO) -> info; level_atom(?LEVEL_DEBUG) -> debug. start_link() -> couch_event_sup:start_link({local, couch_log}, error_logger, couch_log, []). stop() -> couch_event_sup:stop(couch_log). init([]) -> % read config and register for configuration changes % just stop if one of the config settings change. couch_server_sup % will restart us and then we will pick up the new settings. ok = couch_config:register( fun("log", "file") -> ?MODULE:stop(); ("log", "level") -> ?MODULE:stop(); ("log", "include_sasl") -> ?MODULE:stop(); ("log_level_by_module", _) -> ?MODULE:stop() end), Filename = couch_config:get("log", "file", "couchdb.log"), Level = level_integer(list_to_atom(couch_config:get("log", "level", "info"))), Sasl = couch_config:get("log", "include_sasl", "true") =:= "true", LevelByModule = couch_config:get("log_level_by_module"), case ets:info(?MODULE) of undefined -> ets:new(?MODULE, [named_table]); _ -> ok end, ets:insert(?MODULE, {level, Level}), lists:foreach(fun({Module, ModuleLevel}) -> ModuleLevelInteger = level_integer(list_to_atom(ModuleLevel)), ets:insert(?MODULE, {Module, ModuleLevelInteger}) end, LevelByModule), case file:open(Filename, [append]) of {ok, Fd} -> {ok, #state{fd = Fd, level = Level, sasl = Sasl}}; {error, Reason} -> ReasonStr = file:format_error(Reason), io:format("Error opening log file ~s: ~s", [Filename, ReasonStr]), {stop, {error, ReasonStr, Filename}} end. debug_on() -> get_level_integer() =< ?LEVEL_DEBUG. info_on() -> get_level_integer() =< ?LEVEL_INFO. warn_on() -> get_level_integer() =< ?LEVEL_WARN. debug_on(Module) -> get_level_integer(Module) =< ?LEVEL_DEBUG. info_on(Module) -> get_level_integer(Module) =< ?LEVEL_INFO. warn_on(Module) -> get_level_integer(Module) =< ?LEVEL_WARN. set_level(LevelAtom) -> set_level_integer(level_integer(LevelAtom)). set_level(Module, LevelAtom) -> set_level_integer(Module, level_integer(LevelAtom)). get_level() -> level_atom(get_level_integer()). get_level(Module) -> level_atom(get_level_integer(Module)). get_level_integer() -> try ets:lookup_element(?MODULE, level, 2) catch error:badarg -> ?LEVEL_ERROR end. get_level_integer(Module0) -> Module = atom_to_list(Module0), try [{_Module, Level}] = ets:lookup(?MODULE, Module), Level catch error:_ -> get_level_integer() end. set_level_integer(Int) -> gen_event:call(error_logger, couch_log, {set_level_integer, Int}). set_level_integer(Module, Int) -> gen_event:call(error_logger, couch_log, {set_level_integer, Module, Int}). handle_event({couch_error, ConMsg, FileMsg}, State) -> log(State, ConMsg, FileMsg), {ok, State}; handle_event({couch_warn, ConMsg, FileMsg}, State) -> log(State, ConMsg, FileMsg), {ok, State}; handle_event({couch_info, ConMsg, FileMsg}, State) -> log(State, ConMsg, FileMsg), {ok, State}; handle_event({couch_debug, ConMsg, FileMsg}, State) -> log(State, ConMsg, FileMsg), {ok, State}; handle_event({error_report, _, {Pid, _, _}}=Event, #state{sasl = true} = St) -> {ConMsg, FileMsg} = get_log_messages(Pid, error, "~p", [Event]), log(St, ConMsg, FileMsg), {ok, St}; handle_event({error, _, {Pid, Format, Args}}, #state{sasl = true} = State) -> {ConMsg, FileMsg} = get_log_messages(Pid, error, Format, Args), log(State, ConMsg, FileMsg), {ok, State}; handle_event(_Event, State) -> {ok, State}. handle_call({set_level_integer, NewLevel}, State) -> ets:insert(?MODULE, {level, NewLevel}), {ok, ok, State#state{level = NewLevel}}; handle_call({set_level_integer, Module, NewLevel}, State) -> ets:insert(?MODULE, {Module, NewLevel}), {ok, ok, State#state{level = NewLevel}}. handle_info(_Info, State) -> {ok, State}. code_change(_OldVsn, State, _Extra) -> {ok, State}. terminate(_Arg, #state{fd = Fd}) -> file:close(Fd). log(#state{fd = Fd}, ConsoleMsg, FileMsg) -> ok = io:put_chars(ConsoleMsg), ok = io:put_chars(Fd, FileMsg). get_log_messages(Pid, Level, Format, Args) -> ConsoleMsg = unicode:characters_to_binary(io_lib:format( "[~s] [~p] " ++ Format ++ "~n", [Level, Pid | Args])), FileMsg = ["[", couch_util:rfc1123_date(), "] ", ConsoleMsg], {ConsoleMsg, iolist_to_binary(FileMsg)}. % Read Bytes bytes from the end of log file, jumping Offset bytes towards % the beginning of the file first. % % Log File FilePos % ---------- % | | 10 % | | 20 % | | 30 % | | 40 % | | 50 % | | 60 % | | 70 -- Bytes = 20 -- % | | 80 | Chunk % | | 90 -- Offset = 10 -- % |__________| 100 read(Bytes, Offset) -> LogFileName = couch_config:get("log", "file"), LogFileSize = filelib:file_size(LogFileName), MaxChunkSize = list_to_integer( couch_config:get("httpd", "log_max_chunk_size", "1000000")), case Bytes > MaxChunkSize of true -> throw({bad_request, "'bytes' cannot exceed " ++ integer_to_list(MaxChunkSize)}); false -> ok end, {ok, Fd} = file:open(LogFileName, [read]), Start = lists:max([LogFileSize - Bytes - Offset, 0]), % TODO: truncate chopped first line % TODO: make streaming {ok, Chunk} = file:pread(Fd, Start, Bytes), ok = file:close(Fd), Chunk. apache-couchdb-1.5.0/src/couchdb/couch_ejson_compare.erl0000644000175000001440000000566612230722213020176 00000000000000% 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. -module(couch_ejson_compare). -export([less/2, less_json_ids/2, less_json/2]). -on_load(init/0). init() -> LibDir = case couch_config:get("couchdb", "util_driver_dir") of undefined -> filename:join(couch_util:priv_dir(), "lib"); LibDir0 -> LibDir0 end, NumScheds = erlang:system_info(schedulers), (catch erlang:load_nif(filename:join([LibDir, ?MODULE]), NumScheds)), case erlang:system_info(otp_release) of "R13B03" -> true; _ -> ok end. less(A, B) -> try less_nif(A, B) catch error:badarg -> % Maybe the EJSON structure is too deep, fallback to Erlang land. less_erl(A, B) end. less_json_ids({JsonA, IdA}, {JsonB, IdB}) -> case less(JsonA, JsonB) of 0 -> IdA < IdB; Result -> Result < 0 end. less_json(A,B) -> less(A, B) < 0. less_nif(A, B) -> less_erl(A, B). less_erl(A,A) -> 0; less_erl(A,B) when is_atom(A), is_atom(B) -> atom_sort(A) - atom_sort(B); less_erl(A,_) when is_atom(A) -> -1; less_erl(_,B) when is_atom(B) -> 1; less_erl(A,B) when is_number(A), is_number(B) -> A - B; less_erl(A,_) when is_number(A) -> -1; less_erl(_,B) when is_number(B) -> 1; less_erl(A,B) when is_binary(A), is_binary(B) -> couch_util:collate(A,B); less_erl(A,_) when is_binary(A) -> -1; less_erl(_,B) when is_binary(B) -> 1; less_erl(A,B) when is_list(A), is_list(B) -> less_list(A,B); less_erl(A,_) when is_list(A) -> -1; less_erl(_,B) when is_list(B) -> 1; less_erl({A},{B}) when is_list(A), is_list(B) -> less_props(A,B); less_erl({A},_) when is_list(A) -> -1; less_erl(_,{B}) when is_list(B) -> 1. atom_sort(null) -> 1; atom_sort(false) -> 2; atom_sort(true) -> 3. less_props([], [_|_]) -> -1; less_props(_, []) -> 1; less_props([{AKey, AValue}|RestA], [{BKey, BValue}|RestB]) -> case couch_util:collate(AKey, BKey) of 0 -> case less_erl(AValue, BValue) of 0 -> less_props(RestA, RestB); Result -> Result end; Result -> Result end. less_list([], [_|_]) -> -1; less_list(_, []) -> 1; less_list([A|RestA], [B|RestB]) -> case less_erl(A,B) of 0 -> less_list(RestA, RestB); Result -> Result end. apache-couchdb-1.5.0/src/couchdb/couch_file.erl0000644000175000001440000004245712230722213016270 00000000000000% 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. -module(couch_file). -behaviour(gen_server). -include("couch_db.hrl"). -define(SIZE_BLOCK, 4096). -record(file, { fd, eof = 0 }). % public API -export([open/1, open/2, close/1, bytes/1, sync/1, truncate/2]). -export([pread_term/2, pread_iolist/2, pread_binary/2]). -export([append_binary/2, append_binary_md5/2]). -export([append_raw_chunk/2, assemble_file_chunk/1, assemble_file_chunk/2]). -export([append_term/2, append_term/3, append_term_md5/2, append_term_md5/3]). -export([write_header/2, read_header/1]). -export([delete/2, delete/3, nuke_dir/2, init_delete_dir/1]). % gen_server callbacks -export([init/1, terminate/2, code_change/3]). -export([handle_call/3, handle_cast/2, handle_info/2]). %%---------------------------------------------------------------------- %% Args: Valid Options are [create] and [create,overwrite]. %% Files are opened in read/write mode. %% Returns: On success, {ok, Fd} %% or {error, Reason} if the file could not be opened. %%---------------------------------------------------------------------- open(Filepath) -> open(Filepath, []). open(Filepath, Options) -> case gen_server:start_link(couch_file, {Filepath, Options, self(), Ref = make_ref()}, []) of {ok, Fd} -> {ok, Fd}; ignore -> % get the error receive {Ref, Pid, {error, Reason} = Error} -> case process_info(self(), trap_exit) of {trap_exit, true} -> receive {'EXIT', Pid, _} -> ok end; {trap_exit, false} -> ok end, case {lists:member(nologifmissing, Options), Reason} of {true, enoent} -> ok; _ -> ?LOG_ERROR("Could not open file ~s: ~s", [Filepath, file:format_error(Reason)]) end, Error end; Error -> % We can't say much here, because it could be any kind of error. % Just let it bubble and an encapsulating subcomponent can perhaps % be more informative. It will likely appear in the SASL log, anyway. Error end. %%---------------------------------------------------------------------- %% Purpose: To append an Erlang term to the end of the file. %% Args: Erlang term to serialize and append to the file. %% Returns: {ok, Pos, NumBytesWritten} where Pos is the file offset to %% the beginning the serialized term. Use pread_term to read the term %% back. %% or {error, Reason}. %%---------------------------------------------------------------------- append_term(Fd, Term) -> append_term(Fd, Term, []). append_term(Fd, Term, Options) -> Comp = couch_util:get_value(compression, Options, ?DEFAULT_COMPRESSION), append_binary(Fd, couch_compress:compress(Term, Comp)). append_term_md5(Fd, Term) -> append_term_md5(Fd, Term, []). append_term_md5(Fd, Term, Options) -> Comp = couch_util:get_value(compression, Options, ?DEFAULT_COMPRESSION), append_binary_md5(Fd, couch_compress:compress(Term, Comp)). %%---------------------------------------------------------------------- %% Purpose: To append an Erlang binary to the end of the file. %% Args: Erlang term to serialize and append to the file. %% Returns: {ok, Pos, NumBytesWritten} where Pos is the file offset to the %% beginning the serialized term. Use pread_term to read the term back. %% or {error, Reason}. %%---------------------------------------------------------------------- append_binary(Fd, Bin) -> gen_server:call(Fd, {append_bin, assemble_file_chunk(Bin)}, infinity). append_binary_md5(Fd, Bin) -> gen_server:call(Fd, {append_bin, assemble_file_chunk(Bin, couch_util:md5(Bin))}, infinity). append_raw_chunk(Fd, Chunk) -> gen_server:call(Fd, {append_bin, Chunk}, infinity). assemble_file_chunk(Bin) -> [<<0:1/integer, (iolist_size(Bin)):31/integer>>, Bin]. assemble_file_chunk(Bin, Md5) -> [<<1:1/integer, (iolist_size(Bin)):31/integer>>, Md5, Bin]. %%---------------------------------------------------------------------- %% Purpose: Reads a term from a file that was written with append_term %% Args: Pos, the offset into the file where the term is serialized. %% Returns: {ok, Term} %% or {error, Reason}. %%---------------------------------------------------------------------- pread_term(Fd, Pos) -> {ok, Bin} = pread_binary(Fd, Pos), {ok, couch_compress:decompress(Bin)}. %%---------------------------------------------------------------------- %% Purpose: Reads a binrary from a file that was written with append_binary %% Args: Pos, the offset into the file where the term is serialized. %% Returns: {ok, Term} %% or {error, Reason}. %%---------------------------------------------------------------------- pread_binary(Fd, Pos) -> {ok, L} = pread_iolist(Fd, Pos), {ok, iolist_to_binary(L)}. pread_iolist(Fd, Pos) -> case gen_server:call(Fd, {pread_iolist, Pos}, infinity) of {ok, IoList, <<>>} -> {ok, IoList}; {ok, IoList, Md5} -> case couch_util:md5(IoList) of Md5 -> {ok, IoList}; _ -> exit({file_corruption, <<"file corruption">>}) end; Error -> Error end. %%---------------------------------------------------------------------- %% Purpose: The length of a file, in bytes. %% Returns: {ok, Bytes} %% or {error, Reason}. %%---------------------------------------------------------------------- % length in bytes bytes(Fd) -> gen_server:call(Fd, bytes, infinity). %%---------------------------------------------------------------------- %% Purpose: Truncate a file to the number of bytes. %% Returns: ok %% or {error, Reason}. %%---------------------------------------------------------------------- truncate(Fd, Pos) -> gen_server:call(Fd, {truncate, Pos}, infinity). %%---------------------------------------------------------------------- %% Purpose: Ensure all bytes written to the file are flushed to disk. %% Returns: ok %% or {error, Reason}. %%---------------------------------------------------------------------- sync(Filepath) when is_list(Filepath) -> {ok, Fd} = file:open(Filepath, [append, raw]), try ok = file:sync(Fd) after ok = file:close(Fd) end; sync(Fd) -> gen_server:call(Fd, sync, infinity). %%---------------------------------------------------------------------- %% Purpose: Close the file. %% Returns: ok %%---------------------------------------------------------------------- close(Fd) -> couch_util:shutdown_sync(Fd). delete(RootDir, Filepath) -> delete(RootDir, Filepath, true). delete(RootDir, Filepath, Async) -> DelFile = filename:join([RootDir,".delete", ?b2l(couch_uuids:random())]), case file:rename(Filepath, DelFile) of ok -> if (Async) -> spawn(file, delete, [DelFile]), ok; true -> file:delete(DelFile) end; Error -> Error end. nuke_dir(RootDelDir, Dir) -> FoldFun = fun(File) -> Path = Dir ++ "/" ++ File, case filelib:is_dir(Path) of true -> ok = nuke_dir(RootDelDir, Path), file:del_dir(Path); false -> delete(RootDelDir, Path, false) end end, case file:list_dir(Dir) of {ok, Files} -> lists:foreach(FoldFun, Files), ok = file:del_dir(Dir); {error, enoent} -> ok end. init_delete_dir(RootDir) -> Dir = filename:join(RootDir,".delete"), % note: ensure_dir requires an actual filename companent, which is the % reason for "foo". filelib:ensure_dir(filename:join(Dir,"foo")), filelib:fold_files(Dir, ".*", true, fun(Filename, _) -> ok = file:delete(Filename) end, ok). read_header(Fd) -> case gen_server:call(Fd, find_header, infinity) of {ok, Bin} -> {ok, binary_to_term(Bin)}; Else -> Else end. write_header(Fd, Data) -> Bin = term_to_binary(Data), Md5 = couch_util:md5(Bin), % now we assemble the final header binary and write to disk FinalBin = <>, gen_server:call(Fd, {write_header, FinalBin}, infinity). init_status_error(ReturnPid, Ref, Error) -> ReturnPid ! {Ref, self(), Error}, ignore. % server functions init({Filepath, Options, ReturnPid, Ref}) -> process_flag(trap_exit, true), OpenOptions = file_open_options(Options), case lists:member(create, Options) of true -> filelib:ensure_dir(Filepath), case file:open(Filepath, OpenOptions) of {ok, Fd} -> {ok, Length} = file:position(Fd, eof), case Length > 0 of true -> % this means the file already exists and has data. % FYI: We don't differentiate between empty files and non-existant % files here. case lists:member(overwrite, Options) of true -> {ok, 0} = file:position(Fd, 0), ok = file:truncate(Fd), ok = file:sync(Fd), maybe_track_open_os_files(Options), {ok, #file{fd=Fd}}; false -> ok = file:close(Fd), init_status_error(ReturnPid, Ref, {error, eexist}) end; false -> maybe_track_open_os_files(Options), {ok, #file{fd=Fd}} end; Error -> init_status_error(ReturnPid, Ref, Error) end; false -> % open in read mode first, so we don't create the file if it doesn't exist. case file:open(Filepath, [read, raw]) of {ok, Fd_Read} -> {ok, Fd} = file:open(Filepath, OpenOptions), ok = file:close(Fd_Read), maybe_track_open_os_files(Options), {ok, Eof} = file:position(Fd, eof), {ok, #file{fd=Fd, eof=Eof}}; Error -> init_status_error(ReturnPid, Ref, Error) end end. file_open_options(Options) -> [read, raw, binary] ++ case lists:member(read_only, Options) of true -> []; false -> [append] end. maybe_track_open_os_files(FileOptions) -> case lists:member(sys_db, FileOptions) of true -> ok; false -> couch_stats_collector:track_process_count({couchdb, open_os_files}) end. terminate(_Reason, #file{fd = Fd}) -> ok = file:close(Fd). handle_call({pread_iolist, Pos}, _From, File) -> {RawData, NextPos} = try % up to 8Kbs of read ahead read_raw_iolist_int(File, Pos, 2 * ?SIZE_BLOCK - (Pos rem ?SIZE_BLOCK)) catch _:_ -> read_raw_iolist_int(File, Pos, 4) end, <> = iolist_to_binary(RawData), case Prefix of 1 -> {Md5, IoList} = extract_md5( maybe_read_more_iolist(RestRawData, 16 + Len, NextPos, File)), {reply, {ok, IoList, Md5}, File}; 0 -> IoList = maybe_read_more_iolist(RestRawData, Len, NextPos, File), {reply, {ok, IoList, <<>>}, File} end; handle_call(bytes, _From, #file{fd = Fd} = File) -> {reply, file:position(Fd, eof), File}; handle_call(sync, _From, #file{fd=Fd}=File) -> {reply, file:sync(Fd), File}; handle_call({truncate, Pos}, _From, #file{fd=Fd}=File) -> {ok, Pos} = file:position(Fd, Pos), case file:truncate(Fd) of ok -> {reply, ok, File#file{eof = Pos}}; Error -> {reply, Error, File} end; handle_call({append_bin, Bin}, _From, #file{fd = Fd, eof = Pos} = File) -> Blocks = make_blocks(Pos rem ?SIZE_BLOCK, Bin), Size = iolist_size(Blocks), case file:write(Fd, Blocks) of ok -> {reply, {ok, Pos, Size}, File#file{eof = Pos + Size}}; Error -> {reply, Error, File} end; handle_call({write_header, Bin}, _From, #file{fd = Fd, eof = Pos} = File) -> BinSize = byte_size(Bin), case Pos rem ?SIZE_BLOCK of 0 -> Padding = <<>>; BlockOffset -> Padding = <<0:(8*(?SIZE_BLOCK-BlockOffset))>> end, FinalBin = [Padding, <<1, BinSize:32/integer>> | make_blocks(5, [Bin])], case file:write(Fd, FinalBin) of ok -> {reply, ok, File#file{eof = Pos + iolist_size(FinalBin)}}; Error -> {reply, Error, File} end; handle_call(find_header, _From, #file{fd = Fd, eof = Pos} = File) -> {reply, find_header(Fd, Pos div ?SIZE_BLOCK), File}. handle_cast(close, Fd) -> {stop,normal,Fd}. code_change(_OldVsn, State, _Extra) -> {ok, State}. handle_info({'EXIT', _, normal}, Fd) -> {noreply, Fd}; handle_info({'EXIT', _, Reason}, Fd) -> {stop, Reason, Fd}. find_header(_Fd, -1) -> no_valid_header; find_header(Fd, Block) -> case (catch load_header(Fd, Block)) of {ok, Bin} -> {ok, Bin}; _Error -> find_header(Fd, Block -1) end. load_header(Fd, Block) -> {ok, <<1, HeaderLen:32/integer, RestBlock/binary>>} = file:pread(Fd, Block * ?SIZE_BLOCK, ?SIZE_BLOCK), TotalBytes = calculate_total_read_len(5, HeaderLen), case TotalBytes > byte_size(RestBlock) of false -> <> = RestBlock; true -> {ok, Missing} = file:pread( Fd, (Block * ?SIZE_BLOCK) + 5 + byte_size(RestBlock), TotalBytes - byte_size(RestBlock)), RawBin = <> end, <> = iolist_to_binary(remove_block_prefixes(5, RawBin)), Md5Sig = couch_util:md5(HeaderBin), {ok, HeaderBin}. maybe_read_more_iolist(Buffer, DataSize, _, _) when DataSize =< byte_size(Buffer) -> <> = Buffer, [Data]; maybe_read_more_iolist(Buffer, DataSize, NextPos, File) -> {Missing, _} = read_raw_iolist_int(File, NextPos, DataSize - byte_size(Buffer)), [Buffer, Missing]. -spec read_raw_iolist_int(#file{}, Pos::non_neg_integer(), Len::non_neg_integer()) -> {Data::iolist(), CurPos::non_neg_integer()}. read_raw_iolist_int(Fd, {Pos, _Size}, Len) -> % 0110 UPGRADE CODE read_raw_iolist_int(Fd, Pos, Len); read_raw_iolist_int(#file{fd = Fd}, Pos, Len) -> BlockOffset = Pos rem ?SIZE_BLOCK, TotalBytes = calculate_total_read_len(BlockOffset, Len), {ok, <>} = file:pread(Fd, Pos, TotalBytes), {remove_block_prefixes(BlockOffset, RawBin), Pos + TotalBytes}. -spec extract_md5(iolist()) -> {binary(), iolist()}. extract_md5(FullIoList) -> {Md5List, IoList} = split_iolist(FullIoList, 16, []), {iolist_to_binary(Md5List), IoList}. calculate_total_read_len(0, FinalLen) -> calculate_total_read_len(1, FinalLen) + 1; calculate_total_read_len(BlockOffset, FinalLen) -> case ?SIZE_BLOCK - BlockOffset of BlockLeft when BlockLeft >= FinalLen -> FinalLen; BlockLeft -> FinalLen + ((FinalLen - BlockLeft) div (?SIZE_BLOCK -1)) + if ((FinalLen - BlockLeft) rem (?SIZE_BLOCK -1)) =:= 0 -> 0; true -> 1 end end. remove_block_prefixes(_BlockOffset, <<>>) -> []; remove_block_prefixes(0, <<_BlockPrefix,Rest/binary>>) -> remove_block_prefixes(1, Rest); remove_block_prefixes(BlockOffset, Bin) -> BlockBytesAvailable = ?SIZE_BLOCK - BlockOffset, case size(Bin) of Size when Size > BlockBytesAvailable -> <> = Bin, [DataBlock | remove_block_prefixes(0, Rest)]; _Size -> [Bin] end. make_blocks(_BlockOffset, []) -> []; make_blocks(0, IoList) -> [<<0>> | make_blocks(1, IoList)]; make_blocks(BlockOffset, IoList) -> case split_iolist(IoList, (?SIZE_BLOCK - BlockOffset), []) of {Begin, End} -> [Begin | make_blocks(0, End)]; _SplitRemaining -> IoList end. %% @doc Returns a tuple where the first element contains the leading SplitAt %% bytes of the original iolist, and the 2nd element is the tail. If SplitAt %% is larger than byte_size(IoList), return the difference. -spec split_iolist(IoList::iolist(), SplitAt::non_neg_integer(), Acc::list()) -> {iolist(), iolist()} | non_neg_integer(). split_iolist(List, 0, BeginAcc) -> {lists:reverse(BeginAcc), List}; split_iolist([], SplitAt, _BeginAcc) -> SplitAt; split_iolist([<> | Rest], SplitAt, BeginAcc) when SplitAt > byte_size(Bin) -> split_iolist(Rest, SplitAt - byte_size(Bin), [Bin | BeginAcc]); split_iolist([<> | Rest], SplitAt, BeginAcc) -> <> = Bin, split_iolist([End | Rest], 0, [Begin | BeginAcc]); split_iolist([Sublist| Rest], SplitAt, BeginAcc) when is_list(Sublist) -> case split_iolist(Sublist, SplitAt, BeginAcc) of {Begin, End} -> {Begin, [End | Rest]}; SplitRemaining -> split_iolist(Rest, SplitAt - (SplitAt - SplitRemaining), [Sublist | BeginAcc]) end; split_iolist([Byte | Rest], SplitAt, BeginAcc) when is_integer(Byte) -> split_iolist(Rest, SplitAt - 1, [Byte | BeginAcc]). apache-couchdb-1.5.0/src/couchdb/couch_btree.erl0000644000175000001440000006630012230722213016443 00000000000000% 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. -module(couch_btree). -export([open/2, open/3, query_modify/4, add/2, add_remove/3]). -export([fold/4, full_reduce/1, final_reduce/2, size/1, foldl/3, foldl/4]). -export([fold_reduce/4, lookup/2, get_state/1, set_options/2]). -export([less/3]). -include("couch_db.hrl"). -define(CHUNK_THRESHOLD, 16#4ff). extract(#btree{extract_kv=Extract}, Value) -> Extract(Value). assemble(#btree{assemble_kv=Assemble}, Key, Value) -> Assemble(Key, Value). less(#btree{less=Less}, A, B) -> Less(A, B). % pass in 'nil' for State if a new Btree. open(State, Fd) -> {ok, #btree{root=State, fd=Fd}}. set_options(Bt, []) -> Bt; set_options(Bt, [{split, Extract}|Rest]) -> set_options(Bt#btree{extract_kv=Extract}, Rest); set_options(Bt, [{join, Assemble}|Rest]) -> set_options(Bt#btree{assemble_kv=Assemble}, Rest); set_options(Bt, [{less, Less}|Rest]) -> set_options(Bt#btree{less=Less}, Rest); set_options(Bt, [{reduce, Reduce}|Rest]) -> set_options(Bt#btree{reduce=Reduce}, Rest); set_options(Bt, [{compression, Comp}|Rest]) -> set_options(Bt#btree{compression=Comp}, Rest). open(State, Fd, Options) -> {ok, set_options(#btree{root=State, fd=Fd}, Options)}. get_state(#btree{root=Root}) -> Root. final_reduce(#btree{reduce=Reduce}, Val) -> final_reduce(Reduce, Val); final_reduce(Reduce, {[], []}) -> Reduce(reduce, []); final_reduce(_Bt, {[], [Red]}) -> Red; final_reduce(Reduce, {[], Reductions}) -> Reduce(rereduce, Reductions); final_reduce(Reduce, {KVs, Reductions}) -> Red = Reduce(reduce, KVs), final_reduce(Reduce, {[], [Red | Reductions]}). fold_reduce(#btree{root=Root}=Bt, Fun, Acc, Options) -> Dir = couch_util:get_value(dir, Options, fwd), StartKey = couch_util:get_value(start_key, Options), InEndRangeFun = make_key_in_end_range_function(Bt, Dir, Options), KeyGroupFun = couch_util:get_value(key_group_fun, Options, fun(_,_) -> true end), try {ok, Acc2, GroupedRedsAcc2, GroupedKVsAcc2, GroupedKey2} = reduce_stream_node(Bt, Dir, Root, StartKey, InEndRangeFun, undefined, [], [], KeyGroupFun, Fun, Acc), if GroupedKey2 == undefined -> {ok, Acc2}; true -> case Fun(GroupedKey2, {GroupedKVsAcc2, GroupedRedsAcc2}, Acc2) of {ok, Acc3} -> {ok, Acc3}; {stop, Acc3} -> {ok, Acc3} end end catch throw:{stop, AccDone} -> {ok, AccDone} end. full_reduce(#btree{root=nil,reduce=Reduce}) -> {ok, Reduce(reduce, [])}; full_reduce(#btree{root=Root}) -> {ok, element(2, Root)}. size(#btree{root = nil}) -> 0; size(#btree{root = {_P, _Red}}) -> % pre 1.2 format nil; size(#btree{root = {_P, _Red, Size}}) -> Size. % wraps a 2 arity function with the proper 3 arity function convert_fun_arity(Fun) when is_function(Fun, 2) -> fun (visit, KV, _Reds, AccIn) -> Fun(KV, AccIn); (traverse, _K, _Red, AccIn) -> {ok, AccIn} end; convert_fun_arity(Fun) when is_function(Fun, 3) -> fun (visit, KV, Reds, AccIn) -> Fun(KV, Reds, AccIn); (traverse, _K, _Red, AccIn) -> {ok, AccIn} end; convert_fun_arity(Fun) when is_function(Fun, 4) -> Fun. % Already arity 4 make_key_in_end_range_function(#btree{less=Less}, fwd, Options) -> case couch_util:get_value(end_key_gt, Options) of undefined -> case couch_util:get_value(end_key, Options) of undefined -> fun(_Key) -> true end; LastKey -> fun(Key) -> not Less(LastKey, Key) end end; EndKey -> fun(Key) -> Less(Key, EndKey) end end; make_key_in_end_range_function(#btree{less=Less}, rev, Options) -> case couch_util:get_value(end_key_gt, Options) of undefined -> case couch_util:get_value(end_key, Options) of undefined -> fun(_Key) -> true end; LastKey -> fun(Key) -> not Less(Key, LastKey) end end; EndKey -> fun(Key) -> Less(EndKey, Key) end end. foldl(Bt, Fun, Acc) -> fold(Bt, Fun, Acc, []). foldl(Bt, Fun, Acc, Options) -> fold(Bt, Fun, Acc, Options). fold(#btree{root=nil}, _Fun, Acc, _Options) -> {ok, {[], []}, Acc}; fold(#btree{root=Root}=Bt, Fun, Acc, Options) -> Dir = couch_util:get_value(dir, Options, fwd), InRange = make_key_in_end_range_function(Bt, Dir, Options), Result = case couch_util:get_value(start_key, Options) of undefined -> stream_node(Bt, [], Bt#btree.root, InRange, Dir, convert_fun_arity(Fun), Acc); StartKey -> stream_node(Bt, [], Bt#btree.root, StartKey, InRange, Dir, convert_fun_arity(Fun), Acc) end, case Result of {ok, Acc2}-> FullReduction = element(2, Root), {ok, {[], [FullReduction]}, Acc2}; {stop, LastReduction, Acc2} -> {ok, LastReduction, Acc2} end. add(Bt, InsertKeyValues) -> add_remove(Bt, InsertKeyValues, []). add_remove(Bt, InsertKeyValues, RemoveKeys) -> {ok, [], Bt2} = query_modify(Bt, [], InsertKeyValues, RemoveKeys), {ok, Bt2}. query_modify(Bt, LookupKeys, InsertValues, RemoveKeys) -> #btree{root=Root} = Bt, InsertActions = lists:map( fun(KeyValue) -> {Key, Value} = extract(Bt, KeyValue), {insert, Key, Value} end, InsertValues), RemoveActions = [{remove, Key, nil} || Key <- RemoveKeys], FetchActions = [{fetch, Key, nil} || Key <- LookupKeys], SortFun = fun({OpA, A, _}, {OpB, B, _}) -> case A == B of % A and B are equal, sort by op. true -> op_order(OpA) < op_order(OpB); false -> less(Bt, A, B) end end, Actions = lists:sort(SortFun, lists:append([InsertActions, RemoveActions, FetchActions])), {ok, KeyPointers, QueryResults} = modify_node(Bt, Root, Actions, []), {ok, NewRoot} = complete_root(Bt, KeyPointers), {ok, QueryResults, Bt#btree{root=NewRoot}}. % for ordering different operations with the same key. % fetch < remove < insert op_order(fetch) -> 1; op_order(remove) -> 2; op_order(insert) -> 3. lookup(#btree{root=Root, less=Less}=Bt, Keys) -> SortedKeys = lists:sort(Less, Keys), {ok, SortedResults} = lookup(Bt, Root, SortedKeys), % We want to return the results in the same order as the keys were input % but we may have changed the order when we sorted. So we need to put the % order back into the results. couch_util:reorder_results(Keys, SortedResults). lookup(_Bt, nil, Keys) -> {ok, [{Key, not_found} || Key <- Keys]}; lookup(Bt, Node, Keys) -> Pointer = element(1, Node), {NodeType, NodeList} = get_node(Bt, Pointer), case NodeType of kp_node -> lookup_kpnode(Bt, list_to_tuple(NodeList), 1, Keys, []); kv_node -> lookup_kvnode(Bt, list_to_tuple(NodeList), 1, Keys, []) end. lookup_kpnode(_Bt, _NodeTuple, _LowerBound, [], Output) -> {ok, lists:reverse(Output)}; lookup_kpnode(_Bt, NodeTuple, LowerBound, Keys, Output) when tuple_size(NodeTuple) < LowerBound -> {ok, lists:reverse(Output, [{Key, not_found} || Key <- Keys])}; lookup_kpnode(Bt, NodeTuple, LowerBound, [FirstLookupKey | _] = LookupKeys, Output) -> N = find_first_gteq(Bt, NodeTuple, LowerBound, tuple_size(NodeTuple), FirstLookupKey), {Key, PointerInfo} = element(N, NodeTuple), SplitFun = fun(LookupKey) -> not less(Bt, Key, LookupKey) end, case lists:splitwith(SplitFun, LookupKeys) of {[], GreaterQueries} -> lookup_kpnode(Bt, NodeTuple, N + 1, GreaterQueries, Output); {LessEqQueries, GreaterQueries} -> {ok, Results} = lookup(Bt, PointerInfo, LessEqQueries), lookup_kpnode(Bt, NodeTuple, N + 1, GreaterQueries, lists:reverse(Results, Output)) end. lookup_kvnode(_Bt, _NodeTuple, _LowerBound, [], Output) -> {ok, lists:reverse(Output)}; lookup_kvnode(_Bt, NodeTuple, LowerBound, Keys, Output) when tuple_size(NodeTuple) < LowerBound -> % keys not found {ok, lists:reverse(Output, [{Key, not_found} || Key <- Keys])}; lookup_kvnode(Bt, NodeTuple, LowerBound, [LookupKey | RestLookupKeys], Output) -> N = find_first_gteq(Bt, NodeTuple, LowerBound, tuple_size(NodeTuple), LookupKey), {Key, Value} = element(N, NodeTuple), case less(Bt, LookupKey, Key) of true -> % LookupKey is less than Key lookup_kvnode(Bt, NodeTuple, N, RestLookupKeys, [{LookupKey, not_found} | Output]); false -> case less(Bt, Key, LookupKey) of true -> % LookupKey is greater than Key lookup_kvnode(Bt, NodeTuple, N+1, RestLookupKeys, [{LookupKey, not_found} | Output]); false -> % LookupKey is equal to Key lookup_kvnode(Bt, NodeTuple, N, RestLookupKeys, [{LookupKey, {ok, assemble(Bt, LookupKey, Value)}} | Output]) end end. complete_root(_Bt, []) -> {ok, nil}; complete_root(_Bt, [{_Key, PointerInfo}])-> {ok, PointerInfo}; complete_root(Bt, KPs) -> {ok, ResultKeyPointers} = write_node(Bt, kp_node, KPs), complete_root(Bt, ResultKeyPointers). %%%%%%%%%%%%% The chunkify function sucks! %%%%%%%%%%%%% % It is inaccurate as it does not account for compression when blocks are % written. Plus with the "case byte_size(term_to_binary(InList)) of" code % it's probably really inefficient. chunkify(InList) -> case ?term_size(InList) of Size when Size > ?CHUNK_THRESHOLD -> NumberOfChunksLikely = ((Size div ?CHUNK_THRESHOLD) + 1), ChunkThreshold = Size div NumberOfChunksLikely, chunkify(InList, ChunkThreshold, [], 0, []); _Else -> [InList] end. chunkify([], _ChunkThreshold, [], 0, OutputChunks) -> lists:reverse(OutputChunks); chunkify([], _ChunkThreshold, OutList, _OutListSize, OutputChunks) -> lists:reverse([lists:reverse(OutList) | OutputChunks]); chunkify([InElement | RestInList], ChunkThreshold, OutList, OutListSize, OutputChunks) -> case ?term_size(InElement) of Size when (Size + OutListSize) > ChunkThreshold andalso OutList /= [] -> chunkify(RestInList, ChunkThreshold, [], 0, [lists:reverse([InElement | OutList]) | OutputChunks]); Size -> chunkify(RestInList, ChunkThreshold, [InElement | OutList], OutListSize + Size, OutputChunks) end. modify_node(Bt, RootPointerInfo, Actions, QueryOutput) -> case RootPointerInfo of nil -> NodeType = kv_node, NodeList = []; _Tuple -> Pointer = element(1, RootPointerInfo), {NodeType, NodeList} = get_node(Bt, Pointer) end, NodeTuple = list_to_tuple(NodeList), {ok, NewNodeList, QueryOutput2} = case NodeType of kp_node -> modify_kpnode(Bt, NodeTuple, 1, Actions, [], QueryOutput); kv_node -> modify_kvnode(Bt, NodeTuple, 1, Actions, [], QueryOutput) end, case NewNodeList of [] -> % no nodes remain {ok, [], QueryOutput2}; NodeList -> % nothing changed {LastKey, _LastValue} = element(tuple_size(NodeTuple), NodeTuple), {ok, [{LastKey, RootPointerInfo}], QueryOutput2}; _Else2 -> {ok, ResultList} = write_node(Bt, NodeType, NewNodeList), {ok, ResultList, QueryOutput2} end. reduce_node(#btree{reduce=nil}, _NodeType, _NodeList) -> []; reduce_node(#btree{reduce=R}, kp_node, NodeList) -> R(rereduce, [element(2, Node) || {_K, Node} <- NodeList]); reduce_node(#btree{reduce=R}=Bt, kv_node, NodeList) -> R(reduce, [assemble(Bt, K, V) || {K, V} <- NodeList]). reduce_tree_size(kv_node, NodeSize, _KvList) -> NodeSize; reduce_tree_size(kp_node, NodeSize, []) -> NodeSize; reduce_tree_size(kp_node, _NodeSize, [{_K, {_P, _Red}} | _]) -> % pre 1.2 format nil; reduce_tree_size(kp_node, _NodeSize, [{_K, {_P, _Red, nil}} | _]) -> nil; reduce_tree_size(kp_node, NodeSize, [{_K, {_P, _Red, Sz}} | NodeList]) -> reduce_tree_size(kp_node, NodeSize + Sz, NodeList). get_node(#btree{fd = Fd}, NodePos) -> {ok, {NodeType, NodeList}} = couch_file:pread_term(Fd, NodePos), {NodeType, NodeList}. write_node(#btree{fd = Fd, compression = Comp} = Bt, NodeType, NodeList) -> % split up nodes into smaller sizes NodeListList = chunkify(NodeList), % now write out each chunk and return the KeyPointer pairs for those nodes ResultList = [ begin {ok, Pointer, Size} = couch_file:append_term( Fd, {NodeType, ANodeList}, [{compression, Comp}]), {LastKey, _} = lists:last(ANodeList), SubTreeSize = reduce_tree_size(NodeType, Size, ANodeList), {LastKey, {Pointer, reduce_node(Bt, NodeType, ANodeList), SubTreeSize}} end || ANodeList <- NodeListList ], {ok, ResultList}. modify_kpnode(Bt, {}, _LowerBound, Actions, [], QueryOutput) -> modify_node(Bt, nil, Actions, QueryOutput); modify_kpnode(_Bt, NodeTuple, LowerBound, [], ResultNode, QueryOutput) -> {ok, lists:reverse(ResultNode, bounded_tuple_to_list(NodeTuple, LowerBound, tuple_size(NodeTuple), [])), QueryOutput}; modify_kpnode(Bt, NodeTuple, LowerBound, [{_, FirstActionKey, _}|_]=Actions, ResultNode, QueryOutput) -> Sz = tuple_size(NodeTuple), N = find_first_gteq(Bt, NodeTuple, LowerBound, Sz, FirstActionKey), case N =:= Sz of true -> % perform remaining actions on last node {_, PointerInfo} = element(Sz, NodeTuple), {ok, ChildKPs, QueryOutput2} = modify_node(Bt, PointerInfo, Actions, QueryOutput), NodeList = lists:reverse(ResultNode, bounded_tuple_to_list(NodeTuple, LowerBound, Sz - 1, ChildKPs)), {ok, NodeList, QueryOutput2}; false -> {NodeKey, PointerInfo} = element(N, NodeTuple), SplitFun = fun({_ActionType, ActionKey, _ActionValue}) -> not less(Bt, NodeKey, ActionKey) end, {LessEqQueries, GreaterQueries} = lists:splitwith(SplitFun, Actions), {ok, ChildKPs, QueryOutput2} = modify_node(Bt, PointerInfo, LessEqQueries, QueryOutput), ResultNode2 = lists:reverse(ChildKPs, bounded_tuple_to_revlist(NodeTuple, LowerBound, N - 1, ResultNode)), modify_kpnode(Bt, NodeTuple, N+1, GreaterQueries, ResultNode2, QueryOutput2) end. bounded_tuple_to_revlist(_Tuple, Start, End, Tail) when Start > End -> Tail; bounded_tuple_to_revlist(Tuple, Start, End, Tail) -> bounded_tuple_to_revlist(Tuple, Start+1, End, [element(Start, Tuple)|Tail]). bounded_tuple_to_list(Tuple, Start, End, Tail) -> bounded_tuple_to_list2(Tuple, Start, End, [], Tail). bounded_tuple_to_list2(_Tuple, Start, End, Acc, Tail) when Start > End -> lists:reverse(Acc, Tail); bounded_tuple_to_list2(Tuple, Start, End, Acc, Tail) -> bounded_tuple_to_list2(Tuple, Start + 1, End, [element(Start, Tuple) | Acc], Tail). find_first_gteq(_Bt, _Tuple, Start, End, _Key) when Start == End -> End; find_first_gteq(Bt, Tuple, Start, End, Key) -> Mid = Start + ((End - Start) div 2), {TupleKey, _} = element(Mid, Tuple), case less(Bt, TupleKey, Key) of true -> find_first_gteq(Bt, Tuple, Mid+1, End, Key); false -> find_first_gteq(Bt, Tuple, Start, Mid, Key) end. modify_kvnode(_Bt, NodeTuple, LowerBound, [], ResultNode, QueryOutput) -> {ok, lists:reverse(ResultNode, bounded_tuple_to_list(NodeTuple, LowerBound, tuple_size(NodeTuple), [])), QueryOutput}; modify_kvnode(Bt, NodeTuple, LowerBound, [{ActionType, ActionKey, ActionValue} | RestActions], ResultNode, QueryOutput) when LowerBound > tuple_size(NodeTuple) -> case ActionType of insert -> modify_kvnode(Bt, NodeTuple, LowerBound, RestActions, [{ActionKey, ActionValue} | ResultNode], QueryOutput); remove -> % just drop the action modify_kvnode(Bt, NodeTuple, LowerBound, RestActions, ResultNode, QueryOutput); fetch -> % the key/value must not exist in the tree modify_kvnode(Bt, NodeTuple, LowerBound, RestActions, ResultNode, [{not_found, {ActionKey, nil}} | QueryOutput]) end; modify_kvnode(Bt, NodeTuple, LowerBound, [{ActionType, ActionKey, ActionValue} | RestActions], AccNode, QueryOutput) -> N = find_first_gteq(Bt, NodeTuple, LowerBound, tuple_size(NodeTuple), ActionKey), {Key, Value} = element(N, NodeTuple), ResultNode = bounded_tuple_to_revlist(NodeTuple, LowerBound, N - 1, AccNode), case less(Bt, ActionKey, Key) of true -> case ActionType of insert -> % ActionKey is less than the Key, so insert modify_kvnode(Bt, NodeTuple, N, RestActions, [{ActionKey, ActionValue} | ResultNode], QueryOutput); remove -> % ActionKey is less than the Key, just drop the action modify_kvnode(Bt, NodeTuple, N, RestActions, ResultNode, QueryOutput); fetch -> % ActionKey is less than the Key, the key/value must not exist in the tree modify_kvnode(Bt, NodeTuple, N, RestActions, ResultNode, [{not_found, {ActionKey, nil}} | QueryOutput]) end; false -> % ActionKey and Key are maybe equal. case less(Bt, Key, ActionKey) of false -> case ActionType of insert -> modify_kvnode(Bt, NodeTuple, N+1, RestActions, [{ActionKey, ActionValue} | ResultNode], QueryOutput); remove -> modify_kvnode(Bt, NodeTuple, N+1, RestActions, ResultNode, QueryOutput); fetch -> % ActionKey is equal to the Key, insert into the QueryOuput, but re-process the node % since an identical action key can follow it. modify_kvnode(Bt, NodeTuple, N, RestActions, ResultNode, [{ok, assemble(Bt, Key, Value)} | QueryOutput]) end; true -> modify_kvnode(Bt, NodeTuple, N + 1, [{ActionType, ActionKey, ActionValue} | RestActions], [{Key, Value} | ResultNode], QueryOutput) end end. reduce_stream_node(_Bt, _Dir, nil, _KeyStart, _InEndRangeFun, GroupedKey, GroupedKVsAcc, GroupedRedsAcc, _KeyGroupFun, _Fun, Acc) -> {ok, Acc, GroupedRedsAcc, GroupedKVsAcc, GroupedKey}; reduce_stream_node(Bt, Dir, Node, KeyStart, InEndRangeFun, GroupedKey, GroupedKVsAcc, GroupedRedsAcc, KeyGroupFun, Fun, Acc) -> P = element(1, Node), case get_node(Bt, P) of {kp_node, NodeList} -> NodeList2 = adjust_dir(Dir, NodeList), reduce_stream_kp_node(Bt, Dir, NodeList2, KeyStart, InEndRangeFun, GroupedKey, GroupedKVsAcc, GroupedRedsAcc, KeyGroupFun, Fun, Acc); {kv_node, KVs} -> KVs2 = adjust_dir(Dir, KVs), reduce_stream_kv_node(Bt, Dir, KVs2, KeyStart, InEndRangeFun, GroupedKey, GroupedKVsAcc, GroupedRedsAcc, KeyGroupFun, Fun, Acc) end. reduce_stream_kv_node(Bt, Dir, KVs, KeyStart, InEndRangeFun, GroupedKey, GroupedKVsAcc, GroupedRedsAcc, KeyGroupFun, Fun, Acc) -> GTEKeyStartKVs = case KeyStart of undefined -> KVs; _ -> DropFun = case Dir of fwd -> fun({Key, _}) -> less(Bt, Key, KeyStart) end; rev -> fun({Key, _}) -> less(Bt, KeyStart, Key) end end, lists:dropwhile(DropFun, KVs) end, KVs2 = lists:takewhile( fun({Key, _}) -> InEndRangeFun(Key) end, GTEKeyStartKVs), reduce_stream_kv_node2(Bt, KVs2, GroupedKey, GroupedKVsAcc, GroupedRedsAcc, KeyGroupFun, Fun, Acc). reduce_stream_kv_node2(_Bt, [], GroupedKey, GroupedKVsAcc, GroupedRedsAcc, _KeyGroupFun, _Fun, Acc) -> {ok, Acc, GroupedRedsAcc, GroupedKVsAcc, GroupedKey}; reduce_stream_kv_node2(Bt, [{Key, Value}| RestKVs], GroupedKey, GroupedKVsAcc, GroupedRedsAcc, KeyGroupFun, Fun, Acc) -> case GroupedKey of undefined -> reduce_stream_kv_node2(Bt, RestKVs, Key, [assemble(Bt,Key,Value)], [], KeyGroupFun, Fun, Acc); _ -> case KeyGroupFun(GroupedKey, Key) of true -> reduce_stream_kv_node2(Bt, RestKVs, GroupedKey, [assemble(Bt,Key,Value)|GroupedKVsAcc], GroupedRedsAcc, KeyGroupFun, Fun, Acc); false -> case Fun(GroupedKey, {GroupedKVsAcc, GroupedRedsAcc}, Acc) of {ok, Acc2} -> reduce_stream_kv_node2(Bt, RestKVs, Key, [assemble(Bt,Key,Value)], [], KeyGroupFun, Fun, Acc2); {stop, Acc2} -> throw({stop, Acc2}) end end end. reduce_stream_kp_node(Bt, Dir, NodeList, KeyStart, InEndRangeFun, GroupedKey, GroupedKVsAcc, GroupedRedsAcc, KeyGroupFun, Fun, Acc) -> Nodes = case KeyStart of undefined -> NodeList; _ -> case Dir of fwd -> lists:dropwhile(fun({Key, _}) -> less(Bt, Key, KeyStart) end, NodeList); rev -> RevKPs = lists:reverse(NodeList), case lists:splitwith(fun({Key, _}) -> less(Bt, Key, KeyStart) end, RevKPs) of {_Before, []} -> NodeList; {Before, [FirstAfter | _]} -> [FirstAfter | lists:reverse(Before)] end end end, {InRange, MaybeInRange} = lists:splitwith( fun({Key, _}) -> InEndRangeFun(Key) end, Nodes), NodesInRange = case MaybeInRange of [FirstMaybeInRange | _] when Dir =:= fwd -> InRange ++ [FirstMaybeInRange]; _ -> InRange end, reduce_stream_kp_node2(Bt, Dir, NodesInRange, KeyStart, InEndRangeFun, GroupedKey, GroupedKVsAcc, GroupedRedsAcc, KeyGroupFun, Fun, Acc). reduce_stream_kp_node2(Bt, Dir, [{_Key, NodeInfo} | RestNodeList], KeyStart, InEndRangeFun, undefined, [], [], KeyGroupFun, Fun, Acc) -> {ok, Acc2, GroupedRedsAcc2, GroupedKVsAcc2, GroupedKey2} = reduce_stream_node(Bt, Dir, NodeInfo, KeyStart, InEndRangeFun, undefined, [], [], KeyGroupFun, Fun, Acc), reduce_stream_kp_node2(Bt, Dir, RestNodeList, KeyStart, InEndRangeFun, GroupedKey2, GroupedKVsAcc2, GroupedRedsAcc2, KeyGroupFun, Fun, Acc2); reduce_stream_kp_node2(Bt, Dir, NodeList, KeyStart, InEndRangeFun, GroupedKey, GroupedKVsAcc, GroupedRedsAcc, KeyGroupFun, Fun, Acc) -> {Grouped0, Ungrouped0} = lists:splitwith(fun({Key,_}) -> KeyGroupFun(GroupedKey, Key) end, NodeList), {GroupedNodes, UngroupedNodes} = case Grouped0 of [] -> {Grouped0, Ungrouped0}; _ -> [FirstGrouped | RestGrouped] = lists:reverse(Grouped0), {RestGrouped, [FirstGrouped | Ungrouped0]} end, GroupedReds = [element(2, Node) || {_, Node} <- GroupedNodes], case UngroupedNodes of [{_Key, NodeInfo}|RestNodes] -> {ok, Acc2, GroupedRedsAcc2, GroupedKVsAcc2, GroupedKey2} = reduce_stream_node(Bt, Dir, NodeInfo, KeyStart, InEndRangeFun, GroupedKey, GroupedKVsAcc, GroupedReds ++ GroupedRedsAcc, KeyGroupFun, Fun, Acc), reduce_stream_kp_node2(Bt, Dir, RestNodes, KeyStart, InEndRangeFun, GroupedKey2, GroupedKVsAcc2, GroupedRedsAcc2, KeyGroupFun, Fun, Acc2); [] -> {ok, Acc, GroupedReds ++ GroupedRedsAcc, GroupedKVsAcc, GroupedKey} end. adjust_dir(fwd, List) -> List; adjust_dir(rev, List) -> lists:reverse(List). stream_node(Bt, Reds, Node, StartKey, InRange, Dir, Fun, Acc) -> Pointer = element(1, Node), {NodeType, NodeList} = get_node(Bt, Pointer), case NodeType of kp_node -> stream_kp_node(Bt, Reds, adjust_dir(Dir, NodeList), StartKey, InRange, Dir, Fun, Acc); kv_node -> stream_kv_node(Bt, Reds, adjust_dir(Dir, NodeList), StartKey, InRange, Dir, Fun, Acc) end. stream_node(Bt, Reds, Node, InRange, Dir, Fun, Acc) -> Pointer = element(1, Node), {NodeType, NodeList} = get_node(Bt, Pointer), case NodeType of kp_node -> stream_kp_node(Bt, Reds, adjust_dir(Dir, NodeList), InRange, Dir, Fun, Acc); kv_node -> stream_kv_node2(Bt, Reds, [], adjust_dir(Dir, NodeList), InRange, Dir, Fun, Acc) end. stream_kp_node(_Bt, _Reds, [], _InRange, _Dir, _Fun, Acc) -> {ok, Acc}; stream_kp_node(Bt, Reds, [{Key, Node} | Rest], InRange, Dir, Fun, Acc) -> Red = element(2, Node), case Fun(traverse, Key, Red, Acc) of {ok, Acc2} -> case stream_node(Bt, Reds, Node, InRange, Dir, Fun, Acc2) of {ok, Acc3} -> stream_kp_node(Bt, [Red | Reds], Rest, InRange, Dir, Fun, Acc3); {stop, LastReds, Acc3} -> {stop, LastReds, Acc3} end; {skip, Acc2} -> stream_kp_node(Bt, [Red | Reds], Rest, InRange, Dir, Fun, Acc2) end. drop_nodes(_Bt, Reds, _StartKey, []) -> {Reds, []}; drop_nodes(Bt, Reds, StartKey, [{NodeKey, Node} | RestKPs]) -> case less(Bt, NodeKey, StartKey) of true -> drop_nodes(Bt, [element(2, Node) | Reds], StartKey, RestKPs); false -> {Reds, [{NodeKey, Node} | RestKPs]} end. stream_kp_node(Bt, Reds, KPs, StartKey, InRange, Dir, Fun, Acc) -> {NewReds, NodesToStream} = case Dir of fwd -> % drop all nodes sorting before the key drop_nodes(Bt, Reds, StartKey, KPs); rev -> % keep all nodes sorting before the key, AND the first node to sort after RevKPs = lists:reverse(KPs), case lists:splitwith(fun({Key, _Pointer}) -> less(Bt, Key, StartKey) end, RevKPs) of {_RevsBefore, []} -> % everything sorts before it {Reds, KPs}; {RevBefore, [FirstAfter | Drop]} -> {[element(2, Node) || {_K, Node} <- Drop] ++ Reds, [FirstAfter | lists:reverse(RevBefore)]} end end, case NodesToStream of [] -> {ok, Acc}; [{_Key, Node} | Rest] -> case stream_node(Bt, NewReds, Node, StartKey, InRange, Dir, Fun, Acc) of {ok, Acc2} -> Red = element(2, Node), stream_kp_node(Bt, [Red | NewReds], Rest, InRange, Dir, Fun, Acc2); {stop, LastReds, Acc2} -> {stop, LastReds, Acc2} end end. stream_kv_node(Bt, Reds, KVs, StartKey, InRange, Dir, Fun, Acc) -> DropFun = case Dir of fwd -> fun({Key, _}) -> less(Bt, Key, StartKey) end; rev -> fun({Key, _}) -> less(Bt, StartKey, Key) end end, {LTKVs, GTEKVs} = lists:splitwith(DropFun, KVs), AssembleLTKVs = [assemble(Bt,K,V) || {K,V} <- LTKVs], stream_kv_node2(Bt, Reds, AssembleLTKVs, GTEKVs, InRange, Dir, Fun, Acc). stream_kv_node2(_Bt, _Reds, _PrevKVs, [], _InRange, _Dir, _Fun, Acc) -> {ok, Acc}; stream_kv_node2(Bt, Reds, PrevKVs, [{K,V} | RestKVs], InRange, Dir, Fun, Acc) -> case InRange(K) of false -> {stop, {PrevKVs, Reds}, Acc}; true -> AssembledKV = assemble(Bt, K, V), case Fun(visit, AssembledKV, {PrevKVs, Reds}, Acc) of {ok, Acc2} -> stream_kv_node2(Bt, Reds, [AssembledKV | PrevKVs], RestKVs, InRange, Dir, Fun, Acc2); {stop, Acc2} -> {stop, {PrevKVs, Reds}, Acc2} end end. apache-couchdb-1.5.0/src/couchdb/couch_httpd_oauth.erl0000644000175000001440000003252612230722213017670 00000000000000% 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. -module(couch_httpd_oauth). -include("couch_db.hrl"). -include("couch_js_functions.hrl"). -export([oauth_authentication_handler/1, handle_oauth_req/1]). -define(OAUTH_DDOC_ID, <<"_design/oauth">>). -define(OAUTH_VIEW_NAME, <<"oauth_credentials">>). -record(callback_params, { consumer, token, token_secret, url, signature, params, username }). % OAuth auth handler using per-node user db oauth_authentication_handler(Req) -> serve_oauth(Req, fun oauth_auth_callback/2, true). oauth_auth_callback(Req, #callback_params{token_secret = undefined}) -> couch_httpd:send_error( Req, 400, <<"invalid_token">>, <<"Invalid OAuth token.">>); oauth_auth_callback(#httpd{mochi_req = MochiReq} = Req, CbParams) -> Method = atom_to_list(MochiReq:get(method)), #callback_params{ consumer = Consumer, token_secret = TokenSecret, url = Url, signature = Sig, params = Params, username = User } = CbParams, case oauth:verify(Sig, Method, Url, Params, Consumer, TokenSecret) of true -> set_user_ctx(Req, User); false -> ?LOG_DEBUG("OAuth handler: signature verification failed for user `~p`~n" "Received signature is `~p`~n" "HTTP method is `~p`~n" "URL is `~p`~n" "Parameters are `~p`~n" "Consumer is `~p`, token secret is `~p`~n" "Expected signature was `~p`~n", [User, Sig, Method, Url, Params, Consumer, TokenSecret, oauth:signature(Method, Url, Params, Consumer, TokenSecret)]), Req end. % Look up the consumer key and get the roles to give the consumer set_user_ctx(_Req, undefined) -> throw({bad_request, unknown_oauth_token}); set_user_ctx(Req, Name) -> case couch_auth_cache:get_user_creds(Name) of nil -> ?LOG_DEBUG("OAuth handler: user `~p` credentials not found", [Name]), Req; User -> Roles = couch_util:get_value(<<"roles">>, User, []), Req#httpd{user_ctx=#user_ctx{name=Name, roles=Roles}} end. % OAuth request_token handle_oauth_req(#httpd{path_parts=[_OAuth, <<"request_token">>], method=Method}=Req1) -> serve_oauth(Req1, fun(Req, CbParams) -> #callback_params{ consumer = Consumer, token_secret = TokenSecret, url = Url, signature = Sig, params = Params } = CbParams, case oauth:verify( Sig, atom_to_list(Method), Url, Params, Consumer, TokenSecret) of true -> ok(Req, <<"oauth_token=requestkey&oauth_token_secret=requestsecret">>); false -> invalid_signature(Req) end end, false); handle_oauth_req(#httpd{path_parts=[_OAuth, <<"authorize">>]}=Req) -> {ok, serve_oauth_authorize(Req)}; handle_oauth_req(#httpd{path_parts=[_OAuth, <<"access_token">>], method='GET'}=Req1) -> serve_oauth(Req1, fun(Req, CbParams) -> #callback_params{ consumer = Consumer, token = Token, url = Url, signature = Sig, params = Params } = CbParams, case Token of "requestkey" -> case oauth:verify( Sig, "GET", Url, Params, Consumer, "requestsecret") of true -> ok(Req, <<"oauth_token=accesskey&oauth_token_secret=accesssecret">>); false -> invalid_signature(Req) end; _ -> couch_httpd:send_error( Req, 400, <<"invalid_token">>, <<"Invalid OAuth token.">>) end end, false); handle_oauth_req(#httpd{path_parts=[_OAuth, <<"access_token">>]}=Req) -> couch_httpd:send_method_not_allowed(Req, "GET"). invalid_signature(Req) -> couch_httpd:send_error(Req, 400, <<"invalid_signature">>, <<"Invalid signature value.">>). % This needs to be protected i.e. force user to login using HTTP Basic Auth or form-based login. serve_oauth_authorize(#httpd{method=Method}=Req1) -> case Method of 'GET' -> % Confirm with the User that they want to authenticate the Consumer serve_oauth(Req1, fun(Req, CbParams) -> #callback_params{ consumer = Consumer, token_secret = TokenSecret, url = Url, signature = Sig, params = Params } = CbParams, case oauth:verify( Sig, "GET", Url, Params, Consumer, TokenSecret) of true -> ok(Req, <<"oauth_token=requestkey&", "oauth_token_secret=requestsecret">>); false -> invalid_signature(Req) end end, false); 'POST' -> % If the User has confirmed, we direct the User back to the Consumer with a verification code serve_oauth(Req1, fun(Req, CbParams) -> #callback_params{ consumer = Consumer, token_secret = TokenSecret, url = Url, signature = Sig, params = Params } = CbParams, case oauth:verify( Sig, "POST", Url, Params, Consumer, TokenSecret) of true -> %redirect(oauth_callback, oauth_token, oauth_verifier), ok(Req, <<"oauth_token=requestkey&", "oauth_token_secret=requestsecret">>); false -> invalid_signature(Req) end end, false); _ -> couch_httpd:send_method_not_allowed(Req1, "GET,POST") end. serve_oauth(#httpd{mochi_req=MochiReq}=Req, Fun, FailSilently) -> % 1. In the HTTP Authorization header as defined in OAuth HTTP Authorization Scheme. % 2. As the HTTP POST request body with a content-type of application/x-www-form-urlencoded. % 3. Added to the URLs in the query part (as defined by [RFC3986] section 3). AuthHeader = case MochiReq:get_header_value("authorization") of undefined -> ""; Else -> [Head | Tail] = re:split(Else, "\\s", [{parts, 2}, {return, list}]), case [string:to_lower(Head) | Tail] of ["oauth", Rest] -> Rest; _ -> "" end end, HeaderParams = oauth:header_params_decode(AuthHeader), %Realm = couch_util:get_value("realm", HeaderParams), % get requested path RequestedPath = case MochiReq:get_header_value("x-couchdb-requested-path") of undefined -> case MochiReq:get_header_value("x-couchdb-vhost-path") of undefined -> MochiReq:get(raw_path); VHostPath -> VHostPath end; RequestedPath0 -> RequestedPath0 end, {_, QueryString, _} = mochiweb_util:urlsplit_path(RequestedPath), Params = proplists:delete("realm", HeaderParams) ++ mochiweb_util:parse_qs(QueryString), ?LOG_DEBUG("OAuth Params: ~p", [Params]), case couch_util:get_value("oauth_version", Params, "1.0") of "1.0" -> case couch_util:get_value("oauth_consumer_key", Params, undefined) of undefined -> case FailSilently of true -> Req; false -> couch_httpd:send_error(Req, 400, <<"invalid_consumer">>, <<"Invalid consumer.">>) end; ConsumerKey -> Url = couch_httpd:absolute_uri(Req, RequestedPath), case get_callback_params(ConsumerKey, Params, Url) of {ok, CallbackParams} -> Fun(Req, CallbackParams); invalid_consumer_token_pair -> couch_httpd:send_error( Req, 400, <<"invalid_consumer_token_pair">>, <<"Invalid consumer and token pair.">>); {error, {Error, Reason}} -> couch_httpd:send_error(Req, 400, Error, Reason) end end; _ -> couch_httpd:send_error(Req, 400, <<"invalid_oauth_version">>, <<"Invalid OAuth version.">>) end. get_callback_params(ConsumerKey, Params, Url) -> Token = couch_util:get_value("oauth_token", Params), SigMethod = sig_method(Params), CbParams0 = #callback_params{ token = Token, signature = couch_util:get_value("oauth_signature", Params), params = proplists:delete("oauth_signature", Params), url = Url }, case oauth_credentials_info(Token, ConsumerKey) of nil -> invalid_consumer_token_pair; {error, _} = Err -> Err; {OauthCreds} -> User = couch_util:get_value(<<"username">>, OauthCreds, []), ConsumerSecret = ?b2l(couch_util:get_value( <<"consumer_secret">>, OauthCreds, <<>>)), TokenSecret = ?b2l(couch_util:get_value( <<"token_secret">>, OauthCreds, <<>>)), case (User =:= []) orelse (ConsumerSecret =:= []) orelse (TokenSecret =:= []) of true -> invalid_consumer_token_pair; false -> CbParams = CbParams0#callback_params{ consumer = {ConsumerKey, ConsumerSecret, SigMethod}, token_secret = TokenSecret, username = User }, ?LOG_DEBUG("Got OAuth credentials, for ConsumerKey `~p` and " "Token `~p`, from the views, User: `~p`, " "ConsumerSecret: `~p`, TokenSecret: `~p`", [ConsumerKey, Token, User, ConsumerSecret, TokenSecret]), {ok, CbParams} end end. sig_method(Params) -> sig_method_1(couch_util:get_value("oauth_signature_method", Params)). sig_method_1("PLAINTEXT") -> plaintext; % sig_method_1("RSA-SHA1") -> % rsa_sha1; sig_method_1("HMAC-SHA1") -> hmac_sha1; sig_method_1(_) -> undefined. ok(#httpd{mochi_req=MochiReq}, Body) -> {ok, MochiReq:respond({200, [], Body})}. oauth_credentials_info(Token, ConsumerKey) -> case use_auth_db() of {ok, Db} -> Result = case query_oauth_view(Db, [?l2b(ConsumerKey), ?l2b(Token)]) of [] -> nil; [Creds] -> Creds; [_ | _] -> Reason = iolist_to_binary( io_lib:format("Found multiple OAuth credentials for the pair " " (consumer_key: `~p`, token: `~p`)", [ConsumerKey, Token])), {error, {<<"oauth_token_consumer_key_pair">>, Reason}} end, couch_db:close(Db), Result; nil -> { case couch_config:get("oauth_consumer_secrets", ConsumerKey) of undefined -> []; ConsumerSecret -> [{<<"consumer_secret">>, ?l2b(ConsumerSecret)}] end ++ case couch_config:get("oauth_token_secrets", Token) of undefined -> []; TokenSecret -> [{<<"token_secret">>, ?l2b(TokenSecret)}] end ++ case couch_config:get("oauth_token_users", Token) of undefined -> []; User -> [{<<"username">>, ?l2b(User)}] end } end. use_auth_db() -> case couch_config:get("couch_httpd_oauth", "use_users_db", "false") of "false" -> nil; "true" -> AuthDb = open_auth_db(), {ok, _AuthDb2} = ensure_oauth_views_exist(AuthDb) end. open_auth_db() -> DbName = ?l2b(couch_config:get("couch_httpd_auth", "authentication_db")), DbOptions = [{user_ctx, #user_ctx{roles = [<<"_admin">>]}}], {ok, AuthDb} = couch_db:open_int(DbName, DbOptions), AuthDb. ensure_oauth_views_exist(AuthDb) -> case couch_db:open_doc(AuthDb, ?OAUTH_DDOC_ID, []) of {ok, _DDoc} -> {ok, AuthDb}; _ -> {ok, DDoc} = get_oauth_ddoc(), {ok, _Rev} = couch_db:update_doc(AuthDb, DDoc, []), {ok, _AuthDb2} = couch_db:reopen(AuthDb) end. get_oauth_ddoc() -> Json = {[ {<<"_id">>, ?OAUTH_DDOC_ID}, {<<"language">>, <<"javascript">>}, {<<"views">>, {[ {?OAUTH_VIEW_NAME, {[ {<<"map">>, ?OAUTH_MAP_FUN} ]} } ]} } ]}, {ok, couch_doc:from_json_obj(Json)}. query_oauth_view(Db, Key) -> ViewOptions = [ {start_key, Key}, {end_key, Key} ], Callback = fun({row, Row}, Acc) -> {ok, [couch_util:get_value(value, Row) | Acc]}; (_, Acc) -> {ok, Acc} end, {ok, Result} = couch_mrview:query_view( Db, ?OAUTH_DDOC_ID, ?OAUTH_VIEW_NAME, ViewOptions, Callback, []), Result. apache-couchdb-1.5.0/src/ejson/0000755000175000001440000000000012230722306013242 500000000000000apache-couchdb-1.5.0/src/ejson/yajl/0000755000175000001440000000000012230722306014201 500000000000000apache-couchdb-1.5.0/src/ejson/yajl/yajl_alloc.c0000644000175000001440000000423712230722213016401 00000000000000/* * Copyright 2010, Lloyd Hilaiel. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * 3. Neither the name of Lloyd Hilaiel nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ /** * \file yajl_alloc.h * default memory allocation routines for yajl which use malloc/realloc and * free */ #include "yajl_alloc.h" #include static void * yajl_internal_malloc(void *ctx, unsigned int sz) { return malloc(sz); } static void * yajl_internal_realloc(void *ctx, void * previous, unsigned int sz) { return realloc(previous, sz); } static void yajl_internal_free(void *ctx, void * ptr) { free(ptr); } void yajl_set_default_alloc_funcs(yajl_alloc_funcs * yaf) { yaf->malloc = yajl_internal_malloc; yaf->free = yajl_internal_free; yaf->realloc = yajl_internal_realloc; yaf->ctx = NULL; } apache-couchdb-1.5.0/src/ejson/yajl/yajl_alloc.h0000644000175000001440000000366512230722213016412 00000000000000/* * Copyright 2010, Lloyd Hilaiel. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * 3. Neither the name of Lloyd Hilaiel nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ /** * \file yajl_alloc.h * default memory allocation routines for yajl which use malloc/realloc and * free */ #ifndef __YAJL_ALLOC_H__ #define __YAJL_ALLOC_H__ #include "yajl_common.h" #define YA_MALLOC(afs, sz) (afs)->malloc((afs)->ctx, (sz)) #define YA_FREE(afs, ptr) (afs)->free((afs)->ctx, (ptr)) #define YA_REALLOC(afs, ptr, sz) (afs)->realloc((afs)->ctx, (ptr), (sz)) void yajl_set_default_alloc_funcs(yajl_alloc_funcs * yaf); #endif apache-couchdb-1.5.0/src/ejson/yajl/yajl_parse.h0000644000175000001440000002046212230722213016424 00000000000000/* * Copyright 2010, Lloyd Hilaiel. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * 3. Neither the name of Lloyd Hilaiel nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ /** * \file yajl_parse.h * Interface to YAJL's JSON parsing facilities. */ #include "yajl_common.h" #ifndef __YAJL_PARSE_H__ #define __YAJL_PARSE_H__ #ifdef __cplusplus extern "C" { #endif /** error codes returned from this interface */ typedef enum { /** no error was encountered */ yajl_status_ok, /** a client callback returned zero, stopping the parse */ yajl_status_client_canceled, /** The parse cannot yet complete because more json input text * is required, call yajl_parse with the next buffer of input text. * (pertinent only when stream parsing) */ yajl_status_insufficient_data, /** An error occured during the parse. Call yajl_get_error for * more information about the encountered error */ yajl_status_error } yajl_status; /** attain a human readable, english, string for an error */ YAJL_API const char * yajl_status_to_string(yajl_status code); /** an opaque handle to a parser */ typedef struct yajl_handle_t * yajl_handle; /** yajl is an event driven parser. this means as json elements are * parsed, you are called back to do something with the data. The * functions in this table indicate the various events for which * you will be called back. Each callback accepts a "context" * pointer, this is a void * that is passed into the yajl_parse * function which the client code may use to pass around context. * * All callbacks return an integer. If non-zero, the parse will * continue. If zero, the parse will be canceled and * yajl_status_client_canceled will be returned from the parse. * * Note about handling of numbers: * yajl will only convert numbers that can be represented in a double * or a long int. All other numbers will be passed to the client * in string form using the yajl_number callback. Furthermore, if * yajl_number is not NULL, it will always be used to return numbers, * that is yajl_integer and yajl_double will be ignored. If * yajl_number is NULL but one of yajl_integer or yajl_double are * defined, parsing of a number larger than is representable * in a double or long int will result in a parse error. */ typedef struct { int (* yajl_null)(void * ctx); int (* yajl_boolean)(void * ctx, int boolVal); int (* yajl_integer)(void * ctx, long integerVal); int (* yajl_double)(void * ctx, double doubleVal); /** A callback which passes the string representation of the number * back to the client. Will be used for all numbers when present */ int (* yajl_number)(void * ctx, const char * numberVal, unsigned int numberLen); /** strings are returned as pointers into the JSON text when, * possible, as a result, they are _not_ null padded */ int (* yajl_string)(void * ctx, const unsigned char * stringVal, unsigned int stringLen); int (* yajl_start_map)(void * ctx); int (* yajl_map_key)(void * ctx, const unsigned char * key, unsigned int stringLen); int (* yajl_end_map)(void * ctx); int (* yajl_start_array)(void * ctx); int (* yajl_end_array)(void * ctx); } yajl_callbacks; /** configuration structure for the generator */ typedef struct { /** if nonzero, javascript style comments will be allowed in * the json input, both slash star and slash slash */ unsigned int allowComments; /** if nonzero, invalid UTF8 strings will cause a parse * error */ unsigned int checkUTF8; } yajl_parser_config; /** allocate a parser handle * \param callbacks a yajl callbacks structure specifying the * functions to call when different JSON entities * are encountered in the input text. May be NULL, * which is only useful for validation. * \param config configuration parameters for the parse. * \param ctx a context pointer that will be passed to callbacks. */ YAJL_API yajl_handle yajl_alloc(const yajl_callbacks * callbacks, const yajl_parser_config * config, const yajl_alloc_funcs * allocFuncs, void * ctx); /** free a parser handle */ YAJL_API void yajl_free(yajl_handle handle); /** Parse some json! * \param hand - a handle to the json parser allocated with yajl_alloc * \param jsonText - a pointer to the UTF8 json text to be parsed * \param jsonTextLength - the length, in bytes, of input text */ YAJL_API yajl_status yajl_parse(yajl_handle hand, const unsigned char * jsonText, unsigned int jsonTextLength); /** Parse any remaining buffered json. * Since yajl is a stream-based parser, without an explicit end of * input, yajl sometimes can't decide if content at the end of the * stream is valid or not. For example, if "1" has been fed in, * yajl can't know whether another digit is next or some character * that would terminate the integer token. * * \param hand - a handle to the json parser allocated with yajl_alloc */ YAJL_API yajl_status yajl_parse_complete(yajl_handle hand); /** get an error string describing the state of the * parse. * * If verbose is non-zero, the message will include the JSON * text where the error occured, along with an arrow pointing to * the specific char. * * \returns A dynamically allocated string will be returned which should * be freed with yajl_free_error */ YAJL_API unsigned char * yajl_get_error(yajl_handle hand, int verbose, const unsigned char * jsonText, unsigned int jsonTextLength); /** * get the amount of data consumed from the last chunk passed to YAJL. * * In the case of a successful parse this can help you understand if * the entire buffer was consumed (which will allow you to handle * "junk at end of input". * * In the event an error is encountered during parsing, this function * affords the client a way to get the offset into the most recent * chunk where the error occured. 0 will be returned if no error * was encountered. */ YAJL_API unsigned int yajl_get_bytes_consumed(yajl_handle hand); /** free an error returned from yajl_get_error */ YAJL_API void yajl_free_error(yajl_handle hand, unsigned char * str); #ifdef __cplusplus } #endif #endif apache-couchdb-1.5.0/src/ejson/yajl/yajl_buf.c0000644000175000001440000000633412230722213016063 00000000000000/* * Copyright 2010, Lloyd Hilaiel. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * 3. Neither the name of Lloyd Hilaiel nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ #include "yajl_buf.h" #include #include #include #define YAJL_BUF_INIT_SIZE 2048 struct yajl_buf_t { unsigned int len; unsigned int used; unsigned char * data; yajl_alloc_funcs * alloc; }; static void yajl_buf_ensure_available(yajl_buf buf, unsigned int want) { unsigned int need; assert(buf != NULL); /* first call */ if (buf->data == NULL) { buf->len = YAJL_BUF_INIT_SIZE; buf->data = (unsigned char *) YA_MALLOC(buf->alloc, buf->len); buf->data[0] = 0; } need = buf->len; while (want >= (need - buf->used)) need <<= 1; if (need != buf->len) { buf->data = (unsigned char *) YA_REALLOC(buf->alloc, buf->data, need); buf->len = need; } } yajl_buf yajl_buf_alloc(yajl_alloc_funcs * alloc) { yajl_buf b = YA_MALLOC(alloc, sizeof(struct yajl_buf_t)); memset((void *) b, 0, sizeof(struct yajl_buf_t)); b->alloc = alloc; return b; } void yajl_buf_free(yajl_buf buf) { assert(buf != NULL); if (buf->data) YA_FREE(buf->alloc, buf->data); YA_FREE(buf->alloc, buf); } void yajl_buf_append(yajl_buf buf, const void * data, unsigned int len) { yajl_buf_ensure_available(buf, len); if (len > 0) { assert(data != NULL); memcpy(buf->data + buf->used, data, len); buf->used += len; buf->data[buf->used] = 0; } } void yajl_buf_clear(yajl_buf buf) { buf->used = 0; if (buf->data) buf->data[buf->used] = 0; } const unsigned char * yajl_buf_data(yajl_buf buf) { return buf->data; } unsigned int yajl_buf_len(yajl_buf buf) { return buf->used; } void yajl_buf_truncate(yajl_buf buf, unsigned int len) { assert(len <= buf->used); buf->used = len; } apache-couchdb-1.5.0/src/ejson/yajl/yajl_buf.h0000644000175000001440000000505112230722213016063 00000000000000/* * Copyright 2010, Lloyd Hilaiel. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * 3. Neither the name of Lloyd Hilaiel nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ #ifndef __YAJL_BUF_H__ #define __YAJL_BUF_H__ #include "yajl_common.h" #include "yajl_alloc.h" /* * Implementation/performance notes. If this were moved to a header * only implementation using #define's where possible we might be * able to sqeeze a little performance out of the guy by killing function * call overhead. YMMV. */ /** * yajl_buf is a buffer with exponential growth. the buffer ensures that * you are always null padded. */ typedef struct yajl_buf_t * yajl_buf; /* allocate a new buffer */ yajl_buf yajl_buf_alloc(yajl_alloc_funcs * alloc); /* free the buffer */ void yajl_buf_free(yajl_buf buf); /* append a number of bytes to the buffer */ void yajl_buf_append(yajl_buf buf, const void * data, unsigned int len); /* empty the buffer */ void yajl_buf_clear(yajl_buf buf); /* get a pointer to the beginning of the buffer */ const unsigned char * yajl_buf_data(yajl_buf buf); /* get the length of the buffer */ unsigned int yajl_buf_len(yajl_buf buf); /* truncate the buffer */ void yajl_buf_truncate(yajl_buf buf, unsigned int len); #endif apache-couchdb-1.5.0/src/ejson/yajl/yajl_gen.c0000644000175000001440000002332412230722213016056 00000000000000/* * Copyright 2010, Lloyd Hilaiel. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * 3. Neither the name of Lloyd Hilaiel nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ #include "yajl_gen.h" #include "yajl_buf.h" #include "yajl_encode.h" #include #include #include #include typedef enum { yajl_gen_start, yajl_gen_map_start, yajl_gen_map_key, yajl_gen_map_val, yajl_gen_array_start, yajl_gen_in_array, yajl_gen_complete, yajl_gen_error } yajl_gen_state; struct yajl_gen_t { unsigned int depth; unsigned int pretty; const char * indentString; yajl_gen_state state[YAJL_MAX_DEPTH]; yajl_print_t print; void * ctx; /* yajl_buf */ /* memory allocation routines */ yajl_alloc_funcs alloc; }; yajl_gen yajl_gen_alloc(const yajl_gen_config * config, const yajl_alloc_funcs * afs) { return yajl_gen_alloc2(NULL, config, afs, NULL); } yajl_gen yajl_gen_alloc2(const yajl_print_t callback, const yajl_gen_config * config, const yajl_alloc_funcs * afs, void * ctx) { yajl_gen g = NULL; yajl_alloc_funcs afsBuffer; /* first order of business is to set up memory allocation routines */ if (afs != NULL) { if (afs->malloc == NULL || afs->realloc == NULL || afs->free == NULL) { return NULL; } } else { yajl_set_default_alloc_funcs(&afsBuffer); afs = &afsBuffer; } g = (yajl_gen) YA_MALLOC(afs, sizeof(struct yajl_gen_t)); memset((void *) g, 0, sizeof(struct yajl_gen_t)); /* copy in pointers to allocation routines */ memcpy((void *) &(g->alloc), (void *) afs, sizeof(yajl_alloc_funcs)); if (config) { g->pretty = config->beautify; g->indentString = config->indentString ? config->indentString : " "; } if (callback) { g->print = callback; g->ctx = ctx; } else { g->print = (yajl_print_t)&yajl_buf_append; g->ctx = yajl_buf_alloc(&(g->alloc)); } return g; } void yajl_gen_free(yajl_gen g) { if (g->print == (yajl_print_t)&yajl_buf_append) yajl_buf_free((yajl_buf)g->ctx); YA_FREE(&(g->alloc), g); } #define INSERT_SEP \ if (g->state[g->depth] == yajl_gen_map_key || \ g->state[g->depth] == yajl_gen_in_array) { \ g->print(g->ctx, ",", 1); \ if (g->pretty) g->print(g->ctx, "\n", 1); \ } else if (g->state[g->depth] == yajl_gen_map_val) { \ g->print(g->ctx, ":", 1); \ if (g->pretty) g->print(g->ctx, " ", 1); \ } #define INSERT_WHITESPACE \ if (g->pretty) { \ if (g->state[g->depth] != yajl_gen_map_val) { \ unsigned int _i; \ for (_i=0;_idepth;_i++) \ g->print(g->ctx, g->indentString, \ strlen(g->indentString)); \ } \ } #define ENSURE_NOT_KEY \ if (g->state[g->depth] == yajl_gen_map_key) { \ return yajl_gen_keys_must_be_strings; \ } \ /* check that we're not complete, or in error state. in a valid state * to be generating */ #define ENSURE_VALID_STATE \ if (g->state[g->depth] == yajl_gen_error) { \ return yajl_gen_in_error_state;\ } else if (g->state[g->depth] == yajl_gen_complete) { \ return yajl_gen_generation_complete; \ } #define INCREMENT_DEPTH \ if (++(g->depth) >= YAJL_MAX_DEPTH) return yajl_max_depth_exceeded; #define APPENDED_ATOM \ switch (g->state[g->depth]) { \ case yajl_gen_start: \ g->state[g->depth] = yajl_gen_complete; \ break; \ case yajl_gen_map_start: \ case yajl_gen_map_key: \ g->state[g->depth] = yajl_gen_map_val; \ break; \ case yajl_gen_array_start: \ g->state[g->depth] = yajl_gen_in_array; \ break; \ case yajl_gen_map_val: \ g->state[g->depth] = yajl_gen_map_key; \ break; \ default: \ break; \ } \ #define FINAL_NEWLINE \ if (g->pretty && g->state[g->depth] == yajl_gen_complete) \ g->print(g->ctx, "\n", 1); yajl_gen_status yajl_gen_integer(yajl_gen g, long int number) { char i[32]; ENSURE_VALID_STATE; ENSURE_NOT_KEY; INSERT_SEP; INSERT_WHITESPACE; sprintf(i, "%ld", number); g->print(g->ctx, i, strlen(i)); APPENDED_ATOM; FINAL_NEWLINE; return yajl_gen_status_ok; } #if defined(_WIN32) || defined(WIN32) || defined(__WIN32__) #include #define isnan _isnan #define isinf !_finite #endif yajl_gen_status yajl_gen_double(yajl_gen g, double number) { char i[32]; ENSURE_VALID_STATE; ENSURE_NOT_KEY; if (isnan(number) || isinf(number)) return yajl_gen_invalid_number; INSERT_SEP; INSERT_WHITESPACE; sprintf(i, "%g", number); g->print(g->ctx, i, strlen(i)); APPENDED_ATOM; FINAL_NEWLINE; return yajl_gen_status_ok; } yajl_gen_status yajl_gen_number(yajl_gen g, const char * s, unsigned int l) { ENSURE_VALID_STATE; ENSURE_NOT_KEY; INSERT_SEP; INSERT_WHITESPACE; g->print(g->ctx, s, l); APPENDED_ATOM; FINAL_NEWLINE; return yajl_gen_status_ok; } yajl_gen_status yajl_gen_string(yajl_gen g, const unsigned char * str, unsigned int len) { ENSURE_VALID_STATE; INSERT_SEP; INSERT_WHITESPACE; g->print(g->ctx, "\"", 1); yajl_string_encode2(g->print, g->ctx, str, len); g->print(g->ctx, "\"", 1); APPENDED_ATOM; FINAL_NEWLINE; return yajl_gen_status_ok; } yajl_gen_status yajl_gen_null(yajl_gen g) { ENSURE_VALID_STATE; ENSURE_NOT_KEY; INSERT_SEP; INSERT_WHITESPACE; g->print(g->ctx, "null", strlen("null")); APPENDED_ATOM; FINAL_NEWLINE; return yajl_gen_status_ok; } yajl_gen_status yajl_gen_bool(yajl_gen g, int boolean) { const char * val = boolean ? "true" : "false"; ENSURE_VALID_STATE; ENSURE_NOT_KEY; INSERT_SEP; INSERT_WHITESPACE; g->print(g->ctx, val, strlen(val)); APPENDED_ATOM; FINAL_NEWLINE; return yajl_gen_status_ok; } yajl_gen_status yajl_gen_map_open(yajl_gen g) { ENSURE_VALID_STATE; ENSURE_NOT_KEY; INSERT_SEP; INSERT_WHITESPACE; INCREMENT_DEPTH; g->state[g->depth] = yajl_gen_map_start; g->print(g->ctx, "{", 1); if (g->pretty) g->print(g->ctx, "\n", 1); FINAL_NEWLINE; return yajl_gen_status_ok; } yajl_gen_status yajl_gen_map_close(yajl_gen g) { ENSURE_VALID_STATE; (g->depth)--; if (g->pretty) g->print(g->ctx, "\n", 1); APPENDED_ATOM; INSERT_WHITESPACE; g->print(g->ctx, "}", 1); FINAL_NEWLINE; return yajl_gen_status_ok; } yajl_gen_status yajl_gen_array_open(yajl_gen g) { ENSURE_VALID_STATE; ENSURE_NOT_KEY; INSERT_SEP; INSERT_WHITESPACE; INCREMENT_DEPTH; g->state[g->depth] = yajl_gen_array_start; g->print(g->ctx, "[", 1); if (g->pretty) g->print(g->ctx, "\n", 1); FINAL_NEWLINE; return yajl_gen_status_ok; } yajl_gen_status yajl_gen_array_close(yajl_gen g) { ENSURE_VALID_STATE; if (g->pretty) g->print(g->ctx, "\n", 1); (g->depth)--; APPENDED_ATOM; INSERT_WHITESPACE; g->print(g->ctx, "]", 1); FINAL_NEWLINE; return yajl_gen_status_ok; } yajl_gen_status yajl_gen_get_buf(yajl_gen g, const unsigned char ** buf, unsigned int * len) { if (g->print != (yajl_print_t)&yajl_buf_append) return yajl_gen_no_buf; *buf = yajl_buf_data((yajl_buf)g->ctx); *len = yajl_buf_len((yajl_buf)g->ctx); return yajl_gen_status_ok; } void yajl_gen_clear(yajl_gen g) { if (g->print == (yajl_print_t)&yajl_buf_append) yajl_buf_clear((yajl_buf)g->ctx); } apache-couchdb-1.5.0/src/ejson/yajl/yajl_gen.h0000644000175000001440000001605012230722213016061 00000000000000/* * Copyright 2010, Lloyd Hilaiel. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * 3. Neither the name of Lloyd Hilaiel nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ /** * \file yajl_gen.h * Interface to YAJL's JSON generation facilities. */ #include "yajl_common.h" #ifndef __YAJL_GEN_H__ #define __YAJL_GEN_H__ #ifdef __cplusplus extern "C" { #endif /** generator status codes */ typedef enum { /** no error */ yajl_gen_status_ok = 0, /** at a point where a map key is generated, a function other than * yajl_gen_string was called */ yajl_gen_keys_must_be_strings, /** YAJL's maximum generation depth was exceeded. see * YAJL_MAX_DEPTH */ yajl_max_depth_exceeded, /** A generator function (yajl_gen_XXX) was called while in an error * state */ yajl_gen_in_error_state, /** A complete JSON document has been generated */ yajl_gen_generation_complete, /** yajl_gen_double was passed an invalid floating point value * (infinity or NaN). */ yajl_gen_invalid_number, /** A print callback was passed in, so there is no internal * buffer to get from */ yajl_gen_no_buf } yajl_gen_status; /** an opaque handle to a generator */ typedef struct yajl_gen_t * yajl_gen; /** a callback used for "printing" the results. */ typedef void (*yajl_print_t)(void * ctx, const char * str, unsigned int len); /** configuration structure for the generator */ typedef struct { /** generate indented (beautiful) output */ unsigned int beautify; /** an opportunity to define an indent string. such as \\t or * some number of spaces. default is four spaces ' '. This * member is only relevant when beautify is true */ const char * indentString; } yajl_gen_config; /** allocate a generator handle * \param config a pointer to a structure containing parameters which * configure the behavior of the json generator * \param allocFuncs an optional pointer to a structure which allows * the client to overide the memory allocation * used by yajl. May be NULL, in which case * malloc/free/realloc will be used. * * \returns an allocated handle on success, NULL on failure (bad params) */ YAJL_API yajl_gen yajl_gen_alloc(const yajl_gen_config * config, const yajl_alloc_funcs * allocFuncs); /** allocate a generator handle that will print to the specified * callback rather than storing the results in an internal buffer. * \param callback a pointer to a printer function. May be NULL * in which case, the results will be store in an * internal buffer. * \param config a pointer to a structure containing parameters * which configure the behavior of the json * generator. * \param allocFuncs an optional pointer to a structure which allows * the client to overide the memory allocation * used by yajl. May be NULL, in which case * malloc/free/realloc will be used. * \param ctx a context pointer that will be passed to the * printer callback. * * \returns an allocated handle on success, NULL on failure (bad params) */ YAJL_API yajl_gen yajl_gen_alloc2(const yajl_print_t callback, const yajl_gen_config * config, const yajl_alloc_funcs * allocFuncs, void * ctx); /** free a generator handle */ YAJL_API void yajl_gen_free(yajl_gen handle); YAJL_API yajl_gen_status yajl_gen_integer(yajl_gen hand, long int number); /** generate a floating point number. number may not be infinity or * NaN, as these have no representation in JSON. In these cases the * generator will return 'yajl_gen_invalid_number' */ YAJL_API yajl_gen_status yajl_gen_double(yajl_gen hand, double number); YAJL_API yajl_gen_status yajl_gen_number(yajl_gen hand, const char * num, unsigned int len); YAJL_API yajl_gen_status yajl_gen_string(yajl_gen hand, const unsigned char * str, unsigned int len); YAJL_API yajl_gen_status yajl_gen_null(yajl_gen hand); YAJL_API yajl_gen_status yajl_gen_bool(yajl_gen hand, int boolean); YAJL_API yajl_gen_status yajl_gen_map_open(yajl_gen hand); YAJL_API yajl_gen_status yajl_gen_map_close(yajl_gen hand); YAJL_API yajl_gen_status yajl_gen_array_open(yajl_gen hand); YAJL_API yajl_gen_status yajl_gen_array_close(yajl_gen hand); /** access the null terminated generator buffer. If incrementally * outputing JSON, one should call yajl_gen_clear to clear the * buffer. This allows stream generation. */ YAJL_API yajl_gen_status yajl_gen_get_buf(yajl_gen hand, const unsigned char ** buf, unsigned int * len); /** clear yajl's output buffer, but maintain all internal generation * state. This function will not "reset" the generator state, and is * intended to enable incremental JSON outputing. */ YAJL_API void yajl_gen_clear(yajl_gen hand); #ifdef __cplusplus } #endif #endif apache-couchdb-1.5.0/src/ejson/yajl/yajl_lex.c0000644000175000001440000006232512230722213016101 00000000000000/* * Copyright 2010, Lloyd Hilaiel. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * 3. Neither the name of Lloyd Hilaiel nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ #include "yajl_lex.h" #include "yajl_buf.h" #include #include #include #include #ifdef YAJL_LEXER_DEBUG static const char * tokToStr(yajl_tok tok) { switch (tok) { case yajl_tok_bool: return "bool"; case yajl_tok_colon: return "colon"; case yajl_tok_comma: return "comma"; case yajl_tok_eof: return "eof"; case yajl_tok_error: return "error"; case yajl_tok_left_brace: return "brace"; case yajl_tok_left_bracket: return "bracket"; case yajl_tok_null: return "null"; case yajl_tok_integer: return "integer"; case yajl_tok_double: return "double"; case yajl_tok_right_brace: return "brace"; case yajl_tok_right_bracket: return "bracket"; case yajl_tok_string: return "string"; case yajl_tok_string_with_escapes: return "string_with_escapes"; } return "unknown"; } #endif /* Impact of the stream parsing feature on the lexer: * * YAJL support stream parsing. That is, the ability to parse the first * bits of a chunk of JSON before the last bits are available (still on * the network or disk). This makes the lexer more complex. The * responsibility of the lexer is to handle transparently the case where * a chunk boundary falls in the middle of a token. This is * accomplished is via a buffer and a character reading abstraction. * * Overview of implementation * * When we lex to end of input string before end of token is hit, we * copy all of the input text composing the token into our lexBuf. * * Every time we read a character, we do so through the readChar function. * readChar's responsibility is to handle pulling all chars from the buffer * before pulling chars from input text */ struct yajl_lexer_t { /* the overal line and char offset into the data */ unsigned int lineOff; unsigned int charOff; /* error */ yajl_lex_error error; /* a input buffer to handle the case where a token is spread over * multiple chunks */ yajl_buf buf; /* in the case where we have data in the lexBuf, bufOff holds * the current offset into the lexBuf. */ unsigned int bufOff; /* are we using the lex buf? */ unsigned int bufInUse; /* shall we allow comments? */ unsigned int allowComments; /* shall we validate utf8 inside strings? */ unsigned int validateUTF8; yajl_alloc_funcs * alloc; }; #define readChar(lxr, txt, off) \ (((lxr)->bufInUse && yajl_buf_len((lxr)->buf) && lxr->bufOff < yajl_buf_len((lxr)->buf)) ? \ (*((const unsigned char *) yajl_buf_data((lxr)->buf) + ((lxr)->bufOff)++)) : \ ((txt)[(*(off))++])) #define unreadChar(lxr, off) ((*(off) > 0) ? (*(off))-- : ((lxr)->bufOff--)) yajl_lexer yajl_lex_alloc(yajl_alloc_funcs * alloc, unsigned int allowComments, unsigned int validateUTF8) { yajl_lexer lxr = (yajl_lexer) YA_MALLOC(alloc, sizeof(struct yajl_lexer_t)); memset((void *) lxr, 0, sizeof(struct yajl_lexer_t)); lxr->buf = yajl_buf_alloc(alloc); lxr->allowComments = allowComments; lxr->validateUTF8 = validateUTF8; lxr->alloc = alloc; return lxr; } void yajl_lex_free(yajl_lexer lxr) { yajl_buf_free(lxr->buf); YA_FREE(lxr->alloc, lxr); return; } /* a lookup table which lets us quickly determine three things: * VEC - valid escaped conrol char * IJC - invalid json char * VHC - valid hex char * note. the solidus '/' may be escaped or not. * note. the */ #define VEC 1 #define IJC 2 #define VHC 4 static const char charLookupTable[256] = { /*00*/ IJC , IJC , IJC , IJC , IJC , IJC , IJC , IJC , /*08*/ IJC , IJC , IJC , IJC , IJC , IJC , IJC , IJC , /*10*/ IJC , IJC , IJC , IJC , IJC , IJC , IJC , IJC , /*18*/ IJC , IJC , IJC , IJC , IJC , IJC , IJC , IJC , /*20*/ 0 , 0 , VEC|IJC, 0 , 0 , 0 , 0 , 0 , /*28*/ 0 , 0 , 0 , 0 , 0 , 0 , 0 , VEC , /*30*/ VHC , VHC , VHC , VHC , VHC , VHC , VHC , VHC , /*38*/ VHC , VHC , 0 , 0 , 0 , 0 , 0 , 0 , /*40*/ 0 , VHC , VHC , VHC , VHC , VHC , VHC , 0 , /*48*/ 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , /*50*/ 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , /*58*/ 0 , 0 , 0 , 0 , VEC|IJC, 0 , 0 , 0 , /*60*/ 0 , VHC , VEC|VHC, VHC , VHC , VHC , VEC|VHC, 0 , /*68*/ 0 , 0 , 0 , 0 , 0 , 0 , VEC , 0 , /*70*/ 0 , 0 , VEC , 0 , VEC , 0 , 0 , 0 , /*78*/ 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , /* include these so we don't have to always check the range of the char */ 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 }; /** process a variable length utf8 encoded codepoint. * * returns: * yajl_tok_string - if valid utf8 char was parsed and offset was * advanced * yajl_tok_eof - if end of input was hit before validation could * complete * yajl_tok_error - if invalid utf8 was encountered * * NOTE: on error the offset will point to the first char of the * invalid utf8 */ #define UTF8_CHECK_EOF if (*offset >= jsonTextLen) { return yajl_tok_eof; } static yajl_tok yajl_lex_utf8_char(yajl_lexer lexer, const unsigned char * jsonText, unsigned int jsonTextLen, unsigned int * offset, unsigned char curChar) { if (curChar <= 0x7f) { /* single byte */ return yajl_tok_string; } else if ((curChar >> 5) == 0x6) { /* two byte */ UTF8_CHECK_EOF; curChar = readChar(lexer, jsonText, offset); if ((curChar >> 6) == 0x2) return yajl_tok_string; } else if ((curChar >> 4) == 0x0e) { /* three byte */ UTF8_CHECK_EOF; curChar = readChar(lexer, jsonText, offset); if ((curChar >> 6) == 0x2) { UTF8_CHECK_EOF; curChar = readChar(lexer, jsonText, offset); if ((curChar >> 6) == 0x2) return yajl_tok_string; } } else if ((curChar >> 3) == 0x1e) { /* four byte */ UTF8_CHECK_EOF; curChar = readChar(lexer, jsonText, offset); if ((curChar >> 6) == 0x2) { UTF8_CHECK_EOF; curChar = readChar(lexer, jsonText, offset); if ((curChar >> 6) == 0x2) { UTF8_CHECK_EOF; curChar = readChar(lexer, jsonText, offset); if ((curChar >> 6) == 0x2) return yajl_tok_string; } } } return yajl_tok_error; } /* lex a string. input is the lexer, pointer to beginning of * json text, and start of string (offset). * a token is returned which has the following meanings: * yajl_tok_string: lex of string was successful. offset points to * terminating '"'. * yajl_tok_eof: end of text was encountered before we could complete * the lex. * yajl_tok_error: embedded in the string were unallowable chars. offset * points to the offending char */ #define STR_CHECK_EOF \ if (*offset >= jsonTextLen) { \ tok = yajl_tok_eof; \ goto finish_string_lex; \ } static yajl_tok yajl_lex_string(yajl_lexer lexer, const unsigned char * jsonText, unsigned int jsonTextLen, unsigned int * offset) { yajl_tok tok = yajl_tok_error; int hasEscapes = 0; for (;;) { unsigned char curChar; STR_CHECK_EOF; curChar = readChar(lexer, jsonText, offset); /* quote terminates */ if (curChar == '"') { tok = yajl_tok_string; break; } /* backslash escapes a set of control chars, */ else if (curChar == '\\') { hasEscapes = 1; STR_CHECK_EOF; /* special case \u */ curChar = readChar(lexer, jsonText, offset); if (curChar == 'u') { unsigned int i = 0; for (i=0;i<4;i++) { STR_CHECK_EOF; curChar = readChar(lexer, jsonText, offset); if (!(charLookupTable[curChar] & VHC)) { /* back up to offending char */ unreadChar(lexer, offset); lexer->error = yajl_lex_string_invalid_hex_char; goto finish_string_lex; } } } else if (!(charLookupTable[curChar] & VEC)) { /* back up to offending char */ unreadChar(lexer, offset); lexer->error = yajl_lex_string_invalid_escaped_char; goto finish_string_lex; } } /* when not validating UTF8 it's a simple table lookup to determine * if the present character is invalid */ else if(charLookupTable[curChar] & IJC) { /* back up to offending char */ unreadChar(lexer, offset); lexer->error = yajl_lex_string_invalid_json_char; goto finish_string_lex; } /* when in validate UTF8 mode we need to do some extra work */ else if (lexer->validateUTF8) { yajl_tok t = yajl_lex_utf8_char(lexer, jsonText, jsonTextLen, offset, curChar); if (t == yajl_tok_eof) { tok = yajl_tok_eof; goto finish_string_lex; } else if (t == yajl_tok_error) { lexer->error = yajl_lex_string_invalid_utf8; goto finish_string_lex; } } /* accept it, and move on */ } finish_string_lex: /* tell our buddy, the parser, wether he needs to process this string * again */ if (hasEscapes && tok == yajl_tok_string) { tok = yajl_tok_string_with_escapes; } return tok; } #define RETURN_IF_EOF if (*offset >= jsonTextLen) return yajl_tok_eof; static yajl_tok yajl_lex_number(yajl_lexer lexer, const unsigned char * jsonText, unsigned int jsonTextLen, unsigned int * offset) { /** XXX: numbers are the only entities in json that we must lex * _beyond_ in order to know that they are complete. There * is an ambiguous case for integers at EOF. */ unsigned char c; yajl_tok tok = yajl_tok_integer; RETURN_IF_EOF; c = readChar(lexer, jsonText, offset); /* optional leading minus */ if (c == '-') { RETURN_IF_EOF; c = readChar(lexer, jsonText, offset); } /* a single zero, or a series of integers */ if (c == '0') { RETURN_IF_EOF; c = readChar(lexer, jsonText, offset); } else if (c >= '1' && c <= '9') { do { RETURN_IF_EOF; c = readChar(lexer, jsonText, offset); } while (c >= '0' && c <= '9'); } else { unreadChar(lexer, offset); lexer->error = yajl_lex_missing_integer_after_minus; return yajl_tok_error; } /* optional fraction (indicates this is floating point) */ if (c == '.') { int numRd = 0; RETURN_IF_EOF; c = readChar(lexer, jsonText, offset); while (c >= '0' && c <= '9') { numRd++; RETURN_IF_EOF; c = readChar(lexer, jsonText, offset); } if (!numRd) { unreadChar(lexer, offset); lexer->error = yajl_lex_missing_integer_after_decimal; return yajl_tok_error; } tok = yajl_tok_double; } /* optional exponent (indicates this is floating point) */ if (c == 'e' || c == 'E') { RETURN_IF_EOF; c = readChar(lexer, jsonText, offset); /* optional sign */ if (c == '+' || c == '-') { RETURN_IF_EOF; c = readChar(lexer, jsonText, offset); } if (c >= '0' && c <= '9') { do { RETURN_IF_EOF; c = readChar(lexer, jsonText, offset); } while (c >= '0' && c <= '9'); } else { unreadChar(lexer, offset); lexer->error = yajl_lex_missing_integer_after_exponent; return yajl_tok_error; } tok = yajl_tok_double; } /* we always go "one too far" */ unreadChar(lexer, offset); return tok; } static yajl_tok yajl_lex_comment(yajl_lexer lexer, const unsigned char * jsonText, unsigned int jsonTextLen, unsigned int * offset) { unsigned char c; yajl_tok tok = yajl_tok_comment; RETURN_IF_EOF; c = readChar(lexer, jsonText, offset); /* either slash or star expected */ if (c == '/') { /* now we throw away until end of line */ do { RETURN_IF_EOF; c = readChar(lexer, jsonText, offset); } while (c != '\n'); } else if (c == '*') { /* now we throw away until end of comment */ for (;;) { RETURN_IF_EOF; c = readChar(lexer, jsonText, offset); if (c == '*') { RETURN_IF_EOF; c = readChar(lexer, jsonText, offset); if (c == '/') { break; } else { unreadChar(lexer, offset); } } } } else { lexer->error = yajl_lex_invalid_char; tok = yajl_tok_error; } return tok; } yajl_tok yajl_lex_lex(yajl_lexer lexer, const unsigned char * jsonText, unsigned int jsonTextLen, unsigned int * offset, const unsigned char ** outBuf, unsigned int * outLen) { yajl_tok tok = yajl_tok_error; unsigned char c; unsigned int startOffset = *offset; *outBuf = NULL; *outLen = 0; for (;;) { assert(*offset <= jsonTextLen); if (*offset >= jsonTextLen) { tok = yajl_tok_eof; goto lexed; } c = readChar(lexer, jsonText, offset); switch (c) { case '{': tok = yajl_tok_left_bracket; goto lexed; case '}': tok = yajl_tok_right_bracket; goto lexed; case '[': tok = yajl_tok_left_brace; goto lexed; case ']': tok = yajl_tok_right_brace; goto lexed; case ',': tok = yajl_tok_comma; goto lexed; case ':': tok = yajl_tok_colon; goto lexed; case '\t': case '\n': case '\v': case '\f': case '\r': case ' ': startOffset++; break; case 't': { const char * want = "rue"; do { if (*offset >= jsonTextLen) { tok = yajl_tok_eof; goto lexed; } c = readChar(lexer, jsonText, offset); if (c != *want) { unreadChar(lexer, offset); lexer->error = yajl_lex_invalid_string; tok = yajl_tok_error; goto lexed; } } while (*(++want)); tok = yajl_tok_bool; goto lexed; } case 'f': { const char * want = "alse"; do { if (*offset >= jsonTextLen) { tok = yajl_tok_eof; goto lexed; } c = readChar(lexer, jsonText, offset); if (c != *want) { unreadChar(lexer, offset); lexer->error = yajl_lex_invalid_string; tok = yajl_tok_error; goto lexed; } } while (*(++want)); tok = yajl_tok_bool; goto lexed; } case 'n': { const char * want = "ull"; do { if (*offset >= jsonTextLen) { tok = yajl_tok_eof; goto lexed; } c = readChar(lexer, jsonText, offset); if (c != *want) { unreadChar(lexer, offset); lexer->error = yajl_lex_invalid_string; tok = yajl_tok_error; goto lexed; } } while (*(++want)); tok = yajl_tok_null; goto lexed; } case '"': { tok = yajl_lex_string(lexer, (const unsigned char *) jsonText, jsonTextLen, offset); goto lexed; } case '-': case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': { /* integer parsing wants to start from the beginning */ unreadChar(lexer, offset); tok = yajl_lex_number(lexer, (const unsigned char *) jsonText, jsonTextLen, offset); goto lexed; } case '/': /* hey, look, a probable comment! If comments are disabled * it's an error. */ if (!lexer->allowComments) { unreadChar(lexer, offset); lexer->error = yajl_lex_unallowed_comment; tok = yajl_tok_error; goto lexed; } /* if comments are enabled, then we should try to lex * the thing. possible outcomes are * - successful lex (tok_comment, which means continue), * - malformed comment opening (slash not followed by * '*' or '/') (tok_error) * - eof hit. (tok_eof) */ tok = yajl_lex_comment(lexer, (const unsigned char *) jsonText, jsonTextLen, offset); if (tok == yajl_tok_comment) { /* "error" is silly, but that's the initial * state of tok. guilty until proven innocent. */ tok = yajl_tok_error; yajl_buf_clear(lexer->buf); lexer->bufInUse = 0; startOffset = *offset; break; } /* hit error or eof, bail */ goto lexed; default: lexer->error = yajl_lex_invalid_char; tok = yajl_tok_error; goto lexed; } } lexed: /* need to append to buffer if the buffer is in use or * if it's an EOF token */ if (tok == yajl_tok_eof || lexer->bufInUse) { if (!lexer->bufInUse) yajl_buf_clear(lexer->buf); lexer->bufInUse = 1; yajl_buf_append(lexer->buf, jsonText + startOffset, *offset - startOffset); lexer->bufOff = 0; if (tok != yajl_tok_eof) { *outBuf = yajl_buf_data(lexer->buf); *outLen = yajl_buf_len(lexer->buf); lexer->bufInUse = 0; } } else if (tok != yajl_tok_error) { *outBuf = jsonText + startOffset; *outLen = *offset - startOffset; } /* special case for strings. skip the quotes. */ if (tok == yajl_tok_string || tok == yajl_tok_string_with_escapes) { assert(*outLen >= 2); (*outBuf)++; *outLen -= 2; } #ifdef YAJL_LEXER_DEBUG if (tok == yajl_tok_error) { printf("lexical error: %s\n", yajl_lex_error_to_string(yajl_lex_get_error(lexer))); } else if (tok == yajl_tok_eof) { printf("EOF hit\n"); } else { printf("lexed %s: '", tokToStr(tok)); fwrite(*outBuf, 1, *outLen, stdout); printf("'\n"); } #endif return tok; } const char * yajl_lex_error_to_string(yajl_lex_error error) { switch (error) { case yajl_lex_e_ok: return "ok, no error"; case yajl_lex_string_invalid_utf8: return "invalid bytes in UTF8 string."; case yajl_lex_string_invalid_escaped_char: return "inside a string, '\\' occurs before a character " "which it may not."; case yajl_lex_string_invalid_json_char: return "invalid character inside string."; case yajl_lex_string_invalid_hex_char: return "invalid (non-hex) character occurs after '\\u' inside " "string."; case yajl_lex_invalid_char: return "invalid char in json text."; case yajl_lex_invalid_string: return "invalid string in json text."; case yajl_lex_missing_integer_after_exponent: return "malformed number, a digit is required after the exponent."; case yajl_lex_missing_integer_after_decimal: return "malformed number, a digit is required after the " "decimal point."; case yajl_lex_missing_integer_after_minus: return "malformed number, a digit is required after the " "minus sign."; case yajl_lex_unallowed_comment: return "probable comment found in input text, comments are " "not enabled."; } return "unknown error code"; } /** allows access to more specific information about the lexical * error when yajl_lex_lex returns yajl_tok_error. */ yajl_lex_error yajl_lex_get_error(yajl_lexer lexer) { if (lexer == NULL) return (yajl_lex_error) -1; return lexer->error; } unsigned int yajl_lex_current_line(yajl_lexer lexer) { return lexer->lineOff; } unsigned int yajl_lex_current_char(yajl_lexer lexer) { return lexer->charOff; } yajl_tok yajl_lex_peek(yajl_lexer lexer, const unsigned char * jsonText, unsigned int jsonTextLen, unsigned int offset) { const unsigned char * outBuf; unsigned int outLen; unsigned int bufLen = yajl_buf_len(lexer->buf); unsigned int bufOff = lexer->bufOff; unsigned int bufInUse = lexer->bufInUse; yajl_tok tok; tok = yajl_lex_lex(lexer, jsonText, jsonTextLen, &offset, &outBuf, &outLen); lexer->bufOff = bufOff; lexer->bufInUse = bufInUse; yajl_buf_truncate(lexer->buf, bufLen); return tok; } apache-couchdb-1.5.0/src/ejson/yajl/yajl_lex.h0000644000175000001440000001157712230722213016111 00000000000000/* * Copyright 2010, Lloyd Hilaiel. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * 3. Neither the name of Lloyd Hilaiel nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ #ifndef __YAJL_LEX_H__ #define __YAJL_LEX_H__ #include "yajl_common.h" typedef enum { yajl_tok_bool, yajl_tok_colon, yajl_tok_comma, yajl_tok_eof, yajl_tok_error, yajl_tok_left_brace, yajl_tok_left_bracket, yajl_tok_null, yajl_tok_right_brace, yajl_tok_right_bracket, /* we differentiate between integers and doubles to allow the * parser to interpret the number without re-scanning */ yajl_tok_integer, yajl_tok_double, /* we differentiate between strings which require further processing, * and strings that do not */ yajl_tok_string, yajl_tok_string_with_escapes, /* comment tokens are not currently returned to the parser, ever */ yajl_tok_comment } yajl_tok; typedef struct yajl_lexer_t * yajl_lexer; yajl_lexer yajl_lex_alloc(yajl_alloc_funcs * alloc, unsigned int allowComments, unsigned int validateUTF8); void yajl_lex_free(yajl_lexer lexer); /** * run/continue a lex. "offset" is an input/output parameter. * It should be initialized to zero for a * new chunk of target text, and upon subsetquent calls with the same * target text should passed with the value of the previous invocation. * * the client may be interested in the value of offset when an error is * returned from the lexer. This allows the client to render useful n * error messages. * * When you pass the next chunk of data, context should be reinitialized * to zero. * * Finally, the output buffer is usually just a pointer into the jsonText, * however in cases where the entity being lexed spans multiple chunks, * the lexer will buffer the entity and the data returned will be * a pointer into that buffer. * * This behavior is abstracted from client code except for the performance * implications which require that the client choose a reasonable chunk * size to get adequate performance. */ yajl_tok yajl_lex_lex(yajl_lexer lexer, const unsigned char * jsonText, unsigned int jsonTextLen, unsigned int * offset, const unsigned char ** outBuf, unsigned int * outLen); /** have a peek at the next token, but don't move the lexer forward */ yajl_tok yajl_lex_peek(yajl_lexer lexer, const unsigned char * jsonText, unsigned int jsonTextLen, unsigned int offset); typedef enum { yajl_lex_e_ok = 0, yajl_lex_string_invalid_utf8, yajl_lex_string_invalid_escaped_char, yajl_lex_string_invalid_json_char, yajl_lex_string_invalid_hex_char, yajl_lex_invalid_char, yajl_lex_invalid_string, yajl_lex_missing_integer_after_decimal, yajl_lex_missing_integer_after_exponent, yajl_lex_missing_integer_after_minus, yajl_lex_unallowed_comment } yajl_lex_error; const char * yajl_lex_error_to_string(yajl_lex_error error); /** allows access to more specific information about the lexical * error when yajl_lex_lex returns yajl_tok_error. */ yajl_lex_error yajl_lex_get_error(yajl_lexer lexer); /** get the current offset into the most recently lexed json string. */ unsigned int yajl_lex_current_offset(yajl_lexer lexer); /** get the number of lines lexed by this lexer instance */ unsigned int yajl_lex_current_line(yajl_lexer lexer); /** get the number of chars lexed by this lexer instance since the last * \n or \r */ unsigned int yajl_lex_current_char(yajl_lexer lexer); #endif apache-couchdb-1.5.0/src/ejson/yajl/yajl_parser.c0000644000175000001440000005062312230722213016603 00000000000000/* * Copyright 2010, Lloyd Hilaiel. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * 3. Neither the name of Lloyd Hilaiel nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ #include "yajl_lex.h" #include "yajl_parser.h" #include "yajl_encode.h" #include "yajl_bytestack.h" #include #include #include #include #include #include #include #include const char * yajl_parser_error_to_string(yajl_parser_error error) { switch (error) { case yajl_parser_e_ok: return "ok, no error"; case yajl_parser_client_cancelled: return "client cancelled parse via callback return value"; case yajl_parser_integer_overflow: return "integer overflow"; case yajl_parser_numeric_overflow: return "numeric (floating point) overflow"; case yajl_parser_invalid_token: return "unallowed token at this point in JSON text"; case yajl_parser_internal_invalid_token: return "invalid token, internal error"; case yajl_parser_key_must_be_string: return "invalid object key (must be a string)"; case yajl_parser_pair_missing_colon: return "object key and value must be separated by a colon (':')"; case yajl_parser_bad_token_after_map_value: return "after key and value, inside map, I expect ',' or '}'"; case yajl_parser_bad_token_after_array_value: return "after array element, I expect ',' or ']'"; } return "unknown error code"; } unsigned char * yajl_render_error_string(yajl_handle hand, const unsigned char * jsonText, unsigned int jsonTextLen, int verbose) { unsigned int offset = hand->bytesConsumed; unsigned char * str; const char * errorType = NULL; const char * errorText = NULL; char text[72]; const char * arrow = " (right here) ------^\n"; if (yajl_bs_current(hand->stateStack) == yajl_state_parse_error) { errorType = "parse"; errorText = yajl_parser_error_to_string(hand->parserError); } else if (yajl_bs_current(hand->stateStack) == yajl_state_lexical_error) { errorType = "lexical"; errorText = yajl_lex_error_to_string(yajl_lex_get_error(hand->lexer)); } else { errorType = "unknown"; } { unsigned int memneeded = 0; memneeded += strlen(errorType); memneeded += strlen(" error"); if (errorText != NULL) { memneeded += strlen(": "); memneeded += strlen(errorText); } str = (unsigned char *) YA_MALLOC(&(hand->alloc), memneeded + 2); str[0] = 0; strcat((char *) str, errorType); strcat((char *) str, " error"); if (errorText != NULL) { strcat((char *) str, ": "); strcat((char *) str, errorText); } strcat((char *) str, "\n"); } /* now we append as many spaces as needed to make sure the error * falls at char 41, if verbose was specified */ if (verbose) { unsigned int start, end, i; unsigned int spacesNeeded; spacesNeeded = (offset < 30 ? 40 - offset : 10); start = (offset >= 30 ? offset - 30 : 0); end = (offset + 30 > jsonTextLen ? jsonTextLen : offset + 30); for (i=0;ialloc), (strlen((char *) str) + strlen((char *) text) + strlen(arrow) + 1)); newStr[0] = 0; strcat((char *) newStr, (char *) str); strcat((char *) newStr, text); strcat((char *) newStr, arrow); YA_FREE(&(hand->alloc), str); str = (unsigned char *) newStr; } } return str; } /* check for client cancelation */ #define _CC_CHK(x) \ if (!(x)) { \ yajl_bs_set(hand->stateStack, yajl_state_parse_error); \ hand->parserError = yajl_parser_client_cancelled; \ return yajl_status_client_canceled; \ } yajl_status yajl_do_parse(yajl_handle hand, const unsigned char * jsonText, unsigned int jsonTextLen) { yajl_tok tok; const unsigned char * buf; unsigned int bufLen; unsigned int * offset = &(hand->bytesConsumed); *offset = 0; around_again: switch (yajl_bs_current(hand->stateStack)) { case yajl_state_parse_complete: return yajl_status_ok; case yajl_state_lexical_error: case yajl_state_parse_error: return yajl_status_error; case yajl_state_start: case yajl_state_map_need_val: case yajl_state_array_need_val: case yajl_state_array_start: { /* for arrays and maps, we advance the state for this * depth, then push the state of the next depth. * If an error occurs during the parsing of the nesting * enitity, the state at this level will not matter. * a state that needs pushing will be anything other * than state_start */ yajl_state stateToPush = yajl_state_start; tok = yajl_lex_lex(hand->lexer, jsonText, jsonTextLen, offset, &buf, &bufLen); switch (tok) { case yajl_tok_eof: return yajl_status_insufficient_data; case yajl_tok_error: yajl_bs_set(hand->stateStack, yajl_state_lexical_error); goto around_again; case yajl_tok_string: if (hand->callbacks && hand->callbacks->yajl_string) { _CC_CHK(hand->callbacks->yajl_string(hand->ctx, buf, bufLen)); } break; case yajl_tok_string_with_escapes: if (hand->callbacks && hand->callbacks->yajl_string) { yajl_buf_clear(hand->decodeBuf); yajl_string_decode(hand->decodeBuf, buf, bufLen); _CC_CHK(hand->callbacks->yajl_string( hand->ctx, yajl_buf_data(hand->decodeBuf), yajl_buf_len(hand->decodeBuf))); } break; case yajl_tok_bool: if (hand->callbacks && hand->callbacks->yajl_boolean) { _CC_CHK(hand->callbacks->yajl_boolean(hand->ctx, *buf == 't')); } break; case yajl_tok_null: if (hand->callbacks && hand->callbacks->yajl_null) { _CC_CHK(hand->callbacks->yajl_null(hand->ctx)); } break; case yajl_tok_left_bracket: if (hand->callbacks && hand->callbacks->yajl_start_map) { _CC_CHK(hand->callbacks->yajl_start_map(hand->ctx)); } stateToPush = yajl_state_map_start; break; case yajl_tok_left_brace: if (hand->callbacks && hand->callbacks->yajl_start_array) { _CC_CHK(hand->callbacks->yajl_start_array(hand->ctx)); } stateToPush = yajl_state_array_start; break; case yajl_tok_integer: /* * note. strtol does not respect the length of * the lexical token. in a corner case where the * lexed number is a integer with a trailing zero, * immediately followed by the end of buffer, * sscanf could run off into oblivion and cause a * crash. for this reason we copy the integer * (and doubles), into our parse buffer (the same * one used for unescaping strings), before * calling strtol. yajl_buf ensures null padding, * so we're safe. */ if (hand->callbacks) { if (hand->callbacks->yajl_number) { _CC_CHK(hand->callbacks->yajl_number( hand->ctx,(const char *) buf, bufLen)); } else if (hand->callbacks->yajl_integer) { long int i = 0; yajl_buf_clear(hand->decodeBuf); yajl_buf_append(hand->decodeBuf, buf, bufLen); buf = yajl_buf_data(hand->decodeBuf); i = strtol((const char *) buf, NULL, 10); if ((i == LONG_MIN || i == LONG_MAX) && errno == ERANGE) { yajl_bs_set(hand->stateStack, yajl_state_parse_error); hand->parserError = yajl_parser_integer_overflow; /* try to restore error offset */ if (*offset >= bufLen) *offset -= bufLen; else *offset = 0; goto around_again; } _CC_CHK(hand->callbacks->yajl_integer(hand->ctx, i)); } } break; case yajl_tok_double: if (hand->callbacks) { if (hand->callbacks->yajl_number) { _CC_CHK(hand->callbacks->yajl_number( hand->ctx, (const char *) buf, bufLen)); } else if (hand->callbacks->yajl_double) { double d = 0.0; yajl_buf_clear(hand->decodeBuf); yajl_buf_append(hand->decodeBuf, buf, bufLen); buf = yajl_buf_data(hand->decodeBuf); d = strtod((char *) buf, NULL); if ((d == HUGE_VAL || d == -HUGE_VAL) && errno == ERANGE) { yajl_bs_set(hand->stateStack, yajl_state_parse_error); hand->parserError = yajl_parser_numeric_overflow; /* try to restore error offset */ if (*offset >= bufLen) *offset -= bufLen; else *offset = 0; goto around_again; } _CC_CHK(hand->callbacks->yajl_double(hand->ctx, d)); } } break; case yajl_tok_right_brace: { if (yajl_bs_current(hand->stateStack) == yajl_state_array_start) { if (hand->callbacks && hand->callbacks->yajl_end_array) { _CC_CHK(hand->callbacks->yajl_end_array(hand->ctx)); } yajl_bs_pop(hand->stateStack); goto around_again; } /* intentional fall-through */ } case yajl_tok_colon: case yajl_tok_comma: case yajl_tok_right_bracket: yajl_bs_set(hand->stateStack, yajl_state_parse_error); hand->parserError = yajl_parser_invalid_token; goto around_again; default: yajl_bs_set(hand->stateStack, yajl_state_parse_error); hand->parserError = yajl_parser_invalid_token; goto around_again; } /* got a value. transition depends on the state we're in. */ { yajl_state s = yajl_bs_current(hand->stateStack); if (s == yajl_state_start) { yajl_bs_set(hand->stateStack, yajl_state_parse_complete); } else if (s == yajl_state_map_need_val) { yajl_bs_set(hand->stateStack, yajl_state_map_got_val); } else { yajl_bs_set(hand->stateStack, yajl_state_array_got_val); } } if (stateToPush != yajl_state_start) { yajl_bs_push(hand->stateStack, stateToPush); } goto around_again; } case yajl_state_map_start: case yajl_state_map_need_key: { /* only difference between these two states is that in * start '}' is valid, whereas in need_key, we've parsed * a comma, and a string key _must_ follow */ tok = yajl_lex_lex(hand->lexer, jsonText, jsonTextLen, offset, &buf, &bufLen); switch (tok) { case yajl_tok_eof: return yajl_status_insufficient_data; case yajl_tok_error: yajl_bs_set(hand->stateStack, yajl_state_lexical_error); goto around_again; case yajl_tok_string_with_escapes: if (hand->callbacks && hand->callbacks->yajl_map_key) { yajl_buf_clear(hand->decodeBuf); yajl_string_decode(hand->decodeBuf, buf, bufLen); buf = yajl_buf_data(hand->decodeBuf); bufLen = yajl_buf_len(hand->decodeBuf); } /* intentional fall-through */ case yajl_tok_string: if (hand->callbacks && hand->callbacks->yajl_map_key) { _CC_CHK(hand->callbacks->yajl_map_key(hand->ctx, buf, bufLen)); } yajl_bs_set(hand->stateStack, yajl_state_map_sep); goto around_again; case yajl_tok_right_bracket: if (yajl_bs_current(hand->stateStack) == yajl_state_map_start) { if (hand->callbacks && hand->callbacks->yajl_end_map) { _CC_CHK(hand->callbacks->yajl_end_map(hand->ctx)); } yajl_bs_pop(hand->stateStack); goto around_again; } default: yajl_bs_set(hand->stateStack, yajl_state_parse_error); hand->parserError = yajl_parser_key_must_be_string; goto around_again; } } case yajl_state_map_sep: { tok = yajl_lex_lex(hand->lexer, jsonText, jsonTextLen, offset, &buf, &bufLen); switch (tok) { case yajl_tok_colon: yajl_bs_set(hand->stateStack, yajl_state_map_need_val); goto around_again; case yajl_tok_eof: return yajl_status_insufficient_data; case yajl_tok_error: yajl_bs_set(hand->stateStack, yajl_state_lexical_error); goto around_again; default: yajl_bs_set(hand->stateStack, yajl_state_parse_error); hand->parserError = yajl_parser_pair_missing_colon; goto around_again; } } case yajl_state_map_got_val: { tok = yajl_lex_lex(hand->lexer, jsonText, jsonTextLen, offset, &buf, &bufLen); switch (tok) { case yajl_tok_right_bracket: if (hand->callbacks && hand->callbacks->yajl_end_map) { _CC_CHK(hand->callbacks->yajl_end_map(hand->ctx)); } yajl_bs_pop(hand->stateStack); goto around_again; case yajl_tok_comma: yajl_bs_set(hand->stateStack, yajl_state_map_need_key); goto around_again; case yajl_tok_eof: return yajl_status_insufficient_data; case yajl_tok_error: yajl_bs_set(hand->stateStack, yajl_state_lexical_error); goto around_again; default: yajl_bs_set(hand->stateStack, yajl_state_parse_error); hand->parserError = yajl_parser_bad_token_after_map_value; /* try to restore error offset */ if (*offset >= bufLen) *offset -= bufLen; else *offset = 0; goto around_again; } } case yajl_state_array_got_val: { tok = yajl_lex_lex(hand->lexer, jsonText, jsonTextLen, offset, &buf, &bufLen); switch (tok) { case yajl_tok_right_brace: if (hand->callbacks && hand->callbacks->yajl_end_array) { _CC_CHK(hand->callbacks->yajl_end_array(hand->ctx)); } yajl_bs_pop(hand->stateStack); goto around_again; case yajl_tok_comma: yajl_bs_set(hand->stateStack, yajl_state_array_need_val); goto around_again; case yajl_tok_eof: return yajl_status_insufficient_data; case yajl_tok_error: yajl_bs_set(hand->stateStack, yajl_state_lexical_error); goto around_again; default: yajl_bs_set(hand->stateStack, yajl_state_parse_error); hand->parserError = yajl_parser_bad_token_after_array_value; goto around_again; } } } abort(); return yajl_status_error; } apache-couchdb-1.5.0/src/ejson/yajl/yajl_parser.h0000644000175000001440000000640012230722213016602 00000000000000/* * Copyright 2010, Lloyd Hilaiel. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * 3. Neither the name of Lloyd Hilaiel nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ #ifndef __YAJL_PARSER_H__ #define __YAJL_PARSER_H__ #include "yajl_parse.h" #include "yajl_bytestack.h" #include "yajl_buf.h" #include "yajl_lex.h" typedef enum { yajl_state_start = 0, yajl_state_parse_complete, yajl_state_parse_error, yajl_state_lexical_error, yajl_state_map_start, yajl_state_map_sep, yajl_state_map_need_val, yajl_state_map_got_val, yajl_state_map_need_key, yajl_state_array_start, yajl_state_array_got_val, yajl_state_array_need_val } yajl_state; typedef enum { yajl_parser_e_ok = 0, yajl_parser_client_cancelled, yajl_parser_integer_overflow, yajl_parser_numeric_overflow, yajl_parser_invalid_token, yajl_parser_internal_invalid_token, yajl_parser_key_must_be_string, yajl_parser_pair_missing_colon, yajl_parser_bad_token_after_map_value, yajl_parser_bad_token_after_array_value } yajl_parser_error; struct yajl_handle_t { const yajl_callbacks * callbacks; void * ctx; yajl_lexer lexer; yajl_parser_error parserError; /* the number of bytes consumed from the last client buffer, * in the case of an error this will be an error offset, in the * case of an error this can be used as the error offset */ unsigned int bytesConsumed; /* temporary storage for decoded strings */ yajl_buf decodeBuf; /* a stack of states. access with yajl_state_XXX routines */ yajl_bytestack stateStack; /* memory allocation routines */ yajl_alloc_funcs alloc; }; yajl_status yajl_do_parse(yajl_handle handle, const unsigned char * jsonText, unsigned int jsonTextLen); unsigned char * yajl_render_error_string(yajl_handle hand, const unsigned char * jsonText, unsigned int jsonTextLen, int verbose); #endif apache-couchdb-1.5.0/src/ejson/yajl/yajl_encode.c0000644000175000001440000001535012230722213016542 00000000000000/* * Copyright 2010, Lloyd Hilaiel. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * 3. Neither the name of Lloyd Hilaiel nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ #include "yajl_encode.h" #include #include #include #include static void CharToHex(unsigned char c, char * hexBuf) { const char * hexchar = "0123456789ABCDEF"; hexBuf[0] = hexchar[c >> 4]; hexBuf[1] = hexchar[c & 0x0F]; } void yajl_string_encode(yajl_buf buf, const unsigned char * str, unsigned int len) { yajl_string_encode2((const yajl_print_t) &yajl_buf_append, buf, str, len); } void yajl_string_encode2(const yajl_print_t print, void * ctx, const unsigned char * str, unsigned int len) { unsigned int beg = 0; unsigned int end = 0; char hexBuf[7]; hexBuf[0] = '\\'; hexBuf[1] = 'u'; hexBuf[2] = '0'; hexBuf[3] = '0'; hexBuf[6] = 0; while (end < len) { const char * escaped = NULL; switch (str[end]) { case '\r': escaped = "\\r"; break; case '\n': escaped = "\\n"; break; case '\\': escaped = "\\\\"; break; /* case '/': escaped = "\\/"; break; */ case '"': escaped = "\\\""; break; case '\f': escaped = "\\f"; break; case '\b': escaped = "\\b"; break; case '\t': escaped = "\\t"; break; default: if ((unsigned char) str[end] < 32) { CharToHex(str[end], hexBuf + 4); escaped = hexBuf; } break; } if (escaped != NULL) { print(ctx, (const char *) (str + beg), end - beg); print(ctx, escaped, strlen(escaped)); beg = ++end; } else { ++end; } } print(ctx, (const char *) (str + beg), end - beg); } static void hexToDigit(unsigned int * val, const unsigned char * hex) { unsigned int i; for (i=0;i<4;i++) { unsigned char c = hex[i]; if (c >= 'A') c = (c & ~0x20) - 7; c -= '0'; assert(!(c & 0xF0)); *val = (*val << 4) | c; } } static void Utf32toUtf8(unsigned int codepoint, char * utf8Buf) { if (codepoint < 0x80) { utf8Buf[0] = (char) codepoint; utf8Buf[1] = 0; } else if (codepoint < 0x0800) { utf8Buf[0] = (char) ((codepoint >> 6) | 0xC0); utf8Buf[1] = (char) ((codepoint & 0x3F) | 0x80); utf8Buf[2] = 0; } else if (codepoint < 0x10000) { utf8Buf[0] = (char) ((codepoint >> 12) | 0xE0); utf8Buf[1] = (char) (((codepoint >> 6) & 0x3F) | 0x80); utf8Buf[2] = (char) ((codepoint & 0x3F) | 0x80); utf8Buf[3] = 0; } else if (codepoint < 0x200000) { utf8Buf[0] =(char)((codepoint >> 18) | 0xF0); utf8Buf[1] =(char)(((codepoint >> 12) & 0x3F) | 0x80); utf8Buf[2] =(char)(((codepoint >> 6) & 0x3F) | 0x80); utf8Buf[3] =(char)((codepoint & 0x3F) | 0x80); utf8Buf[4] = 0; } else { utf8Buf[0] = '?'; utf8Buf[1] = 0; } } void yajl_string_decode(yajl_buf buf, const unsigned char * str, unsigned int len) { unsigned int beg = 0; unsigned int end = 0; while (end < len) { if (str[end] == '\\') { char utf8Buf[5]; const char * unescaped = "?"; yajl_buf_append(buf, str + beg, end - beg); switch (str[++end]) { case 'r': unescaped = "\r"; break; case 'n': unescaped = "\n"; break; case '\\': unescaped = "\\"; break; case '/': unescaped = "/"; break; case '"': unescaped = "\""; break; case 'f': unescaped = "\f"; break; case 'b': unescaped = "\b"; break; case 't': unescaped = "\t"; break; case 'u': { unsigned int codepoint = 0; hexToDigit(&codepoint, str + ++end); end+=3; /* check if this is a surrogate */ if ((codepoint & 0xFC00) == 0xD800) { end++; if (str[end] == '\\' && str[end + 1] == 'u') { unsigned int surrogate = 0; hexToDigit(&surrogate, str + end + 2); codepoint = (((codepoint & 0x3F) << 10) | ((((codepoint >> 6) & 0xF) + 1) << 16) | (surrogate & 0x3FF)); end += 5; } else { unescaped = "?"; break; } } Utf32toUtf8(codepoint, utf8Buf); unescaped = utf8Buf; if (codepoint == 0) { yajl_buf_append(buf, unescaped, 1); beg = ++end; continue; } break; } default: assert("this should never happen" == NULL); } yajl_buf_append(buf, unescaped, strlen(unescaped)); beg = ++end; } else { end++; } } yajl_buf_append(buf, str + beg, end - beg); } apache-couchdb-1.5.0/src/ejson/yajl/yajl_encode.h0000644000175000001440000000377312230722213016555 00000000000000/* * Copyright 2010, Lloyd Hilaiel. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * 3. Neither the name of Lloyd Hilaiel nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ #ifndef __YAJL_ENCODE_H__ #define __YAJL_ENCODE_H__ #include "yajl_buf.h" #include "yajl_gen.h" void yajl_string_encode2(const yajl_print_t printer, void * ctx, const unsigned char * str, unsigned int length); void yajl_string_encode(yajl_buf buf, const unsigned char * str, unsigned int length); void yajl_string_decode(yajl_buf buf, const unsigned char * str, unsigned int length); #endif apache-couchdb-1.5.0/src/ejson/yajl/yajl_bytestack.h0000644000175000001440000000610312230722213017277 00000000000000/* * Copyright 2010, Lloyd Hilaiel. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * 3. Neither the name of Lloyd Hilaiel nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ /* * A header only implementation of a simple stack of bytes, used in YAJL * to maintain parse state. */ #ifndef __YAJL_BYTESTACK_H__ #define __YAJL_BYTESTACK_H__ #include "yajl_common.h" #define YAJL_BS_INC 128 typedef struct yajl_bytestack_t { unsigned char * stack; unsigned int size; unsigned int used; yajl_alloc_funcs * yaf; } yajl_bytestack; /* initialize a bytestack */ #define yajl_bs_init(obs, _yaf) { \ (obs).stack = NULL; \ (obs).size = 0; \ (obs).used = 0; \ (obs).yaf = (_yaf); \ } \ /* initialize a bytestack */ #define yajl_bs_free(obs) \ if ((obs).stack) (obs).yaf->free((obs).yaf->ctx, (obs).stack); #define yajl_bs_current(obs) \ (assert((obs).used > 0), (obs).stack[(obs).used - 1]) #define yajl_bs_push(obs, byte) { \ if (((obs).size - (obs).used) == 0) { \ (obs).size += YAJL_BS_INC; \ (obs).stack = (obs).yaf->realloc((obs).yaf->ctx,\ (void *) (obs).stack, (obs).size);\ } \ (obs).stack[((obs).used)++] = (byte); \ } /* removes the top item of the stack, returns nothing */ #define yajl_bs_pop(obs) { ((obs).used)--; } #define yajl_bs_set(obs, byte) \ (obs).stack[((obs).used) - 1] = (byte); #endif apache-couchdb-1.5.0/src/ejson/yajl/yajl_common.h0000644000175000001440000000607312230722213016604 00000000000000/* * Copyright 2010, Lloyd Hilaiel. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * 3. Neither the name of Lloyd Hilaiel nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ #ifndef __YAJL_COMMON_H__ #define __YAJL_COMMON_H__ #ifdef __cplusplus extern "C" { #endif #define YAJL_MAX_DEPTH 128 /* msft dll export gunk. To build a DLL on windows, you * must define WIN32, YAJL_SHARED, and YAJL_BUILD. To use a shared * DLL, you must define YAJL_SHARED and WIN32 */ #if defined(WIN32) && defined(YAJL_SHARED) # ifdef YAJL_BUILD # define YAJL_API __declspec(dllexport) # else # define YAJL_API __declspec(dllimport) # endif #else # define YAJL_API #endif /** pointer to a malloc function, supporting client overriding memory * allocation routines */ typedef void * (*yajl_malloc_func)(void *ctx, unsigned int sz); /** pointer to a free function, supporting client overriding memory * allocation routines */ typedef void (*yajl_free_func)(void *ctx, void * ptr); /** pointer to a realloc function which can resize an allocation. */ typedef void * (*yajl_realloc_func)(void *ctx, void * ptr, unsigned int sz); /** A structure which can be passed to yajl_*_alloc routines to allow the * client to specify memory allocation functions to be used. */ typedef struct { /** pointer to a function that can allocate uninitialized memory */ yajl_malloc_func malloc; /** pointer to a function that can resize memory allocations */ yajl_realloc_func realloc; /** pointer to a function that can free memory allocated using * reallocFunction or mallocFunction */ yajl_free_func free; /** a context pointer that will be passed to above allocation routines */ void * ctx; } yajl_alloc_funcs; #ifdef __cplusplus } #endif #endif apache-couchdb-1.5.0/src/ejson/yajl/yajl.c0000644000175000001440000001145512230722213015227 00000000000000/* * Copyright 2010, Lloyd Hilaiel. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * 3. Neither the name of Lloyd Hilaiel nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ #include "yajl_parse.h" #include "yajl_lex.h" #include "yajl_parser.h" #include "yajl_alloc.h" #include #include #include const char * yajl_status_to_string(yajl_status stat) { const char * statStr = "unknown"; switch (stat) { case yajl_status_ok: statStr = "ok, no error"; break; case yajl_status_client_canceled: statStr = "client canceled parse"; break; case yajl_status_insufficient_data: statStr = "eof was met before the parse could complete"; break; case yajl_status_error: statStr = "parse error"; break; } return statStr; } yajl_handle yajl_alloc(const yajl_callbacks * callbacks, const yajl_parser_config * config, const yajl_alloc_funcs * afs, void * ctx) { unsigned int allowComments = 0; unsigned int validateUTF8 = 0; yajl_handle hand = NULL; yajl_alloc_funcs afsBuffer; /* first order of business is to set up memory allocation routines */ if (afs != NULL) { if (afs->malloc == NULL || afs->realloc == NULL || afs->free == NULL) { return NULL; } } else { yajl_set_default_alloc_funcs(&afsBuffer); afs = &afsBuffer; } hand = (yajl_handle) YA_MALLOC(afs, sizeof(struct yajl_handle_t)); /* copy in pointers to allocation routines */ memcpy((void *) &(hand->alloc), (void *) afs, sizeof(yajl_alloc_funcs)); if (config != NULL) { allowComments = config->allowComments; validateUTF8 = config->checkUTF8; } hand->callbacks = callbacks; hand->ctx = ctx; hand->lexer = yajl_lex_alloc(&(hand->alloc), allowComments, validateUTF8); hand->bytesConsumed = 0; hand->decodeBuf = yajl_buf_alloc(&(hand->alloc)); yajl_bs_init(hand->stateStack, &(hand->alloc)); yajl_bs_push(hand->stateStack, yajl_state_start); return hand; } void yajl_free(yajl_handle handle) { yajl_bs_free(handle->stateStack); yajl_buf_free(handle->decodeBuf); yajl_lex_free(handle->lexer); YA_FREE(&(handle->alloc), handle); } yajl_status yajl_parse(yajl_handle hand, const unsigned char * jsonText, unsigned int jsonTextLen) { yajl_status status; status = yajl_do_parse(hand, jsonText, jsonTextLen); return status; } yajl_status yajl_parse_complete(yajl_handle hand) { /* The particular case we want to handle is a trailing number. * Further input consisting of digits could cause our interpretation * of the number to change (buffered "1" but "2" comes in). * A very simple approach to this is to inject whitespace to terminate * any number in the lex buffer. */ return yajl_parse(hand, (const unsigned char *)" ", 1); } unsigned char * yajl_get_error(yajl_handle hand, int verbose, const unsigned char * jsonText, unsigned int jsonTextLen) { return yajl_render_error_string(hand, jsonText, jsonTextLen, verbose); } unsigned int yajl_get_bytes_consumed(yajl_handle hand) { if (!hand) return 0; else return hand->bytesConsumed; } void yajl_free_error(yajl_handle hand, unsigned char * str) { /* use memory allocation functions if set */ YA_FREE(&(hand->alloc), str); } /* XXX: add utility routines to parse from file */ apache-couchdb-1.5.0/src/ejson/ejson.erl0000644000175000001440000001165112230722213015005 00000000000000% 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. -module(ejson). -export([encode/1, decode/1]). -on_load(init/0). init() -> SoName = case code:priv_dir(ejson) of {error, bad_name} -> case filelib:is_dir(filename:join(["..", priv])) of true -> filename:join(["..", priv, ejson]); false -> filename:join([priv, ejson]) end; Dir -> filename:join(Dir, ejson) end, (catch erlang:load_nif(SoName, 0)), case erlang:system_info(otp_release) of "R13B03" -> true; _ -> ok end. decode(undefined) -> throw({invalid_json, undefined}); decode(IoList) -> try nif_decode(IoList) catch exit:ejson_nif_not_loaded -> erl_decode(IoList) end. encode(EJson) -> try nif_encode(EJson) catch exit:ejson_nif_not_loaded -> erl_encode(EJson) end. nif_decode(IoList) -> case reverse_tokens(IoList) of {ok, ReverseTokens} -> [[EJson]] = make_ejson(ReverseTokens, [[]]), EJson; Error -> throw({invalid_json, {Error, IoList}}) end. erl_decode(IoList) -> try (mochijson2:decoder([{object_hook, fun({struct, L}) -> {L} end}]))(IoList) catch _Type:Error -> throw({invalid_json, {Error, IoList}}) end. nif_encode(EJson) -> RevList = encode_rev(EJson), final_encode(lists:reverse(lists:flatten([RevList]))). erl_encode(EJson) -> Opts = [{handler, fun mochi_encode_handler/1}], iolist_to_binary((mochijson2:encoder(Opts))(EJson)). mochi_encode_handler({L}) when is_list(L) -> {struct, L}; mochi_encode_handler(Bad) -> exit({json_encode, {bad_term, Bad}}). % Encode the json into a reverse list that's almost an iolist % everything in the list is the final output except for tuples with % {0, Strings} and {1, Floats}, which are to be converted to strings % inside the NIF. encode_rev(true) -> <<"true">>; encode_rev(false) -> <<"false">>; encode_rev(null) -> <<"null">>; encode_rev(I) when is_integer(I) -> list_to_binary(integer_to_list(I)); encode_rev(S) when is_binary(S) -> {0, S}; encode_rev(S) when is_atom(S) -> {0, list_to_binary(atom_to_list(S))}; encode_rev(F) when is_float(F) -> {1, F}; encode_rev({Props}) when is_list(Props) -> encode_proplist_rev(Props, [<<"{">>]); encode_rev(Array) when is_list(Array) -> encode_array_rev(Array, [<<"[">>]); encode_rev(Bad) -> throw({json_encode, {bad_term, Bad}}). encode_array_rev([], Acc) -> [<<"]">> | Acc]; encode_array_rev([Val | Rest], [<<"[">>]) -> encode_array_rev(Rest, [encode_rev(Val), <<"[">>]); encode_array_rev([Val | Rest], Acc) -> encode_array_rev(Rest, [encode_rev(Val), <<",">> | Acc]). encode_proplist_rev([], Acc) -> [<<"}">> | Acc]; encode_proplist_rev([{Key,Val} | Rest], [<<"{">>]) -> encode_proplist_rev( Rest, [encode_rev(Val), <<":">>, {0, as_binary(Key)}, <<"{">>]); encode_proplist_rev([{Key,Val} | Rest], Acc) -> encode_proplist_rev( Rest, [encode_rev(Val), <<":">>, {0, as_binary(Key)}, <<",">> | Acc]). as_binary(B) when is_binary(B) -> B; as_binary(A) when is_atom(A) -> list_to_binary(atom_to_list(A)); as_binary(L) when is_list(L) -> list_to_binary(L). make_ejson([], Stack) -> Stack; make_ejson([0 | RevEvs], [ArrayValues, PrevValues | RestStack]) -> % 0 ArrayStart make_ejson(RevEvs, [[ArrayValues | PrevValues] | RestStack]); make_ejson([1 | RevEvs], Stack) -> % 1 ArrayEnd make_ejson(RevEvs, [[] | Stack]); make_ejson([2 | RevEvs], [ObjValues, PrevValues | RestStack]) -> % 2 ObjectStart make_ejson(RevEvs, [[{ObjValues} | PrevValues] | RestStack]); make_ejson([3 | RevEvs], Stack) -> % 3 ObjectEnd make_ejson(RevEvs, [[] | Stack]); make_ejson([{0, Value} | RevEvs], [Vals | RestStack] = _Stack) -> % {0, IntegerString} make_ejson(RevEvs, [[list_to_integer(binary_to_list(Value)) | Vals] | RestStack]); make_ejson([{1, Value} | RevEvs], [Vals | RestStack] = _Stack) -> % {1, FloatString} make_ejson(RevEvs, [[list_to_float(binary_to_list(Value)) | Vals] | RestStack]); make_ejson([{3, String} | RevEvs], [[PrevValue|RestObject] | RestStack] = _Stack) -> % {3 , ObjectKey} make_ejson(RevEvs, [[{String, PrevValue}|RestObject] | RestStack]); make_ejson([Value | RevEvs], [Vals | RestStack] = _Stack) -> make_ejson(RevEvs, [[Value | Vals] | RestStack]). reverse_tokens(_) -> exit(ejson_nif_not_loaded). final_encode(_) -> exit(ejson_nif_not_loaded). apache-couchdb-1.5.0/src/ejson/ejson.c0000644000175000001440000000121312230722213014436 00000000000000#include "erl_nif.h" ERL_NIF_TERM final_encode(ErlNifEnv* env, int argc, const ERL_NIF_TERM argv[]); ERL_NIF_TERM reverse_tokens(ErlNifEnv* env, int argc, const ERL_NIF_TERM argv[]); int on_load(ErlNifEnv* env, void** priv_data, ERL_NIF_TERM info) { return 0; } int on_reload(ErlNifEnv* env, void** priv_data, ERL_NIF_TERM info) { return 0; } int on_upgrade(ErlNifEnv* env, void** priv_data, void** old_data, ERL_NIF_TERM info) { return 0; } static ErlNifFunc nif_funcs[] = { {"final_encode", 1, final_encode}, {"reverse_tokens", 1, reverse_tokens} }; ERL_NIF_INIT(ejson, nif_funcs, &on_load, &on_reload, &on_upgrade, NULL); apache-couchdb-1.5.0/src/ejson/encode.c0000644000175000001440000001341412230722213014563 00000000000000// 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. #include #include #include #include "erl_nif.h" #include "erl_nif_compat.h" #include "yajl/yajl_encode.h" #if defined(_WIN32) || defined(WIN32) || defined(__WIN32__) #include #define isnan _isnan #define isinf !_finite #define snprintf _snprintf #endif #define SUCCESS 0 #define NOMEM 1 #define BADARG 2 typedef struct { ErlNifEnv* env; ErlNifBinary bin; size_t fill_offset; int error; } encode_ctx; static int ensure_buffer(void* vctx, unsigned int len) { encode_ctx* ctx = (encode_ctx*)vctx; if ((ctx->bin.size - ctx->fill_offset) < len) { if(!enif_realloc_binary_compat(ctx->env, &(ctx->bin), (ctx->bin.size * 2) + len)) { return NOMEM; } } return SUCCESS; } static void fill_buffer(void* vctx, const char* str, unsigned int len) { encode_ctx* ctx = (encode_ctx*)vctx; if (ctx->error || (ctx->error = ensure_buffer(vctx, len))) { return; } memcpy(ctx->bin.data + ctx->fill_offset, str, len); ctx->fill_offset += len; } /* Json encode the string binary into the ctx.bin, with surrounding quotes and all */ static int encode_string(void* vctx, ERL_NIF_TERM binary) { encode_ctx* ctx = (encode_ctx*)vctx; ErlNifBinary bin; if(!enif_inspect_binary(ctx->env, binary, &bin)) { return NOMEM; } fill_buffer(ctx, "\"", 1); if (ctx->error) { return ctx->error; } yajl_string_encode2(fill_buffer, ctx, bin.data, bin.size); fill_buffer(ctx, "\"", 1); return ctx->error; } static ERL_NIF_TERM no_mem_error(ErlNifEnv* env) { return enif_make_tuple(env, 2, enif_make_atom(env, "error"), enif_make_atom(env, "insufficient_memory")); } ERL_NIF_TERM final_encode(ErlNifEnv* env, int argc, const ERL_NIF_TERM argv[]) { ERL_NIF_TERM head = argv[0]; ERL_NIF_TERM term; double number; encode_ctx ctx; char* start; size_t len; size_t i; ctx.env = env; ctx.fill_offset = 0; ctx.error = 0; if (!enif_alloc_binary_compat(env, 100, &ctx.bin)) { return no_mem_error(env); } while(enif_get_list_cell(env, head, &term, &head)) { ErlNifBinary termbin; const ERL_NIF_TERM* array; int arity; int code; // We scan the list, looking for things to write into the binary, or // encode and then write into the binary. We encode values that are // tuples tagged with a type and a value: {Type, Value} where Type // is a an Integer and Value is what is to be encoded if (enif_get_tuple(env, term, &arity, &array)) { // It's a tuple to encode and copy if (arity != 2 || !enif_get_int(env, array[0], &code)) { // not arity 2 or the first element isn't an int ctx.error = BADARG; goto done; } if (code == 0) { // {0, String} if (encode_string(&ctx, array[1]) != SUCCESS) { goto done; } } else { // {1, Double} if(!enif_get_double(env, array[1], &number)) { ctx.error = BADARG; goto done; } // We can't encode these. if (isnan(number) || isinf(number)) { ctx.error = BADARG; goto done; } if ((ctx.error = ensure_buffer(&ctx, 32)) != SUCCESS) { goto done; } // write the string into the buffer start = (char*) (ctx.bin.data + ctx.fill_offset); snprintf(start, 32, "%0.20g", number); len = strlen(start); for(i = 0; i < len; i++) { if(start[i] == '.' || start[i] == 'e' || start[i] == 'E') { break; } } if(i == len) { if(i > 29) { ctx.error = BADARG; goto done; } start[len++] = '.'; start[len++] = '0'; } // increment the length ctx.fill_offset += len; } } else if (enif_inspect_binary(env, term, &termbin)) { // this is a regular binary, copy the contents into the buffer fill_buffer(&ctx, (char*)termbin.data, termbin.size); if (ctx.error) { goto done; } } else { //not a binary, not a tuple, wtf! ctx.error = BADARG; goto done; } } done: if (ctx.error == NOMEM) { enif_release_binary_compat(env, &ctx.bin); return no_mem_error(env); } else if (ctx.error == BADARG) { enif_release_binary_compat(env, &ctx.bin); return enif_make_badarg(env); } // Resize the binary to our exact final size if(!enif_realloc_binary_compat(env, &(ctx.bin), ctx.fill_offset)) { enif_release_binary_compat(env, &ctx.bin); return no_mem_error(env); } // make the binary term which transfers ownership return enif_make_binary(env, &ctx.bin); } apache-couchdb-1.5.0/src/ejson/decode.c0000644000175000001440000001646312230722213014560 00000000000000// 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. #include #include #include #include "erl_nif.h" #include "erl_nif_compat.h" #include "yajl/yajl_parse.h" #include "yajl/yajl_parser.h" #include "yajl/yajl_lex.h" typedef struct { ERL_NIF_TERM head; ErlNifEnv* env; } decode_ctx; #define ENV(ctxarg) (((decode_ctx*)ctxarg)->env) #define CONTINUE 1 #define CANCEL 0 static ERL_NIF_TERM make_error(yajl_handle handle, ErlNifEnv* env) { char* yajlError = (char*) yajl_get_error(handle, 0, NULL, 0); ERL_NIF_TERM errMsg; if(yajlError != NULL) { errMsg = enif_make_string(env, yajlError, ERL_NIF_LATIN1); yajl_free_error(handle, (unsigned char*) yajlError); } else { errMsg = enif_make_string(env, "unknown parse error", ERL_NIF_LATIN1); } return enif_make_tuple(env, 2, enif_make_atom(env, "error"), enif_make_tuple(env, 2, enif_make_uint(env, handle->bytesConsumed), errMsg ) ); } static void add_to_head(void* vctx, ERL_NIF_TERM newhead) { decode_ctx* ctx = (decode_ctx*)vctx; ctx->head = enif_make_list_cell(ctx->env, newhead, ctx->head); } static int decode_null(void* ctx) { add_to_head(ctx, enif_make_atom(ENV(ctx), "null")); return CONTINUE; } static int decode_boolean(void* ctx, int val) { add_to_head(ctx, enif_make_atom(ENV(ctx), val ? "true" : "false")); return CONTINUE; } static int decode_number(void * ctx, const char * numberVal, unsigned int numberLen) { // scan in the input to see if it's a float or int int numberType = 0; // 0 means integer, 1 means float unsigned int i; ErlNifBinary bin; int missingDot = 1; unsigned int expPos; for(i=0; ibytesConsumed; // Parsing something like "2.0" (without quotes) will // cause a spurious semi-error. We add the extra size // check so that "2008-20-10" doesn't pass. if(status == yajl_status_insufficient_data && used == bin.size) { status = yajl_parse_complete(handle); } if(status == yajl_status_ok && used != bin.size) { if(check_rest(bin.data, bin.size, used) == CANCEL) { ret = enif_make_tuple(env, 2, enif_make_atom(env, "error"), enif_make_atom(env, "garbage_after_value") ); goto done; } } switch(status) { case yajl_status_ok: ret = enif_make_tuple(env, 2, enif_make_atom(env, "ok"), ctx.head); goto done; case yajl_status_error: ret = make_error(handle, env); goto done; case yajl_status_insufficient_data: ret = enif_make_tuple(env, 2, enif_make_atom(env, "error"), enif_make_atom(env, "insufficient_data") ); goto done; case yajl_status_client_canceled: /* the only time we do this is when we can't allocate a binary. */ ret = enif_make_tuple(env, 2, enif_make_atom(env, "error"), enif_make_atom(env, "insufficient_memory") ); goto done; default: ret = enif_make_tuple(env, 2, enif_make_atom(env, "error"), enif_make_atom(env, "unknown") ); goto done; } done: if(handle != NULL) yajl_free(handle); return ret; } apache-couchdb-1.5.0/src/ejson/Makefile.am0000644000175000001440000000373712230722213015225 00000000000000## 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. ejsonebindir = $(localerlanglibdir)/ejson-0.1.0/ebin ejsonprivdir = $(localerlanglibdir)/ejson-0.1.0/priv CLEANFILES = \ $(ejsonebin_make_generated_file_list) \ $(ejsonpriv_make_generated_file_list) \ priv/ejson.so EJSON_C_SRCS = \ ejson.c \ decode.c \ encode.c \ yajl/yajl_alloc.c \ yajl/yajl_buf.c \ yajl/yajl.c \ yajl/yajl_encode.c \ yajl/yajl_gen.c \ yajl/yajl_lex.c \ yajl/yajl_parser.c EJSON_C_HDRS = \ erl_nif_compat.h \ yajl/yajl_alloc.h \ yajl/yajl_buf.h \ yajl/yajl_bytestack.h \ yajl/yajl_common.h \ yajl/yajl_encode.h \ yajl/yajl_gen.h \ yajl/yajl_lex.h \ yajl/yajl_parse.h \ yajl/yajl_parser.h ejson_file_collection = \ ejson.app.in \ ejson.erl \ mochijson2.erl \ mochinum.erl ejsonebin_make_generated_file_list = \ ejson.app \ ejson.beam \ mochijson2.beam \ mochinum.beam EXTRA_DIST = \ $(EJSON_C_HDRS) \ $(ejson_file_collection) ejsonebin_DATA = \ $(ejsonebin_make_generated_file_list) if USE_OTP_NIFS ejsonpriv_LTLIBRARIES = ejson.la ejson_la_SOURCES = $(EJSON_C_SRCS) ejson_la_CFLAGS = $(ERLANG_FLAGS) ejson_la_LDFLAGS = -module -avoid-version if WINDOWS ejson_la_LDFLAGS += -no-undefined EJSON_SO_NAME = ejson.dll else EJSON_SO_NAME = ejson.so endif priv/$(EJSON_SO_NAME): ejson.la @mkdir -p ./priv cp .libs/$(EJSON_SO_NAME) $@ all: priv/$(EJSON_SO_NAME) endif %.app: %.app.in cp $< $@ %.beam: %.erl $(ERLC) $(ERLC_FLAGS) $< apache-couchdb-1.5.0/src/ejson/Makefile.in0000644000175000001440000010115712230722244015235 00000000000000# Makefile.in generated by automake 1.11.6 from Makefile.am. # @configure_input@ # Copyright (C) 1994, 1995, 1996, 1997, 1998, 1999, 2000, 2001, 2002, # 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011 Free Software # Foundation, Inc. # This Makefile.in is free software; the Free Software Foundation # gives unlimited permission to copy and/or distribute it, # with or without modifications, as long as this notice is preserved. # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY, to the extent permitted by law; without # even the implied warranty of MERCHANTABILITY or FITNESS FOR A # PARTICULAR PURPOSE. @SET_MAKE@ VPATH = @srcdir@ am__make_dryrun = \ { \ am__dry=no; \ case $$MAKEFLAGS in \ *\\[\ \ ]*) \ echo 'am--echo: ; @echo "AM" OK' | $(MAKE) -f - 2>/dev/null \ | grep '^AM OK$$' >/dev/null || am__dry=yes;; \ *) \ for am__flg in $$MAKEFLAGS; do \ case $$am__flg in \ *=*|--*) ;; \ *n*) am__dry=yes; break;; \ esac; \ done;; \ esac; \ test $$am__dry = yes; \ } pkgdatadir = $(datadir)/@PACKAGE@ pkgincludedir = $(includedir)/@PACKAGE@ pkglibdir = $(libdir)/@PACKAGE@ pkglibexecdir = $(libexecdir)/@PACKAGE@ am__cd = CDPATH="$${ZSH_VERSION+.}$(PATH_SEPARATOR)" && cd install_sh_DATA = $(install_sh) -c -m 644 install_sh_PROGRAM = $(install_sh) -c install_sh_SCRIPT = $(install_sh) -c INSTALL_HEADER = $(INSTALL_DATA) transform = $(program_transform_name) NORMAL_INSTALL = : PRE_INSTALL = : POST_INSTALL = : NORMAL_UNINSTALL = : PRE_UNINSTALL = : POST_UNINSTALL = : build_triplet = @build@ host_triplet = @host@ @USE_OTP_NIFS_TRUE@@WINDOWS_TRUE@am__append_1 = -no-undefined subdir = src/ejson DIST_COMMON = $(srcdir)/Makefile.am $(srcdir)/Makefile.in ACLOCAL_M4 = $(top_srcdir)/aclocal.m4 am__aclocal_m4_deps = $(top_srcdir)/m4/libtool.m4 \ $(top_srcdir)/m4/ltoptions.m4 $(top_srcdir)/m4/ltsugar.m4 \ $(top_srcdir)/m4/ltversion.m4 $(top_srcdir)/m4/lt~obsolete.m4 \ $(top_srcdir)/acinclude.m4 $(top_srcdir)/configure.ac am__configure_deps = $(am__aclocal_m4_deps) $(CONFIGURE_DEPENDENCIES) \ $(ACLOCAL_M4) mkinstalldirs = $(install_sh) -d CONFIG_HEADER = $(top_builddir)/config.h \ $(top_builddir)/src/snappy/google-snappy/config.h CONFIG_CLEAN_FILES = CONFIG_CLEAN_VPATH_FILES = am__vpath_adj_setup = srcdirstrip=`echo "$(srcdir)" | sed 's|.|.|g'`; am__vpath_adj = case $$p in \ $(srcdir)/*) f=`echo "$$p" | sed "s|^$$srcdirstrip/||"`;; \ *) f=$$p;; \ esac; am__strip_dir = f=`echo $$p | sed -e 's|^.*/||'`; am__install_max = 40 am__nobase_strip_setup = \ srcdirstrip=`echo "$(srcdir)" | sed 's/[].[^$$\\*|]/\\\\&/g'` am__nobase_strip = \ for p in $$list; do echo "$$p"; done | sed -e "s|$$srcdirstrip/||" am__nobase_list = $(am__nobase_strip_setup); \ for p in $$list; do echo "$$p $$p"; done | \ sed "s| $$srcdirstrip/| |;"' / .*\//!s/ .*/ ./; s,\( .*\)/[^/]*$$,\1,' | \ $(AWK) 'BEGIN { files["."] = "" } { files[$$2] = files[$$2] " " $$1; \ if (++n[$$2] == $(am__install_max)) \ { print $$2, files[$$2]; n[$$2] = 0; files[$$2] = "" } } \ END { for (dir in files) print dir, files[dir] }' am__base_list = \ sed '$$!N;$$!N;$$!N;$$!N;$$!N;$$!N;$$!N;s/\n/ /g' | \ sed '$$!N;$$!N;$$!N;$$!N;s/\n/ /g' am__uninstall_files_from_dir = { \ test -z "$$files" \ || { test ! -d "$$dir" && test ! -f "$$dir" && test ! -r "$$dir"; } \ || { echo " ( cd '$$dir' && rm -f" $$files ")"; \ $(am__cd) "$$dir" && rm -f $$files; }; \ } am__installdirs = "$(DESTDIR)$(ejsonprivdir)" \ "$(DESTDIR)$(ejsonebindir)" LTLIBRARIES = $(ejsonpriv_LTLIBRARIES) ejson_la_LIBADD = am__ejson_la_SOURCES_DIST = ejson.c decode.c encode.c \ yajl/yajl_alloc.c yajl/yajl_buf.c yajl/yajl.c \ yajl/yajl_encode.c yajl/yajl_gen.c yajl/yajl_lex.c \ yajl/yajl_parser.c am__objects_1 = ejson_la-ejson.lo ejson_la-decode.lo \ ejson_la-encode.lo ejson_la-yajl_alloc.lo ejson_la-yajl_buf.lo \ ejson_la-yajl.lo ejson_la-yajl_encode.lo ejson_la-yajl_gen.lo \ ejson_la-yajl_lex.lo ejson_la-yajl_parser.lo @USE_OTP_NIFS_TRUE@am_ejson_la_OBJECTS = $(am__objects_1) ejson_la_OBJECTS = $(am_ejson_la_OBJECTS) ejson_la_LINK = $(LIBTOOL) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) \ --mode=link $(CCLD) $(ejson_la_CFLAGS) $(CFLAGS) \ $(ejson_la_LDFLAGS) $(LDFLAGS) -o $@ @USE_OTP_NIFS_TRUE@am_ejson_la_rpath = -rpath $(ejsonprivdir) DEFAULT_INCLUDES = -I.@am__isrc@ -I$(top_builddir) -I$(top_builddir)/src/snappy/google-snappy depcomp = $(SHELL) $(top_srcdir)/build-aux/depcomp am__depfiles_maybe = depfiles am__mv = mv -f COMPILE = $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) \ $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) LTCOMPILE = $(LIBTOOL) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) \ --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) \ $(AM_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) CCLD = $(CC) LINK = $(LIBTOOL) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) \ --mode=link $(CCLD) $(AM_CFLAGS) $(CFLAGS) $(AM_LDFLAGS) \ $(LDFLAGS) -o $@ SOURCES = $(ejson_la_SOURCES) DIST_SOURCES = $(am__ejson_la_SOURCES_DIST) am__can_run_installinfo = \ case $$AM_UPDATE_INFO_DIR in \ n|no|NO) false;; \ *) (install-info --version) >/dev/null 2>&1;; \ esac DATA = $(ejsonebin_DATA) ETAGS = etags CTAGS = ctags DISTFILES = $(DIST_COMMON) $(DIST_SOURCES) $(TEXINFOS) $(EXTRA_DIST) ACLOCAL = @ACLOCAL@ AMTAR = @AMTAR@ AR = @AR@ AS = @AS@ AUTOCONF = @AUTOCONF@ AUTOHEADER = @AUTOHEADER@ AUTOMAKE = @AUTOMAKE@ AWK = @AWK@ CC = @CC@ CCDEPMODE = @CCDEPMODE@ CFLAGS = @CFLAGS@ CPP = @CPP@ CPPFLAGS = @CPPFLAGS@ CURL_CFLAGS = @CURL_CFLAGS@ CURL_CONFIG = @CURL_CONFIG@ CURL_LIBS = @CURL_LIBS@ CXX = @CXX@ CXXCPP = @CXXCPP@ CXXDEPMODE = @CXXDEPMODE@ CXXFLAGS = @CXXFLAGS@ CYGPATH_W = @CYGPATH_W@ DEFS = @DEFS@ DEPDIR = @DEPDIR@ DLLTOOL = @DLLTOOL@ DSYMUTIL = @DSYMUTIL@ DUMPBIN = @DUMPBIN@ ECHO_C = @ECHO_C@ ECHO_N = @ECHO_N@ ECHO_T = @ECHO_T@ EGREP = @EGREP@ ERL = @ERL@ ERLANG_FLAGS = @ERLANG_FLAGS@ ERLC = @ERLC@ ERLC_FLAGS = @ERLC_FLAGS@ ESCRIPT = @ESCRIPT@ EXEEXT = @EXEEXT@ FGREP = @FGREP@ FLAGS = @FLAGS@ GREP = @GREP@ HAS_HELP2MAN = @HAS_HELP2MAN@ HAS_INSTALLINFO = @HAS_INSTALLINFO@ HAS_MAKEINFO = @HAS_MAKEINFO@ HAS_PDFLATEX = @HAS_PDFLATEX@ HAS_SPHINX_BUILD = @HAS_SPHINX_BUILD@ ICU_BIN = @ICU_BIN@ ICU_CFLAGS = @ICU_CFLAGS@ ICU_CONFIG = @ICU_CONFIG@ ICU_CPPFLAGS = @ICU_CPPFLAGS@ ICU_CXXFLAGS = @ICU_CXXFLAGS@ ICU_LIBS = @ICU_LIBS@ INNO_COMPILER_EXECUTABLE = @INNO_COMPILER_EXECUTABLE@ INSTALL = @INSTALL@ INSTALL_DATA = @INSTALL_DATA@ INSTALL_PROGRAM = @INSTALL_PROGRAM@ INSTALL_SCRIPT = @INSTALL_SCRIPT@ INSTALL_STRIP_PROGRAM = @INSTALL_STRIP_PROGRAM@ JS_CFLAGS = @JS_CFLAGS@ JS_LIBS = @JS_LIBS@ JS_LIB_BINARY = @JS_LIB_BINARY@ LD = @LD@ LDFLAGS = @LDFLAGS@ LIBOBJS = @LIBOBJS@ LIBS = @LIBS@ LIBTOOL = @LIBTOOL@ LIPO = @LIPO@ LN_S = @LN_S@ LTLIBOBJS = @LTLIBOBJS@ MAKEINFO = @MAKEINFO@ MANIFEST_TOOL = @MANIFEST_TOOL@ MKDIR_P = @MKDIR_P@ NM = @NM@ NMEDIT = @NMEDIT@ OBJDUMP = @OBJDUMP@ OBJEXT = @OBJEXT@ OTOOL = @OTOOL@ OTOOL64 = @OTOOL64@ PACKAGE = @PACKAGE@ PACKAGE_BUGREPORT = @PACKAGE_BUGREPORT@ PACKAGE_NAME = @PACKAGE_NAME@ PACKAGE_STRING = @PACKAGE_STRING@ PACKAGE_TARNAME = @PACKAGE_TARNAME@ PACKAGE_URL = @PACKAGE_URL@ PACKAGE_VERSION = @PACKAGE_VERSION@ PATH_SEPARATOR = @PATH_SEPARATOR@ PKG_CONFIG = @PKG_CONFIG@ PKG_CONFIG_LIBDIR = @PKG_CONFIG_LIBDIR@ PKG_CONFIG_PATH = @PKG_CONFIG_PATH@ RANLIB = @RANLIB@ SED = @SED@ SET_MAKE = @SET_MAKE@ SHELL = @SHELL@ SNAPPY_MAJOR = @SNAPPY_MAJOR@ SNAPPY_MINOR = @SNAPPY_MINOR@ SNAPPY_PATCHLEVEL = @SNAPPY_PATCHLEVEL@ STRIP = @STRIP@ VERSION = @VERSION@ abs_builddir = @abs_builddir@ abs_srcdir = @abs_srcdir@ abs_top_builddir = @abs_top_builddir@ abs_top_srcdir = @abs_top_srcdir@ ac_ct_AR = @ac_ct_AR@ ac_ct_CC = @ac_ct_CC@ ac_ct_CXX = @ac_ct_CXX@ ac_ct_DUMPBIN = @ac_ct_DUMPBIN@ ac_cv_have_stddef_h = @ac_cv_have_stddef_h@ ac_cv_have_stdint_h = @ac_cv_have_stdint_h@ am__include = @am__include@ am__leading_dot = @am__leading_dot@ am__quote = @am__quote@ am__tar = @am__tar@ am__untar = @am__untar@ bindir = @bindir@ bug_uri = @bug_uri@ build = @build@ build_alias = @build_alias@ build_cpu = @build_cpu@ build_os = @build_os@ build_vendor = @build_vendor@ builddir = @builddir@ datadir = @datadir@ datarootdir = @datarootdir@ docdir = @docdir@ dvidir = @dvidir@ erlangbin = @erlangbin@ erlangversion = @erlangversion@ exec_prefix = @exec_prefix@ host = @host@ host_alias = @host_alias@ host_cpu = @host_cpu@ host_os = @host_os@ host_vendor = @host_vendor@ htmldir = @htmldir@ includedir = @includedir@ infodir = @infodir@ initdir = @initdir@ install_sh = @install_sh@ launchddir = @launchddir@ libdir = @libdir@ libexecdir = @libexecdir@ localconfdir = @localconfdir@ localdatadir = @localdatadir@ localdocdir = @localdocdir@ localedir = @localedir@ localerlanglibdir = @localerlanglibdir@ locallibbindir = @locallibbindir@ locallibdir = @locallibdir@ localstatedir = @localstatedir@ localstatelibdir = @localstatelibdir@ localstatelogdir = @localstatelogdir@ localstaterundir = @localstaterundir@ mandir = @mandir@ mkdir_p = @mkdir_p@ msvc_redist_dir = @msvc_redist_dir@ msvc_redist_name = @msvc_redist_name@ oldincludedir = @oldincludedir@ openssl_bin_dir = @openssl_bin_dir@ otp_release = @otp_release@ package_author_address = @package_author_address@ package_author_name = @package_author_name@ package_identifier = @package_identifier@ package_name = @package_name@ package_tarname = @package_tarname@ pdfdir = @pdfdir@ prefix = @prefix@ program_transform_name = @program_transform_name@ psdir = @psdir@ sbindir = @sbindir@ sharedstatedir = @sharedstatedir@ srcdir = @srcdir@ sysconfdir = @sysconfdir@ target_alias = @target_alias@ top_build_prefix = @top_build_prefix@ top_builddir = @top_builddir@ top_srcdir = @top_srcdir@ version = @version@ version_major = @version_major@ version_minor = @version_minor@ version_release = @version_release@ version_revision = @version_revision@ version_stage = @version_stage@ ejsonebindir = $(localerlanglibdir)/ejson-0.1.0/ebin ejsonprivdir = $(localerlanglibdir)/ejson-0.1.0/priv CLEANFILES = \ $(ejsonebin_make_generated_file_list) \ $(ejsonpriv_make_generated_file_list) \ priv/ejson.so EJSON_C_SRCS = \ ejson.c \ decode.c \ encode.c \ yajl/yajl_alloc.c \ yajl/yajl_buf.c \ yajl/yajl.c \ yajl/yajl_encode.c \ yajl/yajl_gen.c \ yajl/yajl_lex.c \ yajl/yajl_parser.c EJSON_C_HDRS = \ erl_nif_compat.h \ yajl/yajl_alloc.h \ yajl/yajl_buf.h \ yajl/yajl_bytestack.h \ yajl/yajl_common.h \ yajl/yajl_encode.h \ yajl/yajl_gen.h \ yajl/yajl_lex.h \ yajl/yajl_parse.h \ yajl/yajl_parser.h ejson_file_collection = \ ejson.app.in \ ejson.erl \ mochijson2.erl \ mochinum.erl ejsonebin_make_generated_file_list = \ ejson.app \ ejson.beam \ mochijson2.beam \ mochinum.beam EXTRA_DIST = \ $(EJSON_C_HDRS) \ $(ejson_file_collection) ejsonebin_DATA = \ $(ejsonebin_make_generated_file_list) @USE_OTP_NIFS_TRUE@ejsonpriv_LTLIBRARIES = ejson.la @USE_OTP_NIFS_TRUE@ejson_la_SOURCES = $(EJSON_C_SRCS) @USE_OTP_NIFS_TRUE@ejson_la_CFLAGS = $(ERLANG_FLAGS) @USE_OTP_NIFS_TRUE@ejson_la_LDFLAGS = -module -avoid-version \ @USE_OTP_NIFS_TRUE@ $(am__append_1) @USE_OTP_NIFS_TRUE@@WINDOWS_FALSE@EJSON_SO_NAME = ejson.so @USE_OTP_NIFS_TRUE@@WINDOWS_TRUE@EJSON_SO_NAME = ejson.dll all: all-am .SUFFIXES: .SUFFIXES: .c .lo .o .obj $(srcdir)/Makefile.in: $(srcdir)/Makefile.am $(am__configure_deps) @for dep in $?; do \ case '$(am__configure_deps)' in \ *$$dep*) \ ( cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh ) \ && { if test -f $@; then exit 0; else break; fi; }; \ exit 1;; \ esac; \ done; \ echo ' cd $(top_srcdir) && $(AUTOMAKE) --foreign src/ejson/Makefile'; \ $(am__cd) $(top_srcdir) && \ $(AUTOMAKE) --foreign src/ejson/Makefile .PRECIOUS: Makefile Makefile: $(srcdir)/Makefile.in $(top_builddir)/config.status @case '$?' in \ *config.status*) \ cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh;; \ *) \ echo ' cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ $(am__depfiles_maybe)'; \ cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ $(am__depfiles_maybe);; \ esac; $(top_builddir)/config.status: $(top_srcdir)/configure $(CONFIG_STATUS_DEPENDENCIES) cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh $(top_srcdir)/configure: $(am__configure_deps) cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh $(ACLOCAL_M4): $(am__aclocal_m4_deps) cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh $(am__aclocal_m4_deps): install-ejsonprivLTLIBRARIES: $(ejsonpriv_LTLIBRARIES) @$(NORMAL_INSTALL) @list='$(ejsonpriv_LTLIBRARIES)'; test -n "$(ejsonprivdir)" || list=; \ list2=; for p in $$list; do \ if test -f $$p; then \ list2="$$list2 $$p"; \ else :; fi; \ done; \ test -z "$$list2" || { \ echo " $(MKDIR_P) '$(DESTDIR)$(ejsonprivdir)'"; \ $(MKDIR_P) "$(DESTDIR)$(ejsonprivdir)" || exit 1; \ echo " $(LIBTOOL) $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=install $(INSTALL) $(INSTALL_STRIP_FLAG) $$list2 '$(DESTDIR)$(ejsonprivdir)'"; \ $(LIBTOOL) $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=install $(INSTALL) $(INSTALL_STRIP_FLAG) $$list2 "$(DESTDIR)$(ejsonprivdir)"; \ } uninstall-ejsonprivLTLIBRARIES: @$(NORMAL_UNINSTALL) @list='$(ejsonpriv_LTLIBRARIES)'; test -n "$(ejsonprivdir)" || list=; \ for p in $$list; do \ $(am__strip_dir) \ echo " $(LIBTOOL) $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=uninstall rm -f '$(DESTDIR)$(ejsonprivdir)/$$f'"; \ $(LIBTOOL) $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=uninstall rm -f "$(DESTDIR)$(ejsonprivdir)/$$f"; \ done clean-ejsonprivLTLIBRARIES: -test -z "$(ejsonpriv_LTLIBRARIES)" || rm -f $(ejsonpriv_LTLIBRARIES) @list='$(ejsonpriv_LTLIBRARIES)'; for p in $$list; do \ dir="`echo $$p | sed -e 's|/[^/]*$$||'`"; \ test "$$dir" != "$$p" || dir=.; \ echo "rm -f \"$${dir}/so_locations\""; \ rm -f "$${dir}/so_locations"; \ done ejson.la: $(ejson_la_OBJECTS) $(ejson_la_DEPENDENCIES) $(EXTRA_ejson_la_DEPENDENCIES) $(ejson_la_LINK) $(am_ejson_la_rpath) $(ejson_la_OBJECTS) $(ejson_la_LIBADD) $(LIBS) mostlyclean-compile: -rm -f *.$(OBJEXT) distclean-compile: -rm -f *.tab.c @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/ejson_la-decode.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/ejson_la-ejson.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/ejson_la-encode.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/ejson_la-yajl.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/ejson_la-yajl_alloc.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/ejson_la-yajl_buf.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/ejson_la-yajl_encode.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/ejson_la-yajl_gen.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/ejson_la-yajl_lex.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/ejson_la-yajl_parser.Plo@am__quote@ .c.o: @am__fastdepCC_TRUE@ $(COMPILE) -MT $@ -MD -MP -MF $(DEPDIR)/$*.Tpo -c -o $@ $< @am__fastdepCC_TRUE@ $(am__mv) $(DEPDIR)/$*.Tpo $(DEPDIR)/$*.Po @AMDEP_TRUE@@am__fastdepCC_FALSE@ source='$<' object='$@' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(COMPILE) -c $< .c.obj: @am__fastdepCC_TRUE@ $(COMPILE) -MT $@ -MD -MP -MF $(DEPDIR)/$*.Tpo -c -o $@ `$(CYGPATH_W) '$<'` @am__fastdepCC_TRUE@ $(am__mv) $(DEPDIR)/$*.Tpo $(DEPDIR)/$*.Po @AMDEP_TRUE@@am__fastdepCC_FALSE@ source='$<' object='$@' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(COMPILE) -c `$(CYGPATH_W) '$<'` .c.lo: @am__fastdepCC_TRUE@ $(LTCOMPILE) -MT $@ -MD -MP -MF $(DEPDIR)/$*.Tpo -c -o $@ $< @am__fastdepCC_TRUE@ $(am__mv) $(DEPDIR)/$*.Tpo $(DEPDIR)/$*.Plo @AMDEP_TRUE@@am__fastdepCC_FALSE@ source='$<' object='$@' libtool=yes @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(LTCOMPILE) -c -o $@ $< ejson_la-ejson.lo: ejson.c @am__fastdepCC_TRUE@ $(LIBTOOL) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(ejson_la_CFLAGS) $(CFLAGS) -MT ejson_la-ejson.lo -MD -MP -MF $(DEPDIR)/ejson_la-ejson.Tpo -c -o ejson_la-ejson.lo `test -f 'ejson.c' || echo '$(srcdir)/'`ejson.c @am__fastdepCC_TRUE@ $(am__mv) $(DEPDIR)/ejson_la-ejson.Tpo $(DEPDIR)/ejson_la-ejson.Plo @AMDEP_TRUE@@am__fastdepCC_FALSE@ source='ejson.c' object='ejson_la-ejson.lo' libtool=yes @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(LIBTOOL) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(ejson_la_CFLAGS) $(CFLAGS) -c -o ejson_la-ejson.lo `test -f 'ejson.c' || echo '$(srcdir)/'`ejson.c ejson_la-decode.lo: decode.c @am__fastdepCC_TRUE@ $(LIBTOOL) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(ejson_la_CFLAGS) $(CFLAGS) -MT ejson_la-decode.lo -MD -MP -MF $(DEPDIR)/ejson_la-decode.Tpo -c -o ejson_la-decode.lo `test -f 'decode.c' || echo '$(srcdir)/'`decode.c @am__fastdepCC_TRUE@ $(am__mv) $(DEPDIR)/ejson_la-decode.Tpo $(DEPDIR)/ejson_la-decode.Plo @AMDEP_TRUE@@am__fastdepCC_FALSE@ source='decode.c' object='ejson_la-decode.lo' libtool=yes @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(LIBTOOL) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(ejson_la_CFLAGS) $(CFLAGS) -c -o ejson_la-decode.lo `test -f 'decode.c' || echo '$(srcdir)/'`decode.c ejson_la-encode.lo: encode.c @am__fastdepCC_TRUE@ $(LIBTOOL) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(ejson_la_CFLAGS) $(CFLAGS) -MT ejson_la-encode.lo -MD -MP -MF $(DEPDIR)/ejson_la-encode.Tpo -c -o ejson_la-encode.lo `test -f 'encode.c' || echo '$(srcdir)/'`encode.c @am__fastdepCC_TRUE@ $(am__mv) $(DEPDIR)/ejson_la-encode.Tpo $(DEPDIR)/ejson_la-encode.Plo @AMDEP_TRUE@@am__fastdepCC_FALSE@ source='encode.c' object='ejson_la-encode.lo' libtool=yes @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(LIBTOOL) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(ejson_la_CFLAGS) $(CFLAGS) -c -o ejson_la-encode.lo `test -f 'encode.c' || echo '$(srcdir)/'`encode.c ejson_la-yajl_alloc.lo: yajl/yajl_alloc.c @am__fastdepCC_TRUE@ $(LIBTOOL) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(ejson_la_CFLAGS) $(CFLAGS) -MT ejson_la-yajl_alloc.lo -MD -MP -MF $(DEPDIR)/ejson_la-yajl_alloc.Tpo -c -o ejson_la-yajl_alloc.lo `test -f 'yajl/yajl_alloc.c' || echo '$(srcdir)/'`yajl/yajl_alloc.c @am__fastdepCC_TRUE@ $(am__mv) $(DEPDIR)/ejson_la-yajl_alloc.Tpo $(DEPDIR)/ejson_la-yajl_alloc.Plo @AMDEP_TRUE@@am__fastdepCC_FALSE@ source='yajl/yajl_alloc.c' object='ejson_la-yajl_alloc.lo' libtool=yes @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(LIBTOOL) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(ejson_la_CFLAGS) $(CFLAGS) -c -o ejson_la-yajl_alloc.lo `test -f 'yajl/yajl_alloc.c' || echo '$(srcdir)/'`yajl/yajl_alloc.c ejson_la-yajl_buf.lo: yajl/yajl_buf.c @am__fastdepCC_TRUE@ $(LIBTOOL) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(ejson_la_CFLAGS) $(CFLAGS) -MT ejson_la-yajl_buf.lo -MD -MP -MF $(DEPDIR)/ejson_la-yajl_buf.Tpo -c -o ejson_la-yajl_buf.lo `test -f 'yajl/yajl_buf.c' || echo '$(srcdir)/'`yajl/yajl_buf.c @am__fastdepCC_TRUE@ $(am__mv) $(DEPDIR)/ejson_la-yajl_buf.Tpo $(DEPDIR)/ejson_la-yajl_buf.Plo @AMDEP_TRUE@@am__fastdepCC_FALSE@ source='yajl/yajl_buf.c' object='ejson_la-yajl_buf.lo' libtool=yes @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(LIBTOOL) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(ejson_la_CFLAGS) $(CFLAGS) -c -o ejson_la-yajl_buf.lo `test -f 'yajl/yajl_buf.c' || echo '$(srcdir)/'`yajl/yajl_buf.c ejson_la-yajl.lo: yajl/yajl.c @am__fastdepCC_TRUE@ $(LIBTOOL) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(ejson_la_CFLAGS) $(CFLAGS) -MT ejson_la-yajl.lo -MD -MP -MF $(DEPDIR)/ejson_la-yajl.Tpo -c -o ejson_la-yajl.lo `test -f 'yajl/yajl.c' || echo '$(srcdir)/'`yajl/yajl.c @am__fastdepCC_TRUE@ $(am__mv) $(DEPDIR)/ejson_la-yajl.Tpo $(DEPDIR)/ejson_la-yajl.Plo @AMDEP_TRUE@@am__fastdepCC_FALSE@ source='yajl/yajl.c' object='ejson_la-yajl.lo' libtool=yes @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(LIBTOOL) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(ejson_la_CFLAGS) $(CFLAGS) -c -o ejson_la-yajl.lo `test -f 'yajl/yajl.c' || echo '$(srcdir)/'`yajl/yajl.c ejson_la-yajl_encode.lo: yajl/yajl_encode.c @am__fastdepCC_TRUE@ $(LIBTOOL) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(ejson_la_CFLAGS) $(CFLAGS) -MT ejson_la-yajl_encode.lo -MD -MP -MF $(DEPDIR)/ejson_la-yajl_encode.Tpo -c -o ejson_la-yajl_encode.lo `test -f 'yajl/yajl_encode.c' || echo '$(srcdir)/'`yajl/yajl_encode.c @am__fastdepCC_TRUE@ $(am__mv) $(DEPDIR)/ejson_la-yajl_encode.Tpo $(DEPDIR)/ejson_la-yajl_encode.Plo @AMDEP_TRUE@@am__fastdepCC_FALSE@ source='yajl/yajl_encode.c' object='ejson_la-yajl_encode.lo' libtool=yes @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(LIBTOOL) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(ejson_la_CFLAGS) $(CFLAGS) -c -o ejson_la-yajl_encode.lo `test -f 'yajl/yajl_encode.c' || echo '$(srcdir)/'`yajl/yajl_encode.c ejson_la-yajl_gen.lo: yajl/yajl_gen.c @am__fastdepCC_TRUE@ $(LIBTOOL) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(ejson_la_CFLAGS) $(CFLAGS) -MT ejson_la-yajl_gen.lo -MD -MP -MF $(DEPDIR)/ejson_la-yajl_gen.Tpo -c -o ejson_la-yajl_gen.lo `test -f 'yajl/yajl_gen.c' || echo '$(srcdir)/'`yajl/yajl_gen.c @am__fastdepCC_TRUE@ $(am__mv) $(DEPDIR)/ejson_la-yajl_gen.Tpo $(DEPDIR)/ejson_la-yajl_gen.Plo @AMDEP_TRUE@@am__fastdepCC_FALSE@ source='yajl/yajl_gen.c' object='ejson_la-yajl_gen.lo' libtool=yes @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(LIBTOOL) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(ejson_la_CFLAGS) $(CFLAGS) -c -o ejson_la-yajl_gen.lo `test -f 'yajl/yajl_gen.c' || echo '$(srcdir)/'`yajl/yajl_gen.c ejson_la-yajl_lex.lo: yajl/yajl_lex.c @am__fastdepCC_TRUE@ $(LIBTOOL) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(ejson_la_CFLAGS) $(CFLAGS) -MT ejson_la-yajl_lex.lo -MD -MP -MF $(DEPDIR)/ejson_la-yajl_lex.Tpo -c -o ejson_la-yajl_lex.lo `test -f 'yajl/yajl_lex.c' || echo '$(srcdir)/'`yajl/yajl_lex.c @am__fastdepCC_TRUE@ $(am__mv) $(DEPDIR)/ejson_la-yajl_lex.Tpo $(DEPDIR)/ejson_la-yajl_lex.Plo @AMDEP_TRUE@@am__fastdepCC_FALSE@ source='yajl/yajl_lex.c' object='ejson_la-yajl_lex.lo' libtool=yes @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(LIBTOOL) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(ejson_la_CFLAGS) $(CFLAGS) -c -o ejson_la-yajl_lex.lo `test -f 'yajl/yajl_lex.c' || echo '$(srcdir)/'`yajl/yajl_lex.c ejson_la-yajl_parser.lo: yajl/yajl_parser.c @am__fastdepCC_TRUE@ $(LIBTOOL) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(ejson_la_CFLAGS) $(CFLAGS) -MT ejson_la-yajl_parser.lo -MD -MP -MF $(DEPDIR)/ejson_la-yajl_parser.Tpo -c -o ejson_la-yajl_parser.lo `test -f 'yajl/yajl_parser.c' || echo '$(srcdir)/'`yajl/yajl_parser.c @am__fastdepCC_TRUE@ $(am__mv) $(DEPDIR)/ejson_la-yajl_parser.Tpo $(DEPDIR)/ejson_la-yajl_parser.Plo @AMDEP_TRUE@@am__fastdepCC_FALSE@ source='yajl/yajl_parser.c' object='ejson_la-yajl_parser.lo' libtool=yes @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(LIBTOOL) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(ejson_la_CFLAGS) $(CFLAGS) -c -o ejson_la-yajl_parser.lo `test -f 'yajl/yajl_parser.c' || echo '$(srcdir)/'`yajl/yajl_parser.c mostlyclean-libtool: -rm -f *.lo clean-libtool: -rm -rf .libs _libs install-ejsonebinDATA: $(ejsonebin_DATA) @$(NORMAL_INSTALL) @list='$(ejsonebin_DATA)'; test -n "$(ejsonebindir)" || list=; \ if test -n "$$list"; then \ echo " $(MKDIR_P) '$(DESTDIR)$(ejsonebindir)'"; \ $(MKDIR_P) "$(DESTDIR)$(ejsonebindir)" || exit 1; \ fi; \ for p in $$list; do \ if test -f "$$p"; then d=; else d="$(srcdir)/"; fi; \ echo "$$d$$p"; \ done | $(am__base_list) | \ while read files; do \ echo " $(INSTALL_DATA) $$files '$(DESTDIR)$(ejsonebindir)'"; \ $(INSTALL_DATA) $$files "$(DESTDIR)$(ejsonebindir)" || exit $$?; \ done uninstall-ejsonebinDATA: @$(NORMAL_UNINSTALL) @list='$(ejsonebin_DATA)'; test -n "$(ejsonebindir)" || list=; \ files=`for p in $$list; do echo $$p; done | sed -e 's|^.*/||'`; \ dir='$(DESTDIR)$(ejsonebindir)'; $(am__uninstall_files_from_dir) ID: $(HEADERS) $(SOURCES) $(LISP) $(TAGS_FILES) list='$(SOURCES) $(HEADERS) $(LISP) $(TAGS_FILES)'; \ unique=`for i in $$list; do \ if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \ done | \ $(AWK) '{ files[$$0] = 1; nonempty = 1; } \ END { if (nonempty) { for (i in files) print i; }; }'`; \ mkid -fID $$unique tags: TAGS TAGS: $(HEADERS) $(SOURCES) $(TAGS_DEPENDENCIES) \ $(TAGS_FILES) $(LISP) set x; \ here=`pwd`; \ list='$(SOURCES) $(HEADERS) $(LISP) $(TAGS_FILES)'; \ unique=`for i in $$list; do \ if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \ done | \ $(AWK) '{ files[$$0] = 1; nonempty = 1; } \ END { if (nonempty) { for (i in files) print i; }; }'`; \ shift; \ if test -z "$(ETAGS_ARGS)$$*$$unique"; then :; else \ test -n "$$unique" || unique=$$empty_fix; \ if test $$# -gt 0; then \ $(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \ "$$@" $$unique; \ else \ $(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \ $$unique; \ fi; \ fi ctags: CTAGS CTAGS: $(HEADERS) $(SOURCES) $(TAGS_DEPENDENCIES) \ $(TAGS_FILES) $(LISP) list='$(SOURCES) $(HEADERS) $(LISP) $(TAGS_FILES)'; \ unique=`for i in $$list; do \ if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \ done | \ $(AWK) '{ files[$$0] = 1; nonempty = 1; } \ END { if (nonempty) { for (i in files) print i; }; }'`; \ test -z "$(CTAGS_ARGS)$$unique" \ || $(CTAGS) $(CTAGSFLAGS) $(AM_CTAGSFLAGS) $(CTAGS_ARGS) \ $$unique GTAGS: here=`$(am__cd) $(top_builddir) && pwd` \ && $(am__cd) $(top_srcdir) \ && gtags -i $(GTAGS_ARGS) "$$here" distclean-tags: -rm -f TAGS ID GTAGS GRTAGS GSYMS GPATH tags distdir: $(DISTFILES) @srcdirstrip=`echo "$(srcdir)" | sed 's/[].[^$$\\*]/\\\\&/g'`; \ topsrcdirstrip=`echo "$(top_srcdir)" | sed 's/[].[^$$\\*]/\\\\&/g'`; \ list='$(DISTFILES)'; \ dist_files=`for file in $$list; do echo $$file; done | \ sed -e "s|^$$srcdirstrip/||;t" \ -e "s|^$$topsrcdirstrip/|$(top_builddir)/|;t"`; \ case $$dist_files in \ */*) $(MKDIR_P) `echo "$$dist_files" | \ sed '/\//!d;s|^|$(distdir)/|;s,/[^/]*$$,,' | \ sort -u` ;; \ esac; \ for file in $$dist_files; do \ if test -f $$file || test -d $$file; then d=.; else d=$(srcdir); fi; \ if test -d $$d/$$file; then \ dir=`echo "/$$file" | sed -e 's,/[^/]*$$,,'`; \ if test -d "$(distdir)/$$file"; then \ find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} \;; \ fi; \ if test -d $(srcdir)/$$file && test $$d != $(srcdir); then \ cp -fpR $(srcdir)/$$file "$(distdir)$$dir" || exit 1; \ find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} \;; \ fi; \ cp -fpR $$d/$$file "$(distdir)$$dir" || exit 1; \ else \ test -f "$(distdir)/$$file" \ || cp -p $$d/$$file "$(distdir)/$$file" \ || exit 1; \ fi; \ done check-am: all-am check: check-am all-am: Makefile $(LTLIBRARIES) $(DATA) installdirs: for dir in "$(DESTDIR)$(ejsonprivdir)" "$(DESTDIR)$(ejsonebindir)"; do \ test -z "$$dir" || $(MKDIR_P) "$$dir"; \ done install: install-am install-exec: install-exec-am install-data: install-data-am uninstall: uninstall-am install-am: all-am @$(MAKE) $(AM_MAKEFLAGS) install-exec-am install-data-am installcheck: installcheck-am install-strip: if test -z '$(STRIP)'; then \ $(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(INSTALL_STRIP_PROGRAM)" \ install_sh_PROGRAM="$(INSTALL_STRIP_PROGRAM)" INSTALL_STRIP_FLAG=-s \ install; \ else \ $(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(INSTALL_STRIP_PROGRAM)" \ install_sh_PROGRAM="$(INSTALL_STRIP_PROGRAM)" INSTALL_STRIP_FLAG=-s \ "INSTALL_PROGRAM_ENV=STRIPPROG='$(STRIP)'" install; \ fi mostlyclean-generic: clean-generic: -test -z "$(CLEANFILES)" || rm -f $(CLEANFILES) distclean-generic: -test -z "$(CONFIG_CLEAN_FILES)" || rm -f $(CONFIG_CLEAN_FILES) -test . = "$(srcdir)" || test -z "$(CONFIG_CLEAN_VPATH_FILES)" || rm -f $(CONFIG_CLEAN_VPATH_FILES) maintainer-clean-generic: @echo "This command is intended for maintainers to use" @echo "it deletes files that may require special tools to rebuild." clean: clean-am clean-am: clean-ejsonprivLTLIBRARIES clean-generic clean-libtool \ mostlyclean-am distclean: distclean-am -rm -rf ./$(DEPDIR) -rm -f Makefile distclean-am: clean-am distclean-compile distclean-generic \ distclean-tags dvi: dvi-am dvi-am: html: html-am html-am: info: info-am info-am: install-data-am: install-ejsonebinDATA install-ejsonprivLTLIBRARIES install-dvi: install-dvi-am install-dvi-am: install-exec-am: install-html: install-html-am install-html-am: install-info: install-info-am install-info-am: install-man: install-pdf: install-pdf-am install-pdf-am: install-ps: install-ps-am install-ps-am: installcheck-am: maintainer-clean: maintainer-clean-am -rm -rf ./$(DEPDIR) -rm -f Makefile maintainer-clean-am: distclean-am maintainer-clean-generic mostlyclean: mostlyclean-am mostlyclean-am: mostlyclean-compile mostlyclean-generic \ mostlyclean-libtool pdf: pdf-am pdf-am: ps: ps-am ps-am: uninstall-am: uninstall-ejsonebinDATA uninstall-ejsonprivLTLIBRARIES .MAKE: install-am install-strip .PHONY: CTAGS GTAGS all all-am check check-am clean \ clean-ejsonprivLTLIBRARIES clean-generic clean-libtool ctags \ distclean distclean-compile distclean-generic \ distclean-libtool distclean-tags distdir dvi dvi-am html \ html-am info info-am install install-am install-data \ install-data-am install-dvi install-dvi-am \ install-ejsonebinDATA install-ejsonprivLTLIBRARIES \ install-exec install-exec-am install-html install-html-am \ install-info install-info-am install-man install-pdf \ install-pdf-am install-ps install-ps-am install-strip \ installcheck installcheck-am installdirs maintainer-clean \ maintainer-clean-generic mostlyclean mostlyclean-compile \ mostlyclean-generic mostlyclean-libtool pdf pdf-am ps ps-am \ tags uninstall uninstall-am uninstall-ejsonebinDATA \ uninstall-ejsonprivLTLIBRARIES @USE_OTP_NIFS_TRUE@priv/$(EJSON_SO_NAME): ejson.la @USE_OTP_NIFS_TRUE@ @mkdir -p ./priv @USE_OTP_NIFS_TRUE@ cp .libs/$(EJSON_SO_NAME) $@ @USE_OTP_NIFS_TRUE@all: priv/$(EJSON_SO_NAME) %.app: %.app.in cp $< $@ %.beam: %.erl $(ERLC) $(ERLC_FLAGS) $< # Tell versions [3.59,3.63) of GNU make to not export all variables. # Otherwise a system limit (for SysV at least) may be exceeded. .NOEXPORT: apache-couchdb-1.5.0/src/ejson/erl_nif_compat.h0000644000175000001440000000657012230722213016321 00000000000000/* Copyright (c) 2010-2011 Basho Technologies, Inc. * With some minor modifications for Apache CouchDB. * * This file is provided to you 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. */ #ifndef ERL_NIF_COMPAT_H_ #define ERL_NIF_COMPAT_H_ #ifdef __cplusplus extern "C" { #endif /* __cplusplus */ #include "erl_nif.h" #if ERL_NIF_MAJOR_VERSION == 0 && ERL_NIF_MINOR_VERSION == 1 #define OTP_R13B03 #elif ERL_NIF_MAJOR_VERSION == 1 && ERL_NIF_MINOR_VERSION == 0 #define OTP_R13B04 #elif ERL_NIF_MAJOR_VERSION == 2 && ERL_NIF_MINOR_VERSION == 0 #define OTP_R14A #define OTP_R14B #define OTP_R14B01 #elif ERL_NIF_MAJOR_VERSION == 2 && ERL_NIF_MINOR_VERSION == 1 #define OTP_R14B02 #endif #ifdef OTP_R13B03 #define enif_open_resource_type_compat enif_open_resource_type #define enif_alloc_resource_compat enif_alloc_resource #define enif_release_resource_compat enif_release_resource #define enif_alloc_binary_compat enif_alloc_binary #define enif_alloc_compat enif_alloc #define enif_release_binary_compat enif_release_binary #define enif_free_compat enif_free #define enif_get_atom_compat enif_get_atom #define enif_priv_data_compat enif_get_data #define enif_make_uint_compat enif_make_ulong #define enif_make_string_compat(E, B, Enc) \ enif_make_string(E, B) #endif /* R13B03 */ #ifdef OTP_R13B04 #define enif_open_resource_type_compat enif_open_resource_type #define enif_alloc_resource_compat enif_alloc_resource #define enif_release_resource_compat enif_release_resource #define enif_alloc_binary_compat enif_alloc_binary #define enif_realloc_binary_compat enif_realloc_binary #define enif_release_binary_compat enif_release_binary #define enif_alloc_compat enif_alloc #define enif_free_compat enif_free #define enif_get_atom_compat enif_get_atom #define enif_priv_data_compat enif_priv_data #define enif_make_string_compat enif_make_string #define enif_make_uint_compat enif_make_uint #endif /* R13B04 */ /* OTP R14 and future releases */ #if !defined(OTP_R13B03) && !defined(OTP_R13B04) #define enif_open_resource_type_compat(E, N, D, F, T) \ enif_open_resource_type(E, NULL, N, D, F, T) #define enif_alloc_resource_compat(E, T, S) \ enif_alloc_resource(T, S) #define enif_release_resource_compat(E, H) \ enif_release_resource(H) #define enif_alloc_binary_compat(E, S, B) \ enif_alloc_binary(S, B) #define enif_realloc_binary_compat(E, S, B) \ enif_realloc_binary(S, B) #define enif_release_binary_compat(E, B) \ enif_release_binary(B) #define enif_alloc_compat(E, S) \ enif_alloc(S) #define enif_free_compat(E, P) \ enif_free(P) #define enif_get_atom_compat(E, T, B, S) \ enif_get_atom(E, T, B, S, ERL_NIF_LATIN1) #define enif_priv_data_compat enif_priv_data #define enif_make_string_compat enif_make_string #define enif_make_uint_compat enif_make_uint #endif /* R14 and future releases */ #ifdef __cplusplus } #endif /* __cplusplus */ #endif /* ERL_NIF_COMPAT_H_ */ apache-couchdb-1.5.0/src/ejson/ejson.app.in0000644000175000001440000000033612230722213015406 00000000000000{application, ejson, [ {description, "EJSON - decode and encode JSON into/from Erlang terms"}, {vsn, "0.1.0"}, {modules, [ejson]}, {registered, []}, {applications, [kernel, stdlib]}, {env, []} ]}. apache-couchdb-1.5.0/src/ejson/mochinum.erl0000644000175000001440000002441312230722213015506 00000000000000%% @copyright 2007 Mochi Media, Inc. %% @author Bob Ippolito %% @doc Useful numeric algorithms for floats that cover some deficiencies %% in the math module. More interesting is digits/1, which implements %% the algorithm from: %% http://www.cs.indiana.edu/~burger/fp/index.html %% See also "Printing Floating-Point Numbers Quickly and Accurately" %% in Proceedings of the SIGPLAN '96 Conference on Programming Language %% Design and Implementation. -module(mochinum). -author("Bob Ippolito "). -export([digits/1, frexp/1, int_pow/2, int_ceil/1]). %% IEEE 754 Float exponent bias -define(FLOAT_BIAS, 1022). -define(MIN_EXP, -1074). -define(BIG_POW, 4503599627370496). %% External API %% @spec digits(number()) -> string() %% @doc Returns a string that accurately represents the given integer or float %% using a conservative amount of digits. Great for generating %% human-readable output, or compact ASCII serializations for floats. digits(N) when is_integer(N) -> integer_to_list(N); digits(0.0) -> "0.0"; digits(Float) -> {Frac1, Exp1} = frexp_int(Float), [Place0 | Digits0] = digits1(Float, Exp1, Frac1), {Place, Digits} = transform_digits(Place0, Digits0), R = insert_decimal(Place, Digits), case Float < 0 of true -> [$- | R]; _ -> R end. %% @spec frexp(F::float()) -> {Frac::float(), Exp::float()} %% @doc Return the fractional and exponent part of an IEEE 754 double, %% equivalent to the libc function of the same name. %% F = Frac * pow(2, Exp). frexp(F) -> frexp1(unpack(F)). %% @spec int_pow(X::integer(), N::integer()) -> Y::integer() %% @doc Moderately efficient way to exponentiate integers. %% int_pow(10, 2) = 100. int_pow(_X, 0) -> 1; int_pow(X, N) when N > 0 -> int_pow(X, N, 1). %% @spec int_ceil(F::float()) -> integer() %% @doc Return the ceiling of F as an integer. The ceiling is defined as %% F when F == trunc(F); %% trunc(F) when F < 0; %% trunc(F) + 1 when F > 0. int_ceil(X) -> T = trunc(X), case (X - T) of Pos when Pos > 0 -> T + 1; _ -> T end. %% Internal API int_pow(X, N, R) when N < 2 -> R * X; int_pow(X, N, R) -> int_pow(X * X, N bsr 1, case N band 1 of 1 -> R * X; 0 -> R end). insert_decimal(0, S) -> "0." ++ S; insert_decimal(Place, S) when Place > 0 -> L = length(S), case Place - L of 0 -> S ++ ".0"; N when N < 0 -> {S0, S1} = lists:split(L + N, S), S0 ++ "." ++ S1; N when N < 6 -> %% More places than digits S ++ lists:duplicate(N, $0) ++ ".0"; _ -> insert_decimal_exp(Place, S) end; insert_decimal(Place, S) when Place > -6 -> "0." ++ lists:duplicate(abs(Place), $0) ++ S; insert_decimal(Place, S) -> insert_decimal_exp(Place, S). insert_decimal_exp(Place, S) -> [C | S0] = S, S1 = case S0 of [] -> "0"; _ -> S0 end, Exp = case Place < 0 of true -> "e-"; false -> "e+" end, [C] ++ "." ++ S1 ++ Exp ++ integer_to_list(abs(Place - 1)). digits1(Float, Exp, Frac) -> Round = ((Frac band 1) =:= 0), case Exp >= 0 of true -> BExp = 1 bsl Exp, case (Frac =/= ?BIG_POW) of true -> scale((Frac * BExp * 2), 2, BExp, BExp, Round, Round, Float); false -> scale((Frac * BExp * 4), 4, (BExp * 2), BExp, Round, Round, Float) end; false -> case (Exp =:= ?MIN_EXP) orelse (Frac =/= ?BIG_POW) of true -> scale((Frac * 2), 1 bsl (1 - Exp), 1, 1, Round, Round, Float); false -> scale((Frac * 4), 1 bsl (2 - Exp), 2, 1, Round, Round, Float) end end. scale(R, S, MPlus, MMinus, LowOk, HighOk, Float) -> Est = int_ceil(math:log10(abs(Float)) - 1.0e-10), %% Note that the scheme implementation uses a 326 element look-up table %% for int_pow(10, N) where we do not. case Est >= 0 of true -> fixup(R, S * int_pow(10, Est), MPlus, MMinus, Est, LowOk, HighOk); false -> Scale = int_pow(10, -Est), fixup(R * Scale, S, MPlus * Scale, MMinus * Scale, Est, LowOk, HighOk) end. fixup(R, S, MPlus, MMinus, K, LowOk, HighOk) -> TooLow = case HighOk of true -> (R + MPlus) >= S; false -> (R + MPlus) > S end, case TooLow of true -> [(K + 1) | generate(R, S, MPlus, MMinus, LowOk, HighOk)]; false -> [K | generate(R * 10, S, MPlus * 10, MMinus * 10, LowOk, HighOk)] end. generate(R0, S, MPlus, MMinus, LowOk, HighOk) -> D = R0 div S, R = R0 rem S, TC1 = case LowOk of true -> R =< MMinus; false -> R < MMinus end, TC2 = case HighOk of true -> (R + MPlus) >= S; false -> (R + MPlus) > S end, case TC1 of false -> case TC2 of false -> [D | generate(R * 10, S, MPlus * 10, MMinus * 10, LowOk, HighOk)]; true -> [D + 1] end; true -> case TC2 of false -> [D]; true -> case R * 2 < S of true -> [D]; false -> [D + 1] end end end. unpack(Float) -> <> = <>, {Sign, Exp, Frac}. frexp1({_Sign, 0, 0}) -> {0.0, 0}; frexp1({Sign, 0, Frac}) -> Exp = log2floor(Frac), <> = <>, {Frac1, -(?FLOAT_BIAS) - 52 + Exp}; frexp1({Sign, Exp, Frac}) -> <> = <>, {Frac1, Exp - ?FLOAT_BIAS}. log2floor(Int) -> log2floor(Int, 0). log2floor(0, N) -> N; log2floor(Int, N) -> log2floor(Int bsr 1, 1 + N). transform_digits(Place, [0 | Rest]) -> transform_digits(Place, Rest); transform_digits(Place, Digits) -> {Place, [$0 + D || D <- Digits]}. frexp_int(F) -> case unpack(F) of {_Sign, 0, Frac} -> {Frac, ?MIN_EXP}; {_Sign, Exp, Frac} -> {Frac + (1 bsl 52), Exp - 53 - ?FLOAT_BIAS} end. %% %% Tests %% -ifdef(TEST). -include_lib("eunit/include/eunit.hrl"). int_ceil_test() -> ?assertEqual(1, int_ceil(0.0001)), ?assertEqual(0, int_ceil(0.0)), ?assertEqual(1, int_ceil(0.99)), ?assertEqual(1, int_ceil(1.0)), ?assertEqual(-1, int_ceil(-1.5)), ?assertEqual(-2, int_ceil(-2.0)), ok. int_pow_test() -> ?assertEqual(1, int_pow(1, 1)), ?assertEqual(1, int_pow(1, 0)), ?assertEqual(1, int_pow(10, 0)), ?assertEqual(10, int_pow(10, 1)), ?assertEqual(100, int_pow(10, 2)), ?assertEqual(1000, int_pow(10, 3)), ok. digits_test() -> ?assertEqual("0", digits(0)), ?assertEqual("0.0", digits(0.0)), ?assertEqual("1.0", digits(1.0)), ?assertEqual("-1.0", digits(-1.0)), ?assertEqual("0.1", digits(0.1)), ?assertEqual("0.01", digits(0.01)), ?assertEqual("0.001", digits(0.001)), ?assertEqual("1.0e+6", digits(1000000.0)), ?assertEqual("0.5", digits(0.5)), ?assertEqual("4503599627370496.0", digits(4503599627370496.0)), %% small denormalized number %% 4.94065645841246544177e-324 =:= 5.0e-324 <> = <<0,0,0,0,0,0,0,1>>, ?assertEqual("5.0e-324", digits(SmallDenorm)), ?assertEqual(SmallDenorm, list_to_float(digits(SmallDenorm))), %% large denormalized number %% 2.22507385850720088902e-308 <> = <<0,15,255,255,255,255,255,255>>, ?assertEqual("2.225073858507201e-308", digits(BigDenorm)), ?assertEqual(BigDenorm, list_to_float(digits(BigDenorm))), %% small normalized number %% 2.22507385850720138309e-308 <> = <<0,16,0,0,0,0,0,0>>, ?assertEqual("2.2250738585072014e-308", digits(SmallNorm)), ?assertEqual(SmallNorm, list_to_float(digits(SmallNorm))), %% large normalized number %% 1.79769313486231570815e+308 <> = <<127,239,255,255,255,255,255,255>>, ?assertEqual("1.7976931348623157e+308", digits(LargeNorm)), ?assertEqual(LargeNorm, list_to_float(digits(LargeNorm))), %% issue #10 - mochinum:frexp(math:pow(2, -1074)). ?assertEqual("5.0e-324", digits(math:pow(2, -1074))), ok. frexp_test() -> %% zero ?assertEqual({0.0, 0}, frexp(0.0)), %% one ?assertEqual({0.5, 1}, frexp(1.0)), %% negative one ?assertEqual({-0.5, 1}, frexp(-1.0)), %% small denormalized number %% 4.94065645841246544177e-324 <> = <<0,0,0,0,0,0,0,1>>, ?assertEqual({0.5, -1073}, frexp(SmallDenorm)), %% large denormalized number %% 2.22507385850720088902e-308 <> = <<0,15,255,255,255,255,255,255>>, ?assertEqual( {0.99999999999999978, -1022}, frexp(BigDenorm)), %% small normalized number %% 2.22507385850720138309e-308 <> = <<0,16,0,0,0,0,0,0>>, ?assertEqual({0.5, -1021}, frexp(SmallNorm)), %% large normalized number %% 1.79769313486231570815e+308 <> = <<127,239,255,255,255,255,255,255>>, ?assertEqual( {0.99999999999999989, 1024}, frexp(LargeNorm)), %% issue #10 - mochinum:frexp(math:pow(2, -1074)). ?assertEqual( {0.5, -1073}, frexp(math:pow(2, -1074))), ok. -endif. apache-couchdb-1.5.0/src/ejson/mochijson2.erl0000644000175000001440000007134212230722213015745 00000000000000%% @author Bob Ippolito %% @copyright 2007 Mochi Media, Inc. %% @doc Yet another JSON (RFC 4627) library for Erlang. mochijson2 works %% with binaries as strings, arrays as lists (without an {array, _}) %% wrapper and it only knows how to decode UTF-8 (and ASCII). %% %% JSON terms are decoded as follows (javascript -> erlang): %%
    %%
  • {"key": "value"} -> %% {struct, [{<<"key">>, <<"value">>}]}
  • %%
  • ["array", 123, 12.34, true, false, null] -> %% [<<"array">>, 123, 12.34, true, false, null] %%
  • %%
%%
    %%
  • Strings in JSON decode to UTF-8 binaries in Erlang
  • %%
  • Objects decode to {struct, PropList}
  • %%
  • Numbers decode to integer or float
  • %%
  • true, false, null decode to their respective terms.
  • %%
%% The encoder will accept the same format that the decoder will produce, %% but will also allow additional cases for leniency: %%
    %%
  • atoms other than true, false, null will be considered UTF-8 %% strings (even as a proplist key) %%
  • %%
  • {json, IoList} will insert IoList directly into the output %% with no validation %%
  • %%
  • {array, Array} will be encoded as Array %% (legacy mochijson style) %%
  • %%
  • A non-empty raw proplist will be encoded as an object as long %% as the first pair does not have an atom key of json, struct, %% or array %%
  • %%
-module(mochijson2). -author('bob@mochimedia.com'). -export([encoder/1, encode/1]). -export([decoder/1, decode/1]). % This is a macro to placate syntax highlighters.. -define(Q, $\"). -define(ADV_COL(S, N), S#decoder{offset=N+S#decoder.offset, column=N+S#decoder.column}). -define(INC_COL(S), S#decoder{offset=1+S#decoder.offset, column=1+S#decoder.column}). -define(INC_LINE(S), S#decoder{offset=1+S#decoder.offset, column=1, line=1+S#decoder.line}). -define(INC_CHAR(S, C), case C of $\n -> S#decoder{column=1, line=1+S#decoder.line, offset=1+S#decoder.offset}; _ -> S#decoder{column=1+S#decoder.column, offset=1+S#decoder.offset} end). -define(IS_WHITESPACE(C), (C =:= $\s orelse C =:= $\t orelse C =:= $\r orelse C =:= $\n)). %% @type iolist() = [char() | binary() | iolist()] %% @type iodata() = iolist() | binary() %% @type json_string() = atom | binary() %% @type json_number() = integer() | float() %% @type json_array() = [json_term()] %% @type json_object() = {struct, [{json_string(), json_term()}]} %% @type json_iolist() = {json, iolist()} %% @type json_term() = json_string() | json_number() | json_array() | %% json_object() | json_iolist() -record(encoder, {handler=null, utf8=false}). -record(decoder, {object_hook=null, offset=0, line=1, column=1, state=null}). %% @spec encoder([encoder_option()]) -> function() %% @doc Create an encoder/1 with the given options. %% @type encoder_option() = handler_option() | utf8_option() %% @type utf8_option() = boolean(). Emit unicode as utf8 (default - false) encoder(Options) -> State = parse_encoder_options(Options, #encoder{}), fun (O) -> json_encode(O, State) end. %% @spec encode(json_term()) -> iolist() %% @doc Encode the given as JSON to an iolist. encode(Any) -> json_encode(Any, #encoder{}). %% @spec decoder([decoder_option()]) -> function() %% @doc Create a decoder/1 with the given options. decoder(Options) -> State = parse_decoder_options(Options, #decoder{}), fun (O) -> json_decode(O, State) end. %% @spec decode(iolist()) -> json_term() %% @doc Decode the given iolist to Erlang terms. decode(S) -> json_decode(S, #decoder{}). %% Internal API parse_encoder_options([], State) -> State; parse_encoder_options([{handler, Handler} | Rest], State) -> parse_encoder_options(Rest, State#encoder{handler=Handler}); parse_encoder_options([{utf8, Switch} | Rest], State) -> parse_encoder_options(Rest, State#encoder{utf8=Switch}). parse_decoder_options([], State) -> State; parse_decoder_options([{object_hook, Hook} | Rest], State) -> parse_decoder_options(Rest, State#decoder{object_hook=Hook}). json_encode(true, _State) -> <<"true">>; json_encode(false, _State) -> <<"false">>; json_encode(null, _State) -> <<"null">>; json_encode(I, _State) when is_integer(I) -> integer_to_list(I); json_encode(F, _State) when is_float(F) -> mochinum:digits(F); json_encode(S, State) when is_binary(S); is_atom(S) -> json_encode_string(S, State); json_encode([{K, _}|_] = Props, State) when (K =/= struct andalso K =/= array andalso K =/= json) -> json_encode_proplist(Props, State); json_encode({struct, Props}, State) when is_list(Props) -> json_encode_proplist(Props, State); json_encode(Array, State) when is_list(Array) -> json_encode_array(Array, State); json_encode({array, Array}, State) when is_list(Array) -> json_encode_array(Array, State); json_encode({json, IoList}, _State) -> IoList; json_encode(Bad, #encoder{handler=null}) -> exit({json_encode, {bad_term, Bad}}); json_encode(Bad, State=#encoder{handler=Handler}) -> json_encode(Handler(Bad), State). json_encode_array([], _State) -> <<"[]">>; json_encode_array(L, State) -> F = fun (O, Acc) -> [$,, json_encode(O, State) | Acc] end, [$, | Acc1] = lists:foldl(F, "[", L), lists:reverse([$\] | Acc1]). json_encode_proplist([], _State) -> <<"{}">>; json_encode_proplist(Props, State) -> F = fun ({K, V}, Acc) -> KS = json_encode_string(K, State), VS = json_encode(V, State), [$,, VS, $:, KS | Acc] end, [$, | Acc1] = lists:foldl(F, "{", Props), lists:reverse([$\} | Acc1]). json_encode_string(A, State) when is_atom(A) -> L = atom_to_list(A), case json_string_is_safe(L) of true -> [?Q, L, ?Q]; false -> json_encode_string_unicode(xmerl_ucs:from_utf8(L), State, [?Q]) end; json_encode_string(B, State) when is_binary(B) -> case json_bin_is_safe(B) of true -> [?Q, B, ?Q]; false -> json_encode_string_unicode(xmerl_ucs:from_utf8(B), State, [?Q]) end; json_encode_string(I, _State) when is_integer(I) -> [?Q, integer_to_list(I), ?Q]; json_encode_string(L, State) when is_list(L) -> case json_string_is_safe(L) of true -> [?Q, L, ?Q]; false -> json_encode_string_unicode(L, State, [?Q]) end. json_string_is_safe([]) -> true; json_string_is_safe([C | Rest]) -> case C of ?Q -> false; $\\ -> false; $\b -> false; $\f -> false; $\n -> false; $\r -> false; $\t -> false; C when C >= 0, C < $\s; C >= 16#7f, C =< 16#10FFFF -> false; C when C < 16#7f -> json_string_is_safe(Rest); _ -> false end. json_bin_is_safe(<<>>) -> true; json_bin_is_safe(<>) -> case C of ?Q -> false; $\\ -> false; $\b -> false; $\f -> false; $\n -> false; $\r -> false; $\t -> false; C when C >= 0, C < $\s; C >= 16#7f -> false; C when C < 16#7f -> json_bin_is_safe(Rest) end. json_encode_string_unicode([], _State, Acc) -> lists:reverse([$\" | Acc]); json_encode_string_unicode([C | Cs], State, Acc) -> Acc1 = case C of ?Q -> [?Q, $\\ | Acc]; %% Escaping solidus is only useful when trying to protect %% against "" injection attacks which are only %% possible when JSON is inserted into a HTML document %% in-line. mochijson2 does not protect you from this, so %% if you do insert directly into HTML then you need to %% uncomment the following case or escape the output of encode. %% %% $/ -> %% [$/, $\\ | Acc]; %% $\\ -> [$\\, $\\ | Acc]; $\b -> [$b, $\\ | Acc]; $\f -> [$f, $\\ | Acc]; $\n -> [$n, $\\ | Acc]; $\r -> [$r, $\\ | Acc]; $\t -> [$t, $\\ | Acc]; C when C >= 0, C < $\s -> [unihex(C) | Acc]; C when C >= 16#7f, C =< 16#10FFFF, State#encoder.utf8 -> [xmerl_ucs:to_utf8(C) | Acc]; C when C >= 16#7f, C =< 16#10FFFF, not State#encoder.utf8 -> [unihex(C) | Acc]; C when C < 16#7f -> [C | Acc]; _ -> exit({json_encode, {bad_char, C}}) end, json_encode_string_unicode(Cs, State, Acc1). hexdigit(C) when C >= 0, C =< 9 -> C + $0; hexdigit(C) when C =< 15 -> C + $a - 10. unihex(C) when C < 16#10000 -> <> = <>, Digits = [hexdigit(D) || D <- [D3, D2, D1, D0]], [$\\, $u | Digits]; unihex(C) when C =< 16#10FFFF -> N = C - 16#10000, S1 = 16#d800 bor ((N bsr 10) band 16#3ff), S2 = 16#dc00 bor (N band 16#3ff), [unihex(S1), unihex(S2)]. json_decode(L, S) when is_list(L) -> json_decode(iolist_to_binary(L), S); json_decode(B, S) -> {Res, S1} = decode1(B, S), {eof, _} = tokenize(B, S1#decoder{state=trim}), Res. decode1(B, S=#decoder{state=null}) -> case tokenize(B, S#decoder{state=any}) of {{const, C}, S1} -> {C, S1}; {start_array, S1} -> decode_array(B, S1); {start_object, S1} -> decode_object(B, S1) end. make_object(V, #decoder{object_hook=null}) -> V; make_object(V, #decoder{object_hook=Hook}) -> Hook(V). decode_object(B, S) -> decode_object(B, S#decoder{state=key}, []). decode_object(B, S=#decoder{state=key}, Acc) -> case tokenize(B, S) of {end_object, S1} -> V = make_object({struct, lists:reverse(Acc)}, S1), {V, S1#decoder{state=null}}; {{const, K}, S1} -> {colon, S2} = tokenize(B, S1), {V, S3} = decode1(B, S2#decoder{state=null}), decode_object(B, S3#decoder{state=comma}, [{K, V} | Acc]) end; decode_object(B, S=#decoder{state=comma}, Acc) -> case tokenize(B, S) of {end_object, S1} -> V = make_object({struct, lists:reverse(Acc)}, S1), {V, S1#decoder{state=null}}; {comma, S1} -> decode_object(B, S1#decoder{state=key}, Acc) end. decode_array(B, S) -> decode_array(B, S#decoder{state=any}, []). decode_array(B, S=#decoder{state=any}, Acc) -> case tokenize(B, S) of {end_array, S1} -> {lists:reverse(Acc), S1#decoder{state=null}}; {start_array, S1} -> {Array, S2} = decode_array(B, S1), decode_array(B, S2#decoder{state=comma}, [Array | Acc]); {start_object, S1} -> {Array, S2} = decode_object(B, S1), decode_array(B, S2#decoder{state=comma}, [Array | Acc]); {{const, Const}, S1} -> decode_array(B, S1#decoder{state=comma}, [Const | Acc]) end; decode_array(B, S=#decoder{state=comma}, Acc) -> case tokenize(B, S) of {end_array, S1} -> {lists:reverse(Acc), S1#decoder{state=null}}; {comma, S1} -> decode_array(B, S1#decoder{state=any}, Acc) end. tokenize_string(B, S=#decoder{offset=O}) -> case tokenize_string_fast(B, O) of {escape, O1} -> Length = O1 - O, S1 = ?ADV_COL(S, Length), <<_:O/binary, Head:Length/binary, _/binary>> = B, tokenize_string(B, S1, lists:reverse(binary_to_list(Head))); O1 -> Length = O1 - O, <<_:O/binary, String:Length/binary, ?Q, _/binary>> = B, {{const, String}, ?ADV_COL(S, Length + 1)} end. tokenize_string_fast(B, O) -> case B of <<_:O/binary, ?Q, _/binary>> -> O; <<_:O/binary, $\\, _/binary>> -> {escape, O}; <<_:O/binary, C1, _/binary>> when C1 < 128 -> tokenize_string_fast(B, 1 + O); <<_:O/binary, C1, C2, _/binary>> when C1 >= 194, C1 =< 223, C2 >= 128, C2 =< 191 -> tokenize_string_fast(B, 2 + O); <<_:O/binary, C1, C2, C3, _/binary>> when C1 >= 224, C1 =< 239, C2 >= 128, C2 =< 191, C3 >= 128, C3 =< 191 -> tokenize_string_fast(B, 3 + O); <<_:O/binary, C1, C2, C3, C4, _/binary>> when C1 >= 240, C1 =< 244, C2 >= 128, C2 =< 191, C3 >= 128, C3 =< 191, C4 >= 128, C4 =< 191 -> tokenize_string_fast(B, 4 + O); _ -> throw(invalid_utf8) end. tokenize_string(B, S=#decoder{offset=O}, Acc) -> case B of <<_:O/binary, ?Q, _/binary>> -> {{const, iolist_to_binary(lists:reverse(Acc))}, ?INC_COL(S)}; <<_:O/binary, "\\\"", _/binary>> -> tokenize_string(B, ?ADV_COL(S, 2), [$\" | Acc]); <<_:O/binary, "\\\\", _/binary>> -> tokenize_string(B, ?ADV_COL(S, 2), [$\\ | Acc]); <<_:O/binary, "\\/", _/binary>> -> tokenize_string(B, ?ADV_COL(S, 2), [$/ | Acc]); <<_:O/binary, "\\b", _/binary>> -> tokenize_string(B, ?ADV_COL(S, 2), [$\b | Acc]); <<_:O/binary, "\\f", _/binary>> -> tokenize_string(B, ?ADV_COL(S, 2), [$\f | Acc]); <<_:O/binary, "\\n", _/binary>> -> tokenize_string(B, ?ADV_COL(S, 2), [$\n | Acc]); <<_:O/binary, "\\r", _/binary>> -> tokenize_string(B, ?ADV_COL(S, 2), [$\r | Acc]); <<_:O/binary, "\\t", _/binary>> -> tokenize_string(B, ?ADV_COL(S, 2), [$\t | Acc]); <<_:O/binary, "\\u", C3, C2, C1, C0, Rest/binary>> -> C = erlang:list_to_integer([C3, C2, C1, C0], 16), if C > 16#D7FF, C < 16#DC00 -> %% coalesce UTF-16 surrogate pair <<"\\u", D3, D2, D1, D0, _/binary>> = Rest, D = erlang:list_to_integer([D3,D2,D1,D0], 16), [CodePoint] = xmerl_ucs:from_utf16be(<>), Acc1 = lists:reverse(xmerl_ucs:to_utf8(CodePoint), Acc), tokenize_string(B, ?ADV_COL(S, 12), Acc1); true -> Acc1 = lists:reverse(xmerl_ucs:to_utf8(C), Acc), tokenize_string(B, ?ADV_COL(S, 6), Acc1) end; <<_:O/binary, C1, _/binary>> when C1 < 128 -> tokenize_string(B, ?INC_CHAR(S, C1), [C1 | Acc]); <<_:O/binary, C1, C2, _/binary>> when C1 >= 194, C1 =< 223, C2 >= 128, C2 =< 191 -> tokenize_string(B, ?ADV_COL(S, 2), [C2, C1 | Acc]); <<_:O/binary, C1, C2, C3, _/binary>> when C1 >= 224, C1 =< 239, C2 >= 128, C2 =< 191, C3 >= 128, C3 =< 191 -> tokenize_string(B, ?ADV_COL(S, 3), [C3, C2, C1 | Acc]); <<_:O/binary, C1, C2, C3, C4, _/binary>> when C1 >= 240, C1 =< 244, C2 >= 128, C2 =< 191, C3 >= 128, C3 =< 191, C4 >= 128, C4 =< 191 -> tokenize_string(B, ?ADV_COL(S, 4), [C4, C3, C2, C1 | Acc]); _ -> throw(invalid_utf8) end. tokenize_number(B, S) -> case tokenize_number(B, sign, S, []) of {{int, Int}, S1} -> {{const, list_to_integer(Int)}, S1}; {{float, Float}, S1} -> {{const, list_to_float(Float)}, S1} end. tokenize_number(B, sign, S=#decoder{offset=O}, []) -> case B of <<_:O/binary, $-, _/binary>> -> tokenize_number(B, int, ?INC_COL(S), [$-]); _ -> tokenize_number(B, int, S, []) end; tokenize_number(B, int, S=#decoder{offset=O}, Acc) -> case B of <<_:O/binary, $0, _/binary>> -> tokenize_number(B, frac, ?INC_COL(S), [$0 | Acc]); <<_:O/binary, C, _/binary>> when C >= $1 andalso C =< $9 -> tokenize_number(B, int1, ?INC_COL(S), [C | Acc]) end; tokenize_number(B, int1, S=#decoder{offset=O}, Acc) -> case B of <<_:O/binary, C, _/binary>> when C >= $0 andalso C =< $9 -> tokenize_number(B, int1, ?INC_COL(S), [C | Acc]); _ -> tokenize_number(B, frac, S, Acc) end; tokenize_number(B, frac, S=#decoder{offset=O}, Acc) -> case B of <<_:O/binary, $., C, _/binary>> when C >= $0, C =< $9 -> tokenize_number(B, frac1, ?ADV_COL(S, 2), [C, $. | Acc]); <<_:O/binary, E, _/binary>> when E =:= $e orelse E =:= $E -> tokenize_number(B, esign, ?INC_COL(S), [$e, $0, $. | Acc]); _ -> {{int, lists:reverse(Acc)}, S} end; tokenize_number(B, frac1, S=#decoder{offset=O}, Acc) -> case B of <<_:O/binary, C, _/binary>> when C >= $0 andalso C =< $9 -> tokenize_number(B, frac1, ?INC_COL(S), [C | Acc]); <<_:O/binary, E, _/binary>> when E =:= $e orelse E =:= $E -> tokenize_number(B, esign, ?INC_COL(S), [$e | Acc]); _ -> {{float, lists:reverse(Acc)}, S} end; tokenize_number(B, esign, S=#decoder{offset=O}, Acc) -> case B of <<_:O/binary, C, _/binary>> when C =:= $- orelse C=:= $+ -> tokenize_number(B, eint, ?INC_COL(S), [C | Acc]); _ -> tokenize_number(B, eint, S, Acc) end; tokenize_number(B, eint, S=#decoder{offset=O}, Acc) -> case B of <<_:O/binary, C, _/binary>> when C >= $0 andalso C =< $9 -> tokenize_number(B, eint1, ?INC_COL(S), [C | Acc]) end; tokenize_number(B, eint1, S=#decoder{offset=O}, Acc) -> case B of <<_:O/binary, C, _/binary>> when C >= $0 andalso C =< $9 -> tokenize_number(B, eint1, ?INC_COL(S), [C | Acc]); _ -> {{float, lists:reverse(Acc)}, S} end. tokenize(B, S=#decoder{offset=O}) -> case B of <<_:O/binary, C, _/binary>> when ?IS_WHITESPACE(C) -> tokenize(B, ?INC_CHAR(S, C)); <<_:O/binary, "{", _/binary>> -> {start_object, ?INC_COL(S)}; <<_:O/binary, "}", _/binary>> -> {end_object, ?INC_COL(S)}; <<_:O/binary, "[", _/binary>> -> {start_array, ?INC_COL(S)}; <<_:O/binary, "]", _/binary>> -> {end_array, ?INC_COL(S)}; <<_:O/binary, ",", _/binary>> -> {comma, ?INC_COL(S)}; <<_:O/binary, ":", _/binary>> -> {colon, ?INC_COL(S)}; <<_:O/binary, "null", _/binary>> -> {{const, null}, ?ADV_COL(S, 4)}; <<_:O/binary, "true", _/binary>> -> {{const, true}, ?ADV_COL(S, 4)}; <<_:O/binary, "false", _/binary>> -> {{const, false}, ?ADV_COL(S, 5)}; <<_:O/binary, "\"", _/binary>> -> tokenize_string(B, ?INC_COL(S)); <<_:O/binary, C, _/binary>> when (C >= $0 andalso C =< $9) orelse C =:= $- -> tokenize_number(B, S); <<_:O/binary>> -> trim = S#decoder.state, {eof, S} end. %% %% Tests %% -ifdef(TEST). -include_lib("eunit/include/eunit.hrl"). %% testing constructs borrowed from the Yaws JSON implementation. %% Create an object from a list of Key/Value pairs. obj_new() -> {struct, []}. is_obj({struct, Props}) -> F = fun ({K, _}) when is_binary(K) -> true end, lists:all(F, Props). obj_from_list(Props) -> Obj = {struct, Props}, ?assert(is_obj(Obj)), Obj. %% Test for equivalence of Erlang terms. %% Due to arbitrary order of construction, equivalent objects might %% compare unequal as erlang terms, so we need to carefully recurse %% through aggregates (tuples and objects). equiv({struct, Props1}, {struct, Props2}) -> equiv_object(Props1, Props2); equiv(L1, L2) when is_list(L1), is_list(L2) -> equiv_list(L1, L2); equiv(N1, N2) when is_number(N1), is_number(N2) -> N1 == N2; equiv(B1, B2) when is_binary(B1), is_binary(B2) -> B1 == B2; equiv(A, A) when A =:= true orelse A =:= false orelse A =:= null -> true. %% Object representation and traversal order is unknown. %% Use the sledgehammer and sort property lists. equiv_object(Props1, Props2) -> L1 = lists:keysort(1, Props1), L2 = lists:keysort(1, Props2), Pairs = lists:zip(L1, L2), true = lists:all(fun({{K1, V1}, {K2, V2}}) -> equiv(K1, K2) and equiv(V1, V2) end, Pairs). %% Recursively compare tuple elements for equivalence. equiv_list([], []) -> true; equiv_list([V1 | L1], [V2 | L2]) -> equiv(V1, V2) andalso equiv_list(L1, L2). decode_test() -> [1199344435545.0, 1] = decode(<<"[1199344435545.0,1]">>), <<16#F0,16#9D,16#9C,16#95>> = decode([34,"\\ud835","\\udf15",34]). e2j_vec_test() -> test_one(e2j_test_vec(utf8), 1). test_one([], _N) -> %% io:format("~p tests passed~n", [N-1]), ok; test_one([{E, J} | Rest], N) -> %% io:format("[~p] ~p ~p~n", [N, E, J]), true = equiv(E, decode(J)), true = equiv(E, decode(encode(E))), test_one(Rest, 1+N). e2j_test_vec(utf8) -> [ {1, "1"}, {3.1416, "3.14160"}, %% text representation may truncate, trail zeroes {-1, "-1"}, {-3.1416, "-3.14160"}, {12.0e10, "1.20000e+11"}, {1.234E+10, "1.23400e+10"}, {-1.234E-10, "-1.23400e-10"}, {10.0, "1.0e+01"}, {123.456, "1.23456E+2"}, {10.0, "1e1"}, {<<"foo">>, "\"foo\""}, {<<"foo", 5, "bar">>, "\"foo\\u0005bar\""}, {<<"">>, "\"\""}, {<<"\n\n\n">>, "\"\\n\\n\\n\""}, {<<"\" \b\f\r\n\t\"">>, "\"\\\" \\b\\f\\r\\n\\t\\\"\""}, {obj_new(), "{}"}, {obj_from_list([{<<"foo">>, <<"bar">>}]), "{\"foo\":\"bar\"}"}, {obj_from_list([{<<"foo">>, <<"bar">>}, {<<"baz">>, 123}]), "{\"foo\":\"bar\",\"baz\":123}"}, {[], "[]"}, {[[]], "[[]]"}, {[1, <<"foo">>], "[1,\"foo\"]"}, %% json array in a json object {obj_from_list([{<<"foo">>, [123]}]), "{\"foo\":[123]}"}, %% json object in a json object {obj_from_list([{<<"foo">>, obj_from_list([{<<"bar">>, true}])}]), "{\"foo\":{\"bar\":true}}"}, %% fold evaluation order {obj_from_list([{<<"foo">>, []}, {<<"bar">>, obj_from_list([{<<"baz">>, true}])}, {<<"alice">>, <<"bob">>}]), "{\"foo\":[],\"bar\":{\"baz\":true},\"alice\":\"bob\"}"}, %% json object in a json array {[-123, <<"foo">>, obj_from_list([{<<"bar">>, []}]), null], "[-123,\"foo\",{\"bar\":[]},null]"} ]. %% test utf8 encoding encoder_utf8_test() -> %% safe conversion case (default) [34,"\\u0001","\\u0442","\\u0435","\\u0441","\\u0442",34] = encode(<<1,"\321\202\320\265\321\201\321\202">>), %% raw utf8 output (optional) Enc = mochijson2:encoder([{utf8, true}]), [34,"\\u0001",[209,130],[208,181],[209,129],[209,130],34] = Enc(<<1,"\321\202\320\265\321\201\321\202">>). input_validation_test() -> Good = [ {16#00A3, <>}, %% pound {16#20AC, <>}, %% euro {16#10196, <>} %% denarius ], lists:foreach(fun({CodePoint, UTF8}) -> Expect = list_to_binary(xmerl_ucs:to_utf8(CodePoint)), Expect = decode(UTF8) end, Good), Bad = [ %% 2nd, 3rd, or 4th byte of a multi-byte sequence w/o leading byte <>, %% missing continuations, last byte in each should be 80-BF <>, <>, <>, %% we don't support code points > 10FFFF per RFC 3629 <>, %% escape characters trigger a different code path <> ], lists:foreach( fun(X) -> ok = try decode(X) catch invalid_utf8 -> ok end, %% could be {ucs,{bad_utf8_character_code}} or %% {json_encode,{bad_char,_}} {'EXIT', _} = (catch encode(X)) end, Bad). inline_json_test() -> ?assertEqual(<<"\"iodata iodata\"">>, iolist_to_binary( encode({json, [<<"\"iodata">>, " iodata\""]}))), ?assertEqual({struct, [{<<"key">>, <<"iodata iodata">>}]}, decode( encode({struct, [{key, {json, [<<"\"iodata">>, " iodata\""]}}]}))), ok. big_unicode_test() -> UTF8Seq = list_to_binary(xmerl_ucs:to_utf8(16#0001d120)), ?assertEqual( <<"\"\\ud834\\udd20\"">>, iolist_to_binary(encode(UTF8Seq))), ?assertEqual( UTF8Seq, decode(iolist_to_binary(encode(UTF8Seq)))), ok. custom_decoder_test() -> ?assertEqual( {struct, [{<<"key">>, <<"value">>}]}, (decoder([]))("{\"key\": \"value\"}")), F = fun ({struct, [{<<"key">>, <<"value">>}]}) -> win end, ?assertEqual( win, (decoder([{object_hook, F}]))("{\"key\": \"value\"}")), ok. atom_test() -> %% JSON native atoms [begin ?assertEqual(A, decode(atom_to_list(A))), ?assertEqual(iolist_to_binary(atom_to_list(A)), iolist_to_binary(encode(A))) end || A <- [true, false, null]], %% Atom to string ?assertEqual( <<"\"foo\"">>, iolist_to_binary(encode(foo))), ?assertEqual( <<"\"\\ud834\\udd20\"">>, iolist_to_binary(encode(list_to_atom(xmerl_ucs:to_utf8(16#0001d120))))), ok. key_encode_test() -> %% Some forms are accepted as keys that would not be strings in other %% cases ?assertEqual( <<"{\"foo\":1}">>, iolist_to_binary(encode({struct, [{foo, 1}]}))), ?assertEqual( <<"{\"foo\":1}">>, iolist_to_binary(encode({struct, [{<<"foo">>, 1}]}))), ?assertEqual( <<"{\"foo\":1}">>, iolist_to_binary(encode({struct, [{"foo", 1}]}))), ?assertEqual( <<"{\"foo\":1}">>, iolist_to_binary(encode([{foo, 1}]))), ?assertEqual( <<"{\"foo\":1}">>, iolist_to_binary(encode([{<<"foo">>, 1}]))), ?assertEqual( <<"{\"foo\":1}">>, iolist_to_binary(encode([{"foo", 1}]))), ?assertEqual( <<"{\"\\ud834\\udd20\":1}">>, iolist_to_binary( encode({struct, [{[16#0001d120], 1}]}))), ?assertEqual( <<"{\"1\":1}">>, iolist_to_binary(encode({struct, [{1, 1}]}))), ok. unsafe_chars_test() -> Chars = "\"\\\b\f\n\r\t", [begin ?assertEqual(false, json_string_is_safe([C])), ?assertEqual(false, json_bin_is_safe(<>)), ?assertEqual(<>, decode(encode(<>))) end || C <- Chars], ?assertEqual( false, json_string_is_safe([16#0001d120])), ?assertEqual( false, json_bin_is_safe(list_to_binary(xmerl_ucs:to_utf8(16#0001d120)))), ?assertEqual( [16#0001d120], xmerl_ucs:from_utf8( binary_to_list( decode(encode(list_to_atom(xmerl_ucs:to_utf8(16#0001d120))))))), ?assertEqual( false, json_string_is_safe([16#110000])), ?assertEqual( false, json_bin_is_safe(list_to_binary(xmerl_ucs:to_utf8([16#110000])))), %% solidus can be escaped but isn't unsafe by default ?assertEqual( <<"/">>, decode(<<"\"\\/\"">>)), ok. int_test() -> ?assertEqual(0, decode("0")), ?assertEqual(1, decode("1")), ?assertEqual(11, decode("11")), ok. large_int_test() -> ?assertEqual(<<"-2147483649214748364921474836492147483649">>, iolist_to_binary(encode(-2147483649214748364921474836492147483649))), ?assertEqual(<<"2147483649214748364921474836492147483649">>, iolist_to_binary(encode(2147483649214748364921474836492147483649))), ok. float_test() -> ?assertEqual(<<"-2147483649.0">>, iolist_to_binary(encode(-2147483649.0))), ?assertEqual(<<"2147483648.0">>, iolist_to_binary(encode(2147483648.0))), ok. handler_test() -> ?assertEqual( {'EXIT',{json_encode,{bad_term,{}}}}, catch encode({})), F = fun ({}) -> [] end, ?assertEqual( <<"[]">>, iolist_to_binary((encoder([{handler, F}]))({}))), ok. -endif. apache-couchdb-1.5.0/src/couch_replicator/0000755000175000001440000000000012230722303015446 500000000000000apache-couchdb-1.5.0/src/couch_replicator/src/0000755000175000001440000000000012230722303016235 500000000000000apache-couchdb-1.5.0/src/couch_replicator/src/couch_replicator_manager.erl0000644000175000001440000005323212230722213023705 00000000000000% 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. -module(couch_replicator_manager). -behaviour(gen_server). % public API -export([replication_started/1, replication_completed/2, replication_error/2]). -export([before_doc_update/2, after_doc_read/2]). % gen_server callbacks -export([start_link/0, init/1, handle_call/3, handle_info/2, handle_cast/2]). -export([code_change/3, terminate/2]). -include("couch_db.hrl"). -include("couch_replicator.hrl"). -include("couch_replicator_js_functions.hrl"). -define(DOC_TO_REP, couch_rep_doc_id_to_rep_id). -define(REP_TO_STATE, couch_rep_id_to_rep_state). -define(INITIAL_WAIT, 2.5). % seconds -define(MAX_WAIT, 600). % seconds -define(OWNER, <<"owner">>). -define(replace(L, K, V), lists:keystore(K, 1, L, {K, V})). -record(rep_state, { rep, starting, retries_left, max_retries, wait = ?INITIAL_WAIT }). -import(couch_util, [ get_value/2, get_value/3, to_binary/1 ]). -record(state, { changes_feed_loop = nil, db_notifier = nil, rep_db_name = nil, rep_start_pids = [], max_retries }). start_link() -> gen_server:start_link({local, ?MODULE}, ?MODULE, [], []). replication_started(#rep{id = {BaseId, _} = RepId}) -> case rep_state(RepId) of nil -> ok; #rep_state{rep = #rep{doc_id = DocId}} -> update_rep_doc(DocId, [ {<<"_replication_state">>, <<"triggered">>}, {<<"_replication_id">>, ?l2b(BaseId)}, {<<"_replication_stats">>, undefined}]), ok = gen_server:call(?MODULE, {rep_started, RepId}, infinity), ?LOG_INFO("Document `~s` triggered replication `~s`", [DocId, pp_rep_id(RepId)]) end. replication_completed(#rep{id = RepId}, Stats) -> case rep_state(RepId) of nil -> ok; #rep_state{rep = #rep{doc_id = DocId}} -> update_rep_doc(DocId, [ {<<"_replication_state">>, <<"completed">>}, {<<"_replication_stats">>, {Stats}}]), ok = gen_server:call(?MODULE, {rep_complete, RepId}, infinity), ?LOG_INFO("Replication `~s` finished (triggered by document `~s`)", [pp_rep_id(RepId), DocId]) end. replication_error(#rep{id = {BaseId, _} = RepId}, Error) -> case rep_state(RepId) of nil -> ok; #rep_state{rep = #rep{doc_id = DocId}} -> % TODO: maybe add error reason to replication document update_rep_doc(DocId, [ {<<"_replication_state">>, <<"error">>}, {<<"_replication_id">>, ?l2b(BaseId)}]), ok = gen_server:call(?MODULE, {rep_error, RepId, Error}, infinity) end. init(_) -> process_flag(trap_exit, true), ?DOC_TO_REP = ets:new(?DOC_TO_REP, [named_table, set, protected]), ?REP_TO_STATE = ets:new(?REP_TO_STATE, [named_table, set, protected]), Server = self(), ok = couch_config:register( fun("replicator", "db", NewName) -> ok = gen_server:cast(Server, {rep_db_changed, ?l2b(NewName)}); ("replicator", "max_replication_retry_count", V) -> ok = gen_server:cast(Server, {set_max_retries, retries_value(V)}) end ), {Loop, RepDbName} = changes_feed_loop(), {ok, #state{ changes_feed_loop = Loop, rep_db_name = RepDbName, db_notifier = db_update_notifier(), max_retries = retries_value( couch_config:get("replicator", "max_replication_retry_count", "10")) }}. handle_call({rep_db_update, {ChangeProps} = Change}, _From, State) -> NewState = try process_update(State, Change) catch _Tag:Error -> {RepProps} = get_value(doc, ChangeProps), DocId = get_value(<<"_id">>, RepProps), rep_db_update_error(Error, DocId), State end, {reply, ok, NewState}; handle_call({rep_started, RepId}, _From, State) -> case rep_state(RepId) of nil -> ok; RepState -> NewRepState = RepState#rep_state{ starting = false, retries_left = State#state.max_retries, max_retries = State#state.max_retries, wait = ?INITIAL_WAIT }, true = ets:insert(?REP_TO_STATE, {RepId, NewRepState}) end, {reply, ok, State}; handle_call({rep_complete, RepId}, _From, State) -> true = ets:delete(?REP_TO_STATE, RepId), {reply, ok, State}; handle_call({rep_error, RepId, Error}, _From, State) -> {reply, ok, replication_error(State, RepId, Error)}; handle_call(Msg, From, State) -> ?LOG_ERROR("Replication manager received unexpected call ~p from ~p", [Msg, From]), {stop, {error, {unexpected_call, Msg}}, State}. handle_cast({rep_db_changed, NewName}, #state{rep_db_name = NewName} = State) -> {noreply, State}; handle_cast({rep_db_changed, _NewName}, State) -> {noreply, restart(State)}; handle_cast({rep_db_created, NewName}, #state{rep_db_name = NewName} = State) -> {noreply, State}; handle_cast({rep_db_created, _NewName}, State) -> {noreply, restart(State)}; handle_cast({set_max_retries, MaxRetries}, State) -> {noreply, State#state{max_retries = MaxRetries}}; handle_cast(Msg, State) -> ?LOG_ERROR("Replication manager received unexpected cast ~p", [Msg]), {stop, {error, {unexpected_cast, Msg}}, State}. handle_info({'EXIT', From, normal}, #state{changes_feed_loop = From} = State) -> % replicator DB deleted {noreply, State#state{changes_feed_loop = nil, rep_db_name = nil}}; handle_info({'EXIT', From, Reason}, #state{db_notifier = From} = State) -> ?LOG_ERROR("Database update notifier died. Reason: ~p", [Reason]), {stop, {db_update_notifier_died, Reason}, State}; handle_info({'EXIT', From, normal}, #state{rep_start_pids = Pids} = State) -> % one of the replication start processes terminated successfully {noreply, State#state{rep_start_pids = Pids -- [From]}}; handle_info({'DOWN', _Ref, _, _, _}, State) -> % From a db monitor created by a replication process. Ignore. {noreply, State}; handle_info(Msg, State) -> ?LOG_ERROR("Replication manager received unexpected message ~p", [Msg]), {stop, {unexpected_msg, Msg}, State}. terminate(_Reason, State) -> #state{ rep_start_pids = StartPids, changes_feed_loop = Loop, db_notifier = DbNotifier } = State, stop_all_replications(), lists:foreach( fun(Pid) -> catch unlink(Pid), catch exit(Pid, stop) end, [Loop | StartPids]), true = ets:delete(?REP_TO_STATE), true = ets:delete(?DOC_TO_REP), couch_db_update_notifier:stop(DbNotifier). code_change(_OldVsn, State, _Extra) -> {ok, State}. changes_feed_loop() -> {ok, RepDb} = ensure_rep_db_exists(), RepDbName = couch_db:name(RepDb), couch_db:close(RepDb), Server = self(), Pid = spawn_link( fun() -> DbOpenOptions = [{user_ctx, RepDb#db.user_ctx}, sys_db], {ok, Db} = couch_db:open_int(RepDbName, DbOpenOptions), ChangesFeedFun = couch_changes:handle_changes( #changes_args{ include_docs = true, feed = "continuous", timeout = infinity }, {json_req, null}, Db ), ChangesFeedFun( fun({change, Change, _}, _) -> case has_valid_rep_id(Change) of true -> ok = gen_server:call( Server, {rep_db_update, Change}, infinity); false -> ok end; (_, _) -> ok end ) end ), {Pid, RepDbName}. has_valid_rep_id({Change}) -> has_valid_rep_id(get_value(<<"id">>, Change)); has_valid_rep_id(<>) -> false; has_valid_rep_id(_Else) -> true. db_update_notifier() -> Server = self(), {ok, Notifier} = couch_db_update_notifier:start_link( fun({created, DbName}) -> case ?l2b(couch_config:get("replicator", "db", "_replicator")) of DbName -> ok = gen_server:cast(Server, {rep_db_created, DbName}); _ -> ok end; (_) -> % no need to handle the 'deleted' event - the changes feed loop % dies when the database is deleted ok end ), Notifier. restart(#state{changes_feed_loop = Loop, rep_start_pids = StartPids} = State) -> stop_all_replications(), lists:foreach( fun(Pid) -> catch unlink(Pid), catch exit(Pid, rep_db_changed) end, [Loop | StartPids]), {NewLoop, NewRepDbName} = changes_feed_loop(), State#state{ changes_feed_loop = NewLoop, rep_db_name = NewRepDbName, rep_start_pids = [] }. process_update(State, {Change}) -> {RepProps} = JsonRepDoc = get_value(doc, Change), DocId = get_value(<<"_id">>, RepProps), case get_value(<<"deleted">>, Change, false) of true -> rep_doc_deleted(DocId), State; false -> case get_value(<<"_replication_state">>, RepProps) of undefined -> maybe_start_replication(State, DocId, JsonRepDoc); <<"triggered">> -> maybe_start_replication(State, DocId, JsonRepDoc); <<"completed">> -> replication_complete(DocId), State; <<"error">> -> case ets:lookup(?DOC_TO_REP, DocId) of [] -> maybe_start_replication(State, DocId, JsonRepDoc); _ -> State end end end. rep_db_update_error(Error, DocId) -> case Error of {bad_rep_doc, Reason} -> ok; _ -> Reason = to_binary(Error) end, ?LOG_ERROR("Replication manager, error processing document `~s`: ~s", [DocId, Reason]), update_rep_doc(DocId, [{<<"_replication_state">>, <<"error">>}]). rep_user_ctx({RepDoc}) -> case get_value(<<"user_ctx">>, RepDoc) of undefined -> #user_ctx{}; {UserCtx} -> #user_ctx{ name = get_value(<<"name">>, UserCtx, null), roles = get_value(<<"roles">>, UserCtx, []) } end. maybe_start_replication(State, DocId, RepDoc) -> #rep{id = {BaseId, _} = RepId} = Rep = parse_rep_doc(RepDoc), case rep_state(RepId) of nil -> RepState = #rep_state{ rep = Rep, starting = true, retries_left = State#state.max_retries, max_retries = State#state.max_retries }, true = ets:insert(?REP_TO_STATE, {RepId, RepState}), true = ets:insert(?DOC_TO_REP, {DocId, RepId}), ?LOG_INFO("Attempting to start replication `~s` (document `~s`).", [pp_rep_id(RepId), DocId]), Pid = spawn_link(fun() -> start_replication(Rep, 0) end), State#state{rep_start_pids = [Pid | State#state.rep_start_pids]}; #rep_state{rep = #rep{doc_id = DocId}} -> State; #rep_state{starting = false, rep = #rep{doc_id = OtherDocId}} -> ?LOG_INFO("The replication specified by the document `~s` was already" " triggered by the document `~s`", [DocId, OtherDocId]), maybe_tag_rep_doc(DocId, RepDoc, ?l2b(BaseId)), State; #rep_state{starting = true, rep = #rep{doc_id = OtherDocId}} -> ?LOG_INFO("The replication specified by the document `~s` is already" " being triggered by the document `~s`", [DocId, OtherDocId]), maybe_tag_rep_doc(DocId, RepDoc, ?l2b(BaseId)), State end. parse_rep_doc(RepDoc) -> {ok, Rep} = try couch_replicator_utils:parse_rep_doc(RepDoc, rep_user_ctx(RepDoc)) catch throw:{error, Reason} -> throw({bad_rep_doc, Reason}); Tag:Err -> throw({bad_rep_doc, to_binary({Tag, Err})}) end, Rep. maybe_tag_rep_doc(DocId, {RepProps}, RepId) -> case get_value(<<"_replication_id">>, RepProps) of RepId -> ok; _ -> update_rep_doc(DocId, [{<<"_replication_id">>, RepId}]) end. start_replication(Rep, Wait) -> ok = timer:sleep(Wait * 1000), case (catch couch_replicator:async_replicate(Rep)) of {ok, _} -> ok; Error -> replication_error(Rep, Error) end. replication_complete(DocId) -> case ets:lookup(?DOC_TO_REP, DocId) of [{DocId, {BaseId, Ext} = RepId}] -> case rep_state(RepId) of nil -> % Prior to OTP R14B02, temporary child specs remain in % in the supervisor after a worker finishes - remove them. % We want to be able to start the same replication but with % eventually different values for parameters that don't % contribute to its ID calculation. case erlang:system_info(otp_release) < "R14B02" of true -> spawn(fun() -> _ = supervisor:delete_child(couch_replicator_job_sup, BaseId ++ Ext) end); false -> ok end; #rep_state{} -> ok end, true = ets:delete(?DOC_TO_REP, DocId); _ -> ok end. rep_doc_deleted(DocId) -> case ets:lookup(?DOC_TO_REP, DocId) of [{DocId, RepId}] -> couch_replicator:cancel_replication(RepId), true = ets:delete(?REP_TO_STATE, RepId), true = ets:delete(?DOC_TO_REP, DocId), ?LOG_INFO("Stopped replication `~s` because replication document `~s`" " was deleted", [pp_rep_id(RepId), DocId]); [] -> ok end. replication_error(State, RepId, Error) -> case rep_state(RepId) of nil -> State; RepState -> maybe_retry_replication(RepState, Error, State) end. maybe_retry_replication(#rep_state{retries_left = 0} = RepState, Error, State) -> #rep_state{ rep = #rep{id = RepId, doc_id = DocId}, max_retries = MaxRetries } = RepState, couch_replicator:cancel_replication(RepId), true = ets:delete(?REP_TO_STATE, RepId), true = ets:delete(?DOC_TO_REP, DocId), ?LOG_ERROR("Error in replication `~s` (triggered by document `~s`): ~s" "~nReached maximum retry attempts (~p).", [pp_rep_id(RepId), DocId, to_binary(error_reason(Error)), MaxRetries]), State; maybe_retry_replication(RepState, Error, State) -> #rep_state{ rep = #rep{id = RepId, doc_id = DocId} = Rep } = RepState, #rep_state{wait = Wait} = NewRepState = state_after_error(RepState), true = ets:insert(?REP_TO_STATE, {RepId, NewRepState}), ?LOG_ERROR("Error in replication `~s` (triggered by document `~s`): ~s" "~nRestarting replication in ~p seconds.", [pp_rep_id(RepId), DocId, to_binary(error_reason(Error)), Wait]), Pid = spawn_link(fun() -> start_replication(Rep, Wait) end), State#state{rep_start_pids = [Pid | State#state.rep_start_pids]}. stop_all_replications() -> ?LOG_INFO("Stopping all ongoing replications because the replicator" " database was deleted or changed", []), ets:foldl( fun({_, RepId}, _) -> couch_replicator:cancel_replication(RepId) end, ok, ?DOC_TO_REP), true = ets:delete_all_objects(?REP_TO_STATE), true = ets:delete_all_objects(?DOC_TO_REP). update_rep_doc(RepDocId, KVs) -> {ok, RepDb} = ensure_rep_db_exists(), try case couch_db:open_doc(RepDb, RepDocId, [ejson_body]) of {ok, LatestRepDoc} -> update_rep_doc(RepDb, LatestRepDoc, KVs); _ -> ok end catch throw:conflict -> % Shouldn't happen, as by default only the role _replicator can % update replication documents. ?LOG_ERROR("Conflict error when updating replication document `~s`." " Retrying.", [RepDocId]), ok = timer:sleep(5), update_rep_doc(RepDocId, KVs) after couch_db:close(RepDb) end. update_rep_doc(RepDb, #doc{body = {RepDocBody}} = RepDoc, KVs) -> NewRepDocBody = lists:foldl( fun({K, undefined}, Body) -> lists:keydelete(K, 1, Body); ({<<"_replication_state">> = K, State} = KV, Body) -> case get_value(K, Body) of State -> Body; _ -> Body1 = lists:keystore(K, 1, Body, KV), lists:keystore( <<"_replication_state_time">>, 1, Body1, {<<"_replication_state_time">>, timestamp()}) end; ({K, _V} = KV, Body) -> lists:keystore(K, 1, Body, KV) end, RepDocBody, KVs), case NewRepDocBody of RepDocBody -> ok; _ -> % Might not succeed - when the replication doc is deleted right % before this update (not an error, ignore). couch_db:update_doc(RepDb, RepDoc#doc{body = {NewRepDocBody}}, []) end. % RFC3339 timestamps. % Note: doesn't include the time seconds fraction (RFC3339 says it's optional). timestamp() -> {{Year, Month, Day}, {Hour, Min, Sec}} = calendar:now_to_local_time(now()), UTime = erlang:universaltime(), LocalTime = calendar:universal_time_to_local_time(UTime), DiffSecs = calendar:datetime_to_gregorian_seconds(LocalTime) - calendar:datetime_to_gregorian_seconds(UTime), zone(DiffSecs div 3600, (DiffSecs rem 3600) div 60), iolist_to_binary( io_lib:format("~4..0w-~2..0w-~2..0wT~2..0w:~2..0w:~2..0w~s", [Year, Month, Day, Hour, Min, Sec, zone(DiffSecs div 3600, (DiffSecs rem 3600) div 60)])). zone(Hr, Min) when Hr >= 0, Min >= 0 -> io_lib:format("+~2..0w:~2..0w", [Hr, Min]); zone(Hr, Min) -> io_lib:format("-~2..0w:~2..0w", [abs(Hr), abs(Min)]). ensure_rep_db_exists() -> DbName = ?l2b(couch_config:get("replicator", "db", "_replicator")), UserCtx = #user_ctx{roles = [<<"_admin">>, <<"_replicator">>]}, case couch_db:open_int(DbName, [sys_db, {user_ctx, UserCtx}, nologifmissing]) of {ok, Db} -> Db; _Error -> {ok, Db} = couch_db:create(DbName, [sys_db, {user_ctx, UserCtx}]) end, ensure_rep_ddoc_exists(Db, <<"_design/_replicator">>), {ok, Db}. ensure_rep_ddoc_exists(RepDb, DDocID) -> case couch_db:open_doc(RepDb, DDocID, []) of {ok, _Doc} -> ok; _ -> DDoc = couch_doc:from_json_obj({[ {<<"_id">>, DDocID}, {<<"language">>, <<"javascript">>}, {<<"validate_doc_update">>, ?REP_DB_DOC_VALIDATE_FUN} ]}), {ok, _Rev} = couch_db:update_doc(RepDb, DDoc, []) end. % pretty-print replication id pp_rep_id(#rep{id = RepId}) -> pp_rep_id(RepId); pp_rep_id({Base, Extension}) -> Base ++ Extension. rep_state(RepId) -> case ets:lookup(?REP_TO_STATE, RepId) of [{RepId, RepState}] -> RepState; [] -> nil end. error_reason({error, Reason}) -> Reason; error_reason(Reason) -> Reason. retries_value("infinity") -> infinity; retries_value(Value) -> list_to_integer(Value). state_after_error(#rep_state{retries_left = Left, wait = Wait} = State) -> Wait2 = erlang:min(trunc(Wait * 2), ?MAX_WAIT), case Left of infinity -> State#rep_state{wait = Wait2}; _ -> State#rep_state{retries_left = Left - 1, wait = Wait2} end. before_doc_update(#doc{id = <>} = Doc, _Db) -> Doc; before_doc_update(#doc{body = {Body}} = Doc, #db{user_ctx=UserCtx} = Db) -> #user_ctx{roles = Roles, name = Name} = UserCtx, case lists:member(<<"_replicator">>, Roles) of true -> Doc; false -> case couch_util:get_value(?OWNER, Body) of undefined -> Doc#doc{body = {?replace(Body, ?OWNER, Name)}}; Name -> Doc; Other -> case (catch couch_db:check_is_admin(Db)) of ok when Other =:= null -> Doc#doc{body = {?replace(Body, ?OWNER, Name)}}; ok -> Doc; _ -> throw({forbidden, <<"Can't update replication documents", " from other users.">>}) end end end. after_doc_read(#doc{id = <>} = Doc, _Db) -> Doc; after_doc_read(#doc{body = {Body}} = Doc, #db{user_ctx=UserCtx} = Db) -> #user_ctx{name = Name} = UserCtx, case (catch couch_db:check_is_admin(Db)) of ok -> Doc; _ -> case couch_util:get_value(?OWNER, Body) of Name -> Doc; _Other -> Source = strip_credentials(couch_util:get_value(<<"source">>, Body)), Target = strip_credentials(couch_util:get_value(<<"target">>, Body)), NewBody0 = ?replace(Body, <<"source">>, Source), NewBody = ?replace(NewBody0, <<"target">>, Target), #doc{revs = {Pos, [_ | Revs]}} = Doc, NewDoc = Doc#doc{body = {NewBody}, revs = {Pos - 1, Revs}}, NewRevId = couch_db:new_revid(NewDoc), NewDoc#doc{revs = {Pos, [NewRevId | Revs]}} end end. strip_credentials(undefined) -> undefined; strip_credentials(Url) when is_binary(Url) -> re:replace(Url, "http(s)?://(?:[^:]+):[^@]+@(.*)$", "http\\1://\\2", [{return, binary}]); strip_credentials({Props}) -> {lists:keydelete(<<"oauth">>, 1, Props)}. apache-couchdb-1.5.0/src/couch_replicator/src/couch_replicator_job_sup.erl0000644000175000001440000000220312230722213023724 00000000000000% 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. -module(couch_replicator_job_sup). -behaviour(supervisor). -export([init/1, start_link/0]). -include("couch_db.hrl"). start_link() -> supervisor:start_link({local,?MODULE}, ?MODULE, []). %%============================================================================= %% supervisor callbacks %%============================================================================= init([]) -> {ok, {{one_for_one, 3, 10}, []}}. %%============================================================================= %% internal functions %%============================================================================= apache-couchdb-1.5.0/src/couch_replicator/src/couch_replicator.erl0000644000175000001440000010404112230722213022206 00000000000000% 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. -module(couch_replicator). -behaviour(gen_server). % public API -export([replicate/1]). % meant to be used only by the replicator database listener -export([async_replicate/1]). -export([cancel_replication/1]). % gen_server callbacks -export([init/1, terminate/2, code_change/3]). -export([handle_call/3, handle_cast/2, handle_info/2]). -include("couch_db.hrl"). -include("couch_replicator_api_wrap.hrl"). -include("couch_replicator.hrl"). -import(couch_util, [ get_value/2, get_value/3, to_binary/1 ]). -import(couch_replicator_utils, [ start_db_compaction_notifier/2, stop_db_compaction_notifier/1 ]). -record(rep_state, { rep_details, source_name, target_name, source, target, history, checkpoint_history, start_seq, committed_seq, current_through_seq, seqs_in_progress = [], highest_seq_done = {0, ?LOWEST_SEQ}, source_log, target_log, rep_starttime, src_starttime, tgt_starttime, timer, % checkpoint timer changes_queue, changes_manager, changes_reader, workers, stats = #rep_stats{}, session_id, source_db_compaction_notifier = nil, target_db_compaction_notifier = nil, source_monitor = nil, target_monitor = nil, source_seq = nil }). replicate(#rep{id = RepId, options = Options, user_ctx = UserCtx} = Rep) -> case get_value(cancel, Options, false) of true -> case get_value(id, Options, nil) of nil -> cancel_replication(RepId); RepId2 -> cancel_replication(RepId2, UserCtx) end; false -> {ok, Listener} = rep_result_listener(RepId), Result = do_replication_loop(Rep), couch_replicator_notifier:stop(Listener), Result end. do_replication_loop(#rep{id = {BaseId, Ext} = Id, options = Options} = Rep) -> case async_replicate(Rep) of {ok, _Pid} -> case get_value(continuous, Options, false) of true -> {ok, {continuous, ?l2b(BaseId ++ Ext)}}; false -> wait_for_result(Id) end; Error -> Error end. async_replicate(#rep{id = {BaseId, Ext}, source = Src, target = Tgt} = Rep) -> RepChildId = BaseId ++ Ext, Source = couch_replicator_api_wrap:db_uri(Src), Target = couch_replicator_api_wrap:db_uri(Tgt), Timeout = get_value(connection_timeout, Rep#rep.options), ChildSpec = { RepChildId, {gen_server, start_link, [?MODULE, Rep, [{timeout, Timeout}]]}, temporary, 250, worker, [?MODULE] }, % All these nested cases to attempt starting/restarting a replication child % are ugly and not 100% race condition free. The following patch submission % is a solution: % % http://erlang.2086793.n4.nabble.com/PATCH-supervisor-atomically-delete-child-spec-when-child-terminates-td3226098.html % case supervisor:start_child(couch_replicator_job_sup, ChildSpec) of {ok, Pid} -> ?LOG_INFO("starting new replication `~s` at ~p (`~s` -> `~s`)", [RepChildId, Pid, Source, Target]), {ok, Pid}; {error, already_present} -> case supervisor:restart_child(couch_replicator_job_sup, RepChildId) of {ok, Pid} -> ?LOG_INFO("restarting replication `~s` at ~p (`~s` -> `~s`)", [RepChildId, Pid, Source, Target]), {ok, Pid}; {error, running} -> %% this error occurs if multiple replicators are racing %% each other to start and somebody else won. Just grab %% the Pid by calling start_child again. {error, {already_started, Pid}} = supervisor:start_child(couch_replicator_job_sup, ChildSpec), ?LOG_INFO("replication `~s` already running at ~p (`~s` -> `~s`)", [RepChildId, Pid, Source, Target]), {ok, Pid}; {error, {'EXIT', {badarg, [{erlang, apply, [gen_server, start_link, undefined]} | _]}}} -> % Clause to deal with a change in the supervisor module introduced % in R14B02. For more details consult the thread at: % http://erlang.org/pipermail/erlang-bugs/2011-March/002273.html _ = supervisor:delete_child(couch_replicator_job_sup, RepChildId), async_replicate(Rep); {error, _} = Error -> Error end; {error, {already_started, Pid}} -> ?LOG_INFO("replication `~s` already running at ~p (`~s` -> `~s`)", [RepChildId, Pid, Source, Target]), {ok, Pid}; {error, {Error, _}} -> {error, Error} end. rep_result_listener(RepId) -> ReplyTo = self(), {ok, _Listener} = couch_replicator_notifier:start_link( fun({_, RepId2, _} = Ev) when RepId2 =:= RepId -> ReplyTo ! Ev; (_) -> ok end). wait_for_result(RepId) -> receive {finished, RepId, RepResult} -> {ok, RepResult}; {error, RepId, Reason} -> {error, Reason} end. cancel_replication({BaseId, Extension}) -> FullRepId = BaseId ++ Extension, ?LOG_INFO("Canceling replication `~s`...", [FullRepId]), case supervisor:terminate_child(couch_replicator_job_sup, FullRepId) of ok -> ?LOG_INFO("Replication `~s` canceled.", [FullRepId]), case supervisor:delete_child(couch_replicator_job_sup, FullRepId) of ok -> {ok, {cancelled, ?l2b(FullRepId)}}; {error, not_found} -> {ok, {cancelled, ?l2b(FullRepId)}}; Error -> Error end; Error -> ?LOG_ERROR("Error canceling replication `~s`: ~p", [FullRepId, Error]), Error end. cancel_replication(RepId, #user_ctx{name = Name, roles = Roles}) -> case lists:member(<<"_admin">>, Roles) of true -> cancel_replication(RepId); false -> {BaseId, Ext} = RepId, case lists:keysearch( BaseId ++ Ext, 1, supervisor:which_children(couch_replicator_job_sup)) of {value, {_, Pid, _, _}} when is_pid(Pid) -> case (catch gen_server:call(Pid, get_details, infinity)) of {ok, #rep{user_ctx = #user_ctx{name = Name}}} -> cancel_replication(RepId); {ok, _} -> throw({unauthorized, <<"Can't cancel a replication triggered by another user">>}); {'EXIT', {noproc, {gen_server, call, _}}} -> {error, not_found}; Error -> throw(Error) end; _ -> {error, not_found} end end. init(InitArgs) -> try do_init(InitArgs) catch throw:{unauthorized, DbUri} -> {stop, {unauthorized, <<"unauthorized to access or create database ", DbUri/binary>>}}; throw:{db_not_found, DbUri} -> {stop, {db_not_found, <<"could not open ", DbUri/binary>>}}; throw:Error -> {stop, Error} end. do_init(#rep{options = Options, id = {BaseId, Ext}} = Rep) -> process_flag(trap_exit, true), #rep_state{ source = Source, target = Target, source_name = SourceName, target_name = TargetName, start_seq = {_Ts, StartSeq}, source_seq = SourceCurSeq, committed_seq = {_, CommittedSeq} } = State = init_state(Rep), NumWorkers = get_value(worker_processes, Options), BatchSize = get_value(worker_batch_size, Options), {ok, ChangesQueue} = couch_work_queue:new([ {max_items, BatchSize * NumWorkers * 2}, {max_size, 100 * 1024 * NumWorkers} ]), % This starts the _changes reader process. It adds the changes from % the source db to the ChangesQueue. ChangesReader = spawn_changes_reader(StartSeq, Source, ChangesQueue, Options), % Changes manager - responsible for dequeing batches from the changes queue % and deliver them to the worker processes. ChangesManager = spawn_changes_manager(self(), ChangesQueue, BatchSize), % This starts the worker processes. They ask the changes queue manager for a % a batch of _changes rows to process -> check which revs are missing in the % target, and for the missing ones, it copies them from the source to the target. MaxConns = get_value(http_connections, Options), Workers = lists:map( fun(_) -> {ok, Pid} = couch_replicator_worker:start_link( self(), Source, Target, ChangesManager, MaxConns), Pid end, lists:seq(1, NumWorkers)), couch_task_status:add_task([ {type, replication}, {replication_id, ?l2b(BaseId ++ Ext)}, {doc_id, Rep#rep.doc_id}, {source, ?l2b(SourceName)}, {target, ?l2b(TargetName)}, {continuous, get_value(continuous, Options, false)}, {revisions_checked, 0}, {missing_revisions_found, 0}, {docs_read, 0}, {docs_written, 0}, {doc_write_failures, 0}, {source_seq, SourceCurSeq}, {checkpointed_source_seq, CommittedSeq}, {progress, 0} ]), couch_task_status:set_update_frequency(1000), % Until OTP R14B03: % % Restarting a temporary supervised child implies that the original arguments % (#rep{} record) specified in the MFA component of the supervisor % child spec will always be used whenever the child is restarted. % This implies the same replication performance tunning parameters will % always be used. The solution is to delete the child spec (see % cancel_replication/1) and then start the replication again, but this is % unfortunately not immune to race conditions. ?LOG_INFO("Replication `~p` is using:~n" "~c~p worker processes~n" "~ca worker batch size of ~p~n" "~c~p HTTP connections~n" "~ca connection timeout of ~p milliseconds~n" "~c~p retries per request~n" "~csocket options are: ~s~s", [BaseId ++ Ext, $\t, NumWorkers, $\t, BatchSize, $\t, MaxConns, $\t, get_value(connection_timeout, Options), $\t, get_value(retries, Options), $\t, io_lib:format("~p", [get_value(socket_options, Options)]), case StartSeq of ?LOWEST_SEQ -> ""; _ -> io_lib:format("~n~csource start sequence ~p", [$\t, StartSeq]) end]), ?LOG_DEBUG("Worker pids are: ~p", [Workers]), couch_replicator_manager:replication_started(Rep), {ok, State#rep_state{ changes_queue = ChangesQueue, changes_manager = ChangesManager, changes_reader = ChangesReader, workers = Workers } }. handle_info(shutdown, St) -> {stop, shutdown, St}; handle_info({'DOWN', Ref, _, _, Why}, #rep_state{source_monitor = Ref} = St) -> ?LOG_ERROR("Source database is down. Reason: ~p", [Why]), {stop, source_db_down, St}; handle_info({'DOWN', Ref, _, _, Why}, #rep_state{target_monitor = Ref} = St) -> ?LOG_ERROR("Target database is down. Reason: ~p", [Why]), {stop, target_db_down, St}; handle_info({'EXIT', Pid, normal}, #rep_state{changes_reader=Pid} = State) -> {noreply, State}; handle_info({'EXIT', Pid, Reason}, #rep_state{changes_reader=Pid} = State) -> ?LOG_ERROR("ChangesReader process died with reason: ~p", [Reason]), {stop, changes_reader_died, cancel_timer(State)}; handle_info({'EXIT', Pid, normal}, #rep_state{changes_manager = Pid} = State) -> {noreply, State}; handle_info({'EXIT', Pid, Reason}, #rep_state{changes_manager = Pid} = State) -> ?LOG_ERROR("ChangesManager process died with reason: ~p", [Reason]), {stop, changes_manager_died, cancel_timer(State)}; handle_info({'EXIT', Pid, normal}, #rep_state{changes_queue=Pid} = State) -> {noreply, State}; handle_info({'EXIT', Pid, Reason}, #rep_state{changes_queue=Pid} = State) -> ?LOG_ERROR("ChangesQueue process died with reason: ~p", [Reason]), {stop, changes_queue_died, cancel_timer(State)}; handle_info({'EXIT', Pid, normal}, #rep_state{workers = Workers} = State) -> case Workers -- [Pid] of Workers -> {stop, {unknown_process_died, Pid, normal}, State}; [] -> catch unlink(State#rep_state.changes_manager), catch exit(State#rep_state.changes_manager, kill), do_last_checkpoint(State); Workers2 -> {noreply, State#rep_state{workers = Workers2}} end; handle_info({'EXIT', Pid, Reason}, #rep_state{workers = Workers} = State) -> State2 = cancel_timer(State), case lists:member(Pid, Workers) of false -> {stop, {unknown_process_died, Pid, Reason}, State2}; true -> ?LOG_ERROR("Worker ~p died with reason: ~p", [Pid, Reason]), {stop, {worker_died, Pid, Reason}, State2} end. handle_call(get_details, _From, #rep_state{rep_details = Rep} = State) -> {reply, {ok, Rep}, State}; handle_call({add_stats, Stats}, From, State) -> gen_server:reply(From, ok), NewStats = couch_replicator_utils:sum_stats(State#rep_state.stats, Stats), {noreply, State#rep_state{stats = NewStats}}; handle_call({report_seq_done, Seq, StatsInc}, From, #rep_state{seqs_in_progress = SeqsInProgress, highest_seq_done = HighestDone, current_through_seq = ThroughSeq, stats = Stats} = State) -> gen_server:reply(From, ok), {NewThroughSeq0, NewSeqsInProgress} = case SeqsInProgress of [Seq | Rest] -> {Seq, Rest}; [_ | _] -> {ThroughSeq, ordsets:del_element(Seq, SeqsInProgress)} end, NewHighestDone = lists:max([HighestDone, Seq]), NewThroughSeq = case NewSeqsInProgress of [] -> lists:max([NewThroughSeq0, NewHighestDone]); _ -> NewThroughSeq0 end, ?LOG_DEBUG("Worker reported seq ~p, through seq was ~p, " "new through seq is ~p, highest seq done was ~p, " "new highest seq done is ~p~n" "Seqs in progress were: ~p~nSeqs in progress are now: ~p", [Seq, ThroughSeq, NewThroughSeq, HighestDone, NewHighestDone, SeqsInProgress, NewSeqsInProgress]), SourceCurSeq = source_cur_seq(State), NewState = State#rep_state{ stats = couch_replicator_utils:sum_stats(Stats, StatsInc), current_through_seq = NewThroughSeq, seqs_in_progress = NewSeqsInProgress, highest_seq_done = NewHighestDone, source_seq = SourceCurSeq }, update_task(NewState), {noreply, NewState}. handle_cast({db_compacted, DbName}, #rep_state{source = #db{name = DbName} = Source} = State) -> {ok, NewSource} = couch_db:reopen(Source), {noreply, State#rep_state{source = NewSource}}; handle_cast({db_compacted, DbName}, #rep_state{target = #db{name = DbName} = Target} = State) -> {ok, NewTarget} = couch_db:reopen(Target), {noreply, State#rep_state{target = NewTarget}}; handle_cast(checkpoint, State) -> case do_checkpoint(State) of {ok, NewState} -> {noreply, NewState#rep_state{timer = start_timer(State)}}; Error -> {stop, Error, State} end; handle_cast({report_seq, Seq}, #rep_state{seqs_in_progress = SeqsInProgress} = State) -> NewSeqsInProgress = ordsets:add_element(Seq, SeqsInProgress), {noreply, State#rep_state{seqs_in_progress = NewSeqsInProgress}}. code_change(_OldVsn, State, _Extra) -> {ok, State}. terminate(normal, #rep_state{rep_details = #rep{id = RepId} = Rep, checkpoint_history = CheckpointHistory} = State) -> terminate_cleanup(State), couch_replicator_notifier:notify({finished, RepId, CheckpointHistory}), couch_replicator_manager:replication_completed(Rep, rep_stats(State)); terminate(shutdown, #rep_state{rep_details = #rep{id = RepId}} = State) -> % cancelled replication throught ?MODULE:cancel_replication/1 couch_replicator_notifier:notify({error, RepId, <<"cancelled">>}), terminate_cleanup(State); terminate(Reason, State) -> #rep_state{ source_name = Source, target_name = Target, rep_details = #rep{id = {BaseId, Ext} = RepId} = Rep } = State, ?LOG_ERROR("Replication `~s` (`~s` -> `~s`) failed: ~s", [BaseId ++ Ext, Source, Target, to_binary(Reason)]), terminate_cleanup(State), couch_replicator_notifier:notify({error, RepId, Reason}), couch_replicator_manager:replication_error(Rep, Reason). terminate_cleanup(State) -> update_task(State), stop_db_compaction_notifier(State#rep_state.source_db_compaction_notifier), stop_db_compaction_notifier(State#rep_state.target_db_compaction_notifier), couch_replicator_api_wrap:db_close(State#rep_state.source), couch_replicator_api_wrap:db_close(State#rep_state.target). do_last_checkpoint(#rep_state{seqs_in_progress = [], highest_seq_done = {_Ts, ?LOWEST_SEQ}} = State) -> {stop, normal, cancel_timer(State)}; do_last_checkpoint(#rep_state{seqs_in_progress = [], highest_seq_done = Seq} = State) -> case do_checkpoint(State#rep_state{current_through_seq = Seq}) of {ok, NewState} -> {stop, normal, cancel_timer(NewState)}; Error -> {stop, Error, State} end. start_timer(State) -> After = checkpoint_interval(State), case timer:apply_after(After, gen_server, cast, [self(), checkpoint]) of {ok, Ref} -> Ref; Error -> ?LOG_ERROR("Replicator, error scheduling checkpoint: ~p", [Error]), nil end. cancel_timer(#rep_state{timer = nil} = State) -> State; cancel_timer(#rep_state{timer = Timer} = State) -> {ok, cancel} = timer:cancel(Timer), State#rep_state{timer = nil}. init_state(Rep) -> #rep{ source = Src, target = Tgt, options = Options, user_ctx = UserCtx } = Rep, {ok, Source} = couch_replicator_api_wrap:db_open(Src, [{user_ctx, UserCtx}]), {ok, Target} = couch_replicator_api_wrap:db_open(Tgt, [{user_ctx, UserCtx}], get_value(create_target, Options, false)), {ok, SourceInfo} = couch_replicator_api_wrap:get_db_info(Source), {ok, TargetInfo} = couch_replicator_api_wrap:get_db_info(Target), [SourceLog, TargetLog] = find_replication_logs([Source, Target], Rep), {StartSeq0, History} = compare_replication_logs(SourceLog, TargetLog), StartSeq1 = get_value(since_seq, Options, StartSeq0), StartSeq = {0, StartSeq1}, #doc{body={CheckpointHistory}} = SourceLog, State = #rep_state{ rep_details = Rep, source_name = couch_replicator_api_wrap:db_uri(Source), target_name = couch_replicator_api_wrap:db_uri(Target), source = Source, target = Target, history = History, checkpoint_history = {[{<<"no_changes">>, true}| CheckpointHistory]}, start_seq = StartSeq, current_through_seq = StartSeq, committed_seq = StartSeq, source_log = SourceLog, target_log = TargetLog, rep_starttime = couch_util:rfc1123_date(), src_starttime = get_value(<<"instance_start_time">>, SourceInfo), tgt_starttime = get_value(<<"instance_start_time">>, TargetInfo), session_id = couch_uuids:random(), source_db_compaction_notifier = start_db_compaction_notifier(Source, self()), target_db_compaction_notifier = start_db_compaction_notifier(Target, self()), source_monitor = db_monitor(Source), target_monitor = db_monitor(Target), source_seq = get_value(<<"update_seq">>, SourceInfo, ?LOWEST_SEQ) }, State#rep_state{timer = start_timer(State)}. find_replication_logs(DbList, #rep{id = {BaseId, _}} = Rep) -> LogId = ?l2b(?LOCAL_DOC_PREFIX ++ BaseId), fold_replication_logs(DbList, ?REP_ID_VERSION, LogId, LogId, Rep, []). fold_replication_logs([], _Vsn, _LogId, _NewId, _Rep, Acc) -> lists:reverse(Acc); fold_replication_logs([Db | Rest] = Dbs, Vsn, LogId, NewId, Rep, Acc) -> case couch_replicator_api_wrap:open_doc(Db, LogId, [ejson_body]) of {error, <<"not_found">>} when Vsn > 1 -> OldRepId = couch_replicator_utils:replication_id(Rep, Vsn - 1), fold_replication_logs(Dbs, Vsn - 1, ?l2b(?LOCAL_DOC_PREFIX ++ OldRepId), NewId, Rep, Acc); {error, <<"not_found">>} -> fold_replication_logs( Rest, ?REP_ID_VERSION, NewId, NewId, Rep, [#doc{id = NewId} | Acc]); {ok, Doc} when LogId =:= NewId -> fold_replication_logs( Rest, ?REP_ID_VERSION, NewId, NewId, Rep, [Doc | Acc]); {ok, Doc} -> MigratedLog = #doc{id = NewId, body = Doc#doc.body}, fold_replication_logs( Rest, ?REP_ID_VERSION, NewId, NewId, Rep, [MigratedLog | Acc]) end. spawn_changes_reader(StartSeq, #httpdb{} = Db, ChangesQueue, Options) -> spawn_link(fun() -> put(last_seq, StartSeq), put(retries_left, Db#httpdb.retries), read_changes(StartSeq, Db#httpdb{retries = 0}, ChangesQueue, Options) end); spawn_changes_reader(StartSeq, Db, ChangesQueue, Options) -> spawn_link(fun() -> read_changes(StartSeq, Db, ChangesQueue, Options) end). read_changes(StartSeq, Db, ChangesQueue, Options) -> try couch_replicator_api_wrap:changes_since(Db, all_docs, StartSeq, fun(#doc_info{high_seq = Seq, id = Id} = DocInfo) -> case Id of <<>> -> % Previous CouchDB releases had a bug which allowed a doc % with an empty ID to be inserted into databases. Such doc % is impossible to GET. ?LOG_ERROR("Replicator: ignoring document with empty ID in " "source database `~s` (_changes sequence ~p)", [couch_replicator_api_wrap:db_uri(Db), Seq]); _ -> ok = couch_work_queue:queue(ChangesQueue, DocInfo) end, put(last_seq, Seq) end, Options), couch_work_queue:close(ChangesQueue) catch exit:{http_request_failed, _, _, _} = Error -> case get(retries_left) of N when N > 0 -> put(retries_left, N - 1), LastSeq = get(last_seq), Db2 = case LastSeq of StartSeq -> ?LOG_INFO("Retrying _changes request to source database ~s" " with since=~p in ~p seconds", [couch_replicator_api_wrap:db_uri(Db), LastSeq, Db#httpdb.wait / 1000]), ok = timer:sleep(Db#httpdb.wait), Db#httpdb{wait = 2 * Db#httpdb.wait}; _ -> ?LOG_INFO("Retrying _changes request to source database ~s" " with since=~p", [couch_replicator_api_wrap:db_uri(Db), LastSeq]), Db end, read_changes(LastSeq, Db2, ChangesQueue, Options); _ -> exit(Error) end end. spawn_changes_manager(Parent, ChangesQueue, BatchSize) -> spawn_link(fun() -> changes_manager_loop_open(Parent, ChangesQueue, BatchSize, 1) end). changes_manager_loop_open(Parent, ChangesQueue, BatchSize, Ts) -> receive {get_changes, From} -> case couch_work_queue:dequeue(ChangesQueue, BatchSize) of closed -> From ! {closed, self()}; {ok, Changes} -> #doc_info{high_seq = Seq} = lists:last(Changes), ReportSeq = {Ts, Seq}, ok = gen_server:cast(Parent, {report_seq, ReportSeq}), From ! {changes, self(), Changes, ReportSeq} end, changes_manager_loop_open(Parent, ChangesQueue, BatchSize, Ts + 1) end. checkpoint_interval(_State) -> 5000. do_checkpoint(#rep_state{current_through_seq=Seq, committed_seq=Seq} = State) -> SourceCurSeq = source_cur_seq(State), NewState = State#rep_state{source_seq = SourceCurSeq}, update_task(NewState), {ok, NewState}; do_checkpoint(State) -> #rep_state{ source_name=SourceName, target_name=TargetName, source = Source, target = Target, history = OldHistory, start_seq = {_, StartSeq}, current_through_seq = {_Ts, NewSeq} = NewTsSeq, source_log = SourceLog, target_log = TargetLog, rep_starttime = ReplicationStartTime, src_starttime = SrcInstanceStartTime, tgt_starttime = TgtInstanceStartTime, stats = Stats, rep_details = #rep{options = Options}, session_id = SessionId } = State, case commit_to_both(Source, Target) of {source_error, Reason} -> {checkpoint_commit_failure, <<"Failure on source commit: ", (to_binary(Reason))/binary>>}; {target_error, Reason} -> {checkpoint_commit_failure, <<"Failure on target commit: ", (to_binary(Reason))/binary>>}; {SrcInstanceStartTime, TgtInstanceStartTime} -> ?LOG_INFO("recording a checkpoint for `~s` -> `~s` at source update_seq ~p", [SourceName, TargetName, NewSeq]), StartTime = ?l2b(ReplicationStartTime), EndTime = ?l2b(couch_util:rfc1123_date()), NewHistoryEntry = {[ {<<"session_id">>, SessionId}, {<<"start_time">>, StartTime}, {<<"end_time">>, EndTime}, {<<"start_last_seq">>, StartSeq}, {<<"end_last_seq">>, NewSeq}, {<<"recorded_seq">>, NewSeq}, {<<"missing_checked">>, Stats#rep_stats.missing_checked}, {<<"missing_found">>, Stats#rep_stats.missing_found}, {<<"docs_read">>, Stats#rep_stats.docs_read}, {<<"docs_written">>, Stats#rep_stats.docs_written}, {<<"doc_write_failures">>, Stats#rep_stats.doc_write_failures} ]}, BaseHistory = [ {<<"session_id">>, SessionId}, {<<"source_last_seq">>, NewSeq}, {<<"replication_id_version">>, ?REP_ID_VERSION} ] ++ case get_value(doc_ids, Options) of undefined -> []; _DocIds -> % backwards compatibility with the result of a replication by % doc IDs in versions 0.11.x and 1.0.x % TODO: deprecate (use same history format, simplify code) [ {<<"start_time">>, StartTime}, {<<"end_time">>, EndTime}, {<<"docs_read">>, Stats#rep_stats.docs_read}, {<<"docs_written">>, Stats#rep_stats.docs_written}, {<<"doc_write_failures">>, Stats#rep_stats.doc_write_failures} ] end, % limit history to 50 entries NewRepHistory = { BaseHistory ++ [{<<"history">>, lists:sublist([NewHistoryEntry | OldHistory], 50)}] }, try {SrcRevPos, SrcRevId} = update_checkpoint( Source, SourceLog#doc{body = NewRepHistory}, source), {TgtRevPos, TgtRevId} = update_checkpoint( Target, TargetLog#doc{body = NewRepHistory}, target), SourceCurSeq = source_cur_seq(State), NewState = State#rep_state{ source_seq = SourceCurSeq, checkpoint_history = NewRepHistory, committed_seq = NewTsSeq, source_log = SourceLog#doc{revs={SrcRevPos, [SrcRevId]}}, target_log = TargetLog#doc{revs={TgtRevPos, [TgtRevId]}} }, update_task(NewState), {ok, NewState} catch throw:{checkpoint_commit_failure, _} = Failure -> Failure end; {SrcInstanceStartTime, _NewTgtInstanceStartTime} -> {checkpoint_commit_failure, <<"Target database out of sync. " "Try to increase max_dbs_open at the target's server.">>}; {_NewSrcInstanceStartTime, TgtInstanceStartTime} -> {checkpoint_commit_failure, <<"Source database out of sync. " "Try to increase max_dbs_open at the source's server.">>}; {_NewSrcInstanceStartTime, _NewTgtInstanceStartTime} -> {checkpoint_commit_failure, <<"Source and target databases out of " "sync. Try to increase max_dbs_open at both servers.">>} end. update_checkpoint(Db, Doc, DbType) -> try update_checkpoint(Db, Doc) catch throw:{checkpoint_commit_failure, Reason} -> throw({checkpoint_commit_failure, <<"Error updating the ", (to_binary(DbType))/binary, " checkpoint document: ", (to_binary(Reason))/binary>>}) end. update_checkpoint(Db, #doc{id = LogId, body = LogBody} = Doc) -> try case couch_replicator_api_wrap:update_doc(Db, Doc, [delay_commit]) of {ok, PosRevId} -> PosRevId; {error, Reason} -> throw({checkpoint_commit_failure, Reason}) end catch throw:conflict -> case (catch couch_replicator_api_wrap:open_doc(Db, LogId, [ejson_body])) of {ok, #doc{body = LogBody, revs = {Pos, [RevId | _]}}} -> % This means that we were able to update successfully the % checkpoint doc in a previous attempt but we got a connection % error (timeout for e.g.) before receiving the success response. % Therefore the request was retried and we got a conflict, as the % revision we sent is not the current one. % We confirm this by verifying the doc body we just got is the same % that we have just sent. {Pos, RevId}; _ -> throw({checkpoint_commit_failure, conflict}) end end. commit_to_both(Source, Target) -> % commit the src async ParentPid = self(), SrcCommitPid = spawn_link( fun() -> Result = (catch couch_replicator_api_wrap:ensure_full_commit(Source)), ParentPid ! {self(), Result} end), % commit tgt sync TargetResult = (catch couch_replicator_api_wrap:ensure_full_commit(Target)), SourceResult = receive {SrcCommitPid, Result} -> unlink(SrcCommitPid), receive {'EXIT', SrcCommitPid, _} -> ok after 0 -> ok end, Result; {'EXIT', SrcCommitPid, Reason} -> {error, Reason} end, case TargetResult of {ok, TargetStartTime} -> case SourceResult of {ok, SourceStartTime} -> {SourceStartTime, TargetStartTime}; SourceError -> {source_error, SourceError} end; TargetError -> {target_error, TargetError} end. compare_replication_logs(SrcDoc, TgtDoc) -> #doc{body={RepRecProps}} = SrcDoc, #doc{body={RepRecPropsTgt}} = TgtDoc, case get_value(<<"session_id">>, RepRecProps) == get_value(<<"session_id">>, RepRecPropsTgt) of true -> % if the records have the same session id, % then we have a valid replication history OldSeqNum = get_value(<<"source_last_seq">>, RepRecProps, ?LOWEST_SEQ), OldHistory = get_value(<<"history">>, RepRecProps, []), {OldSeqNum, OldHistory}; false -> SourceHistory = get_value(<<"history">>, RepRecProps, []), TargetHistory = get_value(<<"history">>, RepRecPropsTgt, []), ?LOG_INFO("Replication records differ. " "Scanning histories to find a common ancestor.", []), ?LOG_DEBUG("Record on source:~p~nRecord on target:~p~n", [RepRecProps, RepRecPropsTgt]), compare_rep_history(SourceHistory, TargetHistory) end. compare_rep_history(S, T) when S =:= [] orelse T =:= [] -> ?LOG_INFO("no common ancestry -- performing full replication", []), {?LOWEST_SEQ, []}; compare_rep_history([{S} | SourceRest], [{T} | TargetRest] = Target) -> SourceId = get_value(<<"session_id">>, S), case has_session_id(SourceId, Target) of true -> RecordSeqNum = get_value(<<"recorded_seq">>, S, ?LOWEST_SEQ), ?LOG_INFO("found a common replication record with source_seq ~p", [RecordSeqNum]), {RecordSeqNum, SourceRest}; false -> TargetId = get_value(<<"session_id">>, T), case has_session_id(TargetId, SourceRest) of true -> RecordSeqNum = get_value(<<"recorded_seq">>, T, ?LOWEST_SEQ), ?LOG_INFO("found a common replication record with source_seq ~p", [RecordSeqNum]), {RecordSeqNum, TargetRest}; false -> compare_rep_history(SourceRest, TargetRest) end end. has_session_id(_SessionId, []) -> false; has_session_id(SessionId, [{Props} | Rest]) -> case get_value(<<"session_id">>, Props, nil) of SessionId -> true; _Else -> has_session_id(SessionId, Rest) end. db_monitor(#db{} = Db) -> couch_db:monitor(Db); db_monitor(_HttpDb) -> nil. source_cur_seq(#rep_state{source = #httpdb{} = Db, source_seq = Seq}) -> case (catch couch_replicator_api_wrap:get_db_info(Db#httpdb{retries = 3})) of {ok, Info} -> get_value(<<"update_seq">>, Info, Seq); _ -> Seq end; source_cur_seq(#rep_state{source = Db, source_seq = Seq}) -> {ok, Info} = couch_replicator_api_wrap:get_db_info(Db), get_value(<<"update_seq">>, Info, Seq). update_task(State) -> #rep_state{ current_through_seq = {_, CurSeq}, source_seq = SourceCurSeq } = State, couch_task_status:update( rep_stats(State) ++ [ {source_seq, SourceCurSeq}, case is_number(CurSeq) andalso is_number(SourceCurSeq) of true -> case SourceCurSeq of 0 -> {progress, 0}; _ -> {progress, (CurSeq * 100) div SourceCurSeq} end; false -> {progress, null} end ]). rep_stats(State) -> #rep_state{ committed_seq = {_, CommittedSeq}, stats = Stats } = State, [ {revisions_checked, Stats#rep_stats.missing_checked}, {missing_revisions_found, Stats#rep_stats.missing_found}, {docs_read, Stats#rep_stats.docs_read}, {docs_written, Stats#rep_stats.docs_written}, {doc_write_failures, Stats#rep_stats.doc_write_failures}, {checkpointed_source_seq, CommittedSeq} ]. apache-couchdb-1.5.0/src/couch_replicator/src/couch_replicator.hrl0000644000175000001440000000144312230722213022213 00000000000000% 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. -define(REP_ID_VERSION, 3). -record(rep, { id, source, target, options, user_ctx, doc_id }). -record(rep_stats, { missing_checked = 0, missing_found = 0, docs_read = 0, docs_written = 0, doc_write_failures = 0 }). apache-couchdb-1.5.0/src/couch_replicator/src/couch_replicator_js_functions.hrl0000644000175000001440000001361112230722213024777 00000000000000% 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. -define(REP_DB_DOC_VALIDATE_FUN, <<" function(newDoc, oldDoc, userCtx) { function reportError(error_msg) { log('Error writing document `' + newDoc._id + '\\' to the replicator database: ' + error_msg); throw({forbidden: error_msg}); } function validateEndpoint(endpoint, fieldName) { if ((typeof endpoint !== 'string') && ((typeof endpoint !== 'object') || (endpoint === null))) { reportError('The `' + fieldName + '\\' property must exist' + ' and be either a string or an object.'); } if (typeof endpoint === 'object') { if ((typeof endpoint.url !== 'string') || !endpoint.url) { reportError('The url property must exist in the `' + fieldName + '\\' field and must be a non-empty string.'); } if ((typeof endpoint.auth !== 'undefined') && ((typeof endpoint.auth !== 'object') || endpoint.auth === null)) { reportError('`' + fieldName + '.auth\\' must be a non-null object.'); } if ((typeof endpoint.headers !== 'undefined') && ((typeof endpoint.headers !== 'object') || endpoint.headers === null)) { reportError('`' + fieldName + '.headers\\' must be a non-null object.'); } } } var isReplicator = (userCtx.roles.indexOf('_replicator') >= 0); var isAdmin = (userCtx.roles.indexOf('_admin') >= 0); if (oldDoc && !newDoc._deleted && !isReplicator && (oldDoc._replication_state === 'triggered')) { reportError('Only the replicator can edit replication documents ' + 'that are in the triggered state.'); } if (!newDoc._deleted) { validateEndpoint(newDoc.source, 'source'); validateEndpoint(newDoc.target, 'target'); if ((typeof newDoc.create_target !== 'undefined') && (typeof newDoc.create_target !== 'boolean')) { reportError('The `create_target\\' field must be a boolean.'); } if ((typeof newDoc.continuous !== 'undefined') && (typeof newDoc.continuous !== 'boolean')) { reportError('The `continuous\\' field must be a boolean.'); } if ((typeof newDoc.doc_ids !== 'undefined') && !isArray(newDoc.doc_ids)) { reportError('The `doc_ids\\' field must be an array of strings.'); } if ((typeof newDoc.filter !== 'undefined') && ((typeof newDoc.filter !== 'string') || !newDoc.filter)) { reportError('The `filter\\' field must be a non-empty string.'); } if ((typeof newDoc.query_params !== 'undefined') && ((typeof newDoc.query_params !== 'object') || newDoc.query_params === null)) { reportError('The `query_params\\' field must be an object.'); } if (newDoc.user_ctx) { var user_ctx = newDoc.user_ctx; if ((typeof user_ctx !== 'object') || (user_ctx === null)) { reportError('The `user_ctx\\' property must be a ' + 'non-null object.'); } if (!(user_ctx.name === null || (typeof user_ctx.name === 'undefined') || ((typeof user_ctx.name === 'string') && user_ctx.name.length > 0))) { reportError('The `user_ctx.name\\' property must be a ' + 'non-empty string or null.'); } if (!isAdmin && (user_ctx.name !== userCtx.name)) { reportError('The given `user_ctx.name\\' is not valid'); } if (user_ctx.roles && !isArray(user_ctx.roles)) { reportError('The `user_ctx.roles\\' property must be ' + 'an array of strings.'); } if (!isAdmin && user_ctx.roles) { for (var i = 0; i < user_ctx.roles.length; i++) { var role = user_ctx.roles[i]; if (typeof role !== 'string' || role.length === 0) { reportError('Roles must be non-empty strings.'); } if (userCtx.roles.indexOf(role) === -1) { reportError('Invalid role (`' + role + '\\') in the `user_ctx\\''); } } } } else { if (!isAdmin) { reportError('The `user_ctx\\' property is missing (it is ' + 'optional for admins only).'); } } } else { if (!isAdmin) { if (!oldDoc.user_ctx || (oldDoc.user_ctx.name !== userCtx.name)) { reportError('Replication documents can only be deleted by ' + 'admins or by the users who created them.'); } } } } ">>). apache-couchdb-1.5.0/src/couch_replicator/src/couch_replicator_worker.erl0000644000175000001440000004212712230722213023605 00000000000000% 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. -module(couch_replicator_worker). -behaviour(gen_server). % public API -export([start_link/5]). % gen_server callbacks -export([init/1, terminate/2, code_change/3]). -export([handle_call/3, handle_cast/2, handle_info/2]). -include("couch_db.hrl"). -include("couch_replicator_api_wrap.hrl"). -include("couch_replicator.hrl"). % TODO: maybe make both buffer max sizes configurable -define(DOC_BUFFER_BYTE_SIZE, 512 * 1024). % for remote targets -define(DOC_BUFFER_LEN, 10). % for local targets, # of documents -define(MAX_BULK_ATT_SIZE, 64 * 1024). -define(MAX_BULK_ATTS_PER_DOC, 8). -define(STATS_DELAY, 10000000). % 10 seconds (in microseconds) -define(inc_stat(StatPos, Stats, Inc), setelement(StatPos, Stats, element(StatPos, Stats) + Inc)). -import(couch_replicator_utils, [ open_db/1, close_db/1, start_db_compaction_notifier/2, stop_db_compaction_notifier/1 ]). -import(couch_util, [ to_binary/1, get_value/2, get_value/3 ]). -record(batch, { docs = [], size = 0 }). -record(state, { cp, loop, max_parallel_conns, source, target, readers = [], writer = nil, pending_fetch = nil, flush_waiter = nil, stats = #rep_stats{}, source_db_compaction_notifier = nil, target_db_compaction_notifier = nil, batch = #batch{} }). start_link(Cp, #db{} = Source, Target, ChangesManager, _MaxConns) -> Pid = spawn_link(fun() -> erlang:put(last_stats_report, now()), queue_fetch_loop(Source, Target, Cp, Cp, ChangesManager) end), {ok, Pid}; start_link(Cp, Source, Target, ChangesManager, MaxConns) -> gen_server:start_link( ?MODULE, {Cp, Source, Target, ChangesManager, MaxConns}, []). init({Cp, Source, Target, ChangesManager, MaxConns}) -> process_flag(trap_exit, true), Parent = self(), LoopPid = spawn_link(fun() -> queue_fetch_loop(Source, Target, Parent, Cp, ChangesManager) end), erlang:put(last_stats_report, now()), State = #state{ cp = Cp, max_parallel_conns = MaxConns, loop = LoopPid, source = open_db(Source), target = open_db(Target), source_db_compaction_notifier = start_db_compaction_notifier(Source, self()), target_db_compaction_notifier = start_db_compaction_notifier(Target, self()) }, {ok, State}. handle_call({fetch_doc, {_Id, _Revs, _PAs} = Params}, {Pid, _} = From, #state{loop = Pid, readers = Readers, pending_fetch = nil, source = Src, target = Tgt, max_parallel_conns = MaxConns} = State) -> case length(Readers) of Size when Size < MaxConns -> Reader = spawn_doc_reader(Src, Tgt, Params), NewState = State#state{ readers = [Reader | Readers] }, {reply, ok, NewState}; _ -> NewState = State#state{ pending_fetch = {From, Params} }, {noreply, NewState} end; handle_call({batch_doc, Doc}, From, State) -> gen_server:reply(From, ok), {noreply, maybe_flush_docs(Doc, State)}; handle_call({add_stats, IncStats}, From, #state{stats = Stats} = State) -> gen_server:reply(From, ok), NewStats = couch_replicator_utils:sum_stats(Stats, IncStats), NewStats2 = maybe_report_stats(State#state.cp, NewStats), {noreply, State#state{stats = NewStats2}}; handle_call(flush, {Pid, _} = From, #state{loop = Pid, writer = nil, flush_waiter = nil, target = Target, batch = Batch} = State) -> State2 = case State#state.readers of [] -> State#state{writer = spawn_writer(Target, Batch)}; _ -> State end, {noreply, State2#state{flush_waiter = From}}. handle_cast({db_compacted, DbName}, #state{source = #db{name = DbName} = Source} = State) -> {ok, NewSource} = couch_db:reopen(Source), {noreply, State#state{source = NewSource}}; handle_cast({db_compacted, DbName}, #state{target = #db{name = DbName} = Target} = State) -> {ok, NewTarget} = couch_db:reopen(Target), {noreply, State#state{target = NewTarget}}; handle_cast(Msg, State) -> {stop, {unexpected_async_call, Msg}, State}. handle_info({'EXIT', Pid, normal}, #state{loop = Pid} = State) -> #state{ batch = #batch{docs = []}, readers = [], writer = nil, pending_fetch = nil, flush_waiter = nil } = State, {stop, normal, State}; handle_info({'EXIT', Pid, normal}, #state{writer = Pid} = State) -> {noreply, after_full_flush(State)}; handle_info({'EXIT', Pid, normal}, #state{writer = nil} = State) -> #state{ readers = Readers, writer = Writer, batch = Batch, source = Source, target = Target, pending_fetch = Fetch, flush_waiter = FlushWaiter } = State, case Readers -- [Pid] of Readers -> {noreply, State}; Readers2 -> State2 = case Fetch of nil -> case (FlushWaiter =/= nil) andalso (Writer =:= nil) andalso (Readers2 =:= []) of true -> State#state{ readers = Readers2, writer = spawn_writer(Target, Batch) }; false -> State#state{readers = Readers2} end; {From, FetchParams} -> Reader = spawn_doc_reader(Source, Target, FetchParams), gen_server:reply(From, ok), State#state{ readers = [Reader | Readers2], pending_fetch = nil } end, {noreply, State2} end; handle_info({'EXIT', Pid, Reason}, State) -> {stop, {process_died, Pid, Reason}, State}. terminate(_Reason, State) -> close_db(State#state.source), close_db(State#state.target), stop_db_compaction_notifier(State#state.source_db_compaction_notifier), stop_db_compaction_notifier(State#state.target_db_compaction_notifier). code_change(_OldVsn, State, _Extra) -> {ok, State}. queue_fetch_loop(Source, Target, Parent, Cp, ChangesManager) -> ChangesManager ! {get_changes, self()}, receive {closed, ChangesManager} -> ok; {changes, ChangesManager, Changes, ReportSeq} -> Target2 = open_db(Target), {IdRevs, Stats0} = find_missing(Changes, Target2), case Source of #db{} -> Source2 = open_db(Source), Stats = local_process_batch( IdRevs, Cp, Source2, Target2, #batch{}, Stats0), close_db(Source2); #httpdb{} -> ok = gen_server:call(Parent, {add_stats, Stats0}, infinity), remote_process_batch(IdRevs, Parent), {ok, Stats} = gen_server:call(Parent, flush, infinity) end, close_db(Target2), ok = gen_server:call(Cp, {report_seq_done, ReportSeq, Stats}, infinity), erlang:put(last_stats_report, now()), ?LOG_DEBUG("Worker reported completion of seq ~p", [ReportSeq]), queue_fetch_loop(Source, Target, Parent, Cp, ChangesManager) end. local_process_batch([], _Cp, _Src, _Tgt, #batch{docs = []}, Stats) -> Stats; local_process_batch([], Cp, Source, Target, #batch{docs = Docs, size = Size}, Stats) -> case Target of #httpdb{} -> ?LOG_DEBUG("Worker flushing doc batch of size ~p bytes", [Size]); #db{} -> ?LOG_DEBUG("Worker flushing doc batch of ~p docs", [Size]) end, Stats2 = flush_docs(Target, Docs), Stats3 = couch_replicator_utils:sum_stats(Stats, Stats2), local_process_batch([], Cp, Source, Target, #batch{}, Stats3); local_process_batch([IdRevs | Rest], Cp, Source, Target, Batch, Stats) -> {ok, {_, DocList, Stats2, _}} = fetch_doc( Source, IdRevs, fun local_doc_handler/2, {Target, [], Stats, Cp}), {Batch2, Stats3} = lists:foldl( fun(Doc, {Batch0, Stats0}) -> {Batch1, S} = maybe_flush_docs(Target, Batch0, Doc), {Batch1, couch_replicator_utils:sum_stats(Stats0, S)} end, {Batch, Stats2}, DocList), local_process_batch(Rest, Cp, Source, Target, Batch2, Stats3). remote_process_batch([], _Parent) -> ok; remote_process_batch([{Id, Revs, PAs} | Rest], Parent) -> % When the source is a remote database, we fetch a single document revision % per HTTP request. This is mostly to facilitate retrying of HTTP requests % due to network transient failures. It also helps not exceeding the maximum % URL length allowed by proxies and Mochiweb. lists:foreach( fun(Rev) -> ok = gen_server:call(Parent, {fetch_doc, {Id, [Rev], PAs}}, infinity) end, Revs), remote_process_batch(Rest, Parent). spawn_doc_reader(Source, Target, FetchParams) -> Parent = self(), spawn_link(fun() -> Source2 = open_db(Source), fetch_doc( Source2, FetchParams, fun remote_doc_handler/2, {Parent, Target}), close_db(Source2) end). fetch_doc(Source, {Id, Revs, PAs}, DocHandler, Acc) -> try couch_replicator_api_wrap:open_doc_revs( Source, Id, Revs, [{atts_since, PAs}, latest], DocHandler, Acc) catch throw:{missing_stub, _} -> ?LOG_ERROR("Retrying fetch and update of document `~s` due to out of " "sync attachment stubs. Missing revisions are: ~s", [Id, couch_doc:revs_to_strs(Revs)]), couch_replicator_api_wrap:open_doc_revs(Source, Id, Revs, [latest], DocHandler, Acc) end. local_doc_handler({ok, Doc}, {Target, DocList, Stats, Cp}) -> Stats2 = ?inc_stat(#rep_stats.docs_read, Stats, 1), case batch_doc(Doc) of true -> {ok, {Target, [Doc | DocList], Stats2, Cp}}; false -> ?LOG_DEBUG("Worker flushing doc with attachments", []), Target2 = open_db(Target), Success = (flush_doc(Target2, Doc) =:= ok), close_db(Target2), Stats3 = case Success of true -> ?inc_stat(#rep_stats.docs_written, Stats2, 1); false -> ?inc_stat(#rep_stats.doc_write_failures, Stats2, 1) end, Stats4 = maybe_report_stats(Cp, Stats3), {ok, {Target, DocList, Stats4, Cp}} end; local_doc_handler(_, Acc) -> {ok, Acc}. remote_doc_handler({ok, #doc{atts = []} = Doc}, {Parent, _} = Acc) -> ok = gen_server:call(Parent, {batch_doc, Doc}, infinity), {ok, Acc}; remote_doc_handler({ok, Doc}, {Parent, Target} = Acc) -> % Immediately flush documents with attachments received from a remote % source. The data property of each attachment is a function that starts % streaming the attachment data from the remote source, therefore it's % convenient to call it ASAP to avoid ibrowse inactivity timeouts. Stats = #rep_stats{docs_read = 1}, ?LOG_DEBUG("Worker flushing doc with attachments", []), Target2 = open_db(Target), Success = (flush_doc(Target2, Doc) =:= ok), close_db(Target2), {Result, Stats2} = case Success of true -> {{ok, Acc}, ?inc_stat(#rep_stats.docs_written, Stats, 1)}; false -> {{skip, Acc}, ?inc_stat(#rep_stats.doc_write_failures, Stats, 1)} end, ok = gen_server:call(Parent, {add_stats, Stats2}, infinity), Result; remote_doc_handler(_, Acc) -> {ok, Acc}. spawn_writer(Target, #batch{docs = DocList, size = Size}) -> case {Target, Size > 0} of {#httpdb{}, true} -> ?LOG_DEBUG("Worker flushing doc batch of size ~p bytes", [Size]); {#db{}, true} -> ?LOG_DEBUG("Worker flushing doc batch of ~p docs", [Size]); _ -> ok end, Parent = self(), spawn_link( fun() -> Target2 = open_db(Target), Stats = flush_docs(Target2, DocList), close_db(Target2), ok = gen_server:call(Parent, {add_stats, Stats}, infinity) end). after_full_flush(#state{stats = Stats, flush_waiter = Waiter} = State) -> gen_server:reply(Waiter, {ok, Stats}), erlang:put(last_stats_report, now()), State#state{ stats = #rep_stats{}, flush_waiter = nil, writer = nil, batch = #batch{} }. maybe_flush_docs(Doc,State) -> #state{ target = Target, batch = Batch, stats = Stats, cp = Cp } = State, {Batch2, WStats} = maybe_flush_docs(Target, Batch, Doc), Stats2 = couch_replicator_utils:sum_stats(Stats, WStats), Stats3 = ?inc_stat(#rep_stats.docs_read, Stats2, 1), Stats4 = maybe_report_stats(Cp, Stats3), State#state{stats = Stats4, batch = Batch2}. maybe_flush_docs(#httpdb{} = Target, Batch, Doc) -> #batch{docs = DocAcc, size = SizeAcc} = Batch, case batch_doc(Doc) of false -> ?LOG_DEBUG("Worker flushing doc with attachments", []), case flush_doc(Target, Doc) of ok -> {Batch, #rep_stats{docs_written = 1}}; _ -> {Batch, #rep_stats{doc_write_failures = 1}} end; true -> JsonDoc = ?JSON_ENCODE(couch_doc:to_json_obj(Doc, [revs, attachments])), case SizeAcc + iolist_size(JsonDoc) of SizeAcc2 when SizeAcc2 > ?DOC_BUFFER_BYTE_SIZE -> ?LOG_DEBUG("Worker flushing doc batch of size ~p bytes", [SizeAcc2]), Stats = flush_docs(Target, [JsonDoc | DocAcc]), {#batch{}, Stats}; SizeAcc2 -> {#batch{docs = [JsonDoc | DocAcc], size = SizeAcc2}, #rep_stats{}} end end; maybe_flush_docs(#db{} = Target, #batch{docs = DocAcc, size = SizeAcc}, Doc) -> case SizeAcc + 1 of SizeAcc2 when SizeAcc2 >= ?DOC_BUFFER_LEN -> ?LOG_DEBUG("Worker flushing doc batch of ~p docs", [SizeAcc2]), Stats = flush_docs(Target, [Doc | DocAcc]), {#batch{}, Stats}; SizeAcc2 -> {#batch{docs = [Doc | DocAcc], size = SizeAcc2}, #rep_stats{}} end. batch_doc(#doc{atts = []}) -> true; batch_doc(#doc{atts = Atts}) -> (length(Atts) =< ?MAX_BULK_ATTS_PER_DOC) andalso lists:all( fun(#att{disk_len = L, data = Data}) -> (L =< ?MAX_BULK_ATT_SIZE) andalso (Data =/= stub) end, Atts). flush_docs(_Target, []) -> #rep_stats{}; flush_docs(Target, DocList) -> {ok, Errors} = couch_replicator_api_wrap:update_docs( Target, DocList, [delay_commit], replicated_changes), DbUri = couch_replicator_api_wrap:db_uri(Target), lists:foreach( fun({Props}) -> ?LOG_ERROR("Replicator: couldn't write document `~s`, revision `~s`," " to target database `~s`. Error: `~s`, reason: `~s`.", [get_value(id, Props, ""), get_value(rev, Props, ""), DbUri, get_value(error, Props, ""), get_value(reason, Props, "")]) end, Errors), #rep_stats{ docs_written = length(DocList) - length(Errors), doc_write_failures = length(Errors) }. flush_doc(Target, #doc{id = Id, revs = {Pos, [RevId | _]}} = Doc) -> try couch_replicator_api_wrap:update_doc(Target, Doc, [], replicated_changes) of {ok, _} -> ok; Error -> ?LOG_ERROR("Replicator: error writing document `~s` to `~s`: ~s", [Id, couch_replicator_api_wrap:db_uri(Target), couch_util:to_binary(Error)]), Error catch throw:{missing_stub, _} = MissingStub -> throw(MissingStub); throw:{Error, Reason} -> ?LOG_ERROR("Replicator: couldn't write document `~s`, revision `~s`," " to target database `~s`. Error: `~s`, reason: `~s`.", [Id, couch_doc:rev_to_str({Pos, RevId}), couch_replicator_api_wrap:db_uri(Target), to_binary(Error), to_binary(Reason)]), {error, Error}; throw:Err -> ?LOG_ERROR("Replicator: couldn't write document `~s`, revision `~s`," " to target database `~s`. Error: `~s`.", [Id, couch_doc:rev_to_str({Pos, RevId}), couch_replicator_api_wrap:db_uri(Target), to_binary(Err)]), {error, Err} end. find_missing(DocInfos, Target) -> {IdRevs, AllRevsCount} = lists:foldr( fun(#doc_info{id = Id, revs = RevsInfo}, {IdRevAcc, CountAcc}) -> Revs = [Rev || #rev_info{rev = Rev} <- RevsInfo], {[{Id, Revs} | IdRevAcc], CountAcc + length(Revs)} end, {[], 0}, DocInfos), {ok, Missing} = couch_replicator_api_wrap:get_missing_revs(Target, IdRevs), MissingRevsCount = lists:foldl( fun({_Id, MissingRevs, _PAs}, Acc) -> Acc + length(MissingRevs) end, 0, Missing), Stats = #rep_stats{ missing_checked = AllRevsCount, missing_found = MissingRevsCount }, {Missing, Stats}. maybe_report_stats(Cp, Stats) -> Now = now(), case timer:now_diff(erlang:get(last_stats_report), Now) >= ?STATS_DELAY of true -> ok = gen_server:call(Cp, {add_stats, Stats}, infinity), erlang:put(last_stats_report, Now), #rep_stats{}; false -> Stats end. apache-couchdb-1.5.0/src/couch_replicator/src/couch_replicator_httpc_pool.erl0000644000175000001440000000756612230722213024457 00000000000000% 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. -module(couch_replicator_httpc_pool). -behaviour(gen_server). % public API -export([start_link/2, stop/1]). -export([get_worker/1, release_worker/2]). % gen_server API -export([init/1, handle_call/3, handle_info/2, handle_cast/2]). -export([code_change/3, terminate/2]). -include("couch_db.hrl"). -import(couch_util, [ get_value/2, get_value/3 ]). -record(state, { url, limit, % max # of workers allowed free = [], % free workers (connections) busy = [], % busy workers (connections) waiting = queue:new() % blocked clients waiting for a worker }). start_link(Url, Options) -> gen_server:start_link(?MODULE, {Url, Options}, []). stop(Pool) -> ok = gen_server:call(Pool, stop, infinity). get_worker(Pool) -> {ok, _Worker} = gen_server:call(Pool, get_worker, infinity). release_worker(Pool, Worker) -> ok = gen_server:cast(Pool, {release_worker, Worker}). init({Url, Options}) -> process_flag(trap_exit, true), State = #state{ url = Url, limit = get_value(max_connections, Options) }, {ok, State}. handle_call(get_worker, From, #state{waiting = Waiting} = State) -> #state{url = Url, limit = Limit, busy = Busy, free = Free} = State, case length(Busy) >= Limit of true -> {noreply, State#state{waiting = queue:in(From, Waiting)}}; false -> case Free of [] -> {ok, Worker} = ibrowse:spawn_link_worker_process(Url), Free2 = Free; [Worker | Free2] -> ok end, NewState = State#state{free = Free2, busy = [Worker | Busy]}, {reply, {ok, Worker}, NewState} end; handle_call(stop, _From, State) -> {stop, normal, ok, State}. handle_cast({release_worker, Worker}, #state{waiting = Waiting} = State) -> case is_process_alive(Worker) andalso lists:member(Worker, State#state.busy) of true -> case queue:out(Waiting) of {empty, Waiting2} -> Busy2 = State#state.busy -- [Worker], Free2 = [Worker | State#state.free]; {{value, From}, Waiting2} -> gen_server:reply(From, {ok, Worker}), Busy2 = State#state.busy, Free2 = State#state.free end, NewState = State#state{ busy = Busy2, free = Free2, waiting = Waiting2 }, {noreply, NewState}; false -> {noreply, State} end. handle_info({'EXIT', Pid, _Reason}, #state{busy = Busy, free = Free} = State) -> case Free -- [Pid] of Free -> case Busy -- [Pid] of Busy -> {noreply, State}; Busy2 -> case queue:out(State#state.waiting) of {empty, _} -> {noreply, State#state{busy = Busy2}}; {{value, From}, Waiting2} -> {ok, Worker} = ibrowse:spawn_link_worker_process(State#state.url), gen_server:reply(From, {ok, Worker}), {noreply, State#state{busy = [Worker | Busy2], waiting = Waiting2}} end end; Free2 -> {noreply, State#state{free = Free2}} end. code_change(_OldVsn, State, _Extra) -> {ok, State}. terminate(_Reason, State) -> lists:foreach(fun ibrowse_http_client:stop/1, State#state.free), lists:foreach(fun ibrowse_http_client:stop/1, State#state.busy). apache-couchdb-1.5.0/src/couch_replicator/src/couch_replicator_utils.erl0000644000175000001440000003432112230722213023431 00000000000000% 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. -module(couch_replicator_utils). -export([parse_rep_doc/2]). -export([open_db/1, close_db/1]). -export([start_db_compaction_notifier/2, stop_db_compaction_notifier/1]). -export([replication_id/2]). -export([sum_stats/2]). -include("couch_db.hrl"). -include("couch_replicator_api_wrap.hrl"). -include("couch_replicator.hrl"). -include("../ibrowse/ibrowse.hrl"). -import(couch_util, [ get_value/2, get_value/3 ]). parse_rep_doc({Props}, UserCtx) -> ProxyParams = parse_proxy_params(get_value(<<"proxy">>, Props, <<>>)), Options = make_options(Props), case get_value(cancel, Options, false) andalso (get_value(id, Options, nil) =/= nil) of true -> {ok, #rep{options = Options, user_ctx = UserCtx}}; false -> Source = parse_rep_db(get_value(<<"source">>, Props), ProxyParams, Options), Target = parse_rep_db(get_value(<<"target">>, Props), ProxyParams, Options), Rep = #rep{ source = Source, target = Target, options = Options, user_ctx = UserCtx, doc_id = get_value(<<"_id">>, Props, null) }, {ok, Rep#rep{id = replication_id(Rep)}} end. replication_id(#rep{options = Options} = Rep) -> BaseId = replication_id(Rep, ?REP_ID_VERSION), {BaseId, maybe_append_options([continuous, create_target], Options)}. % Versioned clauses for generating replication IDs. % If a change is made to how replications are identified, % please add a new clause and increase ?REP_ID_VERSION. replication_id(#rep{user_ctx = UserCtx} = Rep, 3) -> UUID = couch_server:get_uuid(), Src = get_rep_endpoint(UserCtx, Rep#rep.source), Tgt = get_rep_endpoint(UserCtx, Rep#rep.target), maybe_append_filters([UUID, Src, Tgt], Rep); replication_id(#rep{user_ctx = UserCtx} = Rep, 2) -> {ok, HostName} = inet:gethostname(), Port = case (catch mochiweb_socket_server:get(couch_httpd, port)) of P when is_number(P) -> P; _ -> % On restart we might be called before the couch_httpd process is % started. % TODO: we might be under an SSL socket server only, or both under % SSL and a non-SSL socket. % ... mochiweb_socket_server:get(https, port) list_to_integer(couch_config:get("httpd", "port", "5984")) end, Src = get_rep_endpoint(UserCtx, Rep#rep.source), Tgt = get_rep_endpoint(UserCtx, Rep#rep.target), maybe_append_filters([HostName, Port, Src, Tgt], Rep); replication_id(#rep{user_ctx = UserCtx} = Rep, 1) -> {ok, HostName} = inet:gethostname(), Src = get_rep_endpoint(UserCtx, Rep#rep.source), Tgt = get_rep_endpoint(UserCtx, Rep#rep.target), maybe_append_filters([HostName, Src, Tgt], Rep). maybe_append_filters(Base, #rep{source = Source, user_ctx = UserCtx, options = Options}) -> Base2 = Base ++ case get_value(filter, Options) of undefined -> case get_value(doc_ids, Options) of undefined -> []; DocIds -> [DocIds] end; Filter -> [filter_code(Filter, Source, UserCtx), get_value(query_params, Options, {[]})] end, couch_util:to_hex(couch_util:md5(term_to_binary(Base2))). filter_code(Filter, Source, UserCtx) -> {DDocName, FilterName} = case re:run(Filter, "(.*?)/(.*)", [{capture, [1, 2], binary}]) of {match, [DDocName0, FilterName0]} -> {DDocName0, FilterName0}; _ -> throw({error, <<"Invalid filter. Must match `ddocname/filtername`.">>}) end, Db = case (catch couch_replicator_api_wrap:db_open(Source, [{user_ctx, UserCtx}])) of {ok, Db0} -> Db0; DbError -> DbErrorMsg = io_lib:format("Could not open source database `~s`: ~s", [couch_replicator_api_wrap:db_uri(Source), couch_util:to_binary(DbError)]), throw({error, iolist_to_binary(DbErrorMsg)}) end, try Body = case (catch couch_replicator_api_wrap:open_doc( Db, <<"_design/", DDocName/binary>>, [ejson_body])) of {ok, #doc{body = Body0}} -> Body0; DocError -> DocErrorMsg = io_lib:format( "Couldn't open document `_design/~s` from source " "database `~s`: ~s", [DDocName, couch_replicator_api_wrap:db_uri(Source), couch_util:to_binary(DocError)]), throw({error, iolist_to_binary(DocErrorMsg)}) end, Code = couch_util:get_nested_json_value( Body, [<<"filters">>, FilterName]), re:replace(Code, [$^, "\s*(.*?)\s*", $$], "\\1", [{return, binary}]) after couch_replicator_api_wrap:db_close(Db) end. maybe_append_options(Options, RepOptions) -> lists:foldl(fun(Option, Acc) -> Acc ++ case get_value(Option, RepOptions, false) of true -> "+" ++ atom_to_list(Option); false -> "" end end, [], Options). get_rep_endpoint(_UserCtx, #httpdb{url=Url, headers=Headers, oauth=OAuth}) -> DefaultHeaders = (#httpdb{})#httpdb.headers, case OAuth of nil -> {remote, Url, Headers -- DefaultHeaders}; #oauth{} -> {remote, Url, Headers -- DefaultHeaders, OAuth} end; get_rep_endpoint(UserCtx, <>) -> {local, DbName, UserCtx}. parse_rep_db({Props}, ProxyParams, Options) -> Url = maybe_add_trailing_slash(get_value(<<"url">>, Props)), {AuthProps} = get_value(<<"auth">>, Props, {[]}), {BinHeaders} = get_value(<<"headers">>, Props, {[]}), Headers = lists:ukeysort(1, [{?b2l(K), ?b2l(V)} || {K, V} <- BinHeaders]), DefaultHeaders = (#httpdb{})#httpdb.headers, OAuth = case get_value(<<"oauth">>, AuthProps) of undefined -> nil; {OauthProps} -> #oauth{ consumer_key = ?b2l(get_value(<<"consumer_key">>, OauthProps)), token = ?b2l(get_value(<<"token">>, OauthProps)), token_secret = ?b2l(get_value(<<"token_secret">>, OauthProps)), consumer_secret = ?b2l(get_value(<<"consumer_secret">>, OauthProps)), signature_method = case get_value(<<"signature_method">>, OauthProps) of undefined -> hmac_sha1; <<"PLAINTEXT">> -> plaintext; <<"HMAC-SHA1">> -> hmac_sha1; <<"RSA-SHA1">> -> rsa_sha1 end } end, #httpdb{ url = Url, oauth = OAuth, headers = lists:ukeymerge(1, Headers, DefaultHeaders), ibrowse_options = lists:keysort(1, [{socket_options, get_value(socket_options, Options)} | ProxyParams ++ ssl_params(Url)]), timeout = get_value(connection_timeout, Options), http_connections = get_value(http_connections, Options), retries = get_value(retries, Options) }; parse_rep_db(<<"http://", _/binary>> = Url, ProxyParams, Options) -> parse_rep_db({[{<<"url">>, Url}]}, ProxyParams, Options); parse_rep_db(<<"https://", _/binary>> = Url, ProxyParams, Options) -> parse_rep_db({[{<<"url">>, Url}]}, ProxyParams, Options); parse_rep_db(<>, _ProxyParams, _Options) -> DbName. maybe_add_trailing_slash(Url) when is_binary(Url) -> maybe_add_trailing_slash(?b2l(Url)); maybe_add_trailing_slash(Url) -> case lists:last(Url) of $/ -> Url; _ -> Url ++ "/" end. make_options(Props) -> Options = lists:ukeysort(1, convert_options(Props)), DefWorkers = couch_config:get("replicator", "worker_processes", "4"), DefBatchSize = couch_config:get("replicator", "worker_batch_size", "500"), DefConns = couch_config:get("replicator", "http_connections", "20"), DefTimeout = couch_config:get("replicator", "connection_timeout", "30000"), DefRetries = couch_config:get("replicator", "retries_per_request", "10"), {ok, DefSocketOptions} = couch_util:parse_term( couch_config:get("replicator", "socket_options", "[{keepalive, true}, {nodelay, false}]")), lists:ukeymerge(1, Options, lists:keysort(1, [ {connection_timeout, list_to_integer(DefTimeout)}, {retries, list_to_integer(DefRetries)}, {http_connections, list_to_integer(DefConns)}, {socket_options, DefSocketOptions}, {worker_batch_size, list_to_integer(DefBatchSize)}, {worker_processes, list_to_integer(DefWorkers)} ])). convert_options([])-> []; convert_options([{<<"cancel">>, V} | R]) -> [{cancel, V} | convert_options(R)]; convert_options([{IdOpt, V} | R]) when IdOpt =:= <<"_local_id">>; IdOpt =:= <<"replication_id">>; IdOpt =:= <<"id">> -> Id = lists:splitwith(fun(X) -> X =/= $+ end, ?b2l(V)), [{id, Id} | convert_options(R)]; convert_options([{<<"create_target">>, V} | R]) -> [{create_target, V} | convert_options(R)]; convert_options([{<<"continuous">>, V} | R]) -> [{continuous, V} | convert_options(R)]; convert_options([{<<"filter">>, V} | R]) -> [{filter, V} | convert_options(R)]; convert_options([{<<"query_params">>, V} | R]) -> [{query_params, V} | convert_options(R)]; convert_options([{<<"doc_ids">>, null} | R]) -> convert_options(R); convert_options([{<<"doc_ids">>, V} | R]) -> % Ensure same behaviour as old replicator: accept a list of percent % encoded doc IDs. DocIds = [?l2b(couch_httpd:unquote(Id)) || Id <- V], [{doc_ids, DocIds} | convert_options(R)]; convert_options([{<<"worker_processes">>, V} | R]) -> [{worker_processes, couch_util:to_integer(V)} | convert_options(R)]; convert_options([{<<"worker_batch_size">>, V} | R]) -> [{worker_batch_size, couch_util:to_integer(V)} | convert_options(R)]; convert_options([{<<"http_connections">>, V} | R]) -> [{http_connections, couch_util:to_integer(V)} | convert_options(R)]; convert_options([{<<"connection_timeout">>, V} | R]) -> [{connection_timeout, couch_util:to_integer(V)} | convert_options(R)]; convert_options([{<<"retries_per_request">>, V} | R]) -> [{retries, couch_util:to_integer(V)} | convert_options(R)]; convert_options([{<<"socket_options">>, V} | R]) -> {ok, SocketOptions} = couch_util:parse_term(V), [{socket_options, SocketOptions} | convert_options(R)]; convert_options([{<<"since_seq">>, V} | R]) -> [{since_seq, V} | convert_options(R)]; convert_options([_ | R]) -> % skip unknown option convert_options(R). parse_proxy_params(ProxyUrl) when is_binary(ProxyUrl) -> parse_proxy_params(?b2l(ProxyUrl)); parse_proxy_params([]) -> []; parse_proxy_params(ProxyUrl) -> #url{ host = Host, port = Port, username = User, password = Passwd } = ibrowse_lib:parse_url(ProxyUrl), [{proxy_host, Host}, {proxy_port, Port}] ++ case is_list(User) andalso is_list(Passwd) of false -> []; true -> [{proxy_user, User}, {proxy_password, Passwd}] end. ssl_params(Url) -> case ibrowse_lib:parse_url(Url) of #url{protocol = https} -> Depth = list_to_integer( couch_config:get("replicator", "ssl_certificate_max_depth", "3") ), VerifyCerts = couch_config:get("replicator", "verify_ssl_certificates"), CertFile = couch_config:get("replicator", "cert_file", nil), KeyFile = couch_config:get("replicator", "key_file", nil), Password = couch_config:get("replicator", "password", nil), SslOpts = [{depth, Depth} | ssl_verify_options(VerifyCerts =:= "true")], SslOpts1 = case CertFile /= nil andalso KeyFile /= nil of true -> case Password of nil -> [{certfile, CertFile}, {keyfile, KeyFile}] ++ SslOpts; _ -> [{certfile, CertFile}, {keyfile, KeyFile}, {password, Password}] ++ SslOpts end; false -> SslOpts end, [{is_ssl, true}, {ssl_options, SslOpts1}]; #url{protocol = http} -> [] end. ssl_verify_options(Value) -> ssl_verify_options(Value, erlang:system_info(otp_release)). ssl_verify_options(true, OTPVersion) when OTPVersion >= "R14" -> CAFile = couch_config:get("replicator", "ssl_trusted_certificates_file"), [{verify, verify_peer}, {cacertfile, CAFile}]; ssl_verify_options(false, OTPVersion) when OTPVersion >= "R14" -> [{verify, verify_none}]; ssl_verify_options(true, _OTPVersion) -> CAFile = couch_config:get("replicator", "ssl_trusted_certificates_file"), [{verify, 2}, {cacertfile, CAFile}]; ssl_verify_options(false, _OTPVersion) -> [{verify, 0}]. open_db(#db{name = Name, user_ctx = UserCtx, options = Options}) -> {ok, Db} = couch_db:open(Name, [{user_ctx, UserCtx} | Options]), Db; open_db(HttpDb) -> HttpDb. close_db(#db{} = Db) -> couch_db:close(Db); close_db(_HttpDb) -> ok. start_db_compaction_notifier(#db{name = DbName}, Server) -> {ok, Notifier} = couch_db_update_notifier:start_link( fun({compacted, DbName1}) when DbName1 =:= DbName -> ok = gen_server:cast(Server, {db_compacted, DbName}); (_) -> ok end), Notifier; start_db_compaction_notifier(_, _) -> nil. stop_db_compaction_notifier(nil) -> ok; stop_db_compaction_notifier(Notifier) -> couch_db_update_notifier:stop(Notifier). sum_stats(#rep_stats{} = S1, #rep_stats{} = S2) -> #rep_stats{ missing_checked = S1#rep_stats.missing_checked + S2#rep_stats.missing_checked, missing_found = S1#rep_stats.missing_found + S2#rep_stats.missing_found, docs_read = S1#rep_stats.docs_read + S2#rep_stats.docs_read, docs_written = S1#rep_stats.docs_written + S2#rep_stats.docs_written, doc_write_failures = S1#rep_stats.doc_write_failures + S2#rep_stats.doc_write_failures }. apache-couchdb-1.5.0/src/couch_replicator/src/couch_replicator_notifier.erl0000644000175000001440000000271312230722213024110 00000000000000% 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. -module(couch_replicator_notifier). -behaviour(gen_event). % public API -export([start_link/1, stop/1, notify/1]). % gen_event callbacks -export([init/1, terminate/2, code_change/3]). -export([handle_event/2, handle_call/2, handle_info/2]). -include("couch_db.hrl"). start_link(FunAcc) -> couch_event_sup:start_link(couch_replication, {couch_replicator_notifier, make_ref()}, FunAcc). notify(Event) -> gen_event:notify(couch_replication, Event). stop(Pid) -> couch_event_sup:stop(Pid). init(FunAcc) -> {ok, FunAcc}. terminate(_Reason, _State) -> ok. handle_event(Event, Fun) when is_function(Fun, 1) -> Fun(Event), {ok, Fun}; handle_event(Event, {Fun, Acc}) when is_function(Fun, 2) -> Acc2 = Fun(Event, Acc), {ok, {Fun, Acc2}}. handle_call(_Msg, State) -> {reply, ok, State}. handle_info(_Msg, State) -> {ok, State}. code_change(_OldVsn, State, _Extra) -> {ok, State}. apache-couchdb-1.5.0/src/couch_replicator/src/couch_replicator_httpc.erl0000644000175000001440000002510412230722213023412 00000000000000% 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. -module(couch_replicator_httpc). -include("couch_db.hrl"). -include("couch_replicator_api_wrap.hrl"). -include("../ibrowse/ibrowse.hrl"). -export([setup/1]). -export([send_req/3]). -export([full_url/2]). -import(couch_util, [ get_value/2, get_value/3 ]). -define(replace(L, K, V), lists:keystore(K, 1, L, {K, V})). -define(MAX_WAIT, 5 * 60 * 1000). setup(#httpdb{httpc_pool = nil, url = Url, http_connections = MaxConns} = Db) -> {ok, Pid} = couch_replicator_httpc_pool:start_link(Url, [{max_connections, MaxConns}]), {ok, Db#httpdb{httpc_pool = Pid}}. send_req(HttpDb, Params1, Callback) -> Params2 = ?replace(Params1, qs, [{K, ?b2l(iolist_to_binary(V))} || {K, V} <- get_value(qs, Params1, [])]), Params = ?replace(Params2, ibrowse_options, lists:keysort(1, get_value(ibrowse_options, Params2, []))), {Worker, Response} = send_ibrowse_req(HttpDb, Params), process_response(Response, Worker, HttpDb, Params, Callback). send_ibrowse_req(#httpdb{headers = BaseHeaders} = HttpDb, Params) -> Method = get_value(method, Params, get), UserHeaders = lists:keysort(1, get_value(headers, Params, [])), Headers1 = lists:ukeymerge(1, UserHeaders, BaseHeaders), Headers2 = oauth_header(HttpDb, Params) ++ Headers1, Url = full_url(HttpDb, Params), Body = get_value(body, Params, []), case get_value(path, Params) of "_changes" -> {ok, Worker} = ibrowse:spawn_link_worker_process(Url); _ -> {ok, Worker} = couch_replicator_httpc_pool:get_worker(HttpDb#httpdb.httpc_pool) end, IbrowseOptions = [ {response_format, binary}, {inactivity_timeout, HttpDb#httpdb.timeout} | lists:ukeymerge(1, get_value(ibrowse_options, Params, []), HttpDb#httpdb.ibrowse_options) ], Response = ibrowse:send_req_direct( Worker, Url, Headers2, Method, Body, IbrowseOptions, infinity), {Worker, Response}. process_response({error, sel_conn_closed}, _Worker, HttpDb, Params, Callback) -> send_req(HttpDb, Params, Callback); process_response({error, {'EXIT', {normal, _}}}, _Worker, HttpDb, Params, Cb) -> % ibrowse worker terminated because remote peer closed the socket % -> not an error send_req(HttpDb, Params, Cb); process_response({ibrowse_req_id, ReqId}, Worker, HttpDb, Params, Callback) -> process_stream_response(ReqId, Worker, HttpDb, Params, Callback); process_response({ok, Code, Headers, Body}, Worker, HttpDb, Params, Callback) -> release_worker(Worker, HttpDb), case list_to_integer(Code) of Ok when (Ok >= 200 andalso Ok < 300) ; (Ok >= 400 andalso Ok < 500) -> EJson = case Body of <<>> -> null; Json -> ?JSON_DECODE(Json) end, Callback(Ok, Headers, EJson); R when R =:= 301 ; R =:= 302 ; R =:= 303 -> do_redirect(Worker, R, Headers, HttpDb, Params, Callback); Error -> maybe_retry({code, Error}, Worker, HttpDb, Params, Callback) end; process_response(Error, Worker, HttpDb, Params, Callback) -> maybe_retry(Error, Worker, HttpDb, Params, Callback). process_stream_response(ReqId, Worker, HttpDb, Params, Callback) -> receive {ibrowse_async_headers, ReqId, Code, Headers} -> case list_to_integer(Code) of Ok when (Ok >= 200 andalso Ok < 300) ; (Ok >= 400 andalso Ok < 500) -> StreamDataFun = fun() -> stream_data_self(HttpDb, Params, Worker, ReqId, Callback) end, ibrowse:stream_next(ReqId), try Ret = Callback(Ok, Headers, StreamDataFun), release_worker(Worker, HttpDb), clean_mailbox_req(ReqId), Ret catch throw:{maybe_retry_req, Err} -> clean_mailbox_req(ReqId), maybe_retry(Err, Worker, HttpDb, Params, Callback) end; R when R =:= 301 ; R =:= 302 ; R =:= 303 -> do_redirect(Worker, R, Headers, HttpDb, Params, Callback); Error -> report_error(Worker, HttpDb, Params, {code, Error}) end; {ibrowse_async_response, ReqId, {error, _} = Error} -> maybe_retry(Error, Worker, HttpDb, Params, Callback) after HttpDb#httpdb.timeout + 500 -> % Note: ibrowse should always reply with timeouts, but this doesn't % seem to be always true when there's a very high rate of requests % and many open connections. maybe_retry(timeout, Worker, HttpDb, Params, Callback) end. clean_mailbox_req(ReqId) -> receive {ibrowse_async_response, ReqId, _} -> clean_mailbox_req(ReqId); {ibrowse_async_response_end, ReqId} -> clean_mailbox_req(ReqId) after 0 -> ok end. release_worker(Worker, #httpdb{httpc_pool = Pool}) -> ok = couch_replicator_httpc_pool:release_worker(Pool, Worker). maybe_retry(Error, Worker, #httpdb{retries = 0} = HttpDb, Params, _Cb) -> report_error(Worker, HttpDb, Params, {error, Error}); maybe_retry(Error, Worker, #httpdb{retries = Retries, wait = Wait} = HttpDb, Params, Cb) -> release_worker(Worker, HttpDb), Method = string:to_upper(atom_to_list(get_value(method, Params, get))), Url = couch_util:url_strip_password(full_url(HttpDb, Params)), ?LOG_INFO("Retrying ~s request to ~s in ~p seconds due to error ~s", [Method, Url, Wait / 1000, error_cause(Error)]), ok = timer:sleep(Wait), Wait2 = erlang:min(Wait * 2, ?MAX_WAIT), send_req(HttpDb#httpdb{retries = Retries - 1, wait = Wait2}, Params, Cb). report_error(Worker, HttpDb, Params, Error) -> Method = string:to_upper(atom_to_list(get_value(method, Params, get))), Url = couch_util:url_strip_password(full_url(HttpDb, Params)), do_report_error(Url, Method, Error), release_worker(Worker, HttpDb), exit({http_request_failed, Method, Url, Error}). do_report_error(Url, Method, {code, Code}) -> ?LOG_ERROR("Replicator, request ~s to ~p failed. The received " "HTTP error code is ~p", [Method, Url, Code]); do_report_error(FullUrl, Method, Error) -> ?LOG_ERROR("Replicator, request ~s to ~p failed due to error ~s", [Method, FullUrl, error_cause(Error)]). error_cause({error, Cause}) -> lists:flatten(io_lib:format("~p", [Cause])); error_cause(Cause) -> lists:flatten(io_lib:format("~p", [Cause])). stream_data_self(#httpdb{timeout = T} = HttpDb, Params, Worker, ReqId, Cb) -> case accumulate_messages(ReqId, [], T + 500) of {Data, ibrowse_async_response} -> ibrowse:stream_next(ReqId), {Data, fun() -> stream_data_self(HttpDb, Params, Worker, ReqId, Cb) end}; {Data, ibrowse_async_response_end} -> {Data, fun() -> throw({maybe_retry_req, more_data_expected}) end} end. accumulate_messages(ReqId, Acc, Timeout) -> receive {ibrowse_async_response, ReqId, {error, Error}} -> throw({maybe_retry_req, Error}); {ibrowse_async_response, ReqId, <<>>} -> accumulate_messages(ReqId, Acc, Timeout); {ibrowse_async_response, ReqId, Data} -> accumulate_messages(ReqId, [Data | Acc], 0); {ibrowse_async_response_end, ReqId} -> {iolist_to_binary(lists:reverse(Acc)), ibrowse_async_response_end} after Timeout -> % Note: ibrowse should always reply with timeouts, but this doesn't % seem to be always true when there's a very high rate of requests % and many open connections. if Acc =:= [] -> throw({maybe_retry_req, timeout}); true -> {iolist_to_binary(lists:reverse(Acc)), ibrowse_async_response} end end. full_url(#httpdb{url = BaseUrl}, Params) -> Path = get_value(path, Params, []), QueryArgs = get_value(qs, Params, []), BaseUrl ++ Path ++ query_args_to_string(QueryArgs, []). query_args_to_string([], []) -> ""; query_args_to_string([], Acc) -> "?" ++ string:join(lists:reverse(Acc), "&"); query_args_to_string([{K, V} | Rest], Acc) -> query_args_to_string(Rest, [K ++ "=" ++ couch_httpd:quote(V) | Acc]). oauth_header(#httpdb{oauth = nil}, _ConnParams) -> []; oauth_header(#httpdb{url = BaseUrl, oauth = OAuth}, ConnParams) -> Consumer = { OAuth#oauth.consumer_key, OAuth#oauth.consumer_secret, OAuth#oauth.signature_method }, Method = case get_value(method, ConnParams, get) of get -> "GET"; post -> "POST"; put -> "PUT"; head -> "HEAD" end, QSL = get_value(qs, ConnParams, []), OAuthParams = oauth:sign(Method, BaseUrl ++ get_value(path, ConnParams, []), QSL, Consumer, OAuth#oauth.token, OAuth#oauth.token_secret) -- QSL, [{"Authorization", "OAuth " ++ oauth:header_params_encode(OAuthParams)}]. do_redirect(Worker, Code, Headers, #httpdb{url = Url} = HttpDb, Params, Cb) -> release_worker(Worker, HttpDb), RedirectUrl = redirect_url(Headers, Url), {HttpDb2, Params2} = after_redirect(RedirectUrl, Code, HttpDb, Params), send_req(HttpDb2, Params2, Cb). redirect_url(RespHeaders, OrigUrl) -> MochiHeaders = mochiweb_headers:make(RespHeaders), RedUrl = mochiweb_headers:get_value("Location", MochiHeaders), #url{ host = Host, host_type = HostType, port = Port, path = Path, % includes query string protocol = Proto } = ibrowse_lib:parse_url(RedUrl), #url{ username = User, password = Passwd } = ibrowse_lib:parse_url(OrigUrl), Creds = case is_list(User) andalso is_list(Passwd) of true -> User ++ ":" ++ Passwd ++ "@"; false -> [] end, HostPart = case HostType of ipv6_address -> "[" ++ Host ++ "]"; _ -> Host end, atom_to_list(Proto) ++ "://" ++ Creds ++ HostPart ++ ":" ++ integer_to_list(Port) ++ Path. after_redirect(RedirectUrl, 303, HttpDb, Params) -> after_redirect(RedirectUrl, HttpDb, ?replace(Params, method, get)); after_redirect(RedirectUrl, _Code, HttpDb, Params) -> after_redirect(RedirectUrl, HttpDb, Params). after_redirect(RedirectUrl, HttpDb, Params) -> Params2 = lists:keydelete(path, 1, lists:keydelete(qs, 1, Params)), {HttpDb#httpdb{url = RedirectUrl}, Params2}. apache-couchdb-1.5.0/src/couch_replicator/src/couch_replicator_httpd.erl0000644000175000001440000000422112230722213023410 00000000000000% 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. -module(couch_replicator_httpd). -include("couch_db.hrl"). -import(couch_httpd, [ send_json/2, send_json/3, send_method_not_allowed/2 ]). -import(couch_util, [ to_binary/1 ]). -export([handle_req/1]). handle_req(#httpd{method = 'POST', user_ctx = UserCtx} = Req) -> couch_httpd:validate_ctype(Req, "application/json"), RepDoc = {Props} = couch_httpd:json_body_obj(Req), validate_rep_props(Props), {ok, Rep} = couch_replicator_utils:parse_rep_doc(RepDoc, UserCtx), case couch_replicator:replicate(Rep) of {error, {Error, Reason}} -> send_json( Req, 500, {[{error, to_binary(Error)}, {reason, to_binary(Reason)}]}); {error, not_found} -> % Tried to cancel a replication that didn't exist. send_json(Req, 404, {[{error, <<"not found">>}]}); {error, Reason} -> send_json(Req, 500, {[{error, to_binary(Reason)}]}); {ok, {cancelled, RepId}} -> send_json(Req, 200, {[{ok, true}, {<<"_local_id">>, RepId}]}); {ok, {continuous, RepId}} -> send_json(Req, 202, {[{ok, true}, {<<"_local_id">>, RepId}]}); {ok, {HistoryResults}} -> send_json(Req, {[{ok, true} | HistoryResults]}) end; handle_req(Req) -> send_method_not_allowed(Req, "POST"). validate_rep_props([]) -> ok; validate_rep_props([{<<"query_params">>, {Params}}|Rest]) -> lists:foreach(fun ({_,V}) when is_binary(V) -> ok; ({K,_}) -> throw({bad_request, <>}) end, Params), validate_rep_props(Rest); validate_rep_props([_|Rest]) -> validate_rep_props(Rest). apache-couchdb-1.5.0/src/couch_replicator/src/couch_replicator_api_wrap.erl0000644000175000001440000007307712230722213024106 00000000000000% 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. -module(couch_replicator_api_wrap). % This module wraps the native erlang API, and allows for performing % operations on a remote vs. local databases via the same API. % % Notes: % Many options and apis aren't yet supported here, they are added as needed. -include("couch_db.hrl"). -include("couch_replicator_api_wrap.hrl"). -export([ db_open/2, db_open/3, db_close/1, get_db_info/1, update_doc/3, update_doc/4, update_docs/3, update_docs/4, ensure_full_commit/1, get_missing_revs/2, open_doc/3, open_doc_revs/6, changes_since/5, db_uri/1 ]). -import(couch_replicator_httpc, [ send_req/3 ]). -import(couch_util, [ encode_doc_id/1, get_value/2, get_value/3 ]). -define(MAX_WAIT, 5 * 60 * 1000). db_uri(#httpdb{url = Url}) -> couch_util:url_strip_password(Url); db_uri(#db{name = Name}) -> db_uri(Name); db_uri(DbName) -> ?b2l(DbName). db_open(Db, Options) -> db_open(Db, Options, false). db_open(#httpdb{} = Db1, _Options, Create) -> {ok, Db} = couch_replicator_httpc:setup(Db1), case Create of false -> ok; true -> send_req(Db, [{method, put}], fun(_, _, _) -> ok end) end, send_req(Db, [{method, head}], fun(200, _, _) -> {ok, Db}; (401, _, _) -> throw({unauthorized, ?l2b(db_uri(Db))}); (_, _, _) -> throw({db_not_found, ?l2b(db_uri(Db))}) end); db_open(DbName, Options, Create) -> try case Create of false -> ok; true -> ok = couch_httpd:verify_is_server_admin( get_value(user_ctx, Options)), couch_db:create(DbName, Options) end, case couch_db:open(DbName, Options) of {error, illegal_database_name, _} -> throw({db_not_found, DbName}); {not_found, _Reason} -> throw({db_not_found, DbName}); {ok, _Db} = Success -> Success end catch throw:{unauthorized, _} -> throw({unauthorized, DbName}) end. db_close(#httpdb{httpc_pool = Pool}) -> unlink(Pool), ok = couch_replicator_httpc_pool:stop(Pool); db_close(DbName) -> catch couch_db:close(DbName). get_db_info(#httpdb{} = Db) -> send_req(Db, [], fun(200, _, {Props}) -> {ok, Props} end); get_db_info(#db{name = DbName, user_ctx = UserCtx}) -> {ok, Db} = couch_db:open(DbName, [{user_ctx, UserCtx}]), {ok, Info} = couch_db:get_db_info(Db), couch_db:close(Db), {ok, [{couch_util:to_binary(K), V} || {K, V} <- Info]}. ensure_full_commit(#httpdb{} = Db) -> send_req( Db, [{method, post}, {path, "_ensure_full_commit"}, {headers, [{"Content-Type", "application/json"}]}], fun(201, _, {Props}) -> {ok, get_value(<<"instance_start_time">>, Props)}; (_, _, {Props}) -> {error, get_value(<<"error">>, Props)} end); ensure_full_commit(Db) -> couch_db:ensure_full_commit(Db). get_missing_revs(#httpdb{} = Db, IdRevs) -> JsonBody = {[{Id, couch_doc:revs_to_strs(Revs)} || {Id, Revs} <- IdRevs]}, send_req( Db, [{method, post}, {path, "_revs_diff"}, {body, ?JSON_ENCODE(JsonBody)}, {headers, [{"Content-Type", "application/json"}]}], fun(200, _, {Props}) -> ConvertToNativeFun = fun({Id, {Result}}) -> MissingRevs = couch_doc:parse_revs( get_value(<<"missing">>, Result) ), PossibleAncestors = couch_doc:parse_revs( get_value(<<"possible_ancestors">>, Result, []) ), {Id, MissingRevs, PossibleAncestors} end, {ok, lists:map(ConvertToNativeFun, Props)} end); get_missing_revs(Db, IdRevs) -> couch_db:get_missing_revs(Db, IdRevs). open_doc_revs(#httpdb{retries = 0} = HttpDb, Id, Revs, Options, _Fun, _Acc) -> Path = encode_doc_id(Id), QS = options_to_query_args(HttpDb, Path, [revs, {open_revs, Revs} | Options]), Url = couch_util:url_strip_password( couch_replicator_httpc:full_url(HttpDb, [{path,Path}, {qs,QS}]) ), ?LOG_ERROR("Replication crashing because GET ~s failed", [Url]), exit(kaboom); open_doc_revs(#httpdb{} = HttpDb, Id, Revs, Options, Fun, Acc) -> Path = encode_doc_id(Id), QS = options_to_query_args(HttpDb, Path, [revs, {open_revs, Revs} | Options]), {Pid, Ref} = spawn_monitor(fun() -> Self = self(), Callback = fun(200, Headers, StreamDataFun) -> remote_open_doc_revs_streamer_start(Self), {<<"--">>, _, _} = couch_httpd:parse_multipart_request( get_value("Content-Type", Headers), StreamDataFun, fun mp_parse_mixed/1 ) end, Streamer = spawn_link(fun() -> Params = [ {path, Path}, {qs, QS}, {ibrowse_options, [{stream_to, {self(), once}}]}, {headers, [{"Accept", "multipart/mixed"}]} ], % We're setting retries to 0 here to avoid the case where the % Streamer retries the request and ends up jumbling together two % different response bodies. Retries are handled explicitly by % open_doc_revs itself. send_req(HttpDb#httpdb{retries = 0}, Params, Callback) end), % If this process dies normally we can leave % the Streamer process hanging around keeping an % HTTP connection open. This is a bit of a % hammer approach to making sure it releases % that connection back to the pool. spawn(fun() -> Ref = erlang:monitor(process, Self), receive {'DOWN', Ref, process, Self, normal} -> exit(Streamer, {streamer_parent_died, Self}); {'DOWN', Ref, process, Self, _} -> ok end end), receive {started_open_doc_revs, Ref} -> Ret = receive_docs_loop(Streamer, Fun, Id, Revs, Ref, Acc), exit({exit_ok, Ret}) end end), receive {'DOWN', Ref, process, Pid, {exit_ok, Ret}} -> Ret; {'DOWN', Ref, process, Pid, {{nocatch, {missing_stub,_} = Stub}, _}} -> throw(Stub); {'DOWN', Ref, process, Pid, Else} -> Url = couch_util:url_strip_password( couch_replicator_httpc:full_url(HttpDb, [{path,Path}, {qs,QS}]) ), #httpdb{retries = Retries, wait = Wait0} = HttpDb, Wait = 2 * erlang:min(Wait0 * 2, ?MAX_WAIT), ?LOG_INFO("Retrying GET to ~s in ~p seconds due to error ~p", [Url, Wait / 1000, error_reason(Else)] ), ok = timer:sleep(Wait), RetryDb = HttpDb#httpdb{ retries = Retries - 1, wait = Wait }, open_doc_revs(RetryDb, Id, Revs, Options, Fun, Acc) end; open_doc_revs(Db, Id, Revs, Options, Fun, Acc) -> {ok, Results} = couch_db:open_doc_revs(Db, Id, Revs, Options), {ok, lists:foldl(fun(R, A) -> {_, A2} = Fun(R, A), A2 end, Acc, Results)}. error_reason({http_request_failed, "GET", _Url, {error, timeout}}) -> timeout; error_reason({http_request_failed, "GET", _Url, {error, {_, req_timedout}}}) -> req_timedout; error_reason({http_request_failed, "GET", _Url, Error}) -> Error; error_reason(Else) -> Else. open_doc(#httpdb{} = Db, Id, Options) -> send_req( Db, [{path, encode_doc_id(Id)}, {qs, options_to_query_args(Options, [])}], fun(200, _, Body) -> {ok, couch_doc:from_json_obj(Body)}; (_, _, {Props}) -> {error, get_value(<<"error">>, Props)} end); open_doc(Db, Id, Options) -> case couch_db:open_doc(Db, Id, Options) of {ok, _} = Ok -> Ok; {not_found, _Reason} -> {error, <<"not_found">>} end. update_doc(Db, Doc, Options) -> update_doc(Db, Doc, Options, interactive_edit). update_doc(#httpdb{} = HttpDb, #doc{id = DocId} = Doc, Options, Type) -> QArgs = case Type of replicated_changes -> [{"new_edits", "false"}]; _ -> [] end ++ options_to_query_args(Options, []), Boundary = couch_uuids:random(), JsonBytes = ?JSON_ENCODE( couch_doc:to_json_obj( Doc, [revs, attachments, follows, att_encoding_info | Options])), {ContentType, Len} = couch_doc:len_doc_to_multi_part_stream(Boundary, JsonBytes, Doc#doc.atts, true), Headers = case lists:member(delay_commit, Options) of true -> [{"X-Couch-Full-Commit", "false"}]; false -> [] end ++ [{"Content-Type", ?b2l(ContentType)}, {"Content-Length", Len}], Body = {fun stream_doc/1, {JsonBytes, Doc#doc.atts, Boundary, Len}}, send_req( % A crash here bubbles all the way back up to run_user_fun inside % open_doc_revs, which will retry the whole thing. That's the % appropriate course of action, since we've already started streaming % the response body from the GET request. HttpDb#httpdb{retries = 0}, [{method, put}, {path, encode_doc_id(DocId)}, {qs, QArgs}, {headers, Headers}, {body, Body}], fun(Code, _, {Props}) when Code =:= 200 orelse Code =:= 201 -> {ok, couch_doc:parse_rev(get_value(<<"rev">>, Props))}; (409, _, _) -> throw(conflict); (Code, _, {Props}) -> case {Code, get_value(<<"error">>, Props)} of {401, <<"unauthorized">>} -> throw({unauthorized, get_value(<<"reason">>, Props)}); {403, <<"forbidden">>} -> throw({forbidden, get_value(<<"reason">>, Props)}); {412, <<"missing_stub">>} -> throw({missing_stub, get_value(<<"reason">>, Props)}); {_, Error} -> {error, Error} end end); update_doc(Db, Doc, Options, Type) -> couch_db:update_doc(Db, Doc, Options, Type). update_docs(Db, DocList, Options) -> update_docs(Db, DocList, Options, interactive_edit). update_docs(_Db, [], _Options, _UpdateType) -> {ok, []}; update_docs(#httpdb{} = HttpDb, DocList, Options, UpdateType) -> FullCommit = atom_to_list(not lists:member(delay_commit, Options)), Prefix = case UpdateType of replicated_changes -> <<"{\"new_edits\":false,\"docs\":[">>; interactive_edit -> <<"{\"docs\":[">> end, Suffix = <<"]}">>, % Note: nginx and other servers don't like PUT/POST requests without % a Content-Length header, so we can't do a chunked transfer encoding % and JSON encode each doc only before sending it through the socket. {Docs, Len} = lists:mapfoldl( fun(#doc{} = Doc, Acc) -> Json = ?JSON_ENCODE(couch_doc:to_json_obj(Doc, [revs, attachments])), {Json, Acc + iolist_size(Json)}; (Doc, Acc) -> {Doc, Acc + iolist_size(Doc)} end, byte_size(Prefix) + byte_size(Suffix) + length(DocList) - 1, DocList), BodyFun = fun(eof) -> eof; ([]) -> {ok, Suffix, eof}; ([prefix | Rest]) -> {ok, Prefix, Rest}; ([Doc]) -> {ok, Doc, []}; ([Doc | RestDocs]) -> {ok, [Doc, ","], RestDocs} end, Headers = [ {"Content-Length", Len}, {"Content-Type", "application/json"}, {"X-Couch-Full-Commit", FullCommit} ], send_req( HttpDb, [{method, post}, {path, "_bulk_docs"}, {body, {BodyFun, [prefix | Docs]}}, {headers, Headers}], fun(201, _, Results) when is_list(Results) -> {ok, bulk_results_to_errors(DocList, Results, remote)}; (417, _, Results) when is_list(Results) -> {ok, bulk_results_to_errors(DocList, Results, remote)} end); update_docs(Db, DocList, Options, UpdateType) -> Result = couch_db:update_docs(Db, DocList, Options, UpdateType), {ok, bulk_results_to_errors(DocList, Result, UpdateType)}. changes_since(#httpdb{headers = Headers1} = HttpDb, Style, StartSeq, UserFun, Options) -> HeartBeat = erlang:max(1000, HttpDb#httpdb.timeout div 3), BaseQArgs = case get_value(continuous, Options, false) of false -> [{"feed", "normal"}]; true -> [{"feed", "continuous"}] end ++ [ {"style", atom_to_list(Style)}, {"since", ?JSON_ENCODE(StartSeq)}, {"heartbeat", integer_to_list(HeartBeat)} ], DocIds = get_value(doc_ids, Options), {QArgs, Method, Body, Headers} = case DocIds of undefined -> QArgs1 = maybe_add_changes_filter_q_args(BaseQArgs, Options), {QArgs1, get, [], Headers1}; _ when is_list(DocIds) -> Headers2 = [{"Content-Type", "application/json"} | Headers1], JsonDocIds = ?JSON_ENCODE({[{<<"doc_ids">>, DocIds}]}), {[{"filter", "_doc_ids"} | BaseQArgs], post, JsonDocIds, Headers2} end, send_req( HttpDb, [{method, Method}, {path, "_changes"}, {qs, QArgs}, {headers, Headers}, {body, Body}, {ibrowse_options, [{stream_to, {self(), once}}]}], fun(200, _, DataStreamFun) -> parse_changes_feed(Options, UserFun, DataStreamFun); (405, _, _) when is_list(DocIds) -> % CouchDB versions < 1.1.0 don't have the builtin _changes feed % filter "_doc_ids" neither support POST send_req(HttpDb, [{method, get}, {path, "_changes"}, {qs, BaseQArgs}, {headers, Headers1}, {ibrowse_options, [{stream_to, {self(), once}}]}], fun(200, _, DataStreamFun2) -> UserFun2 = fun(#doc_info{id = Id} = DocInfo) -> case lists:member(Id, DocIds) of true -> UserFun(DocInfo); false -> ok end end, parse_changes_feed(Options, UserFun2, DataStreamFun2) end) end); changes_since(Db, Style, StartSeq, UserFun, Options) -> Filter = case get_value(doc_ids, Options) of undefined -> ?b2l(get_value(filter, Options, <<>>)); _DocIds -> "_doc_ids" end, Args = #changes_args{ style = Style, since = StartSeq, filter = Filter, feed = case get_value(continuous, Options, false) of true -> "continuous"; false -> "normal" end, timeout = infinity }, QueryParams = get_value(query_params, Options, {[]}), Req = changes_json_req(Db, Filter, QueryParams, Options), ChangesFeedFun = couch_changes:handle_changes(Args, {json_req, Req}, Db), ChangesFeedFun(fun({change, Change, _}, _) -> UserFun(json_to_doc_info(Change)); (_, _) -> ok end). % internal functions maybe_add_changes_filter_q_args(BaseQS, Options) -> case get_value(filter, Options) of undefined -> BaseQS; FilterName -> {Params} = get_value(query_params, Options, {[]}), [{"filter", ?b2l(FilterName)} | lists:foldl( fun({K, V}, QSAcc) -> Ks = couch_util:to_list(K), case lists:keymember(Ks, 1, QSAcc) of true -> QSAcc; false -> [{Ks, couch_util:to_list(V)} | QSAcc] end end, BaseQS, Params)] end. parse_changes_feed(Options, UserFun, DataStreamFun) -> case get_value(continuous, Options, false) of true -> continuous_changes(DataStreamFun, UserFun); false -> EventFun = fun(Ev) -> changes_ev1(Ev, fun(DocInfo, _) -> UserFun(DocInfo) end, []) end, json_stream_parse:events(DataStreamFun, EventFun) end. changes_json_req(_Db, "", _QueryParams, _Options) -> {[]}; changes_json_req(_Db, "_doc_ids", _QueryParams, Options) -> {[{<<"doc_ids">>, get_value(doc_ids, Options)}]}; changes_json_req(Db, FilterName, {QueryParams}, _Options) -> {ok, Info} = couch_db:get_db_info(Db), % simulate a request to db_name/_changes {[ {<<"info">>, {Info}}, {<<"id">>, null}, {<<"method">>, 'GET'}, {<<"path">>, [couch_db:name(Db), <<"_changes">>]}, {<<"query">>, {[{<<"filter">>, FilterName} | QueryParams]}}, {<<"headers">>, []}, {<<"body">>, []}, {<<"peer">>, <<"replicator">>}, {<<"form">>, []}, {<<"cookie">>, []}, {<<"userCtx">>, couch_util:json_user_ctx(Db)} ]}. options_to_query_args(HttpDb, Path, Options) -> case lists:keytake(atts_since, 1, Options) of false -> options_to_query_args(Options, []); {value, {atts_since, []}, Options2} -> options_to_query_args(Options2, []); {value, {atts_since, PAs}, Options2} -> QueryArgs1 = options_to_query_args(Options2, []), FullUrl = couch_replicator_httpc:full_url( HttpDb, [{path, Path}, {qs, QueryArgs1}]), RevList = atts_since_arg( length("GET " ++ FullUrl ++ " HTTP/1.1\r\n") + length("&atts_since=") + 6, % +6 = % encoded [ and ] PAs, []), [{"atts_since", ?JSON_ENCODE(RevList)} | QueryArgs1] end. options_to_query_args([], Acc) -> lists:reverse(Acc); options_to_query_args([ejson_body | Rest], Acc) -> options_to_query_args(Rest, Acc); options_to_query_args([delay_commit | Rest], Acc) -> options_to_query_args(Rest, Acc); options_to_query_args([revs | Rest], Acc) -> options_to_query_args(Rest, [{"revs", "true"} | Acc]); options_to_query_args([{open_revs, all} | Rest], Acc) -> options_to_query_args(Rest, [{"open_revs", "all"} | Acc]); options_to_query_args([latest | Rest], Acc) -> options_to_query_args(Rest, [{"latest", "true"} | Acc]); options_to_query_args([{open_revs, Revs} | Rest], Acc) -> JsonRevs = ?b2l(?JSON_ENCODE(couch_doc:revs_to_strs(Revs))), options_to_query_args(Rest, [{"open_revs", JsonRevs} | Acc]). -define(MAX_URL_LEN, 7000). atts_since_arg(_UrlLen, [], Acc) -> lists:reverse(Acc); atts_since_arg(UrlLen, [PA | Rest], Acc) -> RevStr = couch_doc:rev_to_str(PA), NewUrlLen = case Rest of [] -> % plus 2 double quotes (% encoded) UrlLen + size(RevStr) + 6; _ -> % plus 2 double quotes and a comma (% encoded) UrlLen + size(RevStr) + 9 end, case NewUrlLen >= ?MAX_URL_LEN of true -> lists:reverse(Acc); false -> atts_since_arg(NewUrlLen, Rest, [RevStr | Acc]) end. % TODO: A less verbose, more elegant and automatic restart strategy for % the exported open_doc_revs/6 function. The restart should be % transparent to the caller like any other Couch API function exported % by this module. receive_docs_loop(Streamer, Fun, Id, Revs, Ref, Acc) -> try % Left only for debugging purposes via an interactive or remote shell erlang:put(open_doc_revs, {Id, Revs, Ref, Streamer}), receive_docs(Streamer, Fun, Ref, Acc) catch error:{restart_open_doc_revs, NewRef} -> receive_docs_loop(Streamer, Fun, Id, Revs, NewRef, Acc) end. receive_docs(Streamer, UserFun, Ref, UserAcc) -> Streamer ! {get_headers, Ref, self()}, receive {started_open_doc_revs, NewRef} -> restart_remote_open_doc_revs(Ref, NewRef); {headers, Ref, Headers} -> case get_value("content-type", Headers) of {"multipart/related", _} = ContentType -> case doc_from_multi_part_stream( ContentType, fun() -> receive_doc_data(Streamer, Ref) end, Ref) of {ok, Doc, Parser} -> case run_user_fun(UserFun, {ok, Doc}, UserAcc, Ref) of {ok, UserAcc2} -> ok; {skip, UserAcc2} -> couch_doc:abort_multi_part_stream(Parser) end, receive_docs(Streamer, UserFun, Ref, UserAcc2) end; {"application/json", []} -> Doc = couch_doc:from_json_obj( ?JSON_DECODE(receive_all(Streamer, Ref, []))), {_, UserAcc2} = run_user_fun(UserFun, {ok, Doc}, UserAcc, Ref), receive_docs(Streamer, UserFun, Ref, UserAcc2); {"application/json", [{"error","true"}]} -> {ErrorProps} = ?JSON_DECODE(receive_all(Streamer, Ref, [])), Rev = get_value(<<"missing">>, ErrorProps), Result = {{not_found, missing}, couch_doc:parse_rev(Rev)}, {_, UserAcc2} = run_user_fun(UserFun, Result, UserAcc, Ref), receive_docs(Streamer, UserFun, Ref, UserAcc2) end; {done, Ref} -> {ok, UserAcc} end. run_user_fun(UserFun, Arg, UserAcc, OldRef) -> {Pid, Ref} = spawn_monitor(fun() -> try UserFun(Arg, UserAcc) of Resp -> exit({exit_ok, Resp}) catch throw:Reason -> exit({exit_throw, Reason}); error:Reason -> exit({exit_error, Reason}); exit:Reason -> exit({exit_exit, Reason}) end end), receive {started_open_doc_revs, NewRef} -> erlang:demonitor(Ref, [flush]), exit(Pid, kill), restart_remote_open_doc_revs(OldRef, NewRef); {'DOWN', Ref, process, Pid, {exit_ok, Ret}} -> Ret; {'DOWN', Ref, process, Pid, {exit_throw, Reason}} -> throw(Reason); {'DOWN', Ref, process, Pid, {exit_error, Reason}} -> erlang:error(Reason); {'DOWN', Ref, process, Pid, {exit_exit, Reason}} -> erlang:exit(Reason) end. restart_remote_open_doc_revs(Ref, NewRef) -> receive {body_bytes, Ref, _} -> restart_remote_open_doc_revs(Ref, NewRef); {body_done, Ref} -> restart_remote_open_doc_revs(Ref, NewRef); {done, Ref} -> restart_remote_open_doc_revs(Ref, NewRef); {headers, Ref, _} -> restart_remote_open_doc_revs(Ref, NewRef) after 0 -> erlang:error({restart_open_doc_revs, NewRef}) end. remote_open_doc_revs_streamer_start(Parent) -> receive {get_headers, _Ref, Parent} -> remote_open_doc_revs_streamer_start(Parent); {next_bytes, _Ref, Parent} -> remote_open_doc_revs_streamer_start(Parent) after 0 -> Parent ! {started_open_doc_revs, make_ref()} end. receive_all(Streamer, Ref, Acc) -> Streamer ! {next_bytes, Ref, self()}, receive {started_open_doc_revs, NewRef} -> restart_remote_open_doc_revs(Ref, NewRef); {body_bytes, Ref, Bytes} -> receive_all(Streamer, Ref, [Bytes | Acc]); {body_done, Ref} -> lists:reverse(Acc) end. mp_parse_mixed(eof) -> receive {get_headers, Ref, From} -> From ! {done, Ref} end; mp_parse_mixed({headers, H}) -> receive {get_headers, Ref, From} -> From ! {headers, Ref, H} end, fun mp_parse_mixed/1; mp_parse_mixed({body, Bytes}) -> receive {next_bytes, Ref, From} -> From ! {body_bytes, Ref, Bytes} end, fun mp_parse_mixed/1; mp_parse_mixed(body_end) -> receive {next_bytes, Ref, From} -> From ! {body_done, Ref}; {get_headers, Ref, From} -> self() ! {get_headers, Ref, From} end, fun mp_parse_mixed/1. receive_doc_data(Streamer, Ref) -> Streamer ! {next_bytes, Ref, self()}, receive {body_bytes, Ref, Bytes} -> {Bytes, fun() -> receive_doc_data(Streamer, Ref) end}; {body_done, Ref} -> {<<>>, fun() -> receive_doc_data(Streamer, Ref) end} end. doc_from_multi_part_stream(ContentType, DataFun, Ref) -> Self = self(), Parser = spawn_link(fun() -> {<<"--">>, _, _} = couch_httpd:parse_multipart_request( ContentType, DataFun, fun(Next) -> couch_doc:mp_parse_doc(Next, []) end), unlink(Self) end), Parser ! {get_doc_bytes, Ref, self()}, receive {started_open_doc_revs, NewRef} -> unlink(Parser), exit(Parser, kill), restart_remote_open_doc_revs(Ref, NewRef); {doc_bytes, Ref, DocBytes} -> Doc = couch_doc:from_json_obj(?JSON_DECODE(DocBytes)), ReadAttachmentDataFun = fun() -> link(Parser), Parser ! {get_bytes, Ref, self()}, receive {started_open_doc_revs, NewRef} -> unlink(Parser), exit(Parser, kill), receive {bytes, Ref, _} -> ok after 0 -> ok end, restart_remote_open_doc_revs(Ref, NewRef); {bytes, Ref, Bytes} -> Bytes end end, Atts2 = lists:map( fun(#att{data = follows} = A) -> A#att{data = ReadAttachmentDataFun}; (A) -> A end, Doc#doc.atts), {ok, Doc#doc{atts = Atts2}, Parser} end. changes_ev1(object_start, UserFun, UserAcc) -> fun(Ev) -> changes_ev2(Ev, UserFun, UserAcc) end. changes_ev2({key, <<"results">>}, UserFun, UserAcc) -> fun(Ev) -> changes_ev3(Ev, UserFun, UserAcc) end; changes_ev2(_, UserFun, UserAcc) -> fun(Ev) -> changes_ev2(Ev, UserFun, UserAcc) end. changes_ev3(array_start, UserFun, UserAcc) -> fun(Ev) -> changes_ev_loop(Ev, UserFun, UserAcc) end. changes_ev_loop(object_start, UserFun, UserAcc) -> fun(Ev) -> json_stream_parse:collect_object(Ev, fun(Obj) -> UserAcc2 = UserFun(json_to_doc_info(Obj), UserAcc), fun(Ev2) -> changes_ev_loop(Ev2, UserFun, UserAcc2) end end) end; changes_ev_loop(array_end, _UserFun, _UserAcc) -> fun(_Ev) -> changes_ev_done() end. changes_ev_done() -> fun(_Ev) -> changes_ev_done() end. continuous_changes(DataFun, UserFun) -> {DataFun2, _, Rest} = json_stream_parse:events( DataFun, fun(Ev) -> parse_changes_line(Ev, UserFun) end), continuous_changes(fun() -> {Rest, DataFun2} end, UserFun). parse_changes_line(object_start, UserFun) -> fun(Ev) -> json_stream_parse:collect_object(Ev, fun(Obj) -> UserFun(json_to_doc_info(Obj)) end) end. json_to_doc_info({Props}) -> RevsInfo = lists:map( fun({Change}) -> Rev = couch_doc:parse_rev(get_value(<<"rev">>, Change)), Del = (true =:= get_value(<<"deleted">>, Change)), #rev_info{rev=Rev, deleted=Del} end, get_value(<<"changes">>, Props)), #doc_info{ id = get_value(<<"id">>, Props), high_seq = get_value(<<"seq">>, Props), revs = RevsInfo }. bulk_results_to_errors(Docs, {ok, Results}, interactive_edit) -> lists:reverse(lists:foldl( fun({_, {ok, _}}, Acc) -> Acc; ({#doc{id = Id, revs = {Pos, [RevId | _]}}, Error}, Acc) -> {_, Error, Reason} = couch_httpd:error_info(Error), [ {[{id, Id}, {rev, rev_to_str({Pos, RevId})}, {error, Error}, {reason, Reason}]} | Acc ] end, [], lists:zip(Docs, Results))); bulk_results_to_errors(Docs, {ok, Results}, replicated_changes) -> bulk_results_to_errors(Docs, {aborted, Results}, interactive_edit); bulk_results_to_errors(_Docs, {aborted, Results}, interactive_edit) -> lists:map( fun({{Id, Rev}, Err}) -> {_, Error, Reason} = couch_httpd:error_info(Err), {[{id, Id}, {rev, rev_to_str(Rev)}, {error, Error}, {reason, Reason}]} end, Results); bulk_results_to_errors(_Docs, Results, remote) -> lists:reverse(lists:foldl( fun({Props}, Acc) -> case get_value(<<"error">>, Props, get_value(error, Props)) of undefined -> Acc; Error -> Id = get_value(<<"id">>, Props, get_value(id, Props)), Rev = get_value(<<"rev">>, Props, get_value(rev, Props)), Reason = get_value(<<"reason">>, Props, get_value(reason, Props)), [ {[{id, Id}, {rev, rev_to_str(Rev)}, {error, Error}, {reason, Reason}]} | Acc ] end end, [], Results)). rev_to_str({_Pos, _Id} = Rev) -> couch_doc:rev_to_str(Rev); rev_to_str(Rev) -> Rev. write_fun() -> fun(Data) -> receive {get_data, Ref, From} -> From ! {data, Ref, Data} end end. stream_doc({JsonBytes, Atts, Boundary, Len}) -> case erlang:erase({doc_streamer, Boundary}) of Pid when is_pid(Pid) -> unlink(Pid), exit(Pid, kill); _ -> ok end, DocStreamer = spawn_link( couch_doc, doc_to_multi_part_stream, [Boundary, JsonBytes, Atts, write_fun(), true] ), erlang:put({doc_streamer, Boundary}, DocStreamer), {ok, <<>>, {Len, Boundary}}; stream_doc({0, Id}) -> erlang:erase({doc_streamer, Id}), eof; stream_doc({LenLeft, Id}) when LenLeft > 0 -> Ref = make_ref(), erlang:get({doc_streamer, Id}) ! {get_data, Ref, self()}, receive {data, Ref, Data} -> {ok, Data, {LenLeft - iolist_size(Data), Id}} end. apache-couchdb-1.5.0/src/couch_replicator/src/couch_replicator_api_wrap.hrl0000644000175000001440000000174512230722213024102 00000000000000% 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. -record(httpdb, { url, oauth = nil, headers = [ {"Accept", "application/json"}, {"User-Agent", "CouchDB/" ++ couch_server:get_version()} ], timeout, % milliseconds ibrowse_options = [], retries = 10, wait = 250, % milliseconds httpc_pool = nil, http_connections }). -record(oauth, { consumer_key, token, token_secret, consumer_secret, signature_method }). apache-couchdb-1.5.0/src/couch_replicator/src/couch_replicator.app.src0000644000175000001440000000211312230722213022767 00000000000000% 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. {application, couch_replicator, [ {description, "CouchDB replicator"}, {vsn, "%version%"}, {modules, [ couch_replicator_api_wrap, couch_replicator_httpc, couch_replicator_httpd, couch_replicator_job_sup, couch_replicator_notifier, couch_replicator_manager, couch_replicator_httpc_pool, couch_replicator_utils, couch_replicator_worker, couch_replicator ]}, {registered, [ couch_replicator_job_sup ]}, {applications, [kernel, stdlib]} ]}. apache-couchdb-1.5.0/src/couch_replicator/test/0000755000175000001440000000000012230722303016425 500000000000000apache-couchdb-1.5.0/src/couch_replicator/test/02-httpc-pool.t0000755000175000001440000002145312230722213021052 00000000000000#!/usr/bin/env escript %% -*- erlang -*- % 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(_) -> test_util:init_code_path(), etap:plan(55), case (catch test()) of ok -> etap:end_tests(); Other -> etap:diag(io_lib:format("Test died abnormally: ~p", [Other])), etap:bail(Other) end, ok. test() -> couch_server_sup:start_link(test_util:config_files()), ibrowse:start(), test_pool_full(), test_worker_dead_pool_non_full(), test_worker_dead_pool_full(), couch_server_sup:stop(), ok. test_pool_full() -> Pool = spawn_pool(), Client1 = spawn_client(Pool), Client2 = spawn_client(Pool), Client3 = spawn_client(Pool), etap:diag("Check that we can spawn the max number of connections."), etap:is(ping_client(Client1), ok, "Client 1 started ok."), etap:is(ping_client(Client2), ok, "Client 2 started ok."), etap:is(ping_client(Client3), ok, "Client 3 started ok."), Worker1 = get_client_worker(Client1, "1"), Worker2 = get_client_worker(Client2, "2"), Worker3 = get_client_worker(Client3, "3"), etap:is(is_process_alive(Worker1), true, "Client's 1 worker is alive."), etap:is(is_process_alive(Worker2), true, "Client's 2 worker is alive."), etap:is(is_process_alive(Worker3), true, "Client's 3 worker is alive."), etap:isnt(Worker1, Worker2, "Clients 1 and 2 got different workers."), etap:isnt(Worker2, Worker3, "Clients 2 and 3 got different workers."), etap:isnt(Worker1, Worker3, "Clients 1 and 3 got different workers."), etap:diag("Check that client 4 blocks waiting for a worker."), Client4 = spawn_client(Pool), etap:is(ping_client(Client4), timeout, "Client 4 blocked while waiting."), etap:diag("Check that stopping a client gives up its worker."), etap:is(stop_client(Client1), ok, "First client stopped."), etap:diag("And check that our blocked client has been unblocked."), etap:is(ping_client(Client4), ok, "Client 4 was unblocked."), Worker4 = get_client_worker(Client4, "4"), etap:is(is_process_alive(Worker4), true, "Client's 4 worker is alive."), etap:is(Worker4, Worker1, "Client 4 got worker that client 1 got before."), lists:foreach(fun(C) -> ok = stop_client(C) end, [Client2, Client3, Client4]), stop_pool(Pool). test_worker_dead_pool_non_full() -> Pool = spawn_pool(), Client1 = spawn_client(Pool), etap:is(ping_client(Client1), ok, "Client 1 started ok."), Worker1 = get_client_worker(Client1, "1"), etap:is(is_process_alive(Worker1), true, "Client's 1 worker is alive."), etap:diag("Kill client's 1 worker."), etap:is(kill_client_worker(Client1), ok, "Killed client's 1 worker."), etap:is(is_process_alive(Worker1), false, "Client's 1 worker process is dead."), etap:is(stop_client(Client1), ok, "First client stopped and released its worker."), Client2 = spawn_client(Pool), etap:is(ping_client(Client2), ok, "Client 2 started ok."), Worker2 = get_client_worker(Client2, "2"), etap:isnt(Worker2, Worker1, "Client 2 got a different worker from client 1"), etap:is(is_process_alive(Worker2), true, "Client's 2 worker is alive."), etap:is(stop_client(Client2), ok, "Second client stopped."), stop_pool(Pool). test_worker_dead_pool_full() -> Pool = spawn_pool(), Client1 = spawn_client(Pool), Client2 = spawn_client(Pool), Client3 = spawn_client(Pool), etap:diag("Check that we can spawn the max number of connections."), etap:is(ping_client(Client1), ok, "Client 1 started ok."), etap:is(ping_client(Client2), ok, "Client 2 started ok."), etap:is(ping_client(Client3), ok, "Client 3 started ok."), Worker1 = get_client_worker(Client1, "1"), Worker2 = get_client_worker(Client2, "2"), Worker3 = get_client_worker(Client3, "3"), etap:is(is_process_alive(Worker1), true, "Client's 1 worker is alive."), etap:is(is_process_alive(Worker2), true, "Client's 2 worker is alive."), etap:is(is_process_alive(Worker3), true, "Client's 3 worker is alive."), etap:isnt(Worker1, Worker2, "Clients 1 and 2 got different workers."), etap:isnt(Worker2, Worker3, "Clients 2 and 3 got different workers."), etap:isnt(Worker1, Worker3, "Clients 1 and 3 got different workers."), etap:diag("Check that client 4 blocks waiting for a worker."), Client4 = spawn_client(Pool), etap:is(ping_client(Client4), timeout, "Client 4 blocked while waiting."), etap:diag("Kill client's 1 worker."), etap:is(kill_client_worker(Client1), ok, "Killed client's 1 worker."), etap:is(is_process_alive(Worker1), false, "Client's 1 worker process is dead."), etap:diag("Check client 4 got unblocked after first worker's death"), etap:is(ping_client(Client4), ok, "Client 4 not blocked anymore."), Worker4 = get_client_worker(Client4, "4"), etap:is(is_process_alive(Worker4), true, "Client's 4 worker is alive."), etap:isnt(Worker4, Worker1, "Client 4 got a worker different from client 1."), etap:isnt(Worker4, Worker2, "Client 4 got a worker different from client 2."), etap:isnt(Worker4, Worker3, "Client 4 got a worker different from client 3."), etap:diag("Check that stopping client 1 is a noop."), etap:is(stop_client(Client1), ok, "First client stopped."), etap:is(is_process_alive(Worker2), true, "Client's 2 worker still alive."), etap:is(is_process_alive(Worker3), true, "Client's 3 worker still alive."), etap:is(is_process_alive(Worker4), true, "Client's 4 worker still alive."), etap:diag("Check that client 5 blocks waiting for a worker."), Client5 = spawn_client(Pool), etap:is(ping_client(Client5), timeout, "Client 5 blocked while waiting."), etap:diag("Check that stopping client 2 gives up its worker."), etap:is(stop_client(Client2), ok, "Second client stopped."), etap:diag("Now check that client 5 has been unblocked."), etap:is(ping_client(Client5), ok, "Client 5 was unblocked."), Worker5 = get_client_worker(Client5, "5"), etap:is(is_process_alive(Worker5), true, "Client's 5 worker is alive."), etap:isnt(Worker5, Worker1, "Client 5 got a worker different from client 1."), etap:is(Worker5, Worker2, "Client 5 got same worker as client 2."), etap:isnt(Worker5, Worker3, "Client 5 got a worker different from client 3."), etap:isnt(Worker5, Worker4, "Client 5 got a worker different from client 4."), etap:is(is_process_alive(Worker3), true, "Client's 3 worker still alive."), etap:is(is_process_alive(Worker4), true, "Client's 4 worker still alive."), etap:is(is_process_alive(Worker5), true, "Client's 5 worker still alive."), lists:foreach(fun(C) -> ok = stop_client(C) end, [Client3, Client4, Client5]), stop_pool(Pool). spawn_client(Pool) -> Parent = self(), Ref = make_ref(), Pid = spawn(fun() -> {ok, Worker} = couch_replicator_httpc_pool:get_worker(Pool), loop(Parent, Ref, Worker, Pool) end), {Pid, Ref}. ping_client({Pid, Ref}) -> Pid ! ping, receive {pong, Ref} -> ok after 3000 -> timeout end. get_client_worker({Pid, Ref}, ClientName) -> Pid ! get_worker, receive {worker, Ref, Worker} -> Worker after 3000 -> etap:bail("Timeout getting client " ++ ClientName ++ " worker.") end. stop_client({Pid, Ref}) -> Pid ! stop, receive {stop, Ref} -> ok after 3000 -> timeout end. kill_client_worker({Pid, Ref}) -> Pid ! get_worker, receive {worker, Ref, Worker} -> exit(Worker, kill), ok after 3000 -> timeout end. loop(Parent, Ref, Worker, Pool) -> receive ping -> Parent ! {pong, Ref}, loop(Parent, Ref, Worker, Pool); get_worker -> Parent ! {worker, Ref, Worker}, loop(Parent, Ref, Worker, Pool); stop -> couch_replicator_httpc_pool:release_worker(Pool, Worker), Parent ! {stop, Ref} end. spawn_pool() -> Host = couch_config:get("httpd", "bind_address", "127.0.0.1"), Port = couch_config:get("httpd", "port", "5984"), {ok, Pool} = couch_replicator_httpc_pool:start_link( "http://" ++ Host ++ ":5984", [{max_connections, 3}]), Pool. stop_pool(Pool) -> ok = couch_replicator_httpc_pool:stop(Pool). apache-couchdb-1.5.0/src/couch_replicator/test/01-load.t0000644000175000001440000000222412230722213017667 00000000000000#!/usr/bin/env escript %% -*- erlang -*- % 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 that we can load each module. main(_) -> test_util:init_code_path(), Modules = [ couch_replicator_api_wrap, couch_replicator_httpc, couch_replicator_httpd, couch_replicator_manager, couch_replicator_notifier, couch_replicator, couch_replicator_worker, couch_replicator_utils, couch_replicator_job_sup ], etap:plan(length(Modules)), lists:foreach( fun(Module) -> etap:loaded_ok(Module, lists:concat(["Loaded: ", Module])) end, Modules), etap:end_tests(). apache-couchdb-1.5.0/src/couch_replicator/test/03-replication-compact.t0000755000175000001440000003646412230722213022727 00000000000000#!/usr/bin/env escript %% -*- erlang -*- % 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. % Verify that compacting databases that are being used as the source or % target of a replication doesn't affect the replication and that the % replication doesn't hold their reference counters forever. -define(b2l(B), binary_to_list(B)). -record(user_ctx, { name = null, roles = [], handler }). -record(db, { main_pid = nil, update_pid = nil, compactor_pid = nil, instance_start_time, % number of microsecs since jan 1 1970 as a binary string fd, updater_fd, fd_ref_counter, header = nil, committed_update_seq, fulldocinfo_by_id_btree, docinfo_by_seq_btree, local_docs_btree, update_seq, name, filepath, validate_doc_funs = [], security = [], security_ptr = nil, user_ctx = #user_ctx{}, waiting_delayed_commit = nil, revs_limit = 1000, fsync_options = [], options = [], compression, before_doc_update, after_doc_read }). -record(rep, { id, source, target, options, user_ctx, doc_id }). source_db_name() -> <<"couch_test_rep_db_a">>. target_db_name() -> <<"couch_test_rep_db_b">>. main(_) -> test_util:init_code_path(), etap:plan(376), case (catch test()) of ok -> etap:end_tests(); Other -> etap:diag(io_lib:format("Test died abnormally: ~p", [Other])), etap:bail(Other) end, ok. test() -> couch_server_sup:start_link(test_util:config_files()), ibrowse:start(), Pairs = [ {source_db_name(), target_db_name()}, {{remote, source_db_name()}, target_db_name()}, {source_db_name(), {remote, target_db_name()}}, {{remote, source_db_name()}, {remote, (target_db_name())}} ], lists:foreach( fun({Source, Target}) -> {ok, SourceDb} = create_db(source_db_name()), etap:is(couch_db:is_idle(SourceDb), true, "Source database is idle before starting replication"), {ok, TargetDb} = create_db(target_db_name()), etap:is(couch_db:is_idle(TargetDb), true, "Target database is idle before starting replication"), {ok, RepPid, RepId} = replicate(Source, Target), check_active_tasks(RepPid, RepId, Source, Target), {ok, DocsWritten} = populate_and_compact_test( RepPid, SourceDb, TargetDb), wait_target_in_sync(DocsWritten, TargetDb), check_active_tasks(RepPid, RepId, Source, Target), cancel_replication(RepId, RepPid), compare_dbs(SourceDb, TargetDb), delete_db(SourceDb), delete_db(TargetDb), couch_server_sup:stop(), ok = timer:sleep(1000), couch_server_sup:start_link(test_util:config_files()) end, Pairs), couch_server_sup:stop(), ok. populate_and_compact_test(RepPid, SourceDb0, TargetDb0) -> etap:is(is_process_alive(RepPid), true, "Replication process is alive"), check_db_alive("source", SourceDb0), check_db_alive("target", TargetDb0), Writer = spawn_writer(SourceDb0), lists:foldl( fun(_, {SourceDb, TargetDb, DocCount}) -> pause_writer(Writer), compact_db("source", SourceDb), etap:is(is_process_alive(RepPid), true, "Replication process is alive after source database compaction"), check_db_alive("source", SourceDb), check_ref_counter("source", SourceDb), compact_db("target", TargetDb), etap:is(is_process_alive(RepPid), true, "Replication process is alive after target database compaction"), check_db_alive("target", TargetDb), check_ref_counter("target", TargetDb), {ok, SourceDb2} = reopen_db(SourceDb), {ok, TargetDb2} = reopen_db(TargetDb), resume_writer(Writer), wait_writer(Writer, DocCount), compact_db("source", SourceDb2), etap:is(is_process_alive(RepPid), true, "Replication process is alive after source database compaction"), check_db_alive("source", SourceDb2), pause_writer(Writer), check_ref_counter("source", SourceDb2), resume_writer(Writer), compact_db("target", TargetDb2), etap:is(is_process_alive(RepPid), true, "Replication process is alive after target database compaction"), check_db_alive("target", TargetDb2), pause_writer(Writer), check_ref_counter("target", TargetDb2), resume_writer(Writer), {ok, SourceDb3} = reopen_db(SourceDb2), {ok, TargetDb3} = reopen_db(TargetDb2), {SourceDb3, TargetDb3, DocCount + 50} end, {SourceDb0, TargetDb0, 50}, lists:seq(1, 5)), DocsWritten = stop_writer(Writer), {ok, DocsWritten}. check_db_alive(Type, #db{main_pid = Pid}) -> etap:is(is_process_alive(Pid), true, "Local " ++ Type ++ " database main pid is alive"). compact_db(Type, #db{name = Name}) -> {ok, Db} = couch_db:open_int(Name, []), {ok, CompactPid} = couch_db:start_compact(Db), MonRef = erlang:monitor(process, CompactPid), receive {'DOWN', MonRef, process, CompactPid, normal} -> ok; {'DOWN', MonRef, process, CompactPid, Reason} -> etap:bail("Error compacting " ++ Type ++ " database " ++ ?b2l(Name) ++ ": " ++ couch_util:to_list(Reason)) after 30000 -> etap:bail("Compaction for " ++ Type ++ " database " ++ ?b2l(Name) ++ " didn't finish") end, ok = couch_db:close(Db). check_ref_counter(Type, #db{name = Name, fd_ref_counter = OldRefCounter}) -> MonRef = erlang:monitor(process, OldRefCounter), receive {'DOWN', MonRef, process, OldRefCounter, _} -> etap:diag("Old " ++ Type ++ " database ref counter terminated") after 30000 -> etap:bail("Old " ++ Type ++ " database ref counter didn't terminate") end, {ok, #db{fd_ref_counter = NewRefCounter} = Db} = couch_db:open_int(Name, []), ok = couch_db:close(Db), etap:isnt( NewRefCounter, OldRefCounter, Type ++ " database has new ref counter"). reopen_db(#db{name = Name}) -> {ok, Db} = couch_db:open_int(Name, []), ok = couch_db:close(Db), {ok, Db}. wait_target_in_sync(DocCount, #db{name = TargetName}) -> wait_target_in_sync_loop(DocCount, TargetName, 300). wait_target_in_sync_loop(_DocCount, _TargetName, 0) -> etap:bail("Could not get source and target databases in sync"); wait_target_in_sync_loop(DocCount, TargetName, RetriesLeft) -> {ok, Target} = couch_db:open_int(TargetName, []), {ok, TargetInfo} = couch_db:get_db_info(Target), ok = couch_db:close(Target), TargetDocCount = couch_util:get_value(doc_count, TargetInfo), case TargetDocCount == DocCount of true -> etap:diag("Source and target databases are in sync"); false -> ok = timer:sleep(100), wait_target_in_sync_loop(DocCount, TargetName, RetriesLeft - 1) end. compare_dbs(#db{name = SourceName}, #db{name = TargetName}) -> {ok, SourceDb} = couch_db:open_int(SourceName, []), {ok, TargetDb} = couch_db:open_int(TargetName, []), Fun = fun(FullDocInfo, _, Acc) -> {ok, Doc} = couch_db:open_doc(SourceDb, FullDocInfo), {Props} = DocJson = couch_doc:to_json_obj(Doc, [attachments]), DocId = couch_util:get_value(<<"_id">>, Props), DocTarget = case couch_db:open_doc(TargetDb, DocId) of {ok, DocT} -> DocT; Error -> etap:bail("Error opening document '" ++ ?b2l(DocId) ++ "' from target: " ++ couch_util:to_list(Error)) end, DocTargetJson = couch_doc:to_json_obj(DocTarget, [attachments]), case DocTargetJson of DocJson -> ok; _ -> etap:bail("Content from document '" ++ ?b2l(DocId) ++ "' differs in target database") end, {ok, Acc} end, {ok, _, _} = couch_db:enum_docs(SourceDb, Fun, [], []), etap:diag("Target database has the same documents as the source database"), ok = couch_db:close(SourceDb), ok = couch_db:close(TargetDb). check_active_tasks(RepPid, {BaseId, Ext} = _RepId, Src, Tgt) -> Source = case Src of {remote, NameSrc} -> <<(db_url(NameSrc))/binary, $/>>; _ -> Src end, Target = case Tgt of {remote, NameTgt} -> <<(db_url(NameTgt))/binary, $/>>; _ -> Tgt end, FullRepId = list_to_binary(BaseId ++ Ext), Pid = list_to_binary(pid_to_list(RepPid)), [RepTask] = couch_task_status:all(), etap:is(couch_util:get_value(pid, RepTask), Pid, "_active_tasks entry has correct pid property"), etap:is(couch_util:get_value(replication_id, RepTask), FullRepId, "_active_tasks entry has right replication id"), etap:is(couch_util:get_value(continuous, RepTask), true, "_active_tasks entry has continuous property set to true"), etap:is(couch_util:get_value(source, RepTask), Source, "_active_tasks entry has correct source property"), etap:is(couch_util:get_value(target, RepTask), Target, "_active_tasks entry has correct target property"), etap:is(is_integer(couch_util:get_value(docs_read, RepTask)), true, "_active_tasks entry has integer docs_read property"), etap:is(is_integer(couch_util:get_value(docs_written, RepTask)), true, "_active_tasks entry has integer docs_written property"), etap:is(is_integer(couch_util:get_value(doc_write_failures, RepTask)), true, "_active_tasks entry has integer doc_write_failures property"), etap:is(is_integer(couch_util:get_value(revisions_checked, RepTask)), true, "_active_tasks entry has integer revisions_checked property"), etap:is(is_integer(couch_util:get_value(missing_revisions_found, RepTask)), true, "_active_tasks entry has integer missing_revisions_found property"), etap:is(is_integer(couch_util:get_value(checkpointed_source_seq, RepTask)), true, "_active_tasks entry has integer checkpointed_source_seq property"), etap:is(is_integer(couch_util:get_value(source_seq, RepTask)), true, "_active_tasks entry has integer source_seq property"), Progress = couch_util:get_value(progress, RepTask), etap:is(is_integer(Progress), true, "_active_tasks entry has an integer progress property"), etap:is(Progress =< 100, true, "Progress is not greater than 100%"). wait_writer(Pid, NumDocs) -> case get_writer_num_docs_written(Pid) of N when N >= NumDocs -> ok; _ -> wait_writer(Pid, NumDocs) end. spawn_writer(Db) -> Parent = self(), Pid = spawn(fun() -> writer_loop(Db, Parent, 0) end), etap:diag("Started source database writer"), Pid. pause_writer(Pid) -> Ref = make_ref(), Pid ! {pause, Ref}, receive {paused, Ref} -> ok after 30000 -> etap:bail("Failed to pause source database writer") end. resume_writer(Pid) -> Ref = make_ref(), Pid ! {continue, Ref}, receive {ok, Ref} -> ok after 30000 -> etap:bail("Failed to unpause source database writer") end. get_writer_num_docs_written(Pid) -> Ref = make_ref(), Pid ! {get_count, Ref}, receive {count, Ref, Count} -> Count after 30000 -> etap:bail("Timeout getting number of documents written from " "source database writer") end. stop_writer(Pid) -> Ref = make_ref(), Pid ! {stop, Ref}, receive {stopped, Ref, DocsWritten} -> MonRef = erlang:monitor(process, Pid), receive {'DOWN', MonRef, process, Pid, _Reason} -> etap:diag("Stopped source database writer"), DocsWritten after 30000 -> etap:bail("Timeout stopping source database writer") end after 30000 -> etap:bail("Timeout stopping source database writer") end. writer_loop(#db{name = DbName}, Parent, Counter) -> maybe_pause(Parent, Counter), Doc = couch_doc:from_json_obj({[ {<<"_id">>, list_to_binary(integer_to_list(Counter + 1))}, {<<"value">>, Counter + 1}, {<<"_attachments">>, {[ {<<"icon1.png">>, {[ {<<"data">>, base64:encode(att_data())}, {<<"content_type">>, <<"image/png">>} ]}}, {<<"icon2.png">>, {[ {<<"data">>, base64:encode(iolist_to_binary( [att_data(), att_data()]))}, {<<"content_type">>, <<"image/png">>} ]}} ]}} ]}), maybe_pause(Parent, Counter), {ok, Db} = couch_db:open_int(DbName, []), {ok, _} = couch_db:update_doc(Db, Doc, []), ok = couch_db:close(Db), receive {get_count, Ref} -> Parent ! {count, Ref, Counter + 1}, writer_loop(Db, Parent, Counter + 1); {stop, Ref} -> Parent ! {stopped, Ref, Counter + 1} after 0 -> ok = timer:sleep(500), writer_loop(Db, Parent, Counter + 1) end. maybe_pause(Parent, Counter) -> receive {get_count, Ref} -> Parent ! {count, Ref, Counter}; {pause, Ref} -> Parent ! {paused, Ref}, receive {continue, Ref2} -> Parent ! {ok, Ref2} end after 0 -> ok end. db_url(DbName) -> iolist_to_binary([ "http://", couch_config:get("httpd", "bind_address", "127.0.0.1"), ":", integer_to_list(mochiweb_socket_server:get(couch_httpd, port)), "/", DbName ]). create_db(DbName) -> {ok, Db} = couch_db:create( DbName, [{user_ctx, #user_ctx{roles = [<<"_admin">>]}}, overwrite]), couch_db:close(Db), {ok, Db}. delete_db(#db{name = DbName, main_pid = Pid}) -> ok = couch_server:delete( DbName, [{user_ctx, #user_ctx{roles = [<<"_admin">>]}}]), MonRef = erlang:monitor(process, Pid), receive {'DOWN', MonRef, process, Pid, _Reason} -> ok after 30000 -> etap:bail("Timeout deleting database") end. replicate({remote, Db}, Target) -> replicate(db_url(Db), Target); replicate(Source, {remote, Db}) -> replicate(Source, db_url(Db)); replicate(Source, Target) -> RepObject = {[ {<<"source">>, Source}, {<<"target">>, Target}, {<<"continuous">>, true} ]}, {ok, Rep} = couch_replicator_utils:parse_rep_doc( RepObject, #user_ctx{roles = [<<"_admin">>]}), {ok, Pid} = couch_replicator:async_replicate(Rep), {ok, Pid, Rep#rep.id}. cancel_replication(RepId, RepPid) -> {ok, _} = couch_replicator:cancel_replication(RepId), etap:is(is_process_alive(RepPid), false, "Replication process is no longer alive after cancel"). att_data() -> {ok, Data} = file:read_file( test_util:source_file("share/www/image/logo.png")), Data. apache-couchdb-1.5.0/src/couch_replicator/test/05-replication-many-leaves.t0000755000175000001440000002255112230722213023514 00000000000000#!/usr/bin/env escript %% -*- erlang -*- % 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 replication of documents with many leaf revisions. % Motivated by COUCHDB-1340 and other similar issues where a document % GET with a too long ?open_revs revision list doesn't work due to % maximum web server limits for the HTTP request path. -record(user_ctx, { name = null, roles = [], handler }). -record(doc, { id = <<"">>, revs = {0, []}, body = {[]}, atts = [], deleted = false, meta = [] }). -record(att, { name, type, att_len, disk_len, md5= <<>>, revpos=0, data, encoding=identity }). -define(b2l(B), binary_to_list(B)). -define(l2b(L), list_to_binary(L)). -define(i2l(I), integer_to_list(I)). source_db_name() -> <<"couch_test_rep_db_a">>. target_db_name() -> <<"couch_test_rep_db_b">>. doc_ids() -> [<<"doc1">>, <<"doc2">>, <<"doc3">>]. doc_num_conflicts(<<"doc1">>) -> 10; doc_num_conflicts(<<"doc2">>) -> 100; % a number > MaxURLlength (7000) / length(DocRevisionString) doc_num_conflicts(<<"doc3">>) -> 210. main(_) -> test_util:init_code_path(), etap:plan(56), case (catch test()) of ok -> etap:end_tests(); Other -> etap:diag(io_lib:format("Test died abnormally: ~p", [Other])), etap:bail(Other) end, ok. test() -> couch_server_sup:start_link(test_util:config_files()), ibrowse:start(), crypto:start(), couch_config:set("replicator", "connection_timeout", "90000", false), Pairs = [ {source_db_name(), target_db_name()}, {{remote, source_db_name()}, target_db_name()}, {source_db_name(), {remote, target_db_name()}}, {{remote, source_db_name()}, {remote, (target_db_name())}} ], lists:foreach( fun({Source, Target}) -> {ok, SourceDb} = create_db(source_db_name()), etap:diag("Populating source database"), {ok, DocRevs} = populate_db(SourceDb), ok = couch_db:close(SourceDb), etap:diag("Creating target database"), {ok, TargetDb} = create_db(target_db_name()), ok = couch_db:close(TargetDb), etap:diag("Triggering replication"), replicate(Source, Target), etap:diag("Replication finished, comparing source and target databases"), {ok, SourceDb2} = couch_db:open_int(source_db_name(), []), {ok, TargetDb2} = couch_db:open_int(target_db_name(), []), verify_target(SourceDb2, TargetDb2, DocRevs), ok = couch_db:close(SourceDb2), ok = couch_db:close(TargetDb2), {ok, SourceDb3} = couch_db:open_int(source_db_name(), []), {ok, DocRevs2} = add_attachments(SourceDb3, DocRevs, 2), ok = couch_db:close(SourceDb3), etap:diag("Triggering replication again"), replicate(Source, Target), etap:diag("Replication finished, comparing source and target databases"), {ok, SourceDb4} = couch_db:open_int(source_db_name(), []), {ok, TargetDb4} = couch_db:open_int(target_db_name(), []), verify_target(SourceDb4, TargetDb4, DocRevs2), ok = couch_db:close(SourceDb4), ok = couch_db:close(TargetDb4), etap:diag("Deleting source and target databases"), delete_db(TargetDb), delete_db(SourceDb), ok = timer:sleep(1000) end, Pairs), couch_server_sup:stop(), ok. populate_db(Db) -> DocRevsDict = lists:foldl( fun(DocId, Acc) -> Value = <<"0">>, Doc = #doc{ id = DocId, body = {[ {<<"value">>, Value} ]} }, {ok, Rev} = couch_db:update_doc(Db, Doc, []), {ok, DocRevs} = add_doc_siblings(Db, DocId, doc_num_conflicts(DocId)), dict:store(DocId, [Rev | DocRevs], Acc) end, dict:new(), doc_ids()), {ok, dict:to_list(DocRevsDict)}. add_doc_siblings(Db, DocId, NumLeaves) when NumLeaves > 0 -> add_doc_siblings(Db, DocId, NumLeaves, [], []). add_doc_siblings(Db, _DocId, 0, AccDocs, AccRevs) -> {ok, []} = couch_db:update_docs(Db, AccDocs, [], replicated_changes), {ok, AccRevs}; add_doc_siblings(Db, DocId, NumLeaves, AccDocs, AccRevs) -> Value = list_to_binary(integer_to_list(NumLeaves)), Rev = couch_util:md5(Value), Doc = #doc{ id = DocId, revs = {1, [Rev]}, body = {[ {<<"value">>, Value} ]} }, add_doc_siblings(Db, DocId, NumLeaves - 1, [Doc | AccDocs], [{1, Rev} | AccRevs]). verify_target(_SourceDb, _TargetDb, []) -> ok; verify_target(SourceDb, TargetDb, [{DocId, RevList} | Rest]) -> {ok, Lookups} = couch_db:open_doc_revs( TargetDb, DocId, RevList, [conflicts, deleted_conflicts]), Docs = [Doc || {ok, Doc} <- Lookups], {ok, SourceLookups} = couch_db:open_doc_revs( SourceDb, DocId, RevList, [conflicts, deleted_conflicts]), SourceDocs = [Doc || {ok, Doc} <- SourceLookups], Total = doc_num_conflicts(DocId) + 1, etap:is( length(Docs), Total, "Target has " ++ ?i2l(Total) ++ " leaf revisions of document " ++ ?b2l(DocId)), etap:diag("Verifying all revisions of document " ++ ?b2l(DocId)), lists:foreach( fun({#doc{id = Id, revs = Revs} = TgtDoc, #doc{id = Id, revs = Revs} = SrcDoc}) -> SourceJson = couch_doc:to_json_obj(SrcDoc, [attachments]), TargetJson = couch_doc:to_json_obj(TgtDoc, [attachments]), case TargetJson of SourceJson -> ok; _ -> {Pos, [Rev | _]} = Revs, etap:bail("Wrong value for revision " ++ ?b2l(couch_doc:rev_to_str({Pos, Rev})) ++ " of document " ++ ?b2l(DocId)) end end, lists:zip(Docs, SourceDocs)), verify_target(SourceDb, TargetDb, Rest). add_attachments(Source, DocIdRevs, NumAtts) -> add_attachments(Source, DocIdRevs, NumAtts, []). add_attachments(_SourceDb, [], _NumAtts, Acc) -> {ok, Acc}; add_attachments(SourceDb, [{DocId, RevList} | Rest], NumAtts, IdRevsAcc) -> {ok, SourceLookups} = couch_db:open_doc_revs( SourceDb, DocId, RevList, []), SourceDocs = [Doc || {ok, Doc} <- SourceLookups], Total = doc_num_conflicts(DocId) + 1, etap:is( length(SourceDocs), Total, "Source still has " ++ ?i2l(Total) ++ " leaf revisions of document " ++ ?b2l(DocId)), etap:diag("Adding " ++ ?i2l(NumAtts) ++ " attachments to each revision of the document " ++ ?b2l(DocId)), NewDocs = lists:foldl( fun(#doc{atts = Atts, revs = {Pos, [Rev | _]}} = Doc, Acc) -> NewAtts = lists:foldl( fun(I, AttAcc) -> AttData = crypto:rand_bytes(100), NewAtt = #att{ name = iolist_to_binary( ["att_", ?i2l(I), "_", couch_doc:rev_to_str({Pos, Rev})]), type = <<"application/foobar">>, att_len = byte_size(AttData), data = AttData }, [NewAtt | AttAcc] end, [], lists:seq(1, NumAtts)), [Doc#doc{atts = Atts ++ NewAtts} | Acc] end, [], SourceDocs), {ok, UpdateResults} = couch_db:update_docs(SourceDb, NewDocs, []), NewRevs = [R || {ok, R} <- UpdateResults], etap:is( length(NewRevs), length(NewDocs), "Document revisions updated with " ++ ?i2l(NumAtts) ++ " attachments"), add_attachments(SourceDb, Rest, NumAtts, [{DocId, NewRevs} | IdRevsAcc]). db_url(DbName) -> iolist_to_binary([ "http://", couch_config:get("httpd", "bind_address", "127.0.0.1"), ":", integer_to_list(mochiweb_socket_server:get(couch_httpd, port)), "/", DbName ]). create_db(DbName) -> couch_db:create( DbName, [{user_ctx, #user_ctx{roles = [<<"_admin">>]}}, overwrite]). delete_db(Db) -> ok = couch_server:delete( couch_db:name(Db), [{user_ctx, #user_ctx{roles = [<<"_admin">>]}}]). replicate({remote, Db}, Target) -> replicate(db_url(Db), Target); replicate(Source, {remote, Db}) -> replicate(Source, db_url(Db)); replicate(Source, Target) -> RepObject = {[ {<<"source">>, Source}, {<<"target">>, Target} ]}, {ok, Rep} = couch_replicator_utils:parse_rep_doc( RepObject, #user_ctx{roles = [<<"_admin">>]}), {ok, Pid} = couch_replicator:async_replicate(Rep), MonRef = erlang:monitor(process, Pid), receive {'DOWN', MonRef, process, Pid, Reason} -> etap:is(Reason, normal, "Replication finished successfully") after 900000 -> etap:bail("Timeout waiting for replication to finish") end. apache-couchdb-1.5.0/src/couch_replicator/test/04-replication-large-atts.t0000755000175000001440000002062412230722213023334 00000000000000#!/usr/bin/env escript %% -*- erlang -*- % 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 replication of large attachments. Verify that both source and % target have the same attachment data and metadata. -define(b2l(Bin), binary_to_list(Bin)). -record(user_ctx, { name = null, roles = [], handler }). -record(doc, { id = <<"">>, revs = {0, []}, body = {[]}, atts = [], deleted = false, meta = [] }). -record(att, { name, type, att_len, disk_len, md5= <<>>, revpos=0, data, encoding=identity }). source_db_name() -> <<"couch_test_rep_db_a">>. target_db_name() -> <<"couch_test_rep_db_b">>. main(_) -> test_util:init_code_path(), etap:plan(1192), case (catch test()) of ok -> etap:end_tests(); Other -> etap:diag(io_lib:format("Test died abnormally: ~p", [Other])), etap:bail(Other) end, ok. test() -> couch_server_sup:start_link(test_util:config_files()), ibrowse:start(), crypto:start(), couch_config:set("attachments", "compressible_types", "text/*", false), Pairs = [ {source_db_name(), target_db_name()}, {{remote, source_db_name()}, target_db_name()}, {source_db_name(), {remote, target_db_name()}}, {{remote, source_db_name()}, {remote, (target_db_name())}} ], {ok, SourceDb} = create_db(source_db_name()), etap:diag("Populating source database"), populate_db(SourceDb, 11), ok = couch_db:close(SourceDb), lists:foreach( fun({Source, Target}) -> etap:diag("Creating target database"), {ok, TargetDb} = create_db(target_db_name()), ok = couch_db:close(TargetDb), etap:diag("Triggering replication"), replicate(Source, Target), etap:diag("Replication finished, comparing source and target databases"), compare_dbs(SourceDb, TargetDb), etap:diag("Deleting target database"), delete_db(TargetDb), ok = timer:sleep(1000) end, Pairs), delete_db(SourceDb), couch_server_sup:stop(), ok. populate_db(Db, DocCount) -> Docs = lists:foldl( fun(DocIdCounter, Acc) -> Doc = #doc{ id = iolist_to_binary(["doc", integer_to_list(DocIdCounter)]), body = {[]}, atts = [ att(<<"att1">>, 2 * 1024 * 1024, <<"text/plain">>), att(<<"att2">>, round(6.6 * 1024 * 1024), <<"app/binary">>) ] }, [Doc | Acc] end, [], lists:seq(1, DocCount)), {ok, _} = couch_db:update_docs(Db, Docs, []). att(Name, Size, Type) -> #att{ name = Name, type = Type, att_len = Size, data = fun(Count) -> crypto:rand_bytes(Count) end }. compare_dbs(Source, Target) -> {ok, SourceDb} = couch_db:open_int(couch_db:name(Source), []), {ok, TargetDb} = couch_db:open_int(couch_db:name(Target), []), Fun = fun(FullDocInfo, _, Acc) -> {ok, DocSource} = couch_db:open_doc(SourceDb, FullDocInfo), Id = DocSource#doc.id, etap:diag("Verifying document " ++ ?b2l(Id)), {ok, DocTarget} = couch_db:open_doc(TargetDb, Id), etap:is(DocTarget#doc.body, DocSource#doc.body, "Same body in source and target databases"), #doc{atts = SourceAtts} = DocSource, #doc{atts = TargetAtts} = DocTarget, etap:is( lists:sort([N || #att{name = N} <- SourceAtts]), lists:sort([N || #att{name = N} <- TargetAtts]), "Document has same number (and names) of attachments in " "source and target databases"), lists:foreach( fun(#att{name = AttName} = Att) -> etap:diag("Verifying attachment " ++ ?b2l(AttName)), {ok, AttTarget} = find_att(TargetAtts, AttName), SourceMd5 = att_md5(Att), TargetMd5 = att_md5(AttTarget), case AttName of <<"att1">> -> etap:is(Att#att.encoding, gzip, "Attachment is gzip encoded in source database"), etap:is(AttTarget#att.encoding, gzip, "Attachment is gzip encoded in target database"), DecSourceMd5 = att_decoded_md5(Att), DecTargetMd5 = att_decoded_md5(AttTarget), etap:is(DecTargetMd5, DecSourceMd5, "Same identity content in source and target databases"); _ -> etap:is(Att#att.encoding, identity, "Attachment is not encoded in source database"), etap:is(AttTarget#att.encoding, identity, "Attachment is not encoded in target database") end, etap:is(TargetMd5, SourceMd5, "Same content in source and target databases"), etap:is(is_integer(Att#att.disk_len), true, "#att.disk_len is an integer in source database"), etap:is(is_integer(Att#att.att_len), true, "#att.att_len is an integer in source database"), etap:is(is_integer(AttTarget#att.disk_len), true, "#att.disk_len is an integer in target database"), etap:is(is_integer(AttTarget#att.att_len), true, "#att.att_len is an integer in target database"), etap:is(Att#att.disk_len, AttTarget#att.disk_len, "Same identity length in source and target databases"), etap:is(Att#att.att_len, AttTarget#att.att_len, "Same encoded length in source and target databases"), etap:is(Att#att.type, AttTarget#att.type, "Same type in source and target databases"), etap:is(Att#att.md5, SourceMd5, "Correct MD5 in source database"), etap:is(AttTarget#att.md5, SourceMd5, "Correct MD5 in target database") end, SourceAtts), {ok, Acc} end, {ok, _, _} = couch_db:enum_docs(SourceDb, Fun, [], []), ok = couch_db:close(SourceDb), ok = couch_db:close(TargetDb). find_att([], _Name) -> nil; find_att([#att{name = Name} = Att | _], Name) -> {ok, Att}; find_att([_ | Rest], Name) -> find_att(Rest, Name). att_md5(Att) -> Md50 = couch_doc:att_foldl( Att, fun(Chunk, Acc) -> couch_util:md5_update(Acc, Chunk) end, couch_util:md5_init()), couch_util:md5_final(Md50). att_decoded_md5(Att) -> Md50 = couch_doc:att_foldl_decode( Att, fun(Chunk, Acc) -> couch_util:md5_update(Acc, Chunk) end, couch_util:md5_init()), couch_util:md5_final(Md50). db_url(DbName) -> iolist_to_binary([ "http://", couch_config:get("httpd", "bind_address", "127.0.0.1"), ":", integer_to_list(mochiweb_socket_server:get(couch_httpd, port)), "/", DbName ]). create_db(DbName) -> couch_db:create( DbName, [{user_ctx, #user_ctx{roles = [<<"_admin">>]}}, overwrite]). delete_db(Db) -> ok = couch_server:delete( couch_db:name(Db), [{user_ctx, #user_ctx{roles = [<<"_admin">>]}}]). replicate({remote, Db}, Target) -> replicate(db_url(Db), Target); replicate(Source, {remote, Db}) -> replicate(Source, db_url(Db)); replicate(Source, Target) -> RepObject = {[ {<<"source">>, Source}, {<<"target">>, Target} ]}, {ok, Rep} = couch_replicator_utils:parse_rep_doc( RepObject, #user_ctx{roles = [<<"_admin">>]}), {ok, Pid} = couch_replicator:async_replicate(Rep), MonRef = erlang:monitor(process, Pid), receive {'DOWN', MonRef, process, Pid, Reason} -> etap:is(Reason, normal, "Replication finished successfully") after 300000 -> etap:bail("Timeout waiting for replication to finish") end. apache-couchdb-1.5.0/src/couch_replicator/test/06-doc-missing-stubs.t0000755000175000001440000002341212230722213022334 00000000000000#!/usr/bin/env escript %% -*- erlang -*- % 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 replication of documents with many leaf revisions. % Motivated by COUCHDB-1340 and other similar issues where a document % GET with a too long ?open_revs revision list doesn't work due to % maximum web server limits for the HTTP request path. -record(user_ctx, { name = null, roles = [], handler }). -record(doc, { id = <<"">>, revs = {0, []}, body = {[]}, atts = [], deleted = false, meta = [] }). -record(att, { name, type, att_len, disk_len, md5= <<>>, revpos=0, data, encoding=identity }). -define(b2l(B), binary_to_list(B)). source_db_name() -> <<"couch_test_rep_db_a">>. target_db_name() -> <<"couch_test_rep_db_b">>. target_revs_limit() -> 3. main(_) -> test_util:init_code_path(), etap:plan(128), case (catch test()) of ok -> etap:end_tests(); Other -> etap:diag(io_lib:format("Test died abnormally: ~p", [Other])), etap:bail(Other) end, ok. % Test motivated by COUCHDB-1365. test() -> couch_server_sup:start_link(test_util:config_files()), ibrowse:start(), Pairs = [ {source_db_name(), target_db_name()}, {{remote, source_db_name()}, target_db_name()}, {source_db_name(), {remote, target_db_name()}}, {{remote, source_db_name()}, {remote, (target_db_name())}} ], lists:foreach( fun({Source, Target}) -> {ok, SourceDb} = create_db(source_db_name()), etap:diag("Populating source database"), populate_db(SourceDb), ok = couch_db:close(SourceDb), etap:diag("Creating target database"), {ok, TargetDb} = create_db(target_db_name()), ok = couch_db:set_revs_limit(TargetDb, target_revs_limit()), ok = couch_db:close(TargetDb), etap:diag("Triggering replication"), replicate(Source, Target), etap:diag("Replication finished, comparing source and target databases"), compare_dbs(SourceDb, TargetDb), etap:diag("Updating source database docs"), update_db_docs(couch_db:name(SourceDb), target_revs_limit() + 2), etap:diag("Triggering replication again"), replicate(Source, Target), etap:diag("Replication finished, comparing source and target databases"), compare_dbs(SourceDb, TargetDb), etap:diag("Deleting databases"), delete_db(TargetDb), delete_db(SourceDb), ok = timer:sleep(1000) end, Pairs), couch_server_sup:stop(), ok. populate_db(Db) -> AttData = crypto:rand_bytes(6000), Doc1 = #doc{ id = <<"doc1">>, atts = [ #att{ name = <<"doc1_att1">>, type = <<"application/foobar">>, att_len = byte_size(AttData), data = AttData } ] }, {ok, _} = couch_db:update_doc(Db, Doc1, []). update_db_docs(DbName, Times) -> {ok, Db} = couch_db:open_int(DbName, []), {ok, _, _} = couch_db:enum_docs( Db, fun(FDI, _, Acc) -> db_fold_fun(FDI, Acc) end, {DbName, Times}, []), ok = couch_db:close(Db). db_fold_fun(FullDocInfo, {DbName, Times}) -> {ok, Db} = couch_db:open_int(DbName, []), {ok, Doc} = couch_db:open_doc(Db, FullDocInfo), lists:foldl( fun(_, {Pos, RevId}) -> {ok, Db2} = couch_db:reopen(Db), NewDocVersion = Doc#doc{ revs = {Pos, [RevId]}, body = {[{<<"value">>, base64:encode(crypto:rand_bytes(100))}]} }, {ok, NewRev} = couch_db:update_doc(Db2, NewDocVersion, []), NewRev end, {element(1, Doc#doc.revs), hd(element(2, Doc#doc.revs))}, lists:seq(1, Times)), ok = couch_db:close(Db), {ok, {DbName, Times}}. compare_dbs(Source, Target) -> {ok, SourceDb} = couch_db:open_int(couch_db:name(Source), []), {ok, TargetDb} = couch_db:open_int(couch_db:name(Target), []), Fun = fun(FullDocInfo, _, Acc) -> {ok, DocSource} = couch_db:open_doc( SourceDb, FullDocInfo, [conflicts, deleted_conflicts]), Id = DocSource#doc.id, etap:diag("Verifying document " ++ ?b2l(Id)), {ok, DocTarget} = couch_db:open_doc( TargetDb, Id, [conflicts, deleted_conflicts]), etap:is(DocTarget#doc.body, DocSource#doc.body, "Same body in source and target databases"), etap:is( couch_doc:to_json_obj(DocTarget, []), couch_doc:to_json_obj(DocSource, []), "Same doc body in source and target databases"), #doc{atts = SourceAtts} = DocSource, #doc{atts = TargetAtts} = DocTarget, etap:is( lists:sort([N || #att{name = N} <- SourceAtts]), lists:sort([N || #att{name = N} <- TargetAtts]), "Document has same number (and names) of attachments in " "source and target databases"), lists:foreach( fun(#att{name = AttName} = Att) -> etap:diag("Verifying attachment " ++ ?b2l(AttName)), {ok, AttTarget} = find_att(TargetAtts, AttName), SourceMd5 = att_md5(Att), TargetMd5 = att_md5(AttTarget), case AttName of <<"att1">> -> etap:is(Att#att.encoding, gzip, "Attachment is gzip encoded in source database"), etap:is(AttTarget#att.encoding, gzip, "Attachment is gzip encoded in target database"), DecSourceMd5 = att_decoded_md5(Att), DecTargetMd5 = att_decoded_md5(AttTarget), etap:is(DecTargetMd5, DecSourceMd5, "Same identity content in source and target databases"); _ -> etap:is(Att#att.encoding, identity, "Attachment is not encoded in source database"), etap:is(AttTarget#att.encoding, identity, "Attachment is not encoded in target database") end, etap:is(TargetMd5, SourceMd5, "Same content in source and target databases"), etap:is(is_integer(Att#att.disk_len), true, "#att.disk_len is an integer in source database"), etap:is(is_integer(Att#att.att_len), true, "#att.att_len is an integer in source database"), etap:is(is_integer(AttTarget#att.disk_len), true, "#att.disk_len is an integer in target database"), etap:is(is_integer(AttTarget#att.att_len), true, "#att.att_len is an integer in target database"), etap:is(Att#att.disk_len, AttTarget#att.disk_len, "Same identity length in source and target databases"), etap:is(Att#att.att_len, AttTarget#att.att_len, "Same encoded length in source and target databases"), etap:is(Att#att.type, AttTarget#att.type, "Same type in source and target databases"), etap:is(Att#att.md5, SourceMd5, "Correct MD5 in source database"), etap:is(AttTarget#att.md5, SourceMd5, "Correct MD5 in target database") end, SourceAtts), {ok, Acc} end, {ok, _, _} = couch_db:enum_docs(SourceDb, Fun, [], []), ok = couch_db:close(SourceDb), ok = couch_db:close(TargetDb). find_att([], _Name) -> nil; find_att([#att{name = Name} = Att | _], Name) -> {ok, Att}; find_att([_ | Rest], Name) -> find_att(Rest, Name). att_md5(Att) -> Md50 = couch_doc:att_foldl( Att, fun(Chunk, Acc) -> couch_util:md5_update(Acc, Chunk) end, couch_util:md5_init()), couch_util:md5_final(Md50). att_decoded_md5(Att) -> Md50 = couch_doc:att_foldl_decode( Att, fun(Chunk, Acc) -> couch_util:md5_update(Acc, Chunk) end, couch_util:md5_init()), couch_util:md5_final(Md50). db_url(DbName) -> iolist_to_binary([ "http://", couch_config:get("httpd", "bind_address", "127.0.0.1"), ":", integer_to_list(mochiweb_socket_server:get(couch_httpd, port)), "/", DbName ]). create_db(DbName) -> couch_db:create( DbName, [{user_ctx, #user_ctx{roles = [<<"_admin">>]}}, overwrite]). delete_db(Db) -> ok = couch_server:delete( couch_db:name(Db), [{user_ctx, #user_ctx{roles = [<<"_admin">>]}}]). replicate({remote, Db}, Target) -> replicate(db_url(Db), Target); replicate(Source, {remote, Db}) -> replicate(Source, db_url(Db)); replicate(Source, Target) -> RepObject = {[ {<<"source">>, Source}, {<<"target">>, Target} ]}, {ok, Rep} = couch_replicator_utils:parse_rep_doc( RepObject, #user_ctx{roles = [<<"_admin">>]}), {ok, Pid} = couch_replicator:async_replicate(Rep), MonRef = erlang:monitor(process, Pid), receive {'DOWN', MonRef, process, Pid, Reason} -> etap:is(Reason, normal, "Replication finished successfully") after 300000 -> etap:bail("Timeout waiting for replication to finish") end. apache-couchdb-1.5.0/src/couch_replicator/Makefile.am0000644000175000001440000000456412230722213017433 00000000000000## 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. couch_replicatorlibdir = $(localerlanglibdir)/couch_replicator-0.1 couch_replicatorincludedir = $(couch_replicatorlibdir)/include couch_replicatorebindir = $(couch_replicatorlibdir)/ebin couch_replicatorinclude_DATA = $(include_files) couch_replicatorebin_DATA = $(compiled_files) include_files = \ src/couch_replicator_api_wrap.hrl \ src/couch_replicator.hrl \ src/couch_replicator_js_functions.hrl source_files = \ src/couch_replicator_api_wrap.erl \ src/couch_replicator_httpc_pool.erl \ src/couch_replicator_httpc.erl \ src/couch_replicator_httpd.erl \ src/couch_replicator_job_sup.erl \ src/couch_replicator_notifier.erl \ src/couch_replicator_manager.erl \ src/couch_replicator_utils.erl \ src/couch_replicator_worker.erl \ src/couch_replicator.app.src \ src/couch_replicator.erl test_files = \ test/01-load.t \ test/02-httpc-pool.t \ test/03-replication-compact.t \ test/04-replication-large-atts.t \ test/05-replication-many-leaves.t \ test/06-doc-missing-stubs.t compiled_files = \ ebin/couch_replicator_api_wrap.beam \ ebin/couch_replicator_httpc_pool.beam \ ebin/couch_replicator_httpc.beam \ ebin/couch_replicator_httpd.beam \ ebin/couch_replicator_job_sup.beam \ ebin/couch_replicator_notifier.beam \ ebin/couch_replicator_manager.beam \ ebin/couch_replicator_utils.beam \ ebin/couch_replicator_worker.beam \ ebin/couch_replicator.app \ ebin/couch_replicator.beam EXTRA_DIST = $(include_files) $(source_files) $(test_files) CLEANFILES = $(compiled_files) check: if TESTS $(abs_top_builddir)/test/etap/run $(abs_top_srcdir)/src/couch_replicator/test endif ebin/%.app: src/%.app.src @mkdir -p ebin/ sed -e "s|%version%|@version@|g" \ < $< > $@ ebin/%.beam: src/%.erl $(include_files) @mkdir -p ebin/ $(ERLC) -Wall -I$(top_srcdir)/src -I$(top_srcdir)/src/couchdb \ -o ebin/ $(ERLC_FLAGS) ${TEST} $<; apache-couchdb-1.5.0/src/couch_replicator/Makefile.in0000644000175000001440000004320012230722243017435 00000000000000# Makefile.in generated by automake 1.11.6 from Makefile.am. # @configure_input@ # Copyright (C) 1994, 1995, 1996, 1997, 1998, 1999, 2000, 2001, 2002, # 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011 Free Software # Foundation, Inc. # This Makefile.in is free software; the Free Software Foundation # gives unlimited permission to copy and/or distribute it, # with or without modifications, as long as this notice is preserved. # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY, to the extent permitted by law; without # even the implied warranty of MERCHANTABILITY or FITNESS FOR A # PARTICULAR PURPOSE. @SET_MAKE@ VPATH = @srcdir@ am__make_dryrun = \ { \ am__dry=no; \ case $$MAKEFLAGS in \ *\\[\ \ ]*) \ echo 'am--echo: ; @echo "AM" OK' | $(MAKE) -f - 2>/dev/null \ | grep '^AM OK$$' >/dev/null || am__dry=yes;; \ *) \ for am__flg in $$MAKEFLAGS; do \ case $$am__flg in \ *=*|--*) ;; \ *n*) am__dry=yes; break;; \ esac; \ done;; \ esac; \ test $$am__dry = yes; \ } pkgdatadir = $(datadir)/@PACKAGE@ pkgincludedir = $(includedir)/@PACKAGE@ pkglibdir = $(libdir)/@PACKAGE@ pkglibexecdir = $(libexecdir)/@PACKAGE@ am__cd = CDPATH="$${ZSH_VERSION+.}$(PATH_SEPARATOR)" && cd install_sh_DATA = $(install_sh) -c -m 644 install_sh_PROGRAM = $(install_sh) -c install_sh_SCRIPT = $(install_sh) -c INSTALL_HEADER = $(INSTALL_DATA) transform = $(program_transform_name) NORMAL_INSTALL = : PRE_INSTALL = : POST_INSTALL = : NORMAL_UNINSTALL = : PRE_UNINSTALL = : POST_UNINSTALL = : build_triplet = @build@ host_triplet = @host@ subdir = src/couch_replicator DIST_COMMON = $(srcdir)/Makefile.am $(srcdir)/Makefile.in ACLOCAL_M4 = $(top_srcdir)/aclocal.m4 am__aclocal_m4_deps = $(top_srcdir)/m4/libtool.m4 \ $(top_srcdir)/m4/ltoptions.m4 $(top_srcdir)/m4/ltsugar.m4 \ $(top_srcdir)/m4/ltversion.m4 $(top_srcdir)/m4/lt~obsolete.m4 \ $(top_srcdir)/acinclude.m4 $(top_srcdir)/configure.ac am__configure_deps = $(am__aclocal_m4_deps) $(CONFIGURE_DEPENDENCIES) \ $(ACLOCAL_M4) mkinstalldirs = $(install_sh) -d CONFIG_HEADER = $(top_builddir)/config.h \ $(top_builddir)/src/snappy/google-snappy/config.h CONFIG_CLEAN_FILES = CONFIG_CLEAN_VPATH_FILES = SOURCES = DIST_SOURCES = am__can_run_installinfo = \ case $$AM_UPDATE_INFO_DIR in \ n|no|NO) false;; \ *) (install-info --version) >/dev/null 2>&1;; \ esac am__vpath_adj_setup = srcdirstrip=`echo "$(srcdir)" | sed 's|.|.|g'`; am__vpath_adj = case $$p in \ $(srcdir)/*) f=`echo "$$p" | sed "s|^$$srcdirstrip/||"`;; \ *) f=$$p;; \ esac; am__strip_dir = f=`echo $$p | sed -e 's|^.*/||'`; am__install_max = 40 am__nobase_strip_setup = \ srcdirstrip=`echo "$(srcdir)" | sed 's/[].[^$$\\*|]/\\\\&/g'` am__nobase_strip = \ for p in $$list; do echo "$$p"; done | sed -e "s|$$srcdirstrip/||" am__nobase_list = $(am__nobase_strip_setup); \ for p in $$list; do echo "$$p $$p"; done | \ sed "s| $$srcdirstrip/| |;"' / .*\//!s/ .*/ ./; s,\( .*\)/[^/]*$$,\1,' | \ $(AWK) 'BEGIN { files["."] = "" } { files[$$2] = files[$$2] " " $$1; \ if (++n[$$2] == $(am__install_max)) \ { print $$2, files[$$2]; n[$$2] = 0; files[$$2] = "" } } \ END { for (dir in files) print dir, files[dir] }' am__base_list = \ sed '$$!N;$$!N;$$!N;$$!N;$$!N;$$!N;$$!N;s/\n/ /g' | \ sed '$$!N;$$!N;$$!N;$$!N;s/\n/ /g' am__uninstall_files_from_dir = { \ test -z "$$files" \ || { test ! -d "$$dir" && test ! -f "$$dir" && test ! -r "$$dir"; } \ || { echo " ( cd '$$dir' && rm -f" $$files ")"; \ $(am__cd) "$$dir" && rm -f $$files; }; \ } am__installdirs = "$(DESTDIR)$(couch_replicatorebindir)" \ "$(DESTDIR)$(couch_replicatorincludedir)" DATA = $(couch_replicatorebin_DATA) $(couch_replicatorinclude_DATA) DISTFILES = $(DIST_COMMON) $(DIST_SOURCES) $(TEXINFOS) $(EXTRA_DIST) ACLOCAL = @ACLOCAL@ AMTAR = @AMTAR@ AR = @AR@ AS = @AS@ AUTOCONF = @AUTOCONF@ AUTOHEADER = @AUTOHEADER@ AUTOMAKE = @AUTOMAKE@ AWK = @AWK@ CC = @CC@ CCDEPMODE = @CCDEPMODE@ CFLAGS = @CFLAGS@ CPP = @CPP@ CPPFLAGS = @CPPFLAGS@ CURL_CFLAGS = @CURL_CFLAGS@ CURL_CONFIG = @CURL_CONFIG@ CURL_LIBS = @CURL_LIBS@ CXX = @CXX@ CXXCPP = @CXXCPP@ CXXDEPMODE = @CXXDEPMODE@ CXXFLAGS = @CXXFLAGS@ CYGPATH_W = @CYGPATH_W@ DEFS = @DEFS@ DEPDIR = @DEPDIR@ DLLTOOL = @DLLTOOL@ DSYMUTIL = @DSYMUTIL@ DUMPBIN = @DUMPBIN@ ECHO_C = @ECHO_C@ ECHO_N = @ECHO_N@ ECHO_T = @ECHO_T@ EGREP = @EGREP@ ERL = @ERL@ ERLANG_FLAGS = @ERLANG_FLAGS@ ERLC = @ERLC@ ERLC_FLAGS = @ERLC_FLAGS@ ESCRIPT = @ESCRIPT@ EXEEXT = @EXEEXT@ FGREP = @FGREP@ FLAGS = @FLAGS@ GREP = @GREP@ HAS_HELP2MAN = @HAS_HELP2MAN@ HAS_INSTALLINFO = @HAS_INSTALLINFO@ HAS_MAKEINFO = @HAS_MAKEINFO@ HAS_PDFLATEX = @HAS_PDFLATEX@ HAS_SPHINX_BUILD = @HAS_SPHINX_BUILD@ ICU_BIN = @ICU_BIN@ ICU_CFLAGS = @ICU_CFLAGS@ ICU_CONFIG = @ICU_CONFIG@ ICU_CPPFLAGS = @ICU_CPPFLAGS@ ICU_CXXFLAGS = @ICU_CXXFLAGS@ ICU_LIBS = @ICU_LIBS@ INNO_COMPILER_EXECUTABLE = @INNO_COMPILER_EXECUTABLE@ INSTALL = @INSTALL@ INSTALL_DATA = @INSTALL_DATA@ INSTALL_PROGRAM = @INSTALL_PROGRAM@ INSTALL_SCRIPT = @INSTALL_SCRIPT@ INSTALL_STRIP_PROGRAM = @INSTALL_STRIP_PROGRAM@ JS_CFLAGS = @JS_CFLAGS@ JS_LIBS = @JS_LIBS@ JS_LIB_BINARY = @JS_LIB_BINARY@ LD = @LD@ LDFLAGS = @LDFLAGS@ LIBOBJS = @LIBOBJS@ LIBS = @LIBS@ LIBTOOL = @LIBTOOL@ LIPO = @LIPO@ LN_S = @LN_S@ LTLIBOBJS = @LTLIBOBJS@ MAKEINFO = @MAKEINFO@ MANIFEST_TOOL = @MANIFEST_TOOL@ MKDIR_P = @MKDIR_P@ NM = @NM@ NMEDIT = @NMEDIT@ OBJDUMP = @OBJDUMP@ OBJEXT = @OBJEXT@ OTOOL = @OTOOL@ OTOOL64 = @OTOOL64@ PACKAGE = @PACKAGE@ PACKAGE_BUGREPORT = @PACKAGE_BUGREPORT@ PACKAGE_NAME = @PACKAGE_NAME@ PACKAGE_STRING = @PACKAGE_STRING@ PACKAGE_TARNAME = @PACKAGE_TARNAME@ PACKAGE_URL = @PACKAGE_URL@ PACKAGE_VERSION = @PACKAGE_VERSION@ PATH_SEPARATOR = @PATH_SEPARATOR@ PKG_CONFIG = @PKG_CONFIG@ PKG_CONFIG_LIBDIR = @PKG_CONFIG_LIBDIR@ PKG_CONFIG_PATH = @PKG_CONFIG_PATH@ RANLIB = @RANLIB@ SED = @SED@ SET_MAKE = @SET_MAKE@ SHELL = @SHELL@ SNAPPY_MAJOR = @SNAPPY_MAJOR@ SNAPPY_MINOR = @SNAPPY_MINOR@ SNAPPY_PATCHLEVEL = @SNAPPY_PATCHLEVEL@ STRIP = @STRIP@ VERSION = @VERSION@ abs_builddir = @abs_builddir@ abs_srcdir = @abs_srcdir@ abs_top_builddir = @abs_top_builddir@ abs_top_srcdir = @abs_top_srcdir@ ac_ct_AR = @ac_ct_AR@ ac_ct_CC = @ac_ct_CC@ ac_ct_CXX = @ac_ct_CXX@ ac_ct_DUMPBIN = @ac_ct_DUMPBIN@ ac_cv_have_stddef_h = @ac_cv_have_stddef_h@ ac_cv_have_stdint_h = @ac_cv_have_stdint_h@ am__include = @am__include@ am__leading_dot = @am__leading_dot@ am__quote = @am__quote@ am__tar = @am__tar@ am__untar = @am__untar@ bindir = @bindir@ bug_uri = @bug_uri@ build = @build@ build_alias = @build_alias@ build_cpu = @build_cpu@ build_os = @build_os@ build_vendor = @build_vendor@ builddir = @builddir@ datadir = @datadir@ datarootdir = @datarootdir@ docdir = @docdir@ dvidir = @dvidir@ erlangbin = @erlangbin@ erlangversion = @erlangversion@ exec_prefix = @exec_prefix@ host = @host@ host_alias = @host_alias@ host_cpu = @host_cpu@ host_os = @host_os@ host_vendor = @host_vendor@ htmldir = @htmldir@ includedir = @includedir@ infodir = @infodir@ initdir = @initdir@ install_sh = @install_sh@ launchddir = @launchddir@ libdir = @libdir@ libexecdir = @libexecdir@ localconfdir = @localconfdir@ localdatadir = @localdatadir@ localdocdir = @localdocdir@ localedir = @localedir@ localerlanglibdir = @localerlanglibdir@ locallibbindir = @locallibbindir@ locallibdir = @locallibdir@ localstatedir = @localstatedir@ localstatelibdir = @localstatelibdir@ localstatelogdir = @localstatelogdir@ localstaterundir = @localstaterundir@ mandir = @mandir@ mkdir_p = @mkdir_p@ msvc_redist_dir = @msvc_redist_dir@ msvc_redist_name = @msvc_redist_name@ oldincludedir = @oldincludedir@ openssl_bin_dir = @openssl_bin_dir@ otp_release = @otp_release@ package_author_address = @package_author_address@ package_author_name = @package_author_name@ package_identifier = @package_identifier@ package_name = @package_name@ package_tarname = @package_tarname@ pdfdir = @pdfdir@ prefix = @prefix@ program_transform_name = @program_transform_name@ psdir = @psdir@ sbindir = @sbindir@ sharedstatedir = @sharedstatedir@ srcdir = @srcdir@ sysconfdir = @sysconfdir@ target_alias = @target_alias@ top_build_prefix = @top_build_prefix@ top_builddir = @top_builddir@ top_srcdir = @top_srcdir@ version = @version@ version_major = @version_major@ version_minor = @version_minor@ version_release = @version_release@ version_revision = @version_revision@ version_stage = @version_stage@ couch_replicatorlibdir = $(localerlanglibdir)/couch_replicator-0.1 couch_replicatorincludedir = $(couch_replicatorlibdir)/include couch_replicatorebindir = $(couch_replicatorlibdir)/ebin couch_replicatorinclude_DATA = $(include_files) couch_replicatorebin_DATA = $(compiled_files) include_files = \ src/couch_replicator_api_wrap.hrl \ src/couch_replicator.hrl \ src/couch_replicator_js_functions.hrl source_files = \ src/couch_replicator_api_wrap.erl \ src/couch_replicator_httpc_pool.erl \ src/couch_replicator_httpc.erl \ src/couch_replicator_httpd.erl \ src/couch_replicator_job_sup.erl \ src/couch_replicator_notifier.erl \ src/couch_replicator_manager.erl \ src/couch_replicator_utils.erl \ src/couch_replicator_worker.erl \ src/couch_replicator.app.src \ src/couch_replicator.erl test_files = \ test/01-load.t \ test/02-httpc-pool.t \ test/03-replication-compact.t \ test/04-replication-large-atts.t \ test/05-replication-many-leaves.t \ test/06-doc-missing-stubs.t compiled_files = \ ebin/couch_replicator_api_wrap.beam \ ebin/couch_replicator_httpc_pool.beam \ ebin/couch_replicator_httpc.beam \ ebin/couch_replicator_httpd.beam \ ebin/couch_replicator_job_sup.beam \ ebin/couch_replicator_notifier.beam \ ebin/couch_replicator_manager.beam \ ebin/couch_replicator_utils.beam \ ebin/couch_replicator_worker.beam \ ebin/couch_replicator.app \ ebin/couch_replicator.beam EXTRA_DIST = $(include_files) $(source_files) $(test_files) CLEANFILES = $(compiled_files) all: all-am .SUFFIXES: $(srcdir)/Makefile.in: $(srcdir)/Makefile.am $(am__configure_deps) @for dep in $?; do \ case '$(am__configure_deps)' in \ *$$dep*) \ ( cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh ) \ && { if test -f $@; then exit 0; else break; fi; }; \ exit 1;; \ esac; \ done; \ echo ' cd $(top_srcdir) && $(AUTOMAKE) --foreign src/couch_replicator/Makefile'; \ $(am__cd) $(top_srcdir) && \ $(AUTOMAKE) --foreign src/couch_replicator/Makefile .PRECIOUS: Makefile Makefile: $(srcdir)/Makefile.in $(top_builddir)/config.status @case '$?' in \ *config.status*) \ cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh;; \ *) \ echo ' cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ $(am__depfiles_maybe)'; \ cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ $(am__depfiles_maybe);; \ esac; $(top_builddir)/config.status: $(top_srcdir)/configure $(CONFIG_STATUS_DEPENDENCIES) cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh $(top_srcdir)/configure: $(am__configure_deps) cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh $(ACLOCAL_M4): $(am__aclocal_m4_deps) cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh $(am__aclocal_m4_deps): mostlyclean-libtool: -rm -f *.lo clean-libtool: -rm -rf .libs _libs install-couch_replicatorebinDATA: $(couch_replicatorebin_DATA) @$(NORMAL_INSTALL) @list='$(couch_replicatorebin_DATA)'; test -n "$(couch_replicatorebindir)" || list=; \ if test -n "$$list"; then \ echo " $(MKDIR_P) '$(DESTDIR)$(couch_replicatorebindir)'"; \ $(MKDIR_P) "$(DESTDIR)$(couch_replicatorebindir)" || exit 1; \ fi; \ for p in $$list; do \ if test -f "$$p"; then d=; else d="$(srcdir)/"; fi; \ echo "$$d$$p"; \ done | $(am__base_list) | \ while read files; do \ echo " $(INSTALL_DATA) $$files '$(DESTDIR)$(couch_replicatorebindir)'"; \ $(INSTALL_DATA) $$files "$(DESTDIR)$(couch_replicatorebindir)" || exit $$?; \ done uninstall-couch_replicatorebinDATA: @$(NORMAL_UNINSTALL) @list='$(couch_replicatorebin_DATA)'; test -n "$(couch_replicatorebindir)" || list=; \ files=`for p in $$list; do echo $$p; done | sed -e 's|^.*/||'`; \ dir='$(DESTDIR)$(couch_replicatorebindir)'; $(am__uninstall_files_from_dir) install-couch_replicatorincludeDATA: $(couch_replicatorinclude_DATA) @$(NORMAL_INSTALL) @list='$(couch_replicatorinclude_DATA)'; test -n "$(couch_replicatorincludedir)" || list=; \ if test -n "$$list"; then \ echo " $(MKDIR_P) '$(DESTDIR)$(couch_replicatorincludedir)'"; \ $(MKDIR_P) "$(DESTDIR)$(couch_replicatorincludedir)" || exit 1; \ fi; \ for p in $$list; do \ if test -f "$$p"; then d=; else d="$(srcdir)/"; fi; \ echo "$$d$$p"; \ done | $(am__base_list) | \ while read files; do \ echo " $(INSTALL_DATA) $$files '$(DESTDIR)$(couch_replicatorincludedir)'"; \ $(INSTALL_DATA) $$files "$(DESTDIR)$(couch_replicatorincludedir)" || exit $$?; \ done uninstall-couch_replicatorincludeDATA: @$(NORMAL_UNINSTALL) @list='$(couch_replicatorinclude_DATA)'; test -n "$(couch_replicatorincludedir)" || list=; \ files=`for p in $$list; do echo $$p; done | sed -e 's|^.*/||'`; \ dir='$(DESTDIR)$(couch_replicatorincludedir)'; $(am__uninstall_files_from_dir) tags: TAGS TAGS: ctags: CTAGS CTAGS: distdir: $(DISTFILES) @srcdirstrip=`echo "$(srcdir)" | sed 's/[].[^$$\\*]/\\\\&/g'`; \ topsrcdirstrip=`echo "$(top_srcdir)" | sed 's/[].[^$$\\*]/\\\\&/g'`; \ list='$(DISTFILES)'; \ dist_files=`for file in $$list; do echo $$file; done | \ sed -e "s|^$$srcdirstrip/||;t" \ -e "s|^$$topsrcdirstrip/|$(top_builddir)/|;t"`; \ case $$dist_files in \ */*) $(MKDIR_P) `echo "$$dist_files" | \ sed '/\//!d;s|^|$(distdir)/|;s,/[^/]*$$,,' | \ sort -u` ;; \ esac; \ for file in $$dist_files; do \ if test -f $$file || test -d $$file; then d=.; else d=$(srcdir); fi; \ if test -d $$d/$$file; then \ dir=`echo "/$$file" | sed -e 's,/[^/]*$$,,'`; \ if test -d "$(distdir)/$$file"; then \ find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} \;; \ fi; \ if test -d $(srcdir)/$$file && test $$d != $(srcdir); then \ cp -fpR $(srcdir)/$$file "$(distdir)$$dir" || exit 1; \ find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} \;; \ fi; \ cp -fpR $$d/$$file "$(distdir)$$dir" || exit 1; \ else \ test -f "$(distdir)/$$file" \ || cp -p $$d/$$file "$(distdir)/$$file" \ || exit 1; \ fi; \ done check-am: all-am check: check-am all-am: Makefile $(DATA) installdirs: for dir in "$(DESTDIR)$(couch_replicatorebindir)" "$(DESTDIR)$(couch_replicatorincludedir)"; do \ test -z "$$dir" || $(MKDIR_P) "$$dir"; \ done install: install-am install-exec: install-exec-am install-data: install-data-am uninstall: uninstall-am install-am: all-am @$(MAKE) $(AM_MAKEFLAGS) install-exec-am install-data-am installcheck: installcheck-am install-strip: if test -z '$(STRIP)'; then \ $(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(INSTALL_STRIP_PROGRAM)" \ install_sh_PROGRAM="$(INSTALL_STRIP_PROGRAM)" INSTALL_STRIP_FLAG=-s \ install; \ else \ $(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(INSTALL_STRIP_PROGRAM)" \ install_sh_PROGRAM="$(INSTALL_STRIP_PROGRAM)" INSTALL_STRIP_FLAG=-s \ "INSTALL_PROGRAM_ENV=STRIPPROG='$(STRIP)'" install; \ fi mostlyclean-generic: clean-generic: -test -z "$(CLEANFILES)" || rm -f $(CLEANFILES) distclean-generic: -test -z "$(CONFIG_CLEAN_FILES)" || rm -f $(CONFIG_CLEAN_FILES) -test . = "$(srcdir)" || test -z "$(CONFIG_CLEAN_VPATH_FILES)" || rm -f $(CONFIG_CLEAN_VPATH_FILES) maintainer-clean-generic: @echo "This command is intended for maintainers to use" @echo "it deletes files that may require special tools to rebuild." clean: clean-am clean-am: clean-generic clean-libtool mostlyclean-am distclean: distclean-am -rm -f Makefile distclean-am: clean-am distclean-generic dvi: dvi-am dvi-am: html: html-am html-am: info: info-am info-am: install-data-am: install-couch_replicatorebinDATA \ install-couch_replicatorincludeDATA install-dvi: install-dvi-am install-dvi-am: install-exec-am: install-html: install-html-am install-html-am: install-info: install-info-am install-info-am: install-man: install-pdf: install-pdf-am install-pdf-am: install-ps: install-ps-am install-ps-am: installcheck-am: maintainer-clean: maintainer-clean-am -rm -f Makefile maintainer-clean-am: distclean-am maintainer-clean-generic mostlyclean: mostlyclean-am mostlyclean-am: mostlyclean-generic mostlyclean-libtool pdf: pdf-am pdf-am: ps: ps-am ps-am: uninstall-am: uninstall-couch_replicatorebinDATA \ uninstall-couch_replicatorincludeDATA .MAKE: install-am install-strip .PHONY: all all-am check check-am clean clean-generic clean-libtool \ distclean distclean-generic distclean-libtool distdir dvi \ dvi-am html html-am info info-am install install-am \ install-couch_replicatorebinDATA \ install-couch_replicatorincludeDATA install-data \ install-data-am install-dvi install-dvi-am install-exec \ install-exec-am install-html install-html-am install-info \ install-info-am install-man install-pdf install-pdf-am \ install-ps install-ps-am install-strip installcheck \ installcheck-am installdirs maintainer-clean \ maintainer-clean-generic mostlyclean mostlyclean-generic \ mostlyclean-libtool pdf pdf-am ps ps-am uninstall uninstall-am \ uninstall-couch_replicatorebinDATA \ uninstall-couch_replicatorincludeDATA check: @TESTS_TRUE@ $(abs_top_builddir)/test/etap/run $(abs_top_srcdir)/src/couch_replicator/test ebin/%.app: src/%.app.src @mkdir -p ebin/ sed -e "s|%version%|@version@|g" \ < $< > $@ ebin/%.beam: src/%.erl $(include_files) @mkdir -p ebin/ $(ERLC) -Wall -I$(top_srcdir)/src -I$(top_srcdir)/src/couchdb \ -o ebin/ $(ERLC_FLAGS) ${TEST} $<; # Tell versions [3.59,3.63) of GNU make to not export all variables. # Otherwise a system limit (for SysV at least) may be exceeded. .NOEXPORT: apache-couchdb-1.5.0/src/couchjs-node/0000755000175000001440000000000012230722306014505 500000000000000apache-couchdb-1.5.0/src/couchjs-node/test/0000755000175000001440000000000012230722306015464 500000000000000apache-couchdb-1.5.0/src/couchjs-node/test/experiment.js0000644000175000001440000000523512230722213020124 00000000000000// 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. var vm = require('vm'); var util = require('util'); var STATE = 'wait'; function main() { process.debugPort = 5859; process.kill(process.pid, 'SIGUSR1'); setTimeout(function() { stuff(0); }, 1000); } function stuff(count) { console.log('Doing stuff: %d', count); STATE = 'vm'; console.log('More stuff: %d', count); if (STATE === 'done') { console.log('Done'); } else if (STATE === 'code') { setTimeout(code, 1000); } else if(STATE === 'eval') { test_eval(); } else if(STATE === 'vm') { test_vm(); } else if(STATE === 'wait') { setTimeout(function() { stuff(count+1); }, 1000); } else { throw new Error('Unknown state: ' + STATE); } } function code() { var code = [ 'var foo = "in the code"', 'console.log("This is some code")', 'debugger', 'console.log("foo = " + foo)' ].join('\n'); var runner = Function([], code); console.log('Run runner in 1s'); setTimeout(run_runner, 1000) function run_runner() { console.log('About to run runner'); debugger; runner(); console.log('Runner done'); } } function test_eval() { console.log('Test eval in 1s'); setTimeout(run_eval, 1000); var code = [ 'var foo = "in eval"', 'console.log("This is eval")', 'debugger', 'console.log("foo = " + foo)' ].join('\n'); function run_eval() { console.log('Run eval now'); debugger; eval(code); } } function test_vm() { console.log('Test vm'); var code = [ 'var i = 10', 'setTimeout(hello, 1000)', '', 'function hello() {', ' debugger', ' console.log("Hello: " + i)', ' if(--i)', ' setTimeout(hello, 1000)', '}' ].join('\n'); console.log('Run vm now'); var filename = '_couchdb:code.js'; var sandbox = {}; var ok = ['console', 'setTimeout']; ok.forEach(function(key) { sandbox[key] = global[key]; }); var ctx = vm.createContext(sandbox); var script = vm.createScript(code, filename); var r = script.runInNewContext(sandbox); console.log('Result:\n%s', util.inspect(r, false, 10)); return r; } if (require.main === module) { main(); } apache-couchdb-1.5.0/src/couchjs-node/stream.js0000644000175000001440000000505012230722213016253 00000000000000// 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. // Text line stream var stream = require('stream'); var util = require('util'); function LineStream() { var self = this; stream.call(self); self.readable = true; self.writable = true; self.buffer = ''; self.downstream = null; self.on('pipe', function(upstream) { upstream.on('end', function(data, encoding) { self.emit('end', data, encoding); }); }); } function LineStream2() { if (!(this instanceof LineStream2)) { return new LineStream2(); } stream.Transform.call(this); this.setEncoding('utf8'); } util.inherits(LineStream2, stream.Transform); LineStream2.prototype._transform = function(message, encoding, done) { var self = this; message = message.toString(encoding); var lines = message.split(/\n/); // If the data ends in "\n" this will be ""; otherwise the final partial line. var remainder = lines.pop(); if (remainder) { this.unshift(remainder); } lines.forEach(function(line) { self.push(line); }); done(); }; util.inherits(LineStream, stream); LineStream.prototype.write = function(data) { var self = this; data = data || ''; if (typeof data !== 'string') { return self.error(new Error('Data was not a string: ' + util.inspect(data))); } self.buffer += data; var lines = self.buffer.split(/\n/); self.buffer = lines.pop(); // If the data ended in "\n" this will be ""; otherwise the final partial line. lines.forEach(function(line) { self.emit('data', line); }); }; LineStream.prototype.end = function(data) { var self = this; self.is_ending = true; self.writable = false; // Always call write, even with no data, so it can fire the "end" event. self.write(data); }; LineStream.prototype.error = function(er) { var self = this; self.readable = false; self.writable = false; self.emit('error', er); // The write() method sometimes returns this value, so if there was an error, make write() return false. return false; }; module.exports = LineStream; module.exports.v2 = LineStream2; apache-couchdb-1.5.0/src/couchjs-node/README.md0000644000175000001440000000220112230722213015674 00000000000000# CouchJS ## Drop-in replacement JavaScript engine for Apache CouchDB CouchJS is a command-line Node.js program. It is 100% compatible with Apache CouchDB's built-in JavaScript system. By using CouchJS, you will get 100% CouchDB compatibility (the test suite completely passes) but your JavaScript environment is V8, or Node.js. See share/doc/src/experimental.rst for installation instructions. ## Idea JavaScript is decoupled from the CouchDB core. To do JavaScript stuff, CouchDB runs a normal Unix subprocess, `couchjs`. This subprocess is just a read-eval-print loop on standard i/o. CouchDB passes `couchjs` a file name, and *that file* contains the view server implementation. This tool duplicates the "REPL" look and feel of `couchjs` and supports the exact same view server implementation. ## Security I have no idea. I would not trust it for production use. ## Log If you create a file, `/tmp/couchjs.log` then *couchjs* will output debugging messages there. ## License Apache 2.0 See the [Apache 2.0 license](named/blob/master/LICENSE). [tap]: https://github.com/isaacs/node-tap [def]: https://github.com/iriscouch/defaultable apache-couchdb-1.5.0/src/couchjs-node/sandbox.js0000644000175000001440000000224212230722213016416 00000000000000// from https://github.com/KlausTrainer/sandbox.js exports.runInSandbox = function(src, ctx, whitelist) { var vm = require('vm'); var sandbox; if (ctx && ctx.require) { whitelist = whitelist || []; var insecureRequire = ctx.require; var module = require('module'); var oldModulePrototype = module.prototype; var secureRequire = function(moduleName) { if (whitelist.indexOf(moduleName) === -1) { module.prototype = oldModulePrototype; throw new Error("'" + moduleName + "' is not whitelisted"); } else { var requiredModule = insecureRequire(moduleName); module.prototype = oldModulePrototype; return requiredModule; } }; module.prototype = { require: secureRequire, load: module.prototype.load, _compile: module.prototype._compile }; module._cache = {}; ctx.require = secureRequire; sandbox = Object.freeze(vm.createContext(ctx)); ctx.require = insecureRequire; } else { sandbox = Object.freeze(vm.createContext(ctx || {})); } return vm.createScript('(function() {"use strict"; return (' + src + ')()}())').runInContext(sandbox); }; apache-couchdb-1.5.0/src/couchjs-node/couchdb.js0000755000175000001440000000154712230722213016401 00000000000000// 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. var http = require('http'); function handler(req, res) { res.writeHead(200); res.end('Hello: ' + req.url + '\n'); } if (require.main === module) { var http = require('http'); var server = http.createServer(handler); server.listen(3000); console.log('Listening on :3000'); } module.exports = handler; apache-couchdb-1.5.0/src/couchjs-node/couchjs.js0000644000175000001440000000523612230722213016424 00000000000000// 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. var vm = require('vm'); var Fiber = require('fibers'); var util = require('util'); var XML = require('./xml'); var log = require('./console').log; var INPUT = { 'queue':[], 'waiting':null }; function print(line) { log('STDOUT %s: %s', process.pid, line); process.stdout.write(line + '\n'); try { line = JSON.parse(line); } catch(er) { return; } if (line[0] === 'log') { log('LOG: %s', line[1]); } } function stdin (line) { log('STDIN %s: %s', process.pid, line.trim()); if (INPUT.waiting) { INPUT.waiting.run(line); } else { INPUT.queue.push(line); } } function readline () { var line = INPUT.queue.shift(); if (line) { return line; } INPUT.waiting = Fiber.current; line = Fiber.yield(); INPUT.waiting = null; return line; } function evalcx (source, sandbox) { sandbox = sandbox || {}; var func; //log('evalcx in %j: %j', Object.keys(sandbox), source) if (source === '') { return sandbox; } // source might be "function(doc) { emit(doc._id, 1) }" source = source.replace(/;+$/, ''); sandbox.XML = sandbox.XML || XML; source = '(' + source + ')'; try { var id = Math.floor(Math.random() * 1000*1000); var filename = '_couchdb:' + id + '.js'; var script = vm.createScript(source, filename); func = script.runInNewContext(sandbox); } catch (er) { log('Error making code: %s', er.stack); return sandbox; } return func; } function quit(code) { code = code || 1; if (code < 0) { code = -code; } process.exit(code); } function gc() { } function toSource() { if (typeof this === 'function') { return '' + this; } if (this instanceof Error) { return this.stack; } return util.inspect(this); } Error.prototype.toSource = Error.prototype.toSource || toSource; Error.prototype.toString = Error.prototype.toString || toSource; Function.prototype.toSource = Function.prototype.toSource || toSource; Function.prototype.toString = Function.prototype.toString || toSource; module.exports = { 'print': print, 'readline': readline, 'stdin': stdin, 'evalcx': evalcx, 'quit': quit, 'gc': gc }; apache-couchdb-1.5.0/src/couchjs-node/inspector.js0000755000175000001440000000456612230722213017004 00000000000000#!/usr/bin/env node // 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. var cp = require('child_process'); var log = require('./console').log; function watchInspector(child) { child.stderr.on('data', function(body) { log('Inspector STDERR: %s', body); }); child.stdout.on('data', function(body) { log('Inspector STDOUT: %s', body); }); child.on('exit', function(code, signal) { log('Inspector exited %d signal=%j', code, signal); process.exit(code); }); process.on('exit', function() { log('Kill inspector upon exit: %d', child.pid); process.kill(child.pid, 'SIGTERM'); }); } function start (debugPort) { if (!debugPort || typeof debugPort !== 'number') { throw new Error('Need a listen debugPort'); } var webPort = debugPort + 1; var cmd = __filename; var args = [debugPort, webPort]; var opts = { 'cwd': __dirname, 'stdio': 'pipe', 'detached': false }; log('Start inspector: %s %j %j', cmd, args, opts); var inspector = cp.spawn(cmd, args, opts); watchInspector(inspector); log('Enable remote debug pid=%d port=%d', process.pid, debugPort); process.debugPort = debugPort; process.kill(process.pid, 'SIGUSR1'); } function main() { var debugPort = +process.argv[2]; var webPort = +process.argv[3]; if (!debugPort || !webPort) { throw new Error('Bad arguments: need debugPort and webPort'); } console.log('Start inspector debugPort=%j webPort=%j', debugPort, webPort); var DebugServer = require('node-inspector/lib/debug-server'); var server = new DebugServer(); server.on('close', function() { console.log('Server closed'); process.exit(0); }); server.start({ 'webPort':webPort, 'debugPort':debugPort }); process.on('uncaughtException', function(er) { console.log('Error:\n%s', er.stack); }); } module.exports = start; if (require.main === module) { main(); } apache-couchdb-1.5.0/src/couchjs-node/console.js0000644000175000001440000000320612230722213016423 00000000000000// 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. var fs = require('fs'); var util = require('util'); var noop = function() {}; module.exports = {}; module.exports.log = noop; module.exports.debug = noop; module.exports.info = noop; module.exports.warn = noop; module.exports.error = noop; var LOG_PATH = '/tmp/couchjs.log'; var stat = null; var LOG = null; try { stat = fs.statSync(LOG_PATH); } catch(er) {} if (stat) { LOG = fs.createWriteStream(LOG_PATH, { 'flags':'a' }); var log = function () { var str = util.format.apply(this, arguments); LOG.write(str + '\n'); }; var on_err = function (er) { module.exports.error('Uncaught error:\n%s', er.stack || er.message || JSON.stringify(er)); if (er.stack) { er = ['fatal', 'unknown_error', er.stack]; } process.stdout.write(JSON.stringify(er) + '\n'); process.exit(1); }; module.exports.log = log; module.exports.debug = log; module.exports.info = log; module.exports.warn = log; module.exports.error = log; process.on('exit', function() { module.exports.log('Exit %d', process.pid); }); process.on('uncaughtException', on_err); } apache-couchdb-1.5.0/src/couchjs-node/cli.js0000755000175000001440000000444412230722213015540 00000000000000#!/usr/bin/env node // 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. var fs = require('fs'); var Fiber = require('fibers'); var optimist = require('optimist'); var couchjs = require('./couchjs'); var package_json = require('./package.json'); var LineStream = require('./stream'); var inspector = require('./inspector'); var log = require('./console').log; var opts = optimist.boolean(['h', 'V', 'H']) .describe({ 'h': 'display a short help message and exit', 'V': 'display version information and exit', 'H': 'enable couchjs cURL bindings (not implemented)' }) .usage('$0 '); function main() { 'use strict'; var main_js = opts.argv._[0]; if (!main_js) { return console.error(opts.help()); } log('couchjs/%s %s: %s', package_json.version, process.pid, main_js); if (process.env.COUCHJS_DEBUG_PORT) { inspector(+process.env.COUCHJS_DEBUG_PORT); } fs.readFile(main_js, 'utf8', function(er, body) { if (er) { throw er; } var stdin = new LineStream.v2(); stdin.on('readable', function() { var buf = stdin.read(); if (buf) { couchjs.stdin(buf); } }); stdin.on('end', function() { log('Terminate; connection to parent closed'); process.exit(0); }); process.stdin.setEncoding('utf8'); process.stdin.pipe(stdin); var main_func = Function(['print', 'readline', 'evalcx', 'gc', 'quit'], body); log('Call main'); new Fiber(function() { main_func(couchjs.print, couchjs.readline, couchjs.evalcx, couchjs.gc); }).run(); }); process.on('uncaughtException', function(er) { log('Error:\n%s', er.stack); }); } if (require.main === module) { main(); } apache-couchdb-1.5.0/src/couchjs-node/Makefile.am0000644000175000001440000000133612230722213016461 00000000000000## 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. EXTRA_DIST = \ cli.js \ console.js \ couchdb.js \ couchjs.js \ inspector.js \ package.json \ README.md \ sandbox.js \ stream.js \ test/experiment.js \ xml.js apache-couchdb-1.5.0/src/couchjs-node/Makefile.in0000644000175000001440000003041512230722243016475 00000000000000# Makefile.in generated by automake 1.11.6 from Makefile.am. # @configure_input@ # Copyright (C) 1994, 1995, 1996, 1997, 1998, 1999, 2000, 2001, 2002, # 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011 Free Software # Foundation, Inc. # This Makefile.in is free software; the Free Software Foundation # gives unlimited permission to copy and/or distribute it, # with or without modifications, as long as this notice is preserved. # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY, to the extent permitted by law; without # even the implied warranty of MERCHANTABILITY or FITNESS FOR A # PARTICULAR PURPOSE. @SET_MAKE@ VPATH = @srcdir@ am__make_dryrun = \ { \ am__dry=no; \ case $$MAKEFLAGS in \ *\\[\ \ ]*) \ echo 'am--echo: ; @echo "AM" OK' | $(MAKE) -f - 2>/dev/null \ | grep '^AM OK$$' >/dev/null || am__dry=yes;; \ *) \ for am__flg in $$MAKEFLAGS; do \ case $$am__flg in \ *=*|--*) ;; \ *n*) am__dry=yes; break;; \ esac; \ done;; \ esac; \ test $$am__dry = yes; \ } pkgdatadir = $(datadir)/@PACKAGE@ pkgincludedir = $(includedir)/@PACKAGE@ pkglibdir = $(libdir)/@PACKAGE@ pkglibexecdir = $(libexecdir)/@PACKAGE@ am__cd = CDPATH="$${ZSH_VERSION+.}$(PATH_SEPARATOR)" && cd install_sh_DATA = $(install_sh) -c -m 644 install_sh_PROGRAM = $(install_sh) -c install_sh_SCRIPT = $(install_sh) -c INSTALL_HEADER = $(INSTALL_DATA) transform = $(program_transform_name) NORMAL_INSTALL = : PRE_INSTALL = : POST_INSTALL = : NORMAL_UNINSTALL = : PRE_UNINSTALL = : POST_UNINSTALL = : build_triplet = @build@ host_triplet = @host@ subdir = src/couchjs-node DIST_COMMON = $(srcdir)/Makefile.am $(srcdir)/Makefile.in ACLOCAL_M4 = $(top_srcdir)/aclocal.m4 am__aclocal_m4_deps = $(top_srcdir)/m4/libtool.m4 \ $(top_srcdir)/m4/ltoptions.m4 $(top_srcdir)/m4/ltsugar.m4 \ $(top_srcdir)/m4/ltversion.m4 $(top_srcdir)/m4/lt~obsolete.m4 \ $(top_srcdir)/acinclude.m4 $(top_srcdir)/configure.ac am__configure_deps = $(am__aclocal_m4_deps) $(CONFIGURE_DEPENDENCIES) \ $(ACLOCAL_M4) mkinstalldirs = $(install_sh) -d CONFIG_HEADER = $(top_builddir)/config.h \ $(top_builddir)/src/snappy/google-snappy/config.h CONFIG_CLEAN_FILES = CONFIG_CLEAN_VPATH_FILES = SOURCES = DIST_SOURCES = am__can_run_installinfo = \ case $$AM_UPDATE_INFO_DIR in \ n|no|NO) false;; \ *) (install-info --version) >/dev/null 2>&1;; \ esac DISTFILES = $(DIST_COMMON) $(DIST_SOURCES) $(TEXINFOS) $(EXTRA_DIST) ACLOCAL = @ACLOCAL@ AMTAR = @AMTAR@ AR = @AR@ AS = @AS@ AUTOCONF = @AUTOCONF@ AUTOHEADER = @AUTOHEADER@ AUTOMAKE = @AUTOMAKE@ AWK = @AWK@ CC = @CC@ CCDEPMODE = @CCDEPMODE@ CFLAGS = @CFLAGS@ CPP = @CPP@ CPPFLAGS = @CPPFLAGS@ CURL_CFLAGS = @CURL_CFLAGS@ CURL_CONFIG = @CURL_CONFIG@ CURL_LIBS = @CURL_LIBS@ CXX = @CXX@ CXXCPP = @CXXCPP@ CXXDEPMODE = @CXXDEPMODE@ CXXFLAGS = @CXXFLAGS@ CYGPATH_W = @CYGPATH_W@ DEFS = @DEFS@ DEPDIR = @DEPDIR@ DLLTOOL = @DLLTOOL@ DSYMUTIL = @DSYMUTIL@ DUMPBIN = @DUMPBIN@ ECHO_C = @ECHO_C@ ECHO_N = @ECHO_N@ ECHO_T = @ECHO_T@ EGREP = @EGREP@ ERL = @ERL@ ERLANG_FLAGS = @ERLANG_FLAGS@ ERLC = @ERLC@ ERLC_FLAGS = @ERLC_FLAGS@ ESCRIPT = @ESCRIPT@ EXEEXT = @EXEEXT@ FGREP = @FGREP@ FLAGS = @FLAGS@ GREP = @GREP@ HAS_HELP2MAN = @HAS_HELP2MAN@ HAS_INSTALLINFO = @HAS_INSTALLINFO@ HAS_MAKEINFO = @HAS_MAKEINFO@ HAS_PDFLATEX = @HAS_PDFLATEX@ HAS_SPHINX_BUILD = @HAS_SPHINX_BUILD@ ICU_BIN = @ICU_BIN@ ICU_CFLAGS = @ICU_CFLAGS@ ICU_CONFIG = @ICU_CONFIG@ ICU_CPPFLAGS = @ICU_CPPFLAGS@ ICU_CXXFLAGS = @ICU_CXXFLAGS@ ICU_LIBS = @ICU_LIBS@ INNO_COMPILER_EXECUTABLE = @INNO_COMPILER_EXECUTABLE@ INSTALL = @INSTALL@ INSTALL_DATA = @INSTALL_DATA@ INSTALL_PROGRAM = @INSTALL_PROGRAM@ INSTALL_SCRIPT = @INSTALL_SCRIPT@ INSTALL_STRIP_PROGRAM = @INSTALL_STRIP_PROGRAM@ JS_CFLAGS = @JS_CFLAGS@ JS_LIBS = @JS_LIBS@ JS_LIB_BINARY = @JS_LIB_BINARY@ LD = @LD@ LDFLAGS = @LDFLAGS@ LIBOBJS = @LIBOBJS@ LIBS = @LIBS@ LIBTOOL = @LIBTOOL@ LIPO = @LIPO@ LN_S = @LN_S@ LTLIBOBJS = @LTLIBOBJS@ MAKEINFO = @MAKEINFO@ MANIFEST_TOOL = @MANIFEST_TOOL@ MKDIR_P = @MKDIR_P@ NM = @NM@ NMEDIT = @NMEDIT@ OBJDUMP = @OBJDUMP@ OBJEXT = @OBJEXT@ OTOOL = @OTOOL@ OTOOL64 = @OTOOL64@ PACKAGE = @PACKAGE@ PACKAGE_BUGREPORT = @PACKAGE_BUGREPORT@ PACKAGE_NAME = @PACKAGE_NAME@ PACKAGE_STRING = @PACKAGE_STRING@ PACKAGE_TARNAME = @PACKAGE_TARNAME@ PACKAGE_URL = @PACKAGE_URL@ PACKAGE_VERSION = @PACKAGE_VERSION@ PATH_SEPARATOR = @PATH_SEPARATOR@ PKG_CONFIG = @PKG_CONFIG@ PKG_CONFIG_LIBDIR = @PKG_CONFIG_LIBDIR@ PKG_CONFIG_PATH = @PKG_CONFIG_PATH@ RANLIB = @RANLIB@ SED = @SED@ SET_MAKE = @SET_MAKE@ SHELL = @SHELL@ SNAPPY_MAJOR = @SNAPPY_MAJOR@ SNAPPY_MINOR = @SNAPPY_MINOR@ SNAPPY_PATCHLEVEL = @SNAPPY_PATCHLEVEL@ STRIP = @STRIP@ VERSION = @VERSION@ abs_builddir = @abs_builddir@ abs_srcdir = @abs_srcdir@ abs_top_builddir = @abs_top_builddir@ abs_top_srcdir = @abs_top_srcdir@ ac_ct_AR = @ac_ct_AR@ ac_ct_CC = @ac_ct_CC@ ac_ct_CXX = @ac_ct_CXX@ ac_ct_DUMPBIN = @ac_ct_DUMPBIN@ ac_cv_have_stddef_h = @ac_cv_have_stddef_h@ ac_cv_have_stdint_h = @ac_cv_have_stdint_h@ am__include = @am__include@ am__leading_dot = @am__leading_dot@ am__quote = @am__quote@ am__tar = @am__tar@ am__untar = @am__untar@ bindir = @bindir@ bug_uri = @bug_uri@ build = @build@ build_alias = @build_alias@ build_cpu = @build_cpu@ build_os = @build_os@ build_vendor = @build_vendor@ builddir = @builddir@ datadir = @datadir@ datarootdir = @datarootdir@ docdir = @docdir@ dvidir = @dvidir@ erlangbin = @erlangbin@ erlangversion = @erlangversion@ exec_prefix = @exec_prefix@ host = @host@ host_alias = @host_alias@ host_cpu = @host_cpu@ host_os = @host_os@ host_vendor = @host_vendor@ htmldir = @htmldir@ includedir = @includedir@ infodir = @infodir@ initdir = @initdir@ install_sh = @install_sh@ launchddir = @launchddir@ libdir = @libdir@ libexecdir = @libexecdir@ localconfdir = @localconfdir@ localdatadir = @localdatadir@ localdocdir = @localdocdir@ localedir = @localedir@ localerlanglibdir = @localerlanglibdir@ locallibbindir = @locallibbindir@ locallibdir = @locallibdir@ localstatedir = @localstatedir@ localstatelibdir = @localstatelibdir@ localstatelogdir = @localstatelogdir@ localstaterundir = @localstaterundir@ mandir = @mandir@ mkdir_p = @mkdir_p@ msvc_redist_dir = @msvc_redist_dir@ msvc_redist_name = @msvc_redist_name@ oldincludedir = @oldincludedir@ openssl_bin_dir = @openssl_bin_dir@ otp_release = @otp_release@ package_author_address = @package_author_address@ package_author_name = @package_author_name@ package_identifier = @package_identifier@ package_name = @package_name@ package_tarname = @package_tarname@ pdfdir = @pdfdir@ prefix = @prefix@ program_transform_name = @program_transform_name@ psdir = @psdir@ sbindir = @sbindir@ sharedstatedir = @sharedstatedir@ srcdir = @srcdir@ sysconfdir = @sysconfdir@ target_alias = @target_alias@ top_build_prefix = @top_build_prefix@ top_builddir = @top_builddir@ top_srcdir = @top_srcdir@ version = @version@ version_major = @version_major@ version_minor = @version_minor@ version_release = @version_release@ version_revision = @version_revision@ version_stage = @version_stage@ EXTRA_DIST = \ cli.js \ console.js \ couchdb.js \ couchjs.js \ inspector.js \ package.json \ README.md \ sandbox.js \ stream.js \ test/experiment.js \ xml.js all: all-am .SUFFIXES: $(srcdir)/Makefile.in: $(srcdir)/Makefile.am $(am__configure_deps) @for dep in $?; do \ case '$(am__configure_deps)' in \ *$$dep*) \ ( cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh ) \ && { if test -f $@; then exit 0; else break; fi; }; \ exit 1;; \ esac; \ done; \ echo ' cd $(top_srcdir) && $(AUTOMAKE) --foreign src/couchjs-node/Makefile'; \ $(am__cd) $(top_srcdir) && \ $(AUTOMAKE) --foreign src/couchjs-node/Makefile .PRECIOUS: Makefile Makefile: $(srcdir)/Makefile.in $(top_builddir)/config.status @case '$?' in \ *config.status*) \ cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh;; \ *) \ echo ' cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ $(am__depfiles_maybe)'; \ cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ $(am__depfiles_maybe);; \ esac; $(top_builddir)/config.status: $(top_srcdir)/configure $(CONFIG_STATUS_DEPENDENCIES) cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh $(top_srcdir)/configure: $(am__configure_deps) cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh $(ACLOCAL_M4): $(am__aclocal_m4_deps) cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh $(am__aclocal_m4_deps): mostlyclean-libtool: -rm -f *.lo clean-libtool: -rm -rf .libs _libs tags: TAGS TAGS: ctags: CTAGS CTAGS: distdir: $(DISTFILES) @srcdirstrip=`echo "$(srcdir)" | sed 's/[].[^$$\\*]/\\\\&/g'`; \ topsrcdirstrip=`echo "$(top_srcdir)" | sed 's/[].[^$$\\*]/\\\\&/g'`; \ list='$(DISTFILES)'; \ dist_files=`for file in $$list; do echo $$file; done | \ sed -e "s|^$$srcdirstrip/||;t" \ -e "s|^$$topsrcdirstrip/|$(top_builddir)/|;t"`; \ case $$dist_files in \ */*) $(MKDIR_P) `echo "$$dist_files" | \ sed '/\//!d;s|^|$(distdir)/|;s,/[^/]*$$,,' | \ sort -u` ;; \ esac; \ for file in $$dist_files; do \ if test -f $$file || test -d $$file; then d=.; else d=$(srcdir); fi; \ if test -d $$d/$$file; then \ dir=`echo "/$$file" | sed -e 's,/[^/]*$$,,'`; \ if test -d "$(distdir)/$$file"; then \ find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} \;; \ fi; \ if test -d $(srcdir)/$$file && test $$d != $(srcdir); then \ cp -fpR $(srcdir)/$$file "$(distdir)$$dir" || exit 1; \ find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} \;; \ fi; \ cp -fpR $$d/$$file "$(distdir)$$dir" || exit 1; \ else \ test -f "$(distdir)/$$file" \ || cp -p $$d/$$file "$(distdir)/$$file" \ || exit 1; \ fi; \ done check-am: all-am check: check-am all-am: Makefile installdirs: install: install-am install-exec: install-exec-am install-data: install-data-am uninstall: uninstall-am install-am: all-am @$(MAKE) $(AM_MAKEFLAGS) install-exec-am install-data-am installcheck: installcheck-am install-strip: if test -z '$(STRIP)'; then \ $(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(INSTALL_STRIP_PROGRAM)" \ install_sh_PROGRAM="$(INSTALL_STRIP_PROGRAM)" INSTALL_STRIP_FLAG=-s \ install; \ else \ $(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(INSTALL_STRIP_PROGRAM)" \ install_sh_PROGRAM="$(INSTALL_STRIP_PROGRAM)" INSTALL_STRIP_FLAG=-s \ "INSTALL_PROGRAM_ENV=STRIPPROG='$(STRIP)'" install; \ fi mostlyclean-generic: clean-generic: distclean-generic: -test -z "$(CONFIG_CLEAN_FILES)" || rm -f $(CONFIG_CLEAN_FILES) -test . = "$(srcdir)" || test -z "$(CONFIG_CLEAN_VPATH_FILES)" || rm -f $(CONFIG_CLEAN_VPATH_FILES) maintainer-clean-generic: @echo "This command is intended for maintainers to use" @echo "it deletes files that may require special tools to rebuild." clean: clean-am clean-am: clean-generic clean-libtool mostlyclean-am distclean: distclean-am -rm -f Makefile distclean-am: clean-am distclean-generic dvi: dvi-am dvi-am: html: html-am html-am: info: info-am info-am: install-data-am: install-dvi: install-dvi-am install-dvi-am: install-exec-am: install-html: install-html-am install-html-am: install-info: install-info-am install-info-am: install-man: install-pdf: install-pdf-am install-pdf-am: install-ps: install-ps-am install-ps-am: installcheck-am: maintainer-clean: maintainer-clean-am -rm -f Makefile maintainer-clean-am: distclean-am maintainer-clean-generic mostlyclean: mostlyclean-am mostlyclean-am: mostlyclean-generic mostlyclean-libtool pdf: pdf-am pdf-am: ps: ps-am ps-am: uninstall-am: .MAKE: install-am install-strip .PHONY: all all-am check check-am clean clean-generic clean-libtool \ distclean distclean-generic distclean-libtool distdir dvi \ dvi-am html html-am info info-am install install-am \ install-data install-data-am install-dvi install-dvi-am \ install-exec install-exec-am install-html install-html-am \ install-info install-info-am install-man install-pdf \ install-pdf-am install-ps install-ps-am install-strip \ installcheck installcheck-am installdirs maintainer-clean \ maintainer-clean-generic mostlyclean mostlyclean-generic \ mostlyclean-libtool pdf pdf-am ps ps-am uninstall uninstall-am # Tell versions [3.59,3.63) of GNU make to not export all variables. # Otherwise a system limit (for SysV at least) may be exceeded. .NOEXPORT: apache-couchdb-1.5.0/src/couchjs-node/xml.js0000644000175000001440000000131012230722213015553 00000000000000// 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. function XML () { this.foo = 'bar'; } XML.prototype.toXMLString = function() { return '\n test\n'; }; module.exports = XML; apache-couchdb-1.5.0/src/couchjs-node/package.json0000644000175000001440000000162712230722213016716 00000000000000{ "name": "couchjs", "description": "Drop-in replacement for CouchDB JavaScript view server", "keywords": [ "couchdb", "couchjs" ], "version": "0.3.2", "author": "Jason Smith (http://www.iriscouch.com)", "repository": { "type":"git", "url":"https://github.com/iriscouch/couchjs" }, "engines": { "node": ">= 0.8" }, "main": "./couchjs.js", "bin": { "couchjs-node":"./cli.js" }, "couchdb": { "main":"./couchdb.js", "vhosts": [ "127.0.0.1.xip.io" ] }, "bundledDependencies": [ "node-inspector" ], "dependencies": { "optimist": "~0.3.4", "async" : "~0.2.5", "mkdirp" : "~0.3.4", "fibers" : "~1.0.0", "request" : "~2.9.203", "pushover": "~1.2.1", "defaultable": "~0.7.2", "node-inspector": "git://github.com/iriscouch/node-inspector#couchjs" }, "devDependencies": { "tap": "~0.2.5" } } apache-couchdb-1.5.0/src/erlang-oauth/0000755000175000001440000000000012230722306014512 500000000000000apache-couchdb-1.5.0/src/erlang-oauth/oauth.app.in0000644000175000001440000000050512230722213016656 00000000000000{application, oauth, [ {description, "Erlang OAuth implementation"}, {vsn, "7d85d3ef"}, {modules, [ oauth, oauth_hmac_sha1, oauth_http, oauth_plaintext, oauth_rsa_sha1, oauth_unix, oauth_uri ]}, {registered, []}, {applications, [ kernel, stdlib, crypto, inets ]} ]}. apache-couchdb-1.5.0/src/erlang-oauth/Makefile.am0000644000175000001440000000204712230722213016466 00000000000000## 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. oauthebindir = $(localerlanglibdir)/erlang-oauth/ebin oauth_file_collection = \ oauth.app.in \ oauth.erl # Removed oauth_rsa_sha1.beam until we require R12B5 or # we add a ./configure option to enable it. oauthebin_make_generated_file_list = \ oauth.app \ oauth.beam oauthebin_DATA = \ $(oauthebin_make_generated_file_list) EXTRA_DIST = \ $(oauth_file_collection) CLEANFILES = \ $(oauthebin_make_generated_file_list) %.app: %.app.in cp $< $@ %.beam: %.erl $(ERLC) $(ERLC_FLAGS) $< apache-couchdb-1.5.0/src/erlang-oauth/Makefile.in0000644000175000001440000003555412230722244016514 00000000000000# Makefile.in generated by automake 1.11.6 from Makefile.am. # @configure_input@ # Copyright (C) 1994, 1995, 1996, 1997, 1998, 1999, 2000, 2001, 2002, # 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011 Free Software # Foundation, Inc. # This Makefile.in is free software; the Free Software Foundation # gives unlimited permission to copy and/or distribute it, # with or without modifications, as long as this notice is preserved. # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY, to the extent permitted by law; without # even the implied warranty of MERCHANTABILITY or FITNESS FOR A # PARTICULAR PURPOSE. @SET_MAKE@ VPATH = @srcdir@ am__make_dryrun = \ { \ am__dry=no; \ case $$MAKEFLAGS in \ *\\[\ \ ]*) \ echo 'am--echo: ; @echo "AM" OK' | $(MAKE) -f - 2>/dev/null \ | grep '^AM OK$$' >/dev/null || am__dry=yes;; \ *) \ for am__flg in $$MAKEFLAGS; do \ case $$am__flg in \ *=*|--*) ;; \ *n*) am__dry=yes; break;; \ esac; \ done;; \ esac; \ test $$am__dry = yes; \ } pkgdatadir = $(datadir)/@PACKAGE@ pkgincludedir = $(includedir)/@PACKAGE@ pkglibdir = $(libdir)/@PACKAGE@ pkglibexecdir = $(libexecdir)/@PACKAGE@ am__cd = CDPATH="$${ZSH_VERSION+.}$(PATH_SEPARATOR)" && cd install_sh_DATA = $(install_sh) -c -m 644 install_sh_PROGRAM = $(install_sh) -c install_sh_SCRIPT = $(install_sh) -c INSTALL_HEADER = $(INSTALL_DATA) transform = $(program_transform_name) NORMAL_INSTALL = : PRE_INSTALL = : POST_INSTALL = : NORMAL_UNINSTALL = : PRE_UNINSTALL = : POST_UNINSTALL = : build_triplet = @build@ host_triplet = @host@ subdir = src/erlang-oauth DIST_COMMON = $(srcdir)/Makefile.am $(srcdir)/Makefile.in ACLOCAL_M4 = $(top_srcdir)/aclocal.m4 am__aclocal_m4_deps = $(top_srcdir)/m4/libtool.m4 \ $(top_srcdir)/m4/ltoptions.m4 $(top_srcdir)/m4/ltsugar.m4 \ $(top_srcdir)/m4/ltversion.m4 $(top_srcdir)/m4/lt~obsolete.m4 \ $(top_srcdir)/acinclude.m4 $(top_srcdir)/configure.ac am__configure_deps = $(am__aclocal_m4_deps) $(CONFIGURE_DEPENDENCIES) \ $(ACLOCAL_M4) mkinstalldirs = $(install_sh) -d CONFIG_HEADER = $(top_builddir)/config.h \ $(top_builddir)/src/snappy/google-snappy/config.h CONFIG_CLEAN_FILES = CONFIG_CLEAN_VPATH_FILES = SOURCES = DIST_SOURCES = am__can_run_installinfo = \ case $$AM_UPDATE_INFO_DIR in \ n|no|NO) false;; \ *) (install-info --version) >/dev/null 2>&1;; \ esac am__vpath_adj_setup = srcdirstrip=`echo "$(srcdir)" | sed 's|.|.|g'`; am__vpath_adj = case $$p in \ $(srcdir)/*) f=`echo "$$p" | sed "s|^$$srcdirstrip/||"`;; \ *) f=$$p;; \ esac; am__strip_dir = f=`echo $$p | sed -e 's|^.*/||'`; am__install_max = 40 am__nobase_strip_setup = \ srcdirstrip=`echo "$(srcdir)" | sed 's/[].[^$$\\*|]/\\\\&/g'` am__nobase_strip = \ for p in $$list; do echo "$$p"; done | sed -e "s|$$srcdirstrip/||" am__nobase_list = $(am__nobase_strip_setup); \ for p in $$list; do echo "$$p $$p"; done | \ sed "s| $$srcdirstrip/| |;"' / .*\//!s/ .*/ ./; s,\( .*\)/[^/]*$$,\1,' | \ $(AWK) 'BEGIN { files["."] = "" } { files[$$2] = files[$$2] " " $$1; \ if (++n[$$2] == $(am__install_max)) \ { print $$2, files[$$2]; n[$$2] = 0; files[$$2] = "" } } \ END { for (dir in files) print dir, files[dir] }' am__base_list = \ sed '$$!N;$$!N;$$!N;$$!N;$$!N;$$!N;$$!N;s/\n/ /g' | \ sed '$$!N;$$!N;$$!N;$$!N;s/\n/ /g' am__uninstall_files_from_dir = { \ test -z "$$files" \ || { test ! -d "$$dir" && test ! -f "$$dir" && test ! -r "$$dir"; } \ || { echo " ( cd '$$dir' && rm -f" $$files ")"; \ $(am__cd) "$$dir" && rm -f $$files; }; \ } am__installdirs = "$(DESTDIR)$(oauthebindir)" DATA = $(oauthebin_DATA) DISTFILES = $(DIST_COMMON) $(DIST_SOURCES) $(TEXINFOS) $(EXTRA_DIST) ACLOCAL = @ACLOCAL@ AMTAR = @AMTAR@ AR = @AR@ AS = @AS@ AUTOCONF = @AUTOCONF@ AUTOHEADER = @AUTOHEADER@ AUTOMAKE = @AUTOMAKE@ AWK = @AWK@ CC = @CC@ CCDEPMODE = @CCDEPMODE@ CFLAGS = @CFLAGS@ CPP = @CPP@ CPPFLAGS = @CPPFLAGS@ CURL_CFLAGS = @CURL_CFLAGS@ CURL_CONFIG = @CURL_CONFIG@ CURL_LIBS = @CURL_LIBS@ CXX = @CXX@ CXXCPP = @CXXCPP@ CXXDEPMODE = @CXXDEPMODE@ CXXFLAGS = @CXXFLAGS@ CYGPATH_W = @CYGPATH_W@ DEFS = @DEFS@ DEPDIR = @DEPDIR@ DLLTOOL = @DLLTOOL@ DSYMUTIL = @DSYMUTIL@ DUMPBIN = @DUMPBIN@ ECHO_C = @ECHO_C@ ECHO_N = @ECHO_N@ ECHO_T = @ECHO_T@ EGREP = @EGREP@ ERL = @ERL@ ERLANG_FLAGS = @ERLANG_FLAGS@ ERLC = @ERLC@ ERLC_FLAGS = @ERLC_FLAGS@ ESCRIPT = @ESCRIPT@ EXEEXT = @EXEEXT@ FGREP = @FGREP@ FLAGS = @FLAGS@ GREP = @GREP@ HAS_HELP2MAN = @HAS_HELP2MAN@ HAS_INSTALLINFO = @HAS_INSTALLINFO@ HAS_MAKEINFO = @HAS_MAKEINFO@ HAS_PDFLATEX = @HAS_PDFLATEX@ HAS_SPHINX_BUILD = @HAS_SPHINX_BUILD@ ICU_BIN = @ICU_BIN@ ICU_CFLAGS = @ICU_CFLAGS@ ICU_CONFIG = @ICU_CONFIG@ ICU_CPPFLAGS = @ICU_CPPFLAGS@ ICU_CXXFLAGS = @ICU_CXXFLAGS@ ICU_LIBS = @ICU_LIBS@ INNO_COMPILER_EXECUTABLE = @INNO_COMPILER_EXECUTABLE@ INSTALL = @INSTALL@ INSTALL_DATA = @INSTALL_DATA@ INSTALL_PROGRAM = @INSTALL_PROGRAM@ INSTALL_SCRIPT = @INSTALL_SCRIPT@ INSTALL_STRIP_PROGRAM = @INSTALL_STRIP_PROGRAM@ JS_CFLAGS = @JS_CFLAGS@ JS_LIBS = @JS_LIBS@ JS_LIB_BINARY = @JS_LIB_BINARY@ LD = @LD@ LDFLAGS = @LDFLAGS@ LIBOBJS = @LIBOBJS@ LIBS = @LIBS@ LIBTOOL = @LIBTOOL@ LIPO = @LIPO@ LN_S = @LN_S@ LTLIBOBJS = @LTLIBOBJS@ MAKEINFO = @MAKEINFO@ MANIFEST_TOOL = @MANIFEST_TOOL@ MKDIR_P = @MKDIR_P@ NM = @NM@ NMEDIT = @NMEDIT@ OBJDUMP = @OBJDUMP@ OBJEXT = @OBJEXT@ OTOOL = @OTOOL@ OTOOL64 = @OTOOL64@ PACKAGE = @PACKAGE@ PACKAGE_BUGREPORT = @PACKAGE_BUGREPORT@ PACKAGE_NAME = @PACKAGE_NAME@ PACKAGE_STRING = @PACKAGE_STRING@ PACKAGE_TARNAME = @PACKAGE_TARNAME@ PACKAGE_URL = @PACKAGE_URL@ PACKAGE_VERSION = @PACKAGE_VERSION@ PATH_SEPARATOR = @PATH_SEPARATOR@ PKG_CONFIG = @PKG_CONFIG@ PKG_CONFIG_LIBDIR = @PKG_CONFIG_LIBDIR@ PKG_CONFIG_PATH = @PKG_CONFIG_PATH@ RANLIB = @RANLIB@ SED = @SED@ SET_MAKE = @SET_MAKE@ SHELL = @SHELL@ SNAPPY_MAJOR = @SNAPPY_MAJOR@ SNAPPY_MINOR = @SNAPPY_MINOR@ SNAPPY_PATCHLEVEL = @SNAPPY_PATCHLEVEL@ STRIP = @STRIP@ VERSION = @VERSION@ abs_builddir = @abs_builddir@ abs_srcdir = @abs_srcdir@ abs_top_builddir = @abs_top_builddir@ abs_top_srcdir = @abs_top_srcdir@ ac_ct_AR = @ac_ct_AR@ ac_ct_CC = @ac_ct_CC@ ac_ct_CXX = @ac_ct_CXX@ ac_ct_DUMPBIN = @ac_ct_DUMPBIN@ ac_cv_have_stddef_h = @ac_cv_have_stddef_h@ ac_cv_have_stdint_h = @ac_cv_have_stdint_h@ am__include = @am__include@ am__leading_dot = @am__leading_dot@ am__quote = @am__quote@ am__tar = @am__tar@ am__untar = @am__untar@ bindir = @bindir@ bug_uri = @bug_uri@ build = @build@ build_alias = @build_alias@ build_cpu = @build_cpu@ build_os = @build_os@ build_vendor = @build_vendor@ builddir = @builddir@ datadir = @datadir@ datarootdir = @datarootdir@ docdir = @docdir@ dvidir = @dvidir@ erlangbin = @erlangbin@ erlangversion = @erlangversion@ exec_prefix = @exec_prefix@ host = @host@ host_alias = @host_alias@ host_cpu = @host_cpu@ host_os = @host_os@ host_vendor = @host_vendor@ htmldir = @htmldir@ includedir = @includedir@ infodir = @infodir@ initdir = @initdir@ install_sh = @install_sh@ launchddir = @launchddir@ libdir = @libdir@ libexecdir = @libexecdir@ localconfdir = @localconfdir@ localdatadir = @localdatadir@ localdocdir = @localdocdir@ localedir = @localedir@ localerlanglibdir = @localerlanglibdir@ locallibbindir = @locallibbindir@ locallibdir = @locallibdir@ localstatedir = @localstatedir@ localstatelibdir = @localstatelibdir@ localstatelogdir = @localstatelogdir@ localstaterundir = @localstaterundir@ mandir = @mandir@ mkdir_p = @mkdir_p@ msvc_redist_dir = @msvc_redist_dir@ msvc_redist_name = @msvc_redist_name@ oldincludedir = @oldincludedir@ openssl_bin_dir = @openssl_bin_dir@ otp_release = @otp_release@ package_author_address = @package_author_address@ package_author_name = @package_author_name@ package_identifier = @package_identifier@ package_name = @package_name@ package_tarname = @package_tarname@ pdfdir = @pdfdir@ prefix = @prefix@ program_transform_name = @program_transform_name@ psdir = @psdir@ sbindir = @sbindir@ sharedstatedir = @sharedstatedir@ srcdir = @srcdir@ sysconfdir = @sysconfdir@ target_alias = @target_alias@ top_build_prefix = @top_build_prefix@ top_builddir = @top_builddir@ top_srcdir = @top_srcdir@ version = @version@ version_major = @version_major@ version_minor = @version_minor@ version_release = @version_release@ version_revision = @version_revision@ version_stage = @version_stage@ oauthebindir = $(localerlanglibdir)/erlang-oauth/ebin oauth_file_collection = \ oauth.app.in \ oauth.erl # Removed oauth_rsa_sha1.beam until we require R12B5 or # we add a ./configure option to enable it. oauthebin_make_generated_file_list = \ oauth.app \ oauth.beam oauthebin_DATA = \ $(oauthebin_make_generated_file_list) EXTRA_DIST = \ $(oauth_file_collection) CLEANFILES = \ $(oauthebin_make_generated_file_list) all: all-am .SUFFIXES: $(srcdir)/Makefile.in: $(srcdir)/Makefile.am $(am__configure_deps) @for dep in $?; do \ case '$(am__configure_deps)' in \ *$$dep*) \ ( cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh ) \ && { if test -f $@; then exit 0; else break; fi; }; \ exit 1;; \ esac; \ done; \ echo ' cd $(top_srcdir) && $(AUTOMAKE) --foreign src/erlang-oauth/Makefile'; \ $(am__cd) $(top_srcdir) && \ $(AUTOMAKE) --foreign src/erlang-oauth/Makefile .PRECIOUS: Makefile Makefile: $(srcdir)/Makefile.in $(top_builddir)/config.status @case '$?' in \ *config.status*) \ cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh;; \ *) \ echo ' cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ $(am__depfiles_maybe)'; \ cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ $(am__depfiles_maybe);; \ esac; $(top_builddir)/config.status: $(top_srcdir)/configure $(CONFIG_STATUS_DEPENDENCIES) cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh $(top_srcdir)/configure: $(am__configure_deps) cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh $(ACLOCAL_M4): $(am__aclocal_m4_deps) cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh $(am__aclocal_m4_deps): mostlyclean-libtool: -rm -f *.lo clean-libtool: -rm -rf .libs _libs install-oauthebinDATA: $(oauthebin_DATA) @$(NORMAL_INSTALL) @list='$(oauthebin_DATA)'; test -n "$(oauthebindir)" || list=; \ if test -n "$$list"; then \ echo " $(MKDIR_P) '$(DESTDIR)$(oauthebindir)'"; \ $(MKDIR_P) "$(DESTDIR)$(oauthebindir)" || exit 1; \ fi; \ for p in $$list; do \ if test -f "$$p"; then d=; else d="$(srcdir)/"; fi; \ echo "$$d$$p"; \ done | $(am__base_list) | \ while read files; do \ echo " $(INSTALL_DATA) $$files '$(DESTDIR)$(oauthebindir)'"; \ $(INSTALL_DATA) $$files "$(DESTDIR)$(oauthebindir)" || exit $$?; \ done uninstall-oauthebinDATA: @$(NORMAL_UNINSTALL) @list='$(oauthebin_DATA)'; test -n "$(oauthebindir)" || list=; \ files=`for p in $$list; do echo $$p; done | sed -e 's|^.*/||'`; \ dir='$(DESTDIR)$(oauthebindir)'; $(am__uninstall_files_from_dir) tags: TAGS TAGS: ctags: CTAGS CTAGS: distdir: $(DISTFILES) @srcdirstrip=`echo "$(srcdir)" | sed 's/[].[^$$\\*]/\\\\&/g'`; \ topsrcdirstrip=`echo "$(top_srcdir)" | sed 's/[].[^$$\\*]/\\\\&/g'`; \ list='$(DISTFILES)'; \ dist_files=`for file in $$list; do echo $$file; done | \ sed -e "s|^$$srcdirstrip/||;t" \ -e "s|^$$topsrcdirstrip/|$(top_builddir)/|;t"`; \ case $$dist_files in \ */*) $(MKDIR_P) `echo "$$dist_files" | \ sed '/\//!d;s|^|$(distdir)/|;s,/[^/]*$$,,' | \ sort -u` ;; \ esac; \ for file in $$dist_files; do \ if test -f $$file || test -d $$file; then d=.; else d=$(srcdir); fi; \ if test -d $$d/$$file; then \ dir=`echo "/$$file" | sed -e 's,/[^/]*$$,,'`; \ if test -d "$(distdir)/$$file"; then \ find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} \;; \ fi; \ if test -d $(srcdir)/$$file && test $$d != $(srcdir); then \ cp -fpR $(srcdir)/$$file "$(distdir)$$dir" || exit 1; \ find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} \;; \ fi; \ cp -fpR $$d/$$file "$(distdir)$$dir" || exit 1; \ else \ test -f "$(distdir)/$$file" \ || cp -p $$d/$$file "$(distdir)/$$file" \ || exit 1; \ fi; \ done check-am: all-am check: check-am all-am: Makefile $(DATA) installdirs: for dir in "$(DESTDIR)$(oauthebindir)"; do \ test -z "$$dir" || $(MKDIR_P) "$$dir"; \ done install: install-am install-exec: install-exec-am install-data: install-data-am uninstall: uninstall-am install-am: all-am @$(MAKE) $(AM_MAKEFLAGS) install-exec-am install-data-am installcheck: installcheck-am install-strip: if test -z '$(STRIP)'; then \ $(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(INSTALL_STRIP_PROGRAM)" \ install_sh_PROGRAM="$(INSTALL_STRIP_PROGRAM)" INSTALL_STRIP_FLAG=-s \ install; \ else \ $(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(INSTALL_STRIP_PROGRAM)" \ install_sh_PROGRAM="$(INSTALL_STRIP_PROGRAM)" INSTALL_STRIP_FLAG=-s \ "INSTALL_PROGRAM_ENV=STRIPPROG='$(STRIP)'" install; \ fi mostlyclean-generic: clean-generic: -test -z "$(CLEANFILES)" || rm -f $(CLEANFILES) distclean-generic: -test -z "$(CONFIG_CLEAN_FILES)" || rm -f $(CONFIG_CLEAN_FILES) -test . = "$(srcdir)" || test -z "$(CONFIG_CLEAN_VPATH_FILES)" || rm -f $(CONFIG_CLEAN_VPATH_FILES) maintainer-clean-generic: @echo "This command is intended for maintainers to use" @echo "it deletes files that may require special tools to rebuild." clean: clean-am clean-am: clean-generic clean-libtool mostlyclean-am distclean: distclean-am -rm -f Makefile distclean-am: clean-am distclean-generic dvi: dvi-am dvi-am: html: html-am html-am: info: info-am info-am: install-data-am: install-oauthebinDATA install-dvi: install-dvi-am install-dvi-am: install-exec-am: install-html: install-html-am install-html-am: install-info: install-info-am install-info-am: install-man: install-pdf: install-pdf-am install-pdf-am: install-ps: install-ps-am install-ps-am: installcheck-am: maintainer-clean: maintainer-clean-am -rm -f Makefile maintainer-clean-am: distclean-am maintainer-clean-generic mostlyclean: mostlyclean-am mostlyclean-am: mostlyclean-generic mostlyclean-libtool pdf: pdf-am pdf-am: ps: ps-am ps-am: uninstall-am: uninstall-oauthebinDATA .MAKE: install-am install-strip .PHONY: all all-am check check-am clean clean-generic clean-libtool \ distclean distclean-generic distclean-libtool distdir dvi \ dvi-am html html-am info info-am install install-am \ install-data install-data-am install-dvi install-dvi-am \ install-exec install-exec-am install-html install-html-am \ install-info install-info-am install-man install-oauthebinDATA \ install-pdf install-pdf-am install-ps install-ps-am \ install-strip installcheck installcheck-am installdirs \ maintainer-clean maintainer-clean-generic mostlyclean \ mostlyclean-generic mostlyclean-libtool pdf pdf-am ps ps-am \ uninstall uninstall-am uninstall-oauthebinDATA %.app: %.app.in cp $< $@ %.beam: %.erl $(ERLC) $(ERLC_FLAGS) $< # Tell versions [3.59,3.63) of GNU make to not export all variables. # Otherwise a system limit (for SysV at least) may be exceeded. .NOEXPORT: apache-couchdb-1.5.0/src/erlang-oauth/oauth.erl0000644000175000001440000002520512230722213016257 00000000000000-module(oauth). -export([get/3, get/5, get/6, post/3, post/5, post/6, put/6, put/7, uri/2, header/1, sign/6, params_decode/1, token/1, token_secret/1, verify/6]). -export([plaintext_signature/2, hmac_sha1_signature/5, hmac_sha1_signature/3, rsa_sha1_signature/4, rsa_sha1_signature/2, signature_base_string/3, params_encode/1]). -export([plaintext_verify/3, hmac_sha1_verify/6, hmac_sha1_verify/4, rsa_sha1_verify/5, rsa_sha1_verify/3]). -export([header_params_encode/1, header_params_decode/1, uri_params_encode/1, uri_params_decode/1]). -include_lib("public_key/include/public_key.hrl"). get(URL, ExtraParams, Consumer) -> get(URL, ExtraParams, Consumer, "", ""). get(URL, ExtraParams, Consumer, Token, TokenSecret) -> get(URL, ExtraParams, Consumer, Token, TokenSecret, []). get(URL, ExtraParams, Consumer, Token, TokenSecret, HttpcOptions) -> SignedParams = sign("GET", URL, ExtraParams, Consumer, Token, TokenSecret), http_request(get, {uri(URL, SignedParams), []}, HttpcOptions). post(URL, ExtraParams, Consumer) -> post(URL, ExtraParams, Consumer, "", ""). post(URL, ExtraParams, Consumer, Token, TokenSecret) -> post(URL, ExtraParams, Consumer, Token, TokenSecret, []). post(URL, ExtraParams, Consumer, Token, TokenSecret, HttpcOptions) -> SignedParams = sign("POST", URL, ExtraParams, Consumer, Token, TokenSecret), http_request(post, {URL, [], "application/x-www-form-urlencoded", uri_params_encode(SignedParams)}, HttpcOptions). put(URL, ExtraParams, {ContentType, Body}, Consumer, Token, TokenSecret) -> put(URL, ExtraParams, {ContentType, Body}, Consumer, Token, TokenSecret, []). put(URL, ExtraParams, {ContentType, Body}, Consumer, Token, TokenSecret, HttpcOptions) -> SignedParams = sign("PUT", URL, ExtraParams, Consumer, Token, TokenSecret), http_request(put, {uri(URL, SignedParams), [], ContentType, Body}, HttpcOptions). uri(Base, []) -> Base; uri(Base, Params) -> lists:concat([Base, "?", uri_params_encode(Params)]). header(Params) -> {"Authorization", "OAuth " ++ header_params_encode(Params)}. token(Params) -> proplists:get_value("oauth_token", Params). token_secret(Params) -> proplists:get_value("oauth_token_secret", Params). consumer_key(_Consumer={Key, _, _}) -> Key. consumer_secret(_Consumer={_, Secret, _}) -> Secret. signature_method(_Consumer={_, _, Method}) -> Method. sign(HttpMethod, URL, Params, Consumer, Token, TokenSecret) -> SignatureParams = signature_params(Consumer, Params, Token), Signature = signature(HttpMethod, URL, SignatureParams, Consumer, TokenSecret), [{"oauth_signature", Signature} | SignatureParams]. signature_params(Consumer, Params, "") -> signature_params(Consumer, Params); signature_params(Consumer, Params, Token) -> signature_params(Consumer, [{"oauth_token", Token} | Params]). signature_params(Consumer, Params) -> Timestamp = unix_timestamp(), Nonce = base64:encode_to_string(crypto:rand_bytes(32)), % cf. ruby-oauth [ {"oauth_version", "1.0"} , {"oauth_nonce", Nonce} , {"oauth_timestamp", integer_to_list(Timestamp)} , {"oauth_signature_method", signature_method_string(Consumer)} , {"oauth_consumer_key", consumer_key(Consumer)} | Params ]. verify(Signature, HttpMethod, URL, Params, Consumer, TokenSecret) -> case signature_method(Consumer) of plaintext -> plaintext_verify(Signature, Consumer, TokenSecret); hmac_sha1 -> hmac_sha1_verify(Signature, HttpMethod, URL, Params, Consumer, TokenSecret); rsa_sha1 -> rsa_sha1_verify(Signature, HttpMethod, URL, Params, Consumer) end. signature(HttpMethod, URL, Params, Consumer, TokenSecret) -> case signature_method(Consumer) of plaintext -> plaintext_signature(Consumer, TokenSecret); hmac_sha1 -> hmac_sha1_signature(HttpMethod, URL, Params, Consumer, TokenSecret); rsa_sha1 -> rsa_sha1_signature(HttpMethod, URL, Params, Consumer) end. signature_method_string(Consumer) -> case signature_method(Consumer) of plaintext -> "PLAINTEXT"; hmac_sha1 -> "HMAC-SHA1"; rsa_sha1 -> "RSA-SHA1" end. plaintext_signature(Consumer, TokenSecret) -> uri_join([consumer_secret(Consumer), TokenSecret]). plaintext_verify(Signature, Consumer, TokenSecret) -> verify_in_constant_time(Signature, plaintext_signature(Consumer, TokenSecret)). hmac_sha1_signature(HttpMethod, URL, Params, Consumer, TokenSecret) -> BaseString = signature_base_string(HttpMethod, URL, Params), hmac_sha1_signature(BaseString, Consumer, TokenSecret). hmac_sha1_signature(BaseString, Consumer, TokenSecret) -> Key = uri_join([consumer_secret(Consumer), TokenSecret]), base64:encode_to_string(crypto:sha_mac(Key, BaseString)). hmac_sha1_verify(Signature, HttpMethod, URL, Params, Consumer, TokenSecret) -> verify_in_constant_time(Signature, hmac_sha1_signature(HttpMethod, URL, Params, Consumer, TokenSecret)). hmac_sha1_verify(Signature, BaseString, Consumer, TokenSecret) -> verify_in_constant_time(Signature, hmac_sha1_signature(BaseString, Consumer, TokenSecret)). rsa_sha1_signature(HttpMethod, URL, Params, Consumer) -> BaseString = signature_base_string(HttpMethod, URL, Params), rsa_sha1_signature(BaseString, Consumer). rsa_sha1_signature(BaseString, Consumer) -> Key = read_private_key(consumer_secret(Consumer)), base64:encode_to_string(public_key:sign(list_to_binary(BaseString), sha, Key)). rsa_sha1_verify(Signature, HttpMethod, URL, Params, Consumer) -> BaseString = signature_base_string(HttpMethod, URL, Params), rsa_sha1_verify(Signature, BaseString, Consumer). rsa_sha1_verify(Signature, BaseString, Consumer) -> Key = read_cert_key(consumer_secret(Consumer)), public_key:verify(to_binary(BaseString), sha, base64:decode(Signature), Key). verify_in_constant_time(<>, <>) -> verify_in_constant_time(binary_to_list(X), binary_to_list(Y)); verify_in_constant_time(X, Y) when is_list(X) and is_list(Y) -> case length(X) == length(Y) of true -> verify_in_constant_time(X, Y, 0); false -> false end. verify_in_constant_time([X | RestX], [Y | RestY], Result) -> verify_in_constant_time(RestX, RestY, (X bxor Y) bor Result); verify_in_constant_time([], [], Result) -> Result == 0. signature_base_string(HttpMethod, URL, Params) -> uri_join([HttpMethod, uri_normalize(URL), params_encode(Params)]). params_encode(Params) -> % cf. http://tools.ietf.org/html/rfc5849#section-3.4.1.3.2 Encoded = [{uri_encode(K), uri_encode(V)} || {K, V} <- Params], Sorted = lists:sort(Encoded), Concatenated = [lists:concat([K, "=", V]) || {K, V} <- Sorted], string:join(Concatenated, "&"). params_decode(_Response={{_, _, _}, _, Body}) -> uri_params_decode(Body). http_request(Method, Request, Options) -> httpc:request(Method, Request, [{autoredirect, false}], Options). unix_timestamp() -> unix_timestamp(calendar:universal_time()). unix_timestamp(DateTime) -> unix_seconds(DateTime) - unix_epoch(). unix_epoch() -> unix_seconds({{1970,1,1},{00,00,00}}). unix_seconds(DateTime) -> calendar:datetime_to_gregorian_seconds(DateTime). read_cert_key(Path) when is_list(Path) -> {ok, Contents} = file:read_file(Path), [{'Certificate', DerCert, not_encrypted}] = public_key:pem_decode(Contents), read_cert_key(public_key:pkix_decode_cert(DerCert, otp)); read_cert_key(#'OTPCertificate'{tbsCertificate=Cert}) -> read_cert_key(Cert); read_cert_key(#'OTPTBSCertificate'{subjectPublicKeyInfo=Info}) -> read_cert_key(Info); read_cert_key(#'OTPSubjectPublicKeyInfo'{subjectPublicKey=Key}) -> Key. read_private_key(Path) -> {ok, Contents} = file:read_file(Path), [Info] = public_key:pem_decode(Contents), public_key:pem_entry_decode(Info). to_binary(Term) when is_list(Term) -> list_to_binary(Term); to_binary(Term) when is_binary(Term) -> Term. header_params_encode(Params) -> intercalate(", ", [lists:concat([uri_encode(K), "=\"", uri_encode(V), "\""]) || {K, V} <- Params]). header_params_decode(String) -> [header_param_decode(Param) || Param <- re:split(String, ",\\s*", [{return, list}]), Param =/= ""]. header_param_decode(Param) -> [Key, QuotedValue] = string:tokens(Param, "="), Value = string:substr(QuotedValue, 2, length(QuotedValue) - 2), {uri_decode(Key), uri_decode(Value)}. uri_normalize(URI) -> case http_uri:parse(URI) of {ok, {Scheme, UserInfo, Host, Port, Path, _Query}} -> % R15B uri_normalize(Scheme, UserInfo, string:to_lower(Host), Port, [Path]); {Scheme, UserInfo, Host, Port, Path, _Query} -> uri_normalize(Scheme, UserInfo, string:to_lower(Host), Port, [Path]); Else -> Else end. uri_normalize(http, UserInfo, Host, 80, Acc) -> uri_normalize(http, UserInfo, [Host|Acc]); uri_normalize(https, UserInfo, Host, 443, Acc) -> uri_normalize(https, UserInfo, [Host|Acc]); uri_normalize(Scheme, UserInfo, Host, Port, Acc) -> uri_normalize(Scheme, UserInfo, [Host, ":", Port|Acc]). uri_normalize(Scheme, [], Acc) -> lists:concat([Scheme, "://" | Acc]); uri_normalize(Scheme, UserInfo, Acc) -> lists:concat([Scheme, "://", UserInfo, "@" | Acc]). uri_params_encode(Params) -> intercalate("&", [uri_join([K, V], "=") || {K, V} <- Params]). uri_params_decode(String) -> [uri_param_decode(Substring) || Substring <- string:tokens(String, "&")]. uri_param_decode(String) -> [Key, Value] = string:tokens(String, "="), {uri_decode(Key), uri_decode(Value)}. uri_join(Values) -> uri_join(Values, "&"). uri_join(Values, Separator) -> string:join([uri_encode(Value) || Value <- Values], Separator). intercalate(Sep, Xs) -> lists:concat(intersperse(Sep, Xs)). intersperse(_, []) -> []; intersperse(_, [X]) -> [X]; intersperse(Sep, [X | Xs]) -> [X, Sep | intersperse(Sep, Xs)]. uri_encode(Term) when is_integer(Term) -> integer_to_list(Term); uri_encode(Term) when is_atom(Term) -> uri_encode(atom_to_list(Term)); uri_encode(Term) when is_list(Term) -> uri_encode(lists:reverse(Term, []), []). -define(is_alphanum(C), C >= $A, C =< $Z; C >= $a, C =< $z; C >= $0, C =< $9). uri_encode([X | T], Acc) when ?is_alphanum(X); X =:= $-; X =:= $_; X =:= $.; X =:= $~ -> uri_encode(T, [X | Acc]); uri_encode([X | T], Acc) -> NewAcc = [$%, dec2hex(X bsr 4), dec2hex(X band 16#0f) | Acc], uri_encode(T, NewAcc); uri_encode([], Acc) -> Acc. uri_decode(Str) when is_list(Str) -> uri_decode(Str, []). uri_decode([$%, A, B | T], Acc) -> uri_decode(T, [(hex2dec(A) bsl 4) + hex2dec(B) | Acc]); uri_decode([X | T], Acc) -> uri_decode(T, [X | Acc]); uri_decode([], Acc) -> lists:reverse(Acc, []). -compile({inline, [{dec2hex, 1}, {hex2dec, 1}]}). dec2hex(N) when N >= 10 andalso N =< 15 -> N + $A - 10; dec2hex(N) when N >= 0 andalso N =< 9 -> N + $0. hex2dec(C) when C >= $A andalso C =< $F -> C - $A + 10; hex2dec(C) when C >= $0 andalso C =< $9 -> C - $0. apache-couchdb-1.5.0/src/mochiweb/0000755000175000001440000000000012230722306013721 500000000000000apache-couchdb-1.5.0/src/mochiweb/mochifmt_std.erl0000644000175000001440000000142112230722213017020 00000000000000%% @author Bob Ippolito %% @copyright 2008 Mochi Media, Inc. %% @doc Template module for a mochifmt formatter. -module(mochifmt_std). -author('bob@mochimedia.com'). -export([new/0, format/3, get_value/3, format_field/3, get_field/3, convert_field/3]). new() -> {?MODULE}. format(Format, Args, {?MODULE}=THIS) -> mochifmt:format(Format, Args, THIS). get_field(Key, Args, {?MODULE}=THIS) -> mochifmt:get_field(Key, Args, THIS). convert_field(Key, Args, {?MODULE}) -> mochifmt:convert_field(Key, Args). get_value(Key, Args, {?MODULE}) -> mochifmt:get_value(Key, Args). format_field(Arg, Format, {?MODULE}=THIS) -> mochifmt:format_field(Arg, Format, THIS). %% %% Tests %% -ifdef(TEST). -include_lib("eunit/include/eunit.hrl"). -endif. apache-couchdb-1.5.0/src/mochiweb/mochiweb_html.erl0000644000175000001440000014050412230722213017167 00000000000000%% @author Bob Ippolito %% @copyright 2007 Mochi Media, Inc. %% @doc Loosely tokenizes and generates parse trees for HTML 4. -module(mochiweb_html). -export([tokens/1, parse/1, parse_tokens/1, to_tokens/1, escape/1, escape_attr/1, to_html/1]). %% This is a macro to placate syntax highlighters.. -define(QUOTE, $\"). -define(SQUOTE, $\'). -define(ADV_COL(S, N), S#decoder{column=N+S#decoder.column, offset=N+S#decoder.offset}). -define(INC_COL(S), S#decoder{column=1+S#decoder.column, offset=1+S#decoder.offset}). -define(INC_LINE(S), S#decoder{column=1, line=1+S#decoder.line, offset=1+S#decoder.offset}). -define(INC_CHAR(S, C), case C of $\n -> S#decoder{column=1, line=1+S#decoder.line, offset=1+S#decoder.offset}; _ -> S#decoder{column=1+S#decoder.column, offset=1+S#decoder.offset} end). -define(IS_WHITESPACE(C), (C =:= $\s orelse C =:= $\t orelse C =:= $\r orelse C =:= $\n)). -define(IS_LITERAL_SAFE(C), ((C >= $A andalso C =< $Z) orelse (C >= $a andalso C =< $z) orelse (C >= $0 andalso C =< $9))). -define(PROBABLE_CLOSE(C), (C =:= $> orelse ?IS_WHITESPACE(C))). -record(decoder, {line=1, column=1, offset=0}). %% @type html_node() = {string(), [html_attr()], [html_node() | string()]} %% @type html_attr() = {string(), string()} %% @type html_token() = html_data() | start_tag() | end_tag() | inline_html() | html_comment() | html_doctype() %% @type html_data() = {data, string(), Whitespace::boolean()} %% @type start_tag() = {start_tag, Name, [html_attr()], Singleton::boolean()} %% @type end_tag() = {end_tag, Name} %% @type html_comment() = {comment, Comment} %% @type html_doctype() = {doctype, [Doctype]} %% @type inline_html() = {'=', iolist()} %% External API. %% @spec parse(string() | binary()) -> html_node() %% @doc tokenize and then transform the token stream into a HTML tree. parse(Input) -> parse_tokens(tokens(Input)). %% @spec parse_tokens([html_token()]) -> html_node() %% @doc Transform the output of tokens(Doc) into a HTML tree. parse_tokens(Tokens) when is_list(Tokens) -> %% Skip over doctype, processing instructions F = fun (X) -> case X of {start_tag, _, _, false} -> false; _ -> true end end, [{start_tag, Tag, Attrs, false} | Rest] = lists:dropwhile(F, Tokens), {Tree, _} = tree(Rest, [norm({Tag, Attrs})]), Tree. %% @spec tokens(StringOrBinary) -> [html_token()] %% @doc Transform the input UTF-8 HTML into a token stream. tokens(Input) -> tokens(iolist_to_binary(Input), #decoder{}, []). %% @spec to_tokens(html_node()) -> [html_token()] %% @doc Convert a html_node() tree to a list of tokens. to_tokens({Tag0}) -> to_tokens({Tag0, [], []}); to_tokens(T={'=', _}) -> [T]; to_tokens(T={doctype, _}) -> [T]; to_tokens(T={comment, _}) -> [T]; to_tokens({Tag0, Acc}) -> %% This is only allowed in sub-tags: {p, [{"class", "foo"}]} to_tokens({Tag0, [], Acc}); to_tokens({Tag0, Attrs, Acc}) -> Tag = to_tag(Tag0), case is_singleton(Tag) of true -> to_tokens([], [{start_tag, Tag, Attrs, true}]); false -> to_tokens([{Tag, Acc}], [{start_tag, Tag, Attrs, false}]) end. %% @spec to_html([html_token()] | html_node()) -> iolist() %% @doc Convert a list of html_token() to a HTML document. to_html(Node) when is_tuple(Node) -> to_html(to_tokens(Node)); to_html(Tokens) when is_list(Tokens) -> to_html(Tokens, []). %% @spec escape(string() | atom() | binary()) -> binary() %% @doc Escape a string such that it's safe for HTML (amp; lt; gt;). escape(B) when is_binary(B) -> escape(binary_to_list(B), []); escape(A) when is_atom(A) -> escape(atom_to_list(A), []); escape(S) when is_list(S) -> escape(S, []). %% @spec escape_attr(string() | binary() | atom() | integer() | float()) -> binary() %% @doc Escape a string such that it's safe for HTML attrs %% (amp; lt; gt; quot;). escape_attr(B) when is_binary(B) -> escape_attr(binary_to_list(B), []); escape_attr(A) when is_atom(A) -> escape_attr(atom_to_list(A), []); escape_attr(S) when is_list(S) -> escape_attr(S, []); escape_attr(I) when is_integer(I) -> escape_attr(integer_to_list(I), []); escape_attr(F) when is_float(F) -> escape_attr(mochinum:digits(F), []). to_html([], Acc) -> lists:reverse(Acc); to_html([{'=', Content} | Rest], Acc) -> to_html(Rest, [Content | Acc]); to_html([{pi, Bin} | Rest], Acc) -> Open = [<<">, Bin, <<"?>">>], to_html(Rest, [Open | Acc]); to_html([{pi, Tag, Attrs} | Rest], Acc) -> Open = [<<">, Tag, attrs_to_html(Attrs, []), <<"?>">>], to_html(Rest, [Open | Acc]); to_html([{comment, Comment} | Rest], Acc) -> to_html(Rest, [[<<"">>] | Acc]); to_html([{doctype, Parts} | Rest], Acc) -> Inside = doctype_to_html(Parts, Acc), to_html(Rest, [[<<">, Inside, <<">">>] | Acc]); to_html([{data, Data, _Whitespace} | Rest], Acc) -> to_html(Rest, [escape(Data) | Acc]); to_html([{start_tag, Tag, Attrs, Singleton} | Rest], Acc) -> Open = [<<"<">>, Tag, attrs_to_html(Attrs, []), case Singleton of true -> <<" />">>; false -> <<">">> end], to_html(Rest, [Open | Acc]); to_html([{end_tag, Tag} | Rest], Acc) -> to_html(Rest, [[<<">, Tag, <<">">>] | Acc]). doctype_to_html([], Acc) -> lists:reverse(Acc); doctype_to_html([Word | Rest], Acc) -> case lists:all(fun (C) -> ?IS_LITERAL_SAFE(C) end, binary_to_list(iolist_to_binary(Word))) of true -> doctype_to_html(Rest, [[<<" ">>, Word] | Acc]); false -> doctype_to_html(Rest, [[<<" \"">>, escape_attr(Word), ?QUOTE] | Acc]) end. attrs_to_html([], Acc) -> lists:reverse(Acc); attrs_to_html([{K, V} | Rest], Acc) -> attrs_to_html(Rest, [[<<" ">>, escape(K), <<"=\"">>, escape_attr(V), <<"\"">>] | Acc]). escape([], Acc) -> list_to_binary(lists:reverse(Acc)); escape("<" ++ Rest, Acc) -> escape(Rest, lists:reverse("<", Acc)); escape(">" ++ Rest, Acc) -> escape(Rest, lists:reverse(">", Acc)); escape("&" ++ Rest, Acc) -> escape(Rest, lists:reverse("&", Acc)); escape([C | Rest], Acc) -> escape(Rest, [C | Acc]). escape_attr([], Acc) -> list_to_binary(lists:reverse(Acc)); escape_attr("<" ++ Rest, Acc) -> escape_attr(Rest, lists:reverse("<", Acc)); escape_attr(">" ++ Rest, Acc) -> escape_attr(Rest, lists:reverse(">", Acc)); escape_attr("&" ++ Rest, Acc) -> escape_attr(Rest, lists:reverse("&", Acc)); escape_attr([?QUOTE | Rest], Acc) -> escape_attr(Rest, lists:reverse(""", Acc)); escape_attr([C | Rest], Acc) -> escape_attr(Rest, [C | Acc]). to_tag(A) when is_atom(A) -> norm(atom_to_list(A)); to_tag(L) -> norm(L). to_tokens([], Acc) -> lists:reverse(Acc); to_tokens([{Tag, []} | Rest], Acc) -> to_tokens(Rest, [{end_tag, to_tag(Tag)} | Acc]); to_tokens([{Tag0, [{T0} | R1]} | Rest], Acc) -> %% Allow {br} to_tokens([{Tag0, [{T0, [], []} | R1]} | Rest], Acc); to_tokens([{Tag0, [T0={'=', _C0} | R1]} | Rest], Acc) -> %% Allow {'=', iolist()} to_tokens([{Tag0, R1} | Rest], [T0 | Acc]); to_tokens([{Tag0, [T0={comment, _C0} | R1]} | Rest], Acc) -> %% Allow {comment, iolist()} to_tokens([{Tag0, R1} | Rest], [T0 | Acc]); to_tokens([{Tag0, [T0={pi, _S0} | R1]} | Rest], Acc) -> %% Allow {pi, binary()} to_tokens([{Tag0, R1} | Rest], [T0 | Acc]); to_tokens([{Tag0, [T0={pi, _S0, _A0} | R1]} | Rest], Acc) -> %% Allow {pi, binary(), list()} to_tokens([{Tag0, R1} | Rest], [T0 | Acc]); to_tokens([{Tag0, [{T0, A0=[{_, _} | _]} | R1]} | Rest], Acc) -> %% Allow {p, [{"class", "foo"}]} to_tokens([{Tag0, [{T0, A0, []} | R1]} | Rest], Acc); to_tokens([{Tag0, [{T0, C0} | R1]} | Rest], Acc) -> %% Allow {p, "content"} and {p, <<"content">>} to_tokens([{Tag0, [{T0, [], C0} | R1]} | Rest], Acc); to_tokens([{Tag0, [{T0, A1, C0} | R1]} | Rest], Acc) when is_binary(C0) -> %% Allow {"p", [{"class", "foo"}], <<"content">>} to_tokens([{Tag0, [{T0, A1, binary_to_list(C0)} | R1]} | Rest], Acc); to_tokens([{Tag0, [{T0, A1, C0=[C | _]} | R1]} | Rest], Acc) when is_integer(C) -> %% Allow {"p", [{"class", "foo"}], "content"} to_tokens([{Tag0, [{T0, A1, [C0]} | R1]} | Rest], Acc); to_tokens([{Tag0, [{T0, A1, C1} | R1]} | Rest], Acc) -> %% Native {"p", [{"class", "foo"}], ["content"]} Tag = to_tag(Tag0), T1 = to_tag(T0), case is_singleton(norm(T1)) of true -> to_tokens([{Tag, R1} | Rest], [{start_tag, T1, A1, true} | Acc]); false -> to_tokens([{T1, C1}, {Tag, R1} | Rest], [{start_tag, T1, A1, false} | Acc]) end; to_tokens([{Tag0, [L | R1]} | Rest], Acc) when is_list(L) -> %% List text Tag = to_tag(Tag0), to_tokens([{Tag, R1} | Rest], [{data, iolist_to_binary(L), false} | Acc]); to_tokens([{Tag0, [B | R1]} | Rest], Acc) when is_binary(B) -> %% Binary text Tag = to_tag(Tag0), to_tokens([{Tag, R1} | Rest], [{data, B, false} | Acc]). tokens(B, S=#decoder{offset=O}, Acc) -> case B of <<_:O/binary>> -> lists:reverse(Acc); _ -> {Tag, S1} = tokenize(B, S), case parse_flag(Tag) of script -> {Tag2, S2} = tokenize_script(B, S1), tokens(B, S2, [Tag2, Tag | Acc]); textarea -> {Tag2, S2} = tokenize_textarea(B, S1), tokens(B, S2, [Tag2, Tag | Acc]); none -> tokens(B, S1, [Tag | Acc]) end end. parse_flag({start_tag, B, _, false}) -> case string:to_lower(binary_to_list(B)) of "script" -> script; "textarea" -> textarea; _ -> none end; parse_flag(_) -> none. tokenize(B, S=#decoder{offset=O}) -> case B of <<_:O/binary, "", _/binary>> -> Len = O - Start, <<_:Start/binary, Raw:Len/binary, _/binary>> = Bin, {{comment, Raw}, ?ADV_COL(S, 3)}; <<_:O/binary, C, _/binary>> -> tokenize_comment(Bin, ?INC_CHAR(S, C), Start); <<_:Start/binary, Raw/binary>> -> {{comment, Raw}, S} end. tokenize_script(Bin, S=#decoder{offset=O}) -> tokenize_script(Bin, S, O). tokenize_script(Bin, S=#decoder{offset=O}, Start) -> case Bin of %% Just a look-ahead, we want the end_tag separately <<_:O/binary, $<, $/, SS, CC, RR, II, PP, TT, ZZ, _/binary>> when (SS =:= $s orelse SS =:= $S) andalso (CC =:= $c orelse CC =:= $C) andalso (RR =:= $r orelse RR =:= $R) andalso (II =:= $i orelse II =:= $I) andalso (PP =:= $p orelse PP =:= $P) andalso (TT=:= $t orelse TT =:= $T) andalso ?PROBABLE_CLOSE(ZZ) -> Len = O - Start, <<_:Start/binary, Raw:Len/binary, _/binary>> = Bin, {{data, Raw, false}, S}; <<_:O/binary, C, _/binary>> -> tokenize_script(Bin, ?INC_CHAR(S, C), Start); <<_:Start/binary, Raw/binary>> -> {{data, Raw, false}, S} end. tokenize_textarea(Bin, S=#decoder{offset=O}) -> tokenize_textarea(Bin, S, O). tokenize_textarea(Bin, S=#decoder{offset=O}, Start) -> case Bin of %% Just a look-ahead, we want the end_tag separately <<_:O/binary, $<, $/, TT, EE, XX, TT2, AA, RR, EE2, AA2, ZZ, _/binary>> when (TT =:= $t orelse TT =:= $T) andalso (EE =:= $e orelse EE =:= $E) andalso (XX =:= $x orelse XX =:= $X) andalso (TT2 =:= $t orelse TT2 =:= $T) andalso (AA =:= $a orelse AA =:= $A) andalso (RR =:= $r orelse RR =:= $R) andalso (EE2 =:= $e orelse EE2 =:= $E) andalso (AA2 =:= $a orelse AA2 =:= $A) andalso ?PROBABLE_CLOSE(ZZ) -> Len = O - Start, <<_:Start/binary, Raw:Len/binary, _/binary>> = Bin, {{data, Raw, false}, S}; <<_:O/binary, C, _/binary>> -> tokenize_textarea(Bin, ?INC_CHAR(S, C), Start); <<_:Start/binary, Raw/binary>> -> {{data, Raw, false}, S} end. %% %% Tests %% -ifdef(TEST). -include_lib("eunit/include/eunit.hrl"). to_html_test() -> ?assertEqual( <<"hey!

what's up

sucka
RAW!">>, iolist_to_binary( to_html({html, [], [{<<"head">>, [], [{title, <<"hey!">>}]}, {body, [], [{p, [{class, foo}], [<<"what's">>, <<" up">>, {br}]}, {'div', <<"sucka">>}, {'=', <<"RAW!">>}, {comment, <<" comment! ">>}]}]}))), ?assertEqual( <<"">>, iolist_to_binary( to_html({doctype, [<<"html">>, <<"PUBLIC">>, <<"-//W3C//DTD XHTML 1.0 Transitional//EN">>, <<"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">>]}))), ?assertEqual( <<"">>, iolist_to_binary( to_html({<<"html">>,[], [{pi, <<"xml:namespace">>, [{<<"prefix">>,<<"o">>}, {<<"ns">>,<<"urn:schemas-microsoft-com:office:office">>}]}]}))), ok. escape_test() -> ?assertEqual( <<"&quot;\"word ><<up!&quot;">>, escape(<<""\"word ><>)), ?assertEqual( <<"&quot;\"word ><<up!&quot;">>, escape(""\"word ><>, escape('"\"word >< ?assertEqual( <<"&quot;"word ><<up!&quot;">>, escape_attr(<<""\"word ><>)), ?assertEqual( <<"&quot;"word ><<up!&quot;">>, escape_attr(""\"word ><>, escape_attr('"\"word ><>, escape_attr(12345)), ?assertEqual( <<"1.5">>, escape_attr(1.5)), ok. tokens_test() -> ?assertEqual( [{start_tag, <<"foo">>, [{<<"bar">>, <<"baz">>}, {<<"wibble">>, <<"wibble">>}, {<<"alice">>, <<"bob">>}], true}], tokens(<<"">>)), ?assertEqual( [{start_tag, <<"foo">>, [{<<"bar">>, <<"baz">>}, {<<"wibble">>, <<"wibble">>}, {<<"alice">>, <<"bob">>}], true}], tokens(<<"">>)), ?assertEqual( [{comment, <<"[if lt IE 7]>\n\n>}], tokens(<<"">>)), ?assertEqual( [{start_tag, <<"script">>, [{<<"type">>, <<"text/javascript">>}], false}, {data, <<" A= B <= C ">>, false}, {end_tag, <<"script">>}], tokens(<<"">>)), ?assertEqual( [{start_tag, <<"script">>, [{<<"type">>, <<"text/javascript">>}], false}, {data, <<" A= B <= C ">>, false}, {end_tag, <<"script">>}], tokens(<<"">>)), ?assertEqual( [{start_tag, <<"script">>, [{<<"type">>, <<"text/javascript">>}], false}, {data, <<" A= B <= C ">>, false}, {end_tag, <<"script">>}], tokens(<<"">>)), ?assertEqual( [{start_tag, <<"script">>, [{<<"type">>, <<"text/javascript">>}], false}, {data, <<" A= B <= C ">>, false}, {end_tag, <<"script">>}], tokens(<<"">>)), ?assertEqual( [{start_tag, <<"textarea">>, [], false}, {data, <<"">>, false}, {end_tag, <<"textarea">>}], tokens(<<"">>)), ?assertEqual( [{start_tag, <<"textarea">>, [], false}, {data, <<"">>, false}], tokens(<<" <% } else { %> <% } %>
Reduce functions are optional.
<% if (newView) { %> <% } else { %> <% } %>
<% if (!this.newView) { %> <% } %>
<% if (hasReduce) { %>
<% } %>
apache-couchdb-1.5.0/src/fauxton/app/templates/documents/all_docs_item.html0000644000175000001440000000176212230722213023776 00000000000000
<%- doc.prettyJSON() %>
<% if (doc.isEditable()) { %>
Edit <%= doc.docType() %>
<% } %>
apache-couchdb-1.5.0/src/fauxton/app/templates/documents/ddoc_info.html0000644000175000001440000000154412230722213023122 00000000000000

Design Doc MetaData

<% i=0; _.map(view_index, function (val, key) { %> <% if(i%2==0){%>
<% }; %>
<%= key %> : <%= val %>
<% if(i%2==1){%>
<% }; %> <% ++i; }); %>
apache-couchdb-1.5.0/src/fauxton/app/templates/documents/index_menu_item.html0000644000175000001440000000135112230722213024343 00000000000000 <%= ddoc %>/<%= index %> apache-couchdb-1.5.0/src/fauxton/app/templates/documents/doc_field_editor.html0000644000175000001440000000517412230722213024457 00000000000000
<% _.each(doc, function(value, key) { %> <% }); %> <%_.each(attachments, function (att) { %> <% }) %>
Key Value
Attachments
<%= att.fileName %> <%= att.contentType %>, <%= formatSize(att.size)%>
New field
apache-couchdb-1.5.0/src/fauxton/app/templates/documents/doc_field_editor_tabs.html0000644000175000001440000000155312230722213025465 00000000000000
  • Code editor
apache-couchdb-1.5.0/src/fauxton/app/templates/documents/search.html0000644000175000001440000000117612230722213022444 00000000000000 apache-couchdb-1.5.0/src/fauxton/app/templates/documents/all_docs_list.html0000644000175000001440000000340712230722214024012 00000000000000
<% if (!viewList) { %>
<% } %>

<% if (totalRows === "unknown"){ %> Showing 0 documents. Create your first document. <% } else { %> Showing <%=offset%> - <%= numModels %> of <%= totalRows %> rows <%}%> <% if (updateSeq) { %> -- Update Sequence: <%= updateSeq %> <% } %> <% if (requestDuration) { %> View request duration: <%= requestDuration %> <% } %>

apache-couchdb-1.5.0/src/fauxton/app/templates/documents/jumpdoc.html0000644000175000001440000000135712230722214022642 00000000000000
apache-couchdb-1.5.0/src/fauxton/app/templates/documents/duplicate_doc_modal.html0000644000175000001440000000241212230722213025144 00000000000000

Duplicate Document

Set new documents ID:

Cancel Duplicate
apache-couchdb-1.5.0/src/fauxton/app/templates/documents/doc.html0000644000175000001440000000325012230722214021740 00000000000000
<% if (attachments) { %> View Attachments
    <%_.each(attachments, function (att) { %>
  • <%= att.fileName %> - <%= att.contentType %>, <%= formatSize(att.size)%>
  • <% }) %>
<% } %>

apache-couchdb-1.5.0/src/fauxton/app/templates/documents/changes.html0000644000175000001440000000235012230722213022602 00000000000000 <% _.each(changes, function (change) { %> <% if (change.deleted) { %> <% } else { %> <% } %> <% }); %>
seq id changes deleted?
<%= change.seq %> <%= change.id %> <%= change.id %>
  <%- JSON.stringify({changes: change.changes, doc: change.doc}, null, " ") %> 
<%= change.deleted ? "true" : "false" %>
apache-couchdb-1.5.0/src/fauxton/app/templates/documents/sidebar.html0000644000175000001440000000470412230722213022610 00000000000000
  • Docs
  • Permissions
  • Changes
  • New doc
  • New view
  • Primary Indices
  • All documents
  • All design docs
  • Secondary Indices
  • New
apache-couchdb-1.5.0/src/fauxton/app/templates/documents/index_row_tabular.html0000644000175000001440000000142012230722213024677 00000000000000
<%- JSON.stringify(doc.get("key")) %>
<%- JSON.stringify(doc.get("value")) %>
apache-couchdb-1.5.0/src/fauxton/app/templates/documents/tabs.html0000644000175000001440000000274712230722213022135 00000000000000
  • Docs
  • Changes
apache-couchdb-1.5.0/src/fauxton/bin/0000755000175000001440000000000012230722303014355 500000000000000apache-couchdb-1.5.0/src/fauxton/bin/grunt0000755000175000001440000000121012230722213015354 00000000000000#!/bin/sh # 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. REL_PATH="`dirname \"$0\"`" GRUNT_PATH="$REL_PATH/../node_modules/.bin/grunt" $GRUNT_PATH $* apache-couchdb-1.5.0/src/fauxton/test/0000755000175000001440000000000012230722303014564 500000000000000apache-couchdb-1.5.0/src/fauxton/test/core/0000755000175000001440000000000012230722303015514 500000000000000apache-couchdb-1.5.0/src/fauxton/test/core/routeObjectSpec.js0000644000175000001440000000665012230722214021102 00000000000000// 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. define([ 'api', 'testUtils' ], function (FauxtonAPI, testUtils) { var assert = testUtils.assert, RouteObject = FauxtonAPI.RouteObject; describe('RouteObjects', function () { describe('renderWith', function () { var TestRouteObject, testRouteObject, mockLayout; beforeEach(function () { TestRouteObject = RouteObject.extend({ crumbs: ['mycrumbs'] }); testRouteObject = new TestRouteObject(); // Need to find a better way of doing this mockLayout = { setTemplate: sinon.spy(), clearBreadcrumbs: sinon.spy(), setView: sinon.spy(), renderView: sinon.spy(), hooks: [], setBreadcrumbs: sinon.spy() }; }); it('Should set template for first render ', function () { testRouteObject.renderWith('the-route', mockLayout, 'args'); assert.ok(mockLayout.setTemplate.calledOnce, 'setTempalte was called'); }); it('Should not set template after first render', function () { testRouteObject.renderWith('the-route', mockLayout, 'args'); testRouteObject.renderWith('the-route', mockLayout, 'args'); assert.ok(mockLayout.setTemplate.calledOnce, 'SetTemplate not meant to be called'); }); it('Should clear breadcrumbs', function () { testRouteObject.renderWith('the-route', mockLayout, 'args'); assert.ok(mockLayout.clearBreadcrumbs.calledOnce, 'Clear Breadcrumbs called'); }); it('Should set breadcrumbs when breadcrumbs exist', function () { testRouteObject.renderWith('the-route', mockLayout, 'args'); assert.ok(mockLayout.setBreadcrumbs.calledOnce, 'Set Breadcrumbs was called'); }); it("Should call establish of routeObject", function () { var establishSpy = sinon.spy(testRouteObject,"establish"); testRouteObject.renderWith('the-route', mockLayout, 'args'); assert.ok(establishSpy.calledOnce, 'Calls establish'); }); it("Should render views", function () { var view = new FauxtonAPI.View(), getViewsSpy = sinon.stub(testRouteObject,"getViews"), viewSpy = sinon.stub(view, "establish"); view.hasRendered = false; getViewsSpy.returns({'#view': view}); testRouteObject.renderWith('the-route', mockLayout, 'args'); assert.ok(viewSpy.calledOnce, 'Should render view'); }); it("Should not re-render a view", function () { var view = new FauxtonAPI.View(), getViewsSpy = sinon.stub(testRouteObject,"getViews"), viewSpy = sinon.stub(view, "establish"); view.hasRendered = true; getViewsSpy.returns({'#view': view}); testRouteObject.renderWith('the-route', mockLayout, 'args'); assert.notOk(viewSpy.calledOnce, 'Should render view'); }); }); }); }); apache-couchdb-1.5.0/src/fauxton/test/core/layoutSpec.js0000644000175000001440000000477212230722213020134 00000000000000// 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. define([ 'modules/fauxton/layout', 'testUtils' ], function (Layout, testUtils) { var assert = testUtils.assert; describe("Faxuton Layout", function () { var layout; beforeEach(function () { var navBar = new Backbone.View(); var apiBar = new Backbone.View(); layout = new Layout(navBar, apiBar); }); describe('#setTemplate', function () { it("Should set template without prefix", function () { layout.setTemplate('myTemplate'); assert.equal(layout.layout.template, 'templates/layouts/myTemplate'); }); it("Should set template with prefix", function () { layout.setTemplate({name: 'myTemplate', prefix: 'myPrefix/'}); assert.equal(layout.layout.template, 'myPrefix/myTemplate'); }); it("Should remove old views", function () { var view = { remove: function () {} }; layout.layoutViews = { 'selector': view }; var mockRemove = sinon.spy(view, 'remove'); layout.setTemplate('myTemplate'); assert.ok(mockRemove.calledOnce); }); it("Should render", function () { var mockRender = sinon.spy(layout, 'render'); layout.setTemplate('myTemplate'); assert.ok(mockRender.calledOnce); }); }); describe('#renderView', function () { it('Should render existing view', function () { var view = new Backbone.View(); var mockRender = sinon.spy(view, 'render'); layout.layoutViews = { '#selector': view }; var out = layout.renderView('#selector'); assert.ok(mockRender.calledOnce); }); it('Should return false for non-existing view', function () { var view = new Backbone.View(); layout.layoutViews = { 'selector': view }; var out = layout.renderView('wrongSelector'); assert.notOk(out, 'No view found'); }); }); }); }); apache-couchdb-1.5.0/src/fauxton/test/core/navbarSpec.js0000644000175000001440000000605612230722213020065 00000000000000// 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. define([ 'modules/fauxton/base', 'testUtils' ], function (Fauxton, testUtils) { var assert = testUtils.assert, NavBar = Fauxton.NavBar; describe('NavBar', function () { describe('adding links', function () { var navBar; beforeEach(function () { navBar = new NavBar(); navBar.navLinks = []; navBar.bottomNavLinks = []; navBar.footerNavLinks = []; }); it('Should add link to navlinks', function () { navBar.addLink({href: '#/test', title: 'Test Title'}); assert.equal(navBar.navLinks.length, 1); assert.equal(navBar.footerNavLinks.length, 0); assert.equal(navBar.bottomNavLinks.length, 0); }); it('Should add link to bottom links', function () { navBar.addLink({href: '#/test', bottomNav: true, title: 'Test Title'}); assert.equal(navBar.bottomNavLinks.length, 1); assert.equal(navBar.navLinks.length, 0); assert.equal(navBar.footerNavLinks.length, 0); }); it('Should add link to footer links', function () { navBar.addLink({href: '#/test', footerNav: true, title: 'Test Title'}); assert.equal(navBar.footerNavLinks.length, 1); assert.equal(navBar.bottomNavLinks.length, 0); assert.equal(navBar.navLinks.length, 0); }); }); describe('removing links', function () { var navBar; beforeEach(function () { navBar = new NavBar(); navBar.navLinks = []; navBar.bottomNavLinks = []; navBar.footerNavLinks = []; navBar.addLink({ href: '#/test', footerNav: true, title: 'Test Title Footer' }); navBar.addLink({ href: '#/test', bottomNav: true, title: 'Test Title Bottom' }); navBar.addLink({ href: '#/test', title: 'Test Title' }); }); it("should remove links from list", function () { navBar.removeLink({ title: 'Test Title Footer', footerNav: true }); assert.equal(navBar.footerNavLinks.length, 0); assert.equal(navBar.bottomNavLinks.length, 1); assert.equal(navBar.navLinks.length, 1); }); it("Should call render after removing links", function () { var renderSpy = sinon.stub(navBar,'render'); navBar.removeLink({ title: 'Test Title Footer', footerNav: true }); assert.ok(renderSpy.calledOnce); }); }); }); }); apache-couchdb-1.5.0/src/fauxton/test/core/paginateSpec.js0000644000175000001440000000557412230722213020410 00000000000000// 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. define([ 'api', 'modules/fauxton/components', 'modules/documents/resources', 'testUtils', 'app' ], function (FauxtonAPI, Views, Models, testUtils, app) { var assert = testUtils.assert, ViewSandbox = testUtils.ViewSandbox; describe('IndexPaginate', function () { var viewSandbox, paginate, collection, navigateMock; beforeEach(function () { app.router = { navigate: function () {} }; collection = new Models.IndexCollection([{ id:'myId1', doc: 'num1' }, { id:'myId2', doc: 'num2' }], { database: {id: 'databaseId'}, design: '_design/myDoc' }); paginate = new Views.IndexPagination({ collection: collection, previousUrlfn: function () {}, nextUrlfn: function () {}, canShowPreviousfn: function () {}, canShowNextfn: function () {} }); viewSandbox = new ViewSandbox(); viewSandbox.renderView(paginate); }); afterEach(function () { viewSandbox.remove(); }); describe('#next', function () { beforeEach(function () { //do this so it doesn't throw an error on other unwired up components FauxtonAPI.triggerRouteEvent = function () {}; }); it('Should navigate', function () { var navigateMock = sinon.spy(FauxtonAPI, 'navigate'); paginate.$('a#next').click(); assert.ok(navigateMock.calledOnce); FauxtonAPI.navigate.restore(); }); it('Should trigger routeEvent', function () { var navigateMock = sinon.spy(FauxtonAPI, 'triggerRouteEvent'); paginate.$('a#next').click(); assert.ok(navigateMock.calledOnce); FauxtonAPI.triggerRouteEvent.restore(); }); }); describe('#previous', function () { it('Should navigate', function () { var navigateMock = sinon.spy(FauxtonAPI, 'navigate'); paginate.$('a#previous').click(); assert.ok(navigateMock.calledOnce); FauxtonAPI.navigate.restore(); }); it('Should trigger routeEvent', function () { var navigateMock = sinon.spy(FauxtonAPI, 'triggerRouteEvent'); paginate.$('a#previous').click(); assert.ok(navigateMock.calledOnce); FauxtonAPI.triggerRouteEvent.restore(); }); }); }); }); apache-couchdb-1.5.0/src/fauxton/test/mocha/0000755000175000001440000000000012230722303015653 500000000000000apache-couchdb-1.5.0/src/fauxton/test/mocha/sinon.js0000644000175000001440000040311412230722213017262 00000000000000/** * Sinon.JS 1.7.3, 2013/06/20 * * @author Christian Johansen (christian@cjohansen.no) * @author Contributors: https://github.com/cjohansen/Sinon.JS/blob/master/AUTHORS * * (The BSD License) * * Copyright (c) 2010-2013, Christian Johansen, christian@cjohansen.no * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, * are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * Neither the name of Christian Johansen nor the names of his contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ this.sinon = (function () { var buster = (function (setTimeout, B) { var isNode = typeof require == "function" && typeof module == "object"; var div = typeof document != "undefined" && document.createElement("div"); var F = function () {}; var buster = { bind: function bind(obj, methOrProp) { var method = typeof methOrProp == "string" ? obj[methOrProp] : methOrProp; var args = Array.prototype.slice.call(arguments, 2); return function () { var allArgs = args.concat(Array.prototype.slice.call(arguments)); return method.apply(obj, allArgs); }; }, partial: function partial(fn) { var args = [].slice.call(arguments, 1); return function () { return fn.apply(this, args.concat([].slice.call(arguments))); }; }, create: function create(object) { F.prototype = object; return new F(); }, extend: function extend(target) { if (!target) { return; } for (var i = 1, l = arguments.length, prop; i < l; ++i) { for (prop in arguments[i]) { target[prop] = arguments[i][prop]; } } return target; }, nextTick: function nextTick(callback) { if (typeof process != "undefined" && process.nextTick) { return process.nextTick(callback); } setTimeout(callback, 0); }, functionName: function functionName(func) { if (!func) return ""; if (func.displayName) return func.displayName; if (func.name) return func.name; var matches = func.toString().match(/function\s+([^\(]+)/m); return matches && matches[1] || ""; }, isNode: function isNode(obj) { if (!div) return false; try { obj.appendChild(div); obj.removeChild(div); } catch (e) { return false; } return true; }, isElement: function isElement(obj) { return obj && obj.nodeType === 1 && buster.isNode(obj); }, isArray: function isArray(arr) { return Object.prototype.toString.call(arr) == "[object Array]"; }, flatten: function flatten(arr) { var result = [], arr = arr || []; for (var i = 0, l = arr.length; i < l; ++i) { result = result.concat(buster.isArray(arr[i]) ? flatten(arr[i]) : arr[i]); } return result; }, each: function each(arr, callback) { for (var i = 0, l = arr.length; i < l; ++i) { callback(arr[i]); } }, map: function map(arr, callback) { var results = []; for (var i = 0, l = arr.length; i < l; ++i) { results.push(callback(arr[i])); } return results; }, parallel: function parallel(fns, callback) { function cb(err, res) { if (typeof callback == "function") { callback(err, res); callback = null; } } if (fns.length == 0) { return cb(null, []); } var remaining = fns.length, results = []; function makeDone(num) { return function done(err, result) { if (err) { return cb(err); } results[num] = result; if (--remaining == 0) { cb(null, results); } }; } for (var i = 0, l = fns.length; i < l; ++i) { fns[i](makeDone(i)); } }, series: function series(fns, callback) { function cb(err, res) { if (typeof callback == "function") { callback(err, res); } } var remaining = fns.slice(); var results = []; function callNext() { if (remaining.length == 0) return cb(null, results); var promise = remaining.shift()(next); if (promise && typeof promise.then == "function") { promise.then(buster.partial(next, null), next); } } function next(err, result) { if (err) return cb(err); results.push(result); callNext(); } callNext(); }, countdown: function countdown(num, done) { return function () { if (--num == 0) done(); }; } }; if (typeof process === "object" && typeof require === "function" && typeof module === "object") { var crypto = require("crypto"); var path = require("path"); buster.tmpFile = function (fileName) { var hashed = crypto.createHash("sha1"); hashed.update(fileName); var tmpfileName = hashed.digest("hex"); if (process.platform == "win32") { return path.join(process.env["TEMP"], tmpfileName); } else { return path.join("/tmp", tmpfileName); } }; } if (Array.prototype.some) { buster.some = function (arr, fn, thisp) { return arr.some(fn, thisp); }; } else { // https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/some buster.some = function (arr, fun, thisp) { if (arr == null) { throw new TypeError(); } arr = Object(arr); var len = arr.length >>> 0; if (typeof fun !== "function") { throw new TypeError(); } for (var i = 0; i < len; i++) { if (arr.hasOwnProperty(i) && fun.call(thisp, arr[i], i, arr)) { return true; } } return false; }; } if (Array.prototype.filter) { buster.filter = function (arr, fn, thisp) { return arr.filter(fn, thisp); }; } else { // https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/filter buster.filter = function (fn, thisp) { if (this == null) { throw new TypeError(); } var t = Object(this); var len = t.length >>> 0; if (typeof fn != "function") { throw new TypeError(); } var res = []; for (var i = 0; i < len; i++) { if (i in t) { var val = t[i]; // in case fun mutates this if (fn.call(thisp, val, i, t)) { res.push(val); } } } return res; }; } if (isNode) { module.exports = buster; buster.eventEmitter = require("./buster-event-emitter"); Object.defineProperty(buster, "defineVersionGetter", { get: function () { return require("./define-version-getter"); } }); } return buster.extend(B || {}, buster); }(setTimeout, buster)); if (typeof buster === "undefined") { var buster = {}; } if (typeof module === "object" && typeof require === "function") { buster = require("buster-core"); } buster.format = buster.format || {}; buster.format.excludeConstructors = ["Object", /^.$/]; buster.format.quoteStrings = true; buster.format.ascii = (function () { var hasOwn = Object.prototype.hasOwnProperty; var specialObjects = []; if (typeof global != "undefined") { specialObjects.push({ obj: global, value: "[object global]" }); } if (typeof document != "undefined") { specialObjects.push({ obj: document, value: "[object HTMLDocument]" }); } if (typeof window != "undefined") { specialObjects.push({ obj: window, value: "[object Window]" }); } function keys(object) { var k = Object.keys && Object.keys(object) || []; if (k.length == 0) { for (var prop in object) { if (hasOwn.call(object, prop)) { k.push(prop); } } } return k.sort(); } function isCircular(object, objects) { if (typeof object != "object") { return false; } for (var i = 0, l = objects.length; i < l; ++i) { if (objects[i] === object) { return true; } } return false; } function ascii(object, processed, indent) { if (typeof object == "string") { var quote = typeof this.quoteStrings != "boolean" || this.quoteStrings; return processed || quote ? '"' + object + '"' : object; } if (typeof object == "function" && !(object instanceof RegExp)) { return ascii.func(object); } processed = processed || []; if (isCircular(object, processed)) { return "[Circular]"; } if (Object.prototype.toString.call(object) == "[object Array]") { return ascii.array.call(this, object, processed); } if (!object) { return "" + object; } if (buster.isElement(object)) { return ascii.element(object); } if (typeof object.toString == "function" && object.toString !== Object.prototype.toString) { return object.toString(); } for (var i = 0, l = specialObjects.length; i < l; i++) { if (object === specialObjects[i].obj) { return specialObjects[i].value; } } return ascii.object.call(this, object, processed, indent); } ascii.func = function (func) { return "function " + buster.functionName(func) + "() {}"; }; ascii.array = function (array, processed) { processed = processed || []; processed.push(array); var pieces = []; for (var i = 0, l = array.length; i < l; ++i) { pieces.push(ascii.call(this, array[i], processed)); } return "[" + pieces.join(", ") + "]"; }; ascii.object = function (object, processed, indent) { processed = processed || []; processed.push(object); indent = indent || 0; var pieces = [], properties = keys(object), prop, str, obj; var is = ""; var length = 3; for (var i = 0, l = indent; i < l; ++i) { is += " "; } for (i = 0, l = properties.length; i < l; ++i) { prop = properties[i]; obj = object[prop]; if (isCircular(obj, processed)) { str = "[Circular]"; } else { str = ascii.call(this, obj, processed, indent + 2); } str = (/\s/.test(prop) ? '"' + prop + '"' : prop) + ": " + str; length += str.length; pieces.push(str); } var cons = ascii.constructorName.call(this, object); var prefix = cons ? "[" + cons + "] " : "" return (length + indent) > 80 ? prefix + "{\n " + is + pieces.join(",\n " + is) + "\n" + is + "}" : prefix + "{ " + pieces.join(", ") + " }"; }; ascii.element = function (element) { var tagName = element.tagName.toLowerCase(); var attrs = element.attributes, attribute, pairs = [], attrName; for (var i = 0, l = attrs.length; i < l; ++i) { attribute = attrs.item(i); attrName = attribute.nodeName.toLowerCase().replace("html:", ""); if (attrName == "contenteditable" && attribute.nodeValue == "inherit") { continue; } if (!!attribute.nodeValue) { pairs.push(attrName + "=\"" + attribute.nodeValue + "\""); } } var formatted = "<" + tagName + (pairs.length > 0 ? " " : ""); var content = element.innerHTML; if (content.length > 20) { content = content.substr(0, 20) + "[...]"; } var res = formatted + pairs.join(" ") + ">" + content + ""; return res.replace(/ contentEditable="inherit"/, ""); }; ascii.constructorName = function (object) { var name = buster.functionName(object && object.constructor); var excludes = this.excludeConstructors || buster.format.excludeConstructors || []; for (var i = 0, l = excludes.length; i < l; ++i) { if (typeof excludes[i] == "string" && excludes[i] == name) { return ""; } else if (excludes[i].test && excludes[i].test(name)) { return ""; } } return name; }; return ascii; }()); if (typeof module != "undefined") { module.exports = buster.format; } /*jslint eqeqeq: false, onevar: false, forin: true, nomen: false, regexp: false, plusplus: false*/ /*global module, require, __dirname, document*/ /** * Sinon core utilities. For internal use only. * * @author Christian Johansen (christian@cjohansen.no) * @license BSD * * Copyright (c) 2010-2013 Christian Johansen */ var sinon = (function (buster) { var div = typeof document != "undefined" && document.createElement("div"); var hasOwn = Object.prototype.hasOwnProperty; function isDOMNode(obj) { var success = false; try { obj.appendChild(div); success = div.parentNode == obj; } catch (e) { return false; } finally { try { obj.removeChild(div); } catch (e) { // Remove failed, not much we can do about that } } return success; } function isElement(obj) { return div && obj && obj.nodeType === 1 && isDOMNode(obj); } function isFunction(obj) { return typeof obj === "function" || !!(obj && obj.constructor && obj.call && obj.apply); } function mirrorProperties(target, source) { for (var prop in source) { if (!hasOwn.call(target, prop)) { target[prop] = source[prop]; } } } function isRestorable (obj) { return typeof obj === "function" && typeof obj.restore === "function" && obj.restore.sinon; } var sinon = { wrapMethod: function wrapMethod(object, property, method) { if (!object) { throw new TypeError("Should wrap property of object"); } if (typeof method != "function") { throw new TypeError("Method wrapper should be function"); } var wrappedMethod = object[property]; if (!isFunction(wrappedMethod)) { throw new TypeError("Attempted to wrap " + (typeof wrappedMethod) + " property " + property + " as function"); } if (wrappedMethod.restore && wrappedMethod.restore.sinon) { throw new TypeError("Attempted to wrap " + property + " which is already wrapped"); } if (wrappedMethod.calledBefore) { var verb = !!wrappedMethod.returns ? "stubbed" : "spied on"; throw new TypeError("Attempted to wrap " + property + " which is already " + verb); } // IE 8 does not support hasOwnProperty on the window object. var owned = hasOwn.call(object, property); object[property] = method; method.displayName = property; method.restore = function () { // For prototype properties try to reset by delete first. // If this fails (ex: localStorage on mobile safari) then force a reset // via direct assignment. if (!owned) { delete object[property]; } if (object[property] === method) { object[property] = wrappedMethod; } }; method.restore.sinon = true; mirrorProperties(method, wrappedMethod); return method; }, extend: function extend(target) { for (var i = 1, l = arguments.length; i < l; i += 1) { for (var prop in arguments[i]) { if (arguments[i].hasOwnProperty(prop)) { target[prop] = arguments[i][prop]; } // DONT ENUM bug, only care about toString if (arguments[i].hasOwnProperty("toString") && arguments[i].toString != target.toString) { target.toString = arguments[i].toString; } } } return target; }, create: function create(proto) { var F = function () {}; F.prototype = proto; return new F(); }, deepEqual: function deepEqual(a, b) { if (sinon.match && sinon.match.isMatcher(a)) { return a.test(b); } if (typeof a != "object" || typeof b != "object") { return a === b; } if (isElement(a) || isElement(b)) { return a === b; } if (a === b) { return true; } if ((a === null && b !== null) || (a !== null && b === null)) { return false; } var aString = Object.prototype.toString.call(a); if (aString != Object.prototype.toString.call(b)) { return false; } if (aString == "[object Array]") { if (a.length !== b.length) { return false; } for (var i = 0, l = a.length; i < l; i += 1) { if (!deepEqual(a[i], b[i])) { return false; } } return true; } if (aString == "[object Date]") { return a.valueOf() === b.valueOf(); } var prop, aLength = 0, bLength = 0; for (prop in a) { aLength += 1; if (!deepEqual(a[prop], b[prop])) { return false; } } for (prop in b) { bLength += 1; } return aLength == bLength; }, functionName: function functionName(func) { var name = func.displayName || func.name; // Use function decomposition as a last resort to get function // name. Does not rely on function decomposition to work - if it // doesn't debugging will be slightly less informative // (i.e. toString will say 'spy' rather than 'myFunc'). if (!name) { var matches = func.toString().match(/function ([^\s\(]+)/); name = matches && matches[1]; } return name; }, functionToString: function toString() { if (this.getCall && this.callCount) { var thisValue, prop, i = this.callCount; while (i--) { thisValue = this.getCall(i).thisValue; for (prop in thisValue) { if (thisValue[prop] === this) { return prop; } } } } return this.displayName || "sinon fake"; }, getConfig: function (custom) { var config = {}; custom = custom || {}; var defaults = sinon.defaultConfig; for (var prop in defaults) { if (defaults.hasOwnProperty(prop)) { config[prop] = custom.hasOwnProperty(prop) ? custom[prop] : defaults[prop]; } } return config; }, format: function (val) { return "" + val; }, defaultConfig: { injectIntoThis: true, injectInto: null, properties: ["spy", "stub", "mock", "clock", "server", "requests"], useFakeTimers: true, useFakeServer: true }, timesInWords: function timesInWords(count) { return count == 1 && "once" || count == 2 && "twice" || count == 3 && "thrice" || (count || 0) + " times"; }, calledInOrder: function (spies) { for (var i = 1, l = spies.length; i < l; i++) { if (!spies[i - 1].calledBefore(spies[i]) || !spies[i].called) { return false; } } return true; }, orderByFirstCall: function (spies) { return spies.sort(function (a, b) { // uuid, won't ever be equal var aCall = a.getCall(0); var bCall = b.getCall(0); var aId = aCall && aCall.callId || -1; var bId = bCall && bCall.callId || -1; return aId < bId ? -1 : 1; }); }, log: function () {}, logError: function (label, err) { var msg = label + " threw exception: " sinon.log(msg + "[" + err.name + "] " + err.message); if (err.stack) { sinon.log(err.stack); } setTimeout(function () { err.message = msg + err.message; throw err; }, 0); }, typeOf: function (value) { if (value === null) { return "null"; } else if (value === undefined) { return "undefined"; } var string = Object.prototype.toString.call(value); return string.substring(8, string.length - 1).toLowerCase(); }, createStubInstance: function (constructor) { if (typeof constructor !== "function") { throw new TypeError("The constructor should be a function."); } return sinon.stub(sinon.create(constructor.prototype)); }, restore: function (object) { if (object !== null && typeof object === "object") { for (var prop in object) { if (isRestorable(object[prop])) { object[prop].restore(); } } } else if (isRestorable(object)) { object.restore(); } } }; var isNode = typeof module == "object" && typeof require == "function"; if (isNode) { try { buster = { format: require("buster-format") }; } catch (e) {} module.exports = sinon; module.exports.spy = require("./sinon/spy"); module.exports.stub = require("./sinon/stub"); module.exports.mock = require("./sinon/mock"); module.exports.collection = require("./sinon/collection"); module.exports.assert = require("./sinon/assert"); module.exports.sandbox = require("./sinon/sandbox"); module.exports.test = require("./sinon/test"); module.exports.testCase = require("./sinon/test_case"); module.exports.assert = require("./sinon/assert"); module.exports.match = require("./sinon/match"); } if (buster) { var formatter = sinon.create(buster.format); formatter.quoteStrings = false; sinon.format = function () { return formatter.ascii.apply(formatter, arguments); }; } else if (isNode) { try { var util = require("util"); sinon.format = function (value) { return typeof value == "object" && value.toString === Object.prototype.toString ? util.inspect(value) : value; }; } catch (e) { /* Node, but no util module - would be very old, but better safe than sorry */ } } return sinon; }(typeof buster == "object" && buster)); /* @depend ../sinon.js */ /*jslint eqeqeq: false, onevar: false, plusplus: false*/ /*global module, require, sinon*/ /** * Match functions * * @author Maximilian Antoni (mail@maxantoni.de) * @license BSD * * Copyright (c) 2012 Maximilian Antoni */ (function (sinon) { var commonJSModule = typeof module == "object" && typeof require == "function"; if (!sinon && commonJSModule) { sinon = require("../sinon"); } if (!sinon) { return; } function assertType(value, type, name) { var actual = sinon.typeOf(value); if (actual !== type) { throw new TypeError("Expected type of " + name + " to be " + type + ", but was " + actual); } } var matcher = { toString: function () { return this.message; } }; function isMatcher(object) { return matcher.isPrototypeOf(object); } function matchObject(expectation, actual) { if (actual === null || actual === undefined) { return false; } for (var key in expectation) { if (expectation.hasOwnProperty(key)) { var exp = expectation[key]; var act = actual[key]; if (match.isMatcher(exp)) { if (!exp.test(act)) { return false; } } else if (sinon.typeOf(exp) === "object") { if (!matchObject(exp, act)) { return false; } } else if (!sinon.deepEqual(exp, act)) { return false; } } } return true; } matcher.or = function (m2) { if (!isMatcher(m2)) { throw new TypeError("Matcher expected"); } var m1 = this; var or = sinon.create(matcher); or.test = function (actual) { return m1.test(actual) || m2.test(actual); }; or.message = m1.message + ".or(" + m2.message + ")"; return or; }; matcher.and = function (m2) { if (!isMatcher(m2)) { throw new TypeError("Matcher expected"); } var m1 = this; var and = sinon.create(matcher); and.test = function (actual) { return m1.test(actual) && m2.test(actual); }; and.message = m1.message + ".and(" + m2.message + ")"; return and; }; var match = function (expectation, message) { var m = sinon.create(matcher); var type = sinon.typeOf(expectation); switch (type) { case "object": if (typeof expectation.test === "function") { m.test = function (actual) { return expectation.test(actual) === true; }; m.message = "match(" + sinon.functionName(expectation.test) + ")"; return m; } var str = []; for (var key in expectation) { if (expectation.hasOwnProperty(key)) { str.push(key + ": " + expectation[key]); } } m.test = function (actual) { return matchObject(expectation, actual); }; m.message = "match(" + str.join(", ") + ")"; break; case "number": m.test = function (actual) { return expectation == actual; }; break; case "string": m.test = function (actual) { if (typeof actual !== "string") { return false; } return actual.indexOf(expectation) !== -1; }; m.message = "match(\"" + expectation + "\")"; break; case "regexp": m.test = function (actual) { if (typeof actual !== "string") { return false; } return expectation.test(actual); }; break; case "function": m.test = expectation; if (message) { m.message = message; } else { m.message = "match(" + sinon.functionName(expectation) + ")"; } break; default: m.test = function (actual) { return sinon.deepEqual(expectation, actual); }; } if (!m.message) { m.message = "match(" + expectation + ")"; } return m; }; match.isMatcher = isMatcher; match.any = match(function () { return true; }, "any"); match.defined = match(function (actual) { return actual !== null && actual !== undefined; }, "defined"); match.truthy = match(function (actual) { return !!actual; }, "truthy"); match.falsy = match(function (actual) { return !actual; }, "falsy"); match.same = function (expectation) { return match(function (actual) { return expectation === actual; }, "same(" + expectation + ")"); }; match.typeOf = function (type) { assertType(type, "string", "type"); return match(function (actual) { return sinon.typeOf(actual) === type; }, "typeOf(\"" + type + "\")"); }; match.instanceOf = function (type) { assertType(type, "function", "type"); return match(function (actual) { return actual instanceof type; }, "instanceOf(" + sinon.functionName(type) + ")"); }; function createPropertyMatcher(propertyTest, messagePrefix) { return function (property, value) { assertType(property, "string", "property"); var onlyProperty = arguments.length === 1; var message = messagePrefix + "(\"" + property + "\""; if (!onlyProperty) { message += ", " + value; } message += ")"; return match(function (actual) { if (actual === undefined || actual === null || !propertyTest(actual, property)) { return false; } return onlyProperty || sinon.deepEqual(value, actual[property]); }, message); }; } match.has = createPropertyMatcher(function (actual, property) { if (typeof actual === "object") { return property in actual; } return actual[property] !== undefined; }, "has"); match.hasOwn = createPropertyMatcher(function (actual, property) { return actual.hasOwnProperty(property); }, "hasOwn"); match.bool = match.typeOf("boolean"); match.number = match.typeOf("number"); match.string = match.typeOf("string"); match.object = match.typeOf("object"); match.func = match.typeOf("function"); match.array = match.typeOf("array"); match.regexp = match.typeOf("regexp"); match.date = match.typeOf("date"); if (commonJSModule) { module.exports = match; } else { sinon.match = match; } }(typeof sinon == "object" && sinon || null)); /** * @depend ../sinon.js * @depend match.js */ /*jslint eqeqeq: false, onevar: false, plusplus: false*/ /*global module, require, sinon*/ /** * Spy calls * * @author Christian Johansen (christian@cjohansen.no) * @author Maximilian Antoni (mail@maxantoni.de) * @license BSD * * Copyright (c) 2010-2013 Christian Johansen * Copyright (c) 2013 Maximilian Antoni */ var commonJSModule = typeof module == "object" && typeof require == "function"; if (!this.sinon && commonJSModule) { var sinon = require("../sinon"); } (function (sinon) { function throwYieldError(proxy, text, args) { var msg = sinon.functionName(proxy) + text; if (args.length) { msg += " Received [" + slice.call(args).join(", ") + "]"; } throw new Error(msg); } var slice = Array.prototype.slice; var callProto = { calledOn: function calledOn(thisValue) { if (sinon.match && sinon.match.isMatcher(thisValue)) { return thisValue.test(this.thisValue); } return this.thisValue === thisValue; }, calledWith: function calledWith() { for (var i = 0, l = arguments.length; i < l; i += 1) { if (!sinon.deepEqual(arguments[i], this.args[i])) { return false; } } return true; }, calledWithMatch: function calledWithMatch() { for (var i = 0, l = arguments.length; i < l; i += 1) { var actual = this.args[i]; var expectation = arguments[i]; if (!sinon.match || !sinon.match(expectation).test(actual)) { return false; } } return true; }, calledWithExactly: function calledWithExactly() { return arguments.length == this.args.length && this.calledWith.apply(this, arguments); }, notCalledWith: function notCalledWith() { return !this.calledWith.apply(this, arguments); }, notCalledWithMatch: function notCalledWithMatch() { return !this.calledWithMatch.apply(this, arguments); }, returned: function returned(value) { return sinon.deepEqual(value, this.returnValue); }, threw: function threw(error) { if (typeof error === "undefined" || !this.exception) { return !!this.exception; } return this.exception === error || this.exception.name === error; }, calledWithNew: function calledWithNew(thisValue) { return this.thisValue instanceof this.proxy; }, calledBefore: function (other) { return this.callId < other.callId; }, calledAfter: function (other) { return this.callId > other.callId; }, callArg: function (pos) { this.args[pos](); }, callArgOn: function (pos, thisValue) { this.args[pos].apply(thisValue); }, callArgWith: function (pos) { this.callArgOnWith.apply(this, [pos, null].concat(slice.call(arguments, 1))); }, callArgOnWith: function (pos, thisValue) { var args = slice.call(arguments, 2); this.args[pos].apply(thisValue, args); }, "yield": function () { this.yieldOn.apply(this, [null].concat(slice.call(arguments, 0))); }, yieldOn: function (thisValue) { var args = this.args; for (var i = 0, l = args.length; i < l; ++i) { if (typeof args[i] === "function") { args[i].apply(thisValue, slice.call(arguments, 1)); return; } } throwYieldError(this.proxy, " cannot yield since no callback was passed.", args); }, yieldTo: function (prop) { this.yieldToOn.apply(this, [prop, null].concat(slice.call(arguments, 1))); }, yieldToOn: function (prop, thisValue) { var args = this.args; for (var i = 0, l = args.length; i < l; ++i) { if (args[i] && typeof args[i][prop] === "function") { args[i][prop].apply(thisValue, slice.call(arguments, 2)); return; } } throwYieldError(this.proxy, " cannot yield to '" + prop + "' since no callback was passed.", args); }, toString: function () { var callStr = this.proxy.toString() + "("; var args = []; for (var i = 0, l = this.args.length; i < l; ++i) { args.push(sinon.format(this.args[i])); } callStr = callStr + args.join(", ") + ")"; if (typeof this.returnValue != "undefined") { callStr += " => " + sinon.format(this.returnValue); } if (this.exception) { callStr += " !" + this.exception.name; if (this.exception.message) { callStr += "(" + this.exception.message + ")"; } } return callStr; } }; callProto.invokeCallback = callProto.yield; function createSpyCall(spy, thisValue, args, returnValue, exception, id) { if (typeof id !== "number") { throw new TypeError("Call id is not a number"); } var proxyCall = sinon.create(callProto); proxyCall.proxy = spy; proxyCall.thisValue = thisValue; proxyCall.args = args; proxyCall.returnValue = returnValue; proxyCall.exception = exception; proxyCall.callId = id; return proxyCall; }; createSpyCall.toString = callProto.toString; // used by mocks sinon.spyCall = createSpyCall; }(typeof sinon == "object" && sinon || null)); /** * @depend ../sinon.js */ /*jslint eqeqeq: false, onevar: false, plusplus: false*/ /*global module, require, sinon*/ /** * Spy functions * * @author Christian Johansen (christian@cjohansen.no) * @license BSD * * Copyright (c) 2010-2013 Christian Johansen */ (function (sinon) { var commonJSModule = typeof module == "object" && typeof require == "function"; var push = Array.prototype.push; var slice = Array.prototype.slice; var callId = 0; function spy(object, property) { if (!property && typeof object == "function") { return spy.create(object); } if (!object && !property) { return spy.create(function () { }); } var method = object[property]; return sinon.wrapMethod(object, property, spy.create(method)); } function matchingFake(fakes, args, strict) { if (!fakes) { return; } var alen = args.length; for (var i = 0, l = fakes.length; i < l; i++) { if (fakes[i].matches(args, strict)) { return fakes[i]; } } } function incrementCallCount() { this.called = true; this.callCount += 1; this.notCalled = false; this.calledOnce = this.callCount == 1; this.calledTwice = this.callCount == 2; this.calledThrice = this.callCount == 3; } function createCallProperties() { this.firstCall = this.getCall(0); this.secondCall = this.getCall(1); this.thirdCall = this.getCall(2); this.lastCall = this.getCall(this.callCount - 1); } var vars = "a,b,c,d,e,f,g,h,i,j,k,l"; function createProxy(func) { // Retain the function length: var p; if (func.length) { eval("p = (function proxy(" + vars.substring(0, func.length * 2 - 1) + ") { return p.invoke(func, this, slice.call(arguments)); });"); } else { p = function proxy() { return p.invoke(func, this, slice.call(arguments)); }; } return p; } var uuid = 0; // Public API var spyApi = { reset: function () { this.called = false; this.notCalled = true; this.calledOnce = false; this.calledTwice = false; this.calledThrice = false; this.callCount = 0; this.firstCall = null; this.secondCall = null; this.thirdCall = null; this.lastCall = null; this.args = []; this.returnValues = []; this.thisValues = []; this.exceptions = []; this.callIds = []; if (this.fakes) { for (var i = 0; i < this.fakes.length; i++) { this.fakes[i].reset(); } } }, create: function create(func) { var name; if (typeof func != "function") { func = function () { }; } else { name = sinon.functionName(func); } var proxy = createProxy(func); sinon.extend(proxy, spy); delete proxy.create; sinon.extend(proxy, func); proxy.reset(); proxy.prototype = func.prototype; proxy.displayName = name || "spy"; proxy.toString = sinon.functionToString; proxy._create = sinon.spy.create; proxy.id = "spy#" + uuid++; return proxy; }, invoke: function invoke(func, thisValue, args) { var matching = matchingFake(this.fakes, args); var exception, returnValue; incrementCallCount.call(this); push.call(this.thisValues, thisValue); push.call(this.args, args); push.call(this.callIds, callId++); try { if (matching) { returnValue = matching.invoke(func, thisValue, args); } else { returnValue = (this.func || func).apply(thisValue, args); } } catch (e) { push.call(this.returnValues, undefined); exception = e; throw e; } finally { push.call(this.exceptions, exception); } push.call(this.returnValues, returnValue); createCallProperties.call(this); return returnValue; }, getCall: function getCall(i) { if (i < 0 || i >= this.callCount) { return null; } return sinon.spyCall(this, this.thisValues[i], this.args[i], this.returnValues[i], this.exceptions[i], this.callIds[i]); }, calledBefore: function calledBefore(spyFn) { if (!this.called) { return false; } if (!spyFn.called) { return true; } return this.callIds[0] < spyFn.callIds[spyFn.callIds.length - 1]; }, calledAfter: function calledAfter(spyFn) { if (!this.called || !spyFn.called) { return false; } return this.callIds[this.callCount - 1] > spyFn.callIds[spyFn.callCount - 1]; }, withArgs: function () { var args = slice.call(arguments); if (this.fakes) { var match = matchingFake(this.fakes, args, true); if (match) { return match; } } else { this.fakes = []; } var original = this; var fake = this._create(); fake.matchingAguments = args; push.call(this.fakes, fake); fake.withArgs = function () { return original.withArgs.apply(original, arguments); }; for (var i = 0; i < this.args.length; i++) { if (fake.matches(this.args[i])) { incrementCallCount.call(fake); push.call(fake.thisValues, this.thisValues[i]); push.call(fake.args, this.args[i]); push.call(fake.returnValues, this.returnValues[i]); push.call(fake.exceptions, this.exceptions[i]); push.call(fake.callIds, this.callIds[i]); } } createCallProperties.call(fake); return fake; }, matches: function (args, strict) { var margs = this.matchingAguments; if (margs.length <= args.length && sinon.deepEqual(margs, args.slice(0, margs.length))) { return !strict || margs.length == args.length; } }, printf: function (format) { var spy = this; var args = slice.call(arguments, 1); var formatter; return (format || "").replace(/%(.)/g, function (match, specifyer) { formatter = spyApi.formatters[specifyer]; if (typeof formatter == "function") { return formatter.call(null, spy, args); } else if (!isNaN(parseInt(specifyer), 10)) { return sinon.format(args[specifyer - 1]); } return "%" + specifyer; }); } }; function delegateToCalls(method, matchAny, actual, notCalled) { spyApi[method] = function () { if (!this.called) { if (notCalled) { return notCalled.apply(this, arguments); } return false; } var currentCall; var matches = 0; for (var i = 0, l = this.callCount; i < l; i += 1) { currentCall = this.getCall(i); if (currentCall[actual || method].apply(currentCall, arguments)) { matches += 1; if (matchAny) { return true; } } } return matches === this.callCount; }; } delegateToCalls("calledOn", true); delegateToCalls("alwaysCalledOn", false, "calledOn"); delegateToCalls("calledWith", true); delegateToCalls("calledWithMatch", true); delegateToCalls("alwaysCalledWith", false, "calledWith"); delegateToCalls("alwaysCalledWithMatch", false, "calledWithMatch"); delegateToCalls("calledWithExactly", true); delegateToCalls("alwaysCalledWithExactly", false, "calledWithExactly"); delegateToCalls("neverCalledWith", false, "notCalledWith", function () { return true; }); delegateToCalls("neverCalledWithMatch", false, "notCalledWithMatch", function () { return true; }); delegateToCalls("threw", true); delegateToCalls("alwaysThrew", false, "threw"); delegateToCalls("returned", true); delegateToCalls("alwaysReturned", false, "returned"); delegateToCalls("calledWithNew", true); delegateToCalls("alwaysCalledWithNew", false, "calledWithNew"); delegateToCalls("callArg", false, "callArgWith", function () { throw new Error(this.toString() + " cannot call arg since it was not yet invoked."); }); spyApi.callArgWith = spyApi.callArg; delegateToCalls("callArgOn", false, "callArgOnWith", function () { throw new Error(this.toString() + " cannot call arg since it was not yet invoked."); }); spyApi.callArgOnWith = spyApi.callArgOn; delegateToCalls("yield", false, "yield", function () { throw new Error(this.toString() + " cannot yield since it was not yet invoked."); }); // "invokeCallback" is an alias for "yield" since "yield" is invalid in strict mode. spyApi.invokeCallback = spyApi.yield; delegateToCalls("yieldOn", false, "yieldOn", function () { throw new Error(this.toString() + " cannot yield since it was not yet invoked."); }); delegateToCalls("yieldTo", false, "yieldTo", function (property) { throw new Error(this.toString() + " cannot yield to '" + property + "' since it was not yet invoked."); }); delegateToCalls("yieldToOn", false, "yieldToOn", function (property) { throw new Error(this.toString() + " cannot yield to '" + property + "' since it was not yet invoked."); }); spyApi.formatters = { "c": function (spy) { return sinon.timesInWords(spy.callCount); }, "n": function (spy) { return spy.toString(); }, "C": function (spy) { var calls = []; for (var i = 0, l = spy.callCount; i < l; ++i) { var stringifiedCall = " " + spy.getCall(i).toString(); if (/\n/.test(calls[i - 1])) { stringifiedCall = "\n" + stringifiedCall; } push.call(calls, stringifiedCall); } return calls.length > 0 ? "\n" + calls.join("\n") : ""; }, "t": function (spy) { var objects = []; for (var i = 0, l = spy.callCount; i < l; ++i) { push.call(objects, sinon.format(spy.thisValues[i])); } return objects.join(", "); }, "*": function (spy, args) { var formatted = []; for (var i = 0, l = args.length; i < l; ++i) { push.call(formatted, sinon.format(args[i])); } return formatted.join(", "); } }; sinon.extend(spy, spyApi); spy.spyCall = sinon.spyCall; if (commonJSModule) { module.exports = spy; } else { sinon.spy = spy; } }(typeof sinon == "object" && sinon || null)); /** * @depend ../sinon.js * @depend spy.js */ /*jslint eqeqeq: false, onevar: false*/ /*global module, require, sinon*/ /** * Stub functions * * @author Christian Johansen (christian@cjohansen.no) * @license BSD * * Copyright (c) 2010-2013 Christian Johansen */ (function (sinon) { var commonJSModule = typeof module == "object" && typeof require == "function"; if (!sinon && commonJSModule) { sinon = require("../sinon"); } if (!sinon) { return; } function stub(object, property, func) { if (!!func && typeof func != "function") { throw new TypeError("Custom stub should be function"); } var wrapper; if (func) { wrapper = sinon.spy && sinon.spy.create ? sinon.spy.create(func) : func; } else { wrapper = stub.create(); } if (!object && !property) { return sinon.stub.create(); } if (!property && !!object && typeof object == "object") { for (var prop in object) { if (typeof object[prop] === "function") { stub(object, prop); } } return object; } return sinon.wrapMethod(object, property, wrapper); } function getChangingValue(stub, property) { var index = stub.callCount - 1; var values = stub[property]; var prop = index in values ? values[index] : values[values.length - 1]; stub[property + "Last"] = prop; return prop; } function getCallback(stub, args) { var callArgAt = getChangingValue(stub, "callArgAts"); if (callArgAt < 0) { var callArgProp = getChangingValue(stub, "callArgProps"); for (var i = 0, l = args.length; i < l; ++i) { if (!callArgProp && typeof args[i] == "function") { return args[i]; } if (callArgProp && args[i] && typeof args[i][callArgProp] == "function") { return args[i][callArgProp]; } } return null; } return args[callArgAt]; } var join = Array.prototype.join; function getCallbackError(stub, func, args) { if (stub.callArgAtsLast < 0) { var msg; if (stub.callArgPropsLast) { msg = sinon.functionName(stub) + " expected to yield to '" + stub.callArgPropsLast + "', but no object with such a property was passed." } else { msg = sinon.functionName(stub) + " expected to yield, but no callback was passed." } if (args.length > 0) { msg += " Received [" + join.call(args, ", ") + "]"; } return msg; } return "argument at index " + stub.callArgAtsLast + " is not a function: " + func; } var nextTick = (function () { if (typeof process === "object" && typeof process.nextTick === "function") { return process.nextTick; } else if (typeof setImmediate === "function") { return setImmediate; } else { return function (callback) { setTimeout(callback, 0); }; } })(); function callCallback(stub, args) { if (stub.callArgAts.length > 0) { var func = getCallback(stub, args); if (typeof func != "function") { throw new TypeError(getCallbackError(stub, func, args)); } var callbackArguments = getChangingValue(stub, "callbackArguments"); var callbackContext = getChangingValue(stub, "callbackContexts"); if (stub.callbackAsync) { nextTick(function() { func.apply(callbackContext, callbackArguments); }); } else { func.apply(callbackContext, callbackArguments); } } } var uuid = 0; sinon.extend(stub, (function () { var slice = Array.prototype.slice, proto; function throwsException(error, message) { if (typeof error == "string") { this.exception = new Error(message || ""); this.exception.name = error; } else if (!error) { this.exception = new Error("Error"); } else { this.exception = error; } return this; } proto = { create: function create() { var functionStub = function () { callCallback(functionStub, arguments); if (functionStub.exception) { throw functionStub.exception; } else if (typeof functionStub.returnArgAt == 'number') { return arguments[functionStub.returnArgAt]; } else if (functionStub.returnThis) { return this; } return functionStub.returnValue; }; functionStub.id = "stub#" + uuid++; var orig = functionStub; functionStub = sinon.spy.create(functionStub); functionStub.func = orig; functionStub.callArgAts = []; functionStub.callbackArguments = []; functionStub.callbackContexts = []; functionStub.callArgProps = []; sinon.extend(functionStub, stub); functionStub._create = sinon.stub.create; functionStub.displayName = "stub"; functionStub.toString = sinon.functionToString; return functionStub; }, resetBehavior: function () { var i; this.callArgAts = []; this.callbackArguments = []; this.callbackContexts = []; this.callArgProps = []; delete this.returnValue; delete this.returnArgAt; this.returnThis = false; if (this.fakes) { for (i = 0; i < this.fakes.length; i++) { this.fakes[i].resetBehavior(); } } }, returns: function returns(value) { this.returnValue = value; return this; }, returnsArg: function returnsArg(pos) { if (typeof pos != "number") { throw new TypeError("argument index is not number"); } this.returnArgAt = pos; return this; }, returnsThis: function returnsThis() { this.returnThis = true; return this; }, "throws": throwsException, throwsException: throwsException, callsArg: function callsArg(pos) { if (typeof pos != "number") { throw new TypeError("argument index is not number"); } this.callArgAts.push(pos); this.callbackArguments.push([]); this.callbackContexts.push(undefined); this.callArgProps.push(undefined); return this; }, callsArgOn: function callsArgOn(pos, context) { if (typeof pos != "number") { throw new TypeError("argument index is not number"); } if (typeof context != "object") { throw new TypeError("argument context is not an object"); } this.callArgAts.push(pos); this.callbackArguments.push([]); this.callbackContexts.push(context); this.callArgProps.push(undefined); return this; }, callsArgWith: function callsArgWith(pos) { if (typeof pos != "number") { throw new TypeError("argument index is not number"); } this.callArgAts.push(pos); this.callbackArguments.push(slice.call(arguments, 1)); this.callbackContexts.push(undefined); this.callArgProps.push(undefined); return this; }, callsArgOnWith: function callsArgWith(pos, context) { if (typeof pos != "number") { throw new TypeError("argument index is not number"); } if (typeof context != "object") { throw new TypeError("argument context is not an object"); } this.callArgAts.push(pos); this.callbackArguments.push(slice.call(arguments, 2)); this.callbackContexts.push(context); this.callArgProps.push(undefined); return this; }, yields: function () { this.callArgAts.push(-1); this.callbackArguments.push(slice.call(arguments, 0)); this.callbackContexts.push(undefined); this.callArgProps.push(undefined); return this; }, yieldsOn: function (context) { if (typeof context != "object") { throw new TypeError("argument context is not an object"); } this.callArgAts.push(-1); this.callbackArguments.push(slice.call(arguments, 1)); this.callbackContexts.push(context); this.callArgProps.push(undefined); return this; }, yieldsTo: function (prop) { this.callArgAts.push(-1); this.callbackArguments.push(slice.call(arguments, 1)); this.callbackContexts.push(undefined); this.callArgProps.push(prop); return this; }, yieldsToOn: function (prop, context) { if (typeof context != "object") { throw new TypeError("argument context is not an object"); } this.callArgAts.push(-1); this.callbackArguments.push(slice.call(arguments, 2)); this.callbackContexts.push(context); this.callArgProps.push(prop); return this; } }; // create asynchronous versions of callsArg* and yields* methods for (var method in proto) { // need to avoid creating anotherasync versions of the newly added async methods if (proto.hasOwnProperty(method) && method.match(/^(callsArg|yields|thenYields$)/) && !method.match(/Async/)) { proto[method + 'Async'] = (function (syncFnName) { return function () { this.callbackAsync = true; return this[syncFnName].apply(this, arguments); }; })(method); } } return proto; }())); if (commonJSModule) { module.exports = stub; } else { sinon.stub = stub; } }(typeof sinon == "object" && sinon || null)); /** * @depend ../sinon.js * @depend stub.js */ /*jslint eqeqeq: false, onevar: false, nomen: false*/ /*global module, require, sinon*/ /** * Mock functions. * * @author Christian Johansen (christian@cjohansen.no) * @license BSD * * Copyright (c) 2010-2013 Christian Johansen */ (function (sinon) { var commonJSModule = typeof module == "object" && typeof require == "function"; var push = [].push; if (!sinon && commonJSModule) { sinon = require("../sinon"); } if (!sinon) { return; } function mock(object) { if (!object) { return sinon.expectation.create("Anonymous mock"); } return mock.create(object); } sinon.mock = mock; sinon.extend(mock, (function () { function each(collection, callback) { if (!collection) { return; } for (var i = 0, l = collection.length; i < l; i += 1) { callback(collection[i]); } } return { create: function create(object) { if (!object) { throw new TypeError("object is null"); } var mockObject = sinon.extend({}, mock); mockObject.object = object; delete mockObject.create; return mockObject; }, expects: function expects(method) { if (!method) { throw new TypeError("method is falsy"); } if (!this.expectations) { this.expectations = {}; this.proxies = []; } if (!this.expectations[method]) { this.expectations[method] = []; var mockObject = this; sinon.wrapMethod(this.object, method, function () { return mockObject.invokeMethod(method, this, arguments); }); push.call(this.proxies, method); } var expectation = sinon.expectation.create(method); push.call(this.expectations[method], expectation); return expectation; }, restore: function restore() { var object = this.object; each(this.proxies, function (proxy) { if (typeof object[proxy].restore == "function") { object[proxy].restore(); } }); }, verify: function verify() { var expectations = this.expectations || {}; var messages = [], met = []; each(this.proxies, function (proxy) { each(expectations[proxy], function (expectation) { if (!expectation.met()) { push.call(messages, expectation.toString()); } else { push.call(met, expectation.toString()); } }); }); this.restore(); if (messages.length > 0) { sinon.expectation.fail(messages.concat(met).join("\n")); } else { sinon.expectation.pass(messages.concat(met).join("\n")); } return true; }, invokeMethod: function invokeMethod(method, thisValue, args) { var expectations = this.expectations && this.expectations[method]; var length = expectations && expectations.length || 0, i; for (i = 0; i < length; i += 1) { if (!expectations[i].met() && expectations[i].allowsCall(thisValue, args)) { return expectations[i].apply(thisValue, args); } } var messages = [], available, exhausted = 0; for (i = 0; i < length; i += 1) { if (expectations[i].allowsCall(thisValue, args)) { available = available || expectations[i]; } else { exhausted += 1; } push.call(messages, " " + expectations[i].toString()); } if (exhausted === 0) { return available.apply(thisValue, args); } messages.unshift("Unexpected call: " + sinon.spyCall.toString.call({ proxy: method, args: args })); sinon.expectation.fail(messages.join("\n")); } }; }())); var times = sinon.timesInWords; sinon.expectation = (function () { var slice = Array.prototype.slice; var _invoke = sinon.spy.invoke; function callCountInWords(callCount) { if (callCount == 0) { return "never called"; } else { return "called " + times(callCount); } } function expectedCallCountInWords(expectation) { var min = expectation.minCalls; var max = expectation.maxCalls; if (typeof min == "number" && typeof max == "number") { var str = times(min); if (min != max) { str = "at least " + str + " and at most " + times(max); } return str; } if (typeof min == "number") { return "at least " + times(min); } return "at most " + times(max); } function receivedMinCalls(expectation) { var hasMinLimit = typeof expectation.minCalls == "number"; return !hasMinLimit || expectation.callCount >= expectation.minCalls; } function receivedMaxCalls(expectation) { if (typeof expectation.maxCalls != "number") { return false; } return expectation.callCount == expectation.maxCalls; } return { minCalls: 1, maxCalls: 1, create: function create(methodName) { var expectation = sinon.extend(sinon.stub.create(), sinon.expectation); delete expectation.create; expectation.method = methodName; return expectation; }, invoke: function invoke(func, thisValue, args) { this.verifyCallAllowed(thisValue, args); return _invoke.apply(this, arguments); }, atLeast: function atLeast(num) { if (typeof num != "number") { throw new TypeError("'" + num + "' is not number"); } if (!this.limitsSet) { this.maxCalls = null; this.limitsSet = true; } this.minCalls = num; return this; }, atMost: function atMost(num) { if (typeof num != "number") { throw new TypeError("'" + num + "' is not number"); } if (!this.limitsSet) { this.minCalls = null; this.limitsSet = true; } this.maxCalls = num; return this; }, never: function never() { return this.exactly(0); }, once: function once() { return this.exactly(1); }, twice: function twice() { return this.exactly(2); }, thrice: function thrice() { return this.exactly(3); }, exactly: function exactly(num) { if (typeof num != "number") { throw new TypeError("'" + num + "' is not a number"); } this.atLeast(num); return this.atMost(num); }, met: function met() { return !this.failed && receivedMinCalls(this); }, verifyCallAllowed: function verifyCallAllowed(thisValue, args) { if (receivedMaxCalls(this)) { this.failed = true; sinon.expectation.fail(this.method + " already called " + times(this.maxCalls)); } if ("expectedThis" in this && this.expectedThis !== thisValue) { sinon.expectation.fail(this.method + " called with " + thisValue + " as thisValue, expected " + this.expectedThis); } if (!("expectedArguments" in this)) { return; } if (!args) { sinon.expectation.fail(this.method + " received no arguments, expected " + sinon.format(this.expectedArguments)); } if (args.length < this.expectedArguments.length) { sinon.expectation.fail(this.method + " received too few arguments (" + sinon.format(args) + "), expected " + sinon.format(this.expectedArguments)); } if (this.expectsExactArgCount && args.length != this.expectedArguments.length) { sinon.expectation.fail(this.method + " received too many arguments (" + sinon.format(args) + "), expected " + sinon.format(this.expectedArguments)); } for (var i = 0, l = this.expectedArguments.length; i < l; i += 1) { if (!sinon.deepEqual(this.expectedArguments[i], args[i])) { sinon.expectation.fail(this.method + " received wrong arguments " + sinon.format(args) + ", expected " + sinon.format(this.expectedArguments)); } } }, allowsCall: function allowsCall(thisValue, args) { if (this.met() && receivedMaxCalls(this)) { return false; } if ("expectedThis" in this && this.expectedThis !== thisValue) { return false; } if (!("expectedArguments" in this)) { return true; } args = args || []; if (args.length < this.expectedArguments.length) { return false; } if (this.expectsExactArgCount && args.length != this.expectedArguments.length) { return false; } for (var i = 0, l = this.expectedArguments.length; i < l; i += 1) { if (!sinon.deepEqual(this.expectedArguments[i], args[i])) { return false; } } return true; }, withArgs: function withArgs() { this.expectedArguments = slice.call(arguments); return this; }, withExactArgs: function withExactArgs() { this.withArgs.apply(this, arguments); this.expectsExactArgCount = true; return this; }, on: function on(thisValue) { this.expectedThis = thisValue; return this; }, toString: function () { var args = (this.expectedArguments || []).slice(); if (!this.expectsExactArgCount) { push.call(args, "[...]"); } var callStr = sinon.spyCall.toString.call({ proxy: this.method || "anonymous mock expectation", args: args }); var message = callStr.replace(", [...", "[, ...") + " " + expectedCallCountInWords(this); if (this.met()) { return "Expectation met: " + message; } return "Expected " + message + " (" + callCountInWords(this.callCount) + ")"; }, verify: function verify() { if (!this.met()) { sinon.expectation.fail(this.toString()); } else { sinon.expectation.pass(this.toString()); } return true; }, pass: function(message) { sinon.assert.pass(message); }, fail: function (message) { var exception = new Error(message); exception.name = "ExpectationError"; throw exception; } }; }()); if (commonJSModule) { module.exports = mock; } else { sinon.mock = mock; } }(typeof sinon == "object" && sinon || null)); /** * @depend ../sinon.js * @depend stub.js * @depend mock.js */ /*jslint eqeqeq: false, onevar: false, forin: true*/ /*global module, require, sinon*/ /** * Collections of stubs, spies and mocks. * * @author Christian Johansen (christian@cjohansen.no) * @license BSD * * Copyright (c) 2010-2013 Christian Johansen */ (function (sinon) { var commonJSModule = typeof module == "object" && typeof require == "function"; var push = [].push; var hasOwnProperty = Object.prototype.hasOwnProperty; if (!sinon && commonJSModule) { sinon = require("../sinon"); } if (!sinon) { return; } function getFakes(fakeCollection) { if (!fakeCollection.fakes) { fakeCollection.fakes = []; } return fakeCollection.fakes; } function each(fakeCollection, method) { var fakes = getFakes(fakeCollection); for (var i = 0, l = fakes.length; i < l; i += 1) { if (typeof fakes[i][method] == "function") { fakes[i][method](); } } } function compact(fakeCollection) { var fakes = getFakes(fakeCollection); var i = 0; while (i < fakes.length) { fakes.splice(i, 1); } } var collection = { verify: function resolve() { each(this, "verify"); }, restore: function restore() { each(this, "restore"); compact(this); }, verifyAndRestore: function verifyAndRestore() { var exception; try { this.verify(); } catch (e) { exception = e; } this.restore(); if (exception) { throw exception; } }, add: function add(fake) { push.call(getFakes(this), fake); return fake; }, spy: function spy() { return this.add(sinon.spy.apply(sinon, arguments)); }, stub: function stub(object, property, value) { if (property) { var original = object[property]; if (typeof original != "function") { if (!hasOwnProperty.call(object, property)) { throw new TypeError("Cannot stub non-existent own property " + property); } object[property] = value; return this.add({ restore: function () { object[property] = original; } }); } } if (!property && !!object && typeof object == "object") { var stubbedObj = sinon.stub.apply(sinon, arguments); for (var prop in stubbedObj) { if (typeof stubbedObj[prop] === "function") { this.add(stubbedObj[prop]); } } return stubbedObj; } return this.add(sinon.stub.apply(sinon, arguments)); }, mock: function mock() { return this.add(sinon.mock.apply(sinon, arguments)); }, inject: function inject(obj) { var col = this; obj.spy = function () { return col.spy.apply(col, arguments); }; obj.stub = function () { return col.stub.apply(col, arguments); }; obj.mock = function () { return col.mock.apply(col, arguments); }; return obj; } }; if (commonJSModule) { module.exports = collection; } else { sinon.collection = collection; } }(typeof sinon == "object" && sinon || null)); /*jslint eqeqeq: false, plusplus: false, evil: true, onevar: false, browser: true, forin: false*/ /*global module, require, window*/ /** * Fake timer API * setTimeout * setInterval * clearTimeout * clearInterval * tick * reset * Date * * Inspired by jsUnitMockTimeOut from JsUnit * * @author Christian Johansen (christian@cjohansen.no) * @license BSD * * Copyright (c) 2010-2013 Christian Johansen */ if (typeof sinon == "undefined") { var sinon = {}; } (function (global) { var id = 1; function addTimer(args, recurring) { if (args.length === 0) { throw new Error("Function requires at least 1 parameter"); } var toId = id++; var delay = args[1] || 0; if (!this.timeouts) { this.timeouts = {}; } this.timeouts[toId] = { id: toId, func: args[0], callAt: this.now + delay, invokeArgs: Array.prototype.slice.call(args, 2) }; if (recurring === true) { this.timeouts[toId].interval = delay; } return toId; } function parseTime(str) { if (!str) { return 0; } var strings = str.split(":"); var l = strings.length, i = l; var ms = 0, parsed; if (l > 3 || !/^(\d\d:){0,2}\d\d?$/.test(str)) { throw new Error("tick only understands numbers and 'h:m:s'"); } while (i--) { parsed = parseInt(strings[i], 10); if (parsed >= 60) { throw new Error("Invalid time " + str); } ms += parsed * Math.pow(60, (l - i - 1)); } return ms * 1000; } function createObject(object) { var newObject; if (Object.create) { newObject = Object.create(object); } else { var F = function () {}; F.prototype = object; newObject = new F(); } newObject.Date.clock = newObject; return newObject; } sinon.clock = { now: 0, create: function create(now) { var clock = createObject(this); if (typeof now == "number") { clock.now = now; } if (!!now && typeof now == "object") { throw new TypeError("now should be milliseconds since UNIX epoch"); } return clock; }, setTimeout: function setTimeout(callback, timeout) { return addTimer.call(this, arguments, false); }, clearTimeout: function clearTimeout(timerId) { if (!this.timeouts) { this.timeouts = []; } if (timerId in this.timeouts) { delete this.timeouts[timerId]; } }, setInterval: function setInterval(callback, timeout) { return addTimer.call(this, arguments, true); }, clearInterval: function clearInterval(timerId) { this.clearTimeout(timerId); }, tick: function tick(ms) { ms = typeof ms == "number" ? ms : parseTime(ms); var tickFrom = this.now, tickTo = this.now + ms, previous = this.now; var timer = this.firstTimerInRange(tickFrom, tickTo); var firstException; while (timer && tickFrom <= tickTo) { if (this.timeouts[timer.id]) { tickFrom = this.now = timer.callAt; try { this.callTimer(timer); } catch (e) { firstException = firstException || e; } } timer = this.firstTimerInRange(previous, tickTo); previous = tickFrom; } this.now = tickTo; if (firstException) { throw firstException; } return this.now; }, firstTimerInRange: function (from, to) { var timer, smallest, originalTimer; for (var id in this.timeouts) { if (this.timeouts.hasOwnProperty(id)) { if (this.timeouts[id].callAt < from || this.timeouts[id].callAt > to) { continue; } if (!smallest || this.timeouts[id].callAt < smallest) { originalTimer = this.timeouts[id]; smallest = this.timeouts[id].callAt; timer = { func: this.timeouts[id].func, callAt: this.timeouts[id].callAt, interval: this.timeouts[id].interval, id: this.timeouts[id].id, invokeArgs: this.timeouts[id].invokeArgs }; } } } return timer || null; }, callTimer: function (timer) { if (typeof timer.interval == "number") { this.timeouts[timer.id].callAt += timer.interval; } else { delete this.timeouts[timer.id]; } try { if (typeof timer.func == "function") { timer.func.apply(null, timer.invokeArgs); } else { eval(timer.func); } } catch (e) { var exception = e; } if (!this.timeouts[timer.id]) { if (exception) { throw exception; } return; } if (exception) { throw exception; } }, reset: function reset() { this.timeouts = {}; }, Date: (function () { var NativeDate = Date; function ClockDate(year, month, date, hour, minute, second, ms) { // Defensive and verbose to avoid potential harm in passing // explicit undefined when user does not pass argument switch (arguments.length) { case 0: return new NativeDate(ClockDate.clock.now); case 1: return new NativeDate(year); case 2: return new NativeDate(year, month); case 3: return new NativeDate(year, month, date); case 4: return new NativeDate(year, month, date, hour); case 5: return new NativeDate(year, month, date, hour, minute); case 6: return new NativeDate(year, month, date, hour, minute, second); default: return new NativeDate(year, month, date, hour, minute, second, ms); } } return mirrorDateProperties(ClockDate, NativeDate); }()) }; function mirrorDateProperties(target, source) { if (source.now) { target.now = function now() { return target.clock.now; }; } else { delete target.now; } if (source.toSource) { target.toSource = function toSource() { return source.toSource(); }; } else { delete target.toSource; } target.toString = function toString() { return source.toString(); }; target.prototype = source.prototype; target.parse = source.parse; target.UTC = source.UTC; target.prototype.toUTCString = source.prototype.toUTCString; return target; } var methods = ["Date", "setTimeout", "setInterval", "clearTimeout", "clearInterval"]; function restore() { var method; for (var i = 0, l = this.methods.length; i < l; i++) { method = this.methods[i]; if (global[method].hadOwnProperty) { global[method] = this["_" + method]; } else { delete global[method]; } } // Prevent multiple executions which will completely remove these props this.methods = []; } function stubGlobal(method, clock) { clock[method].hadOwnProperty = Object.prototype.hasOwnProperty.call(global, method); clock["_" + method] = global[method]; if (method == "Date") { var date = mirrorDateProperties(clock[method], global[method]); global[method] = date; } else { global[method] = function () { return clock[method].apply(clock, arguments); }; for (var prop in clock[method]) { if (clock[method].hasOwnProperty(prop)) { global[method][prop] = clock[method][prop]; } } } global[method].clock = clock; } sinon.useFakeTimers = function useFakeTimers(now) { var clock = sinon.clock.create(now); clock.restore = restore; clock.methods = Array.prototype.slice.call(arguments, typeof now == "number" ? 1 : 0); if (clock.methods.length === 0) { clock.methods = methods; } for (var i = 0, l = clock.methods.length; i < l; i++) { stubGlobal(clock.methods[i], clock); } return clock; }; }(typeof global != "undefined" && typeof global !== "function" ? global : this)); sinon.timers = { setTimeout: setTimeout, clearTimeout: clearTimeout, setInterval: setInterval, clearInterval: clearInterval, Date: Date }; if (typeof module == "object" && typeof require == "function") { module.exports = sinon; } /*jslint eqeqeq: false, onevar: false*/ /*global sinon, module, require, ActiveXObject, XMLHttpRequest, DOMParser*/ /** * Minimal Event interface implementation * * Original implementation by Sven Fuchs: https://gist.github.com/995028 * Modifications and tests by Christian Johansen. * * @author Sven Fuchs (svenfuchs@artweb-design.de) * @author Christian Johansen (christian@cjohansen.no) * @license BSD * * Copyright (c) 2011 Sven Fuchs, Christian Johansen */ if (typeof sinon == "undefined") { this.sinon = {}; } (function () { var push = [].push; sinon.Event = function Event(type, bubbles, cancelable, target) { this.initEvent(type, bubbles, cancelable, target); }; sinon.Event.prototype = { initEvent: function(type, bubbles, cancelable, target) { this.type = type; this.bubbles = bubbles; this.cancelable = cancelable; this.target = target; }, stopPropagation: function () {}, preventDefault: function () { this.defaultPrevented = true; } }; sinon.EventTarget = { addEventListener: function addEventListener(event, listener, useCapture) { this.eventListeners = this.eventListeners || {}; this.eventListeners[event] = this.eventListeners[event] || []; push.call(this.eventListeners[event], listener); }, removeEventListener: function removeEventListener(event, listener, useCapture) { var listeners = this.eventListeners && this.eventListeners[event] || []; for (var i = 0, l = listeners.length; i < l; ++i) { if (listeners[i] == listener) { return listeners.splice(i, 1); } } }, dispatchEvent: function dispatchEvent(event) { var type = event.type; var listeners = this.eventListeners && this.eventListeners[type] || []; for (var i = 0; i < listeners.length; i++) { if (typeof listeners[i] == "function") { listeners[i].call(this, event); } else { listeners[i].handleEvent(event); } } return !!event.defaultPrevented; } }; }()); /** * @depend ../../sinon.js * @depend event.js */ /*jslint eqeqeq: false, onevar: false*/ /*global sinon, module, require, ActiveXObject, XMLHttpRequest, DOMParser*/ /** * Fake XMLHttpRequest object * * @author Christian Johansen (christian@cjohansen.no) * @license BSD * * Copyright (c) 2010-2013 Christian Johansen */ if (typeof sinon == "undefined") { this.sinon = {}; } sinon.xhr = { XMLHttpRequest: this.XMLHttpRequest }; // wrapper for global (function(global) { var xhr = sinon.xhr; xhr.GlobalXMLHttpRequest = global.XMLHttpRequest; xhr.GlobalActiveXObject = global.ActiveXObject; xhr.supportsActiveX = typeof xhr.GlobalActiveXObject != "undefined"; xhr.supportsXHR = typeof xhr.GlobalXMLHttpRequest != "undefined"; xhr.workingXHR = xhr.supportsXHR ? xhr.GlobalXMLHttpRequest : xhr.supportsActiveX ? function() { return new xhr.GlobalActiveXObject("MSXML2.XMLHTTP.3.0") } : false; /*jsl:ignore*/ var unsafeHeaders = { "Accept-Charset": true, "Accept-Encoding": true, "Connection": true, "Content-Length": true, "Cookie": true, "Cookie2": true, "Content-Transfer-Encoding": true, "Date": true, "Expect": true, "Host": true, "Keep-Alive": true, "Referer": true, "TE": true, "Trailer": true, "Transfer-Encoding": true, "Upgrade": true, "User-Agent": true, "Via": true }; /*jsl:end*/ function FakeXMLHttpRequest() { this.readyState = FakeXMLHttpRequest.UNSENT; this.requestHeaders = {}; this.requestBody = null; this.status = 0; this.statusText = ""; var xhr = this; var events = ["loadstart", "load", "abort", "loadend"]; function addEventListener(eventName) { xhr.addEventListener(eventName, function (event) { var listener = xhr["on" + eventName]; if (listener && typeof listener == "function") { listener(event); } }); } for (var i = events.length - 1; i >= 0; i--) { addEventListener(events[i]); } if (typeof FakeXMLHttpRequest.onCreate == "function") { FakeXMLHttpRequest.onCreate(this); } } function verifyState(xhr) { if (xhr.readyState !== FakeXMLHttpRequest.OPENED) { throw new Error("INVALID_STATE_ERR"); } if (xhr.sendFlag) { throw new Error("INVALID_STATE_ERR"); } } // filtering to enable a white-list version of Sinon FakeXhr, // where whitelisted requests are passed through to real XHR function each(collection, callback) { if (!collection) return; for (var i = 0, l = collection.length; i < l; i += 1) { callback(collection[i]); } } function some(collection, callback) { for (var index = 0; index < collection.length; index++) { if(callback(collection[index]) === true) return true; }; return false; } // largest arity in XHR is 5 - XHR#open var apply = function(obj,method,args) { switch(args.length) { case 0: return obj[method](); case 1: return obj[method](args[0]); case 2: return obj[method](args[0],args[1]); case 3: return obj[method](args[0],args[1],args[2]); case 4: return obj[method](args[0],args[1],args[2],args[3]); case 5: return obj[method](args[0],args[1],args[2],args[3],args[4]); }; }; FakeXMLHttpRequest.filters = []; FakeXMLHttpRequest.addFilter = function(fn) { this.filters.push(fn) }; var IE6Re = /MSIE 6/; FakeXMLHttpRequest.defake = function(fakeXhr,xhrArgs) { var xhr = new sinon.xhr.workingXHR(); each(["open","setRequestHeader","send","abort","getResponseHeader", "getAllResponseHeaders","addEventListener","overrideMimeType","removeEventListener"], function(method) { fakeXhr[method] = function() { return apply(xhr,method,arguments); }; }); var copyAttrs = function(args) { each(args, function(attr) { try { fakeXhr[attr] = xhr[attr] } catch(e) { if(!IE6Re.test(navigator.userAgent)) throw e; } }); }; var stateChange = function() { fakeXhr.readyState = xhr.readyState; if(xhr.readyState >= FakeXMLHttpRequest.HEADERS_RECEIVED) { copyAttrs(["status","statusText"]); } if(xhr.readyState >= FakeXMLHttpRequest.LOADING) { copyAttrs(["responseText"]); } if(xhr.readyState === FakeXMLHttpRequest.DONE) { copyAttrs(["responseXML"]); } if(fakeXhr.onreadystatechange) fakeXhr.onreadystatechange.call(fakeXhr); }; if(xhr.addEventListener) { for(var event in fakeXhr.eventListeners) { if(fakeXhr.eventListeners.hasOwnProperty(event)) { each(fakeXhr.eventListeners[event],function(handler) { xhr.addEventListener(event, handler); }); } } xhr.addEventListener("readystatechange",stateChange); } else { xhr.onreadystatechange = stateChange; } apply(xhr,"open",xhrArgs); }; FakeXMLHttpRequest.useFilters = false; function verifyRequestSent(xhr) { if (xhr.readyState == FakeXMLHttpRequest.DONE) { throw new Error("Request done"); } } function verifyHeadersReceived(xhr) { if (xhr.async && xhr.readyState != FakeXMLHttpRequest.HEADERS_RECEIVED) { throw new Error("No headers received"); } } function verifyResponseBodyType(body) { if (typeof body != "string") { var error = new Error("Attempted to respond to fake XMLHttpRequest with " + body + ", which is not a string."); error.name = "InvalidBodyException"; throw error; } } sinon.extend(FakeXMLHttpRequest.prototype, sinon.EventTarget, { async: true, open: function open(method, url, async, username, password) { this.method = method; this.url = url; this.async = typeof async == "boolean" ? async : true; this.username = username; this.password = password; this.responseText = null; this.responseXML = null; this.requestHeaders = {}; this.sendFlag = false; if(sinon.FakeXMLHttpRequest.useFilters === true) { var xhrArgs = arguments; var defake = some(FakeXMLHttpRequest.filters,function(filter) { return filter.apply(this,xhrArgs) }); if (defake) { return sinon.FakeXMLHttpRequest.defake(this,arguments); } } this.readyStateChange(FakeXMLHttpRequest.OPENED); }, readyStateChange: function readyStateChange(state) { this.readyState = state; if (typeof this.onreadystatechange == "function") { try { this.onreadystatechange(); } catch (e) { sinon.logError("Fake XHR onreadystatechange handler", e); } } this.dispatchEvent(new sinon.Event("readystatechange")); switch (this.readyState) { case FakeXMLHttpRequest.DONE: this.dispatchEvent(new sinon.Event("load", false, false, this)); this.dispatchEvent(new sinon.Event("loadend", false, false, this)); break; } }, setRequestHeader: function setRequestHeader(header, value) { verifyState(this); if (unsafeHeaders[header] || /^(Sec-|Proxy-)/.test(header)) { throw new Error("Refused to set unsafe header \"" + header + "\""); } if (this.requestHeaders[header]) { this.requestHeaders[header] += "," + value; } else { this.requestHeaders[header] = value; } }, // Helps testing setResponseHeaders: function setResponseHeaders(headers) { this.responseHeaders = {}; for (var header in headers) { if (headers.hasOwnProperty(header)) { this.responseHeaders[header] = headers[header]; } } if (this.async) { this.readyStateChange(FakeXMLHttpRequest.HEADERS_RECEIVED); } else { this.readyState = FakeXMLHttpRequest.HEADERS_RECEIVED; } }, // Currently treats ALL data as a DOMString (i.e. no Document) send: function send(data) { verifyState(this); if (!/^(get|head)$/i.test(this.method)) { if (this.requestHeaders["Content-Type"]) { var value = this.requestHeaders["Content-Type"].split(";"); this.requestHeaders["Content-Type"] = value[0] + ";charset=utf-8"; } else { this.requestHeaders["Content-Type"] = "text/plain;charset=utf-8"; } this.requestBody = data; } this.errorFlag = false; this.sendFlag = this.async; this.readyStateChange(FakeXMLHttpRequest.OPENED); if (typeof this.onSend == "function") { this.onSend(this); } this.dispatchEvent(new sinon.Event("loadstart", false, false, this)); }, abort: function abort() { this.aborted = true; this.responseText = null; this.errorFlag = true; this.requestHeaders = {}; if (this.readyState > sinon.FakeXMLHttpRequest.UNSENT && this.sendFlag) { this.readyStateChange(sinon.FakeXMLHttpRequest.DONE); this.sendFlag = false; } this.readyState = sinon.FakeXMLHttpRequest.UNSENT; this.dispatchEvent(new sinon.Event("abort", false, false, this)); if (typeof this.onerror === "function") { this.onerror(); } }, getResponseHeader: function getResponseHeader(header) { if (this.readyState < FakeXMLHttpRequest.HEADERS_RECEIVED) { return null; } if (/^Set-Cookie2?$/i.test(header)) { return null; } header = header.toLowerCase(); for (var h in this.responseHeaders) { if (h.toLowerCase() == header) { return this.responseHeaders[h]; } } return null; }, getAllResponseHeaders: function getAllResponseHeaders() { if (this.readyState < FakeXMLHttpRequest.HEADERS_RECEIVED) { return ""; } var headers = ""; for (var header in this.responseHeaders) { if (this.responseHeaders.hasOwnProperty(header) && !/^Set-Cookie2?$/i.test(header)) { headers += header + ": " + this.responseHeaders[header] + "\r\n"; } } return headers; }, setResponseBody: function setResponseBody(body) { verifyRequestSent(this); verifyHeadersReceived(this); verifyResponseBodyType(body); var chunkSize = this.chunkSize || 10; var index = 0; this.responseText = ""; do { if (this.async) { this.readyStateChange(FakeXMLHttpRequest.LOADING); } this.responseText += body.substring(index, index + chunkSize); index += chunkSize; } while (index < body.length); var type = this.getResponseHeader("Content-Type"); if (this.responseText && (!type || /(text\/xml)|(application\/xml)|(\+xml)/.test(type))) { try { this.responseXML = FakeXMLHttpRequest.parseXML(this.responseText); } catch (e) { // Unable to parse XML - no biggie } } if (this.async) { this.readyStateChange(FakeXMLHttpRequest.DONE); } else { this.readyState = FakeXMLHttpRequest.DONE; } }, respond: function respond(status, headers, body) { this.setResponseHeaders(headers || {}); this.status = typeof status == "number" ? status : 200; this.statusText = FakeXMLHttpRequest.statusCodes[this.status]; this.setResponseBody(body || ""); if (typeof this.onload === "function"){ this.onload(); } } }); sinon.extend(FakeXMLHttpRequest, { UNSENT: 0, OPENED: 1, HEADERS_RECEIVED: 2, LOADING: 3, DONE: 4 }); // Borrowed from JSpec FakeXMLHttpRequest.parseXML = function parseXML(text) { var xmlDoc; if (typeof DOMParser != "undefined") { var parser = new DOMParser(); xmlDoc = parser.parseFromString(text, "text/xml"); } else { xmlDoc = new ActiveXObject("Microsoft.XMLDOM"); xmlDoc.async = "false"; xmlDoc.loadXML(text); } return xmlDoc; }; FakeXMLHttpRequest.statusCodes = { 100: "Continue", 101: "Switching Protocols", 200: "OK", 201: "Created", 202: "Accepted", 203: "Non-Authoritative Information", 204: "No Content", 205: "Reset Content", 206: "Partial Content", 300: "Multiple Choice", 301: "Moved Permanently", 302: "Found", 303: "See Other", 304: "Not Modified", 305: "Use Proxy", 307: "Temporary Redirect", 400: "Bad Request", 401: "Unauthorized", 402: "Payment Required", 403: "Forbidden", 404: "Not Found", 405: "Method Not Allowed", 406: "Not Acceptable", 407: "Proxy Authentication Required", 408: "Request Timeout", 409: "Conflict", 410: "Gone", 411: "Length Required", 412: "Precondition Failed", 413: "Request Entity Too Large", 414: "Request-URI Too Long", 415: "Unsupported Media Type", 416: "Requested Range Not Satisfiable", 417: "Expectation Failed", 422: "Unprocessable Entity", 500: "Internal Server Error", 501: "Not Implemented", 502: "Bad Gateway", 503: "Service Unavailable", 504: "Gateway Timeout", 505: "HTTP Version Not Supported" }; sinon.useFakeXMLHttpRequest = function () { sinon.FakeXMLHttpRequest.restore = function restore(keepOnCreate) { if (xhr.supportsXHR) { global.XMLHttpRequest = xhr.GlobalXMLHttpRequest; } if (xhr.supportsActiveX) { global.ActiveXObject = xhr.GlobalActiveXObject; } delete sinon.FakeXMLHttpRequest.restore; if (keepOnCreate !== true) { delete sinon.FakeXMLHttpRequest.onCreate; } }; if (xhr.supportsXHR) { global.XMLHttpRequest = sinon.FakeXMLHttpRequest; } if (xhr.supportsActiveX) { global.ActiveXObject = function ActiveXObject(objId) { if (objId == "Microsoft.XMLHTTP" || /^Msxml2\.XMLHTTP/i.test(objId)) { return new sinon.FakeXMLHttpRequest(); } return new xhr.GlobalActiveXObject(objId); }; } return sinon.FakeXMLHttpRequest; }; sinon.FakeXMLHttpRequest = FakeXMLHttpRequest; })(this); if (typeof module == "object" && typeof require == "function") { module.exports = sinon; } /** * @depend fake_xml_http_request.js */ /*jslint eqeqeq: false, onevar: false, regexp: false, plusplus: false*/ /*global module, require, window*/ /** * The Sinon "server" mimics a web server that receives requests from * sinon.FakeXMLHttpRequest and provides an API to respond to those requests, * both synchronously and asynchronously. To respond synchronuously, canned * answers have to be provided upfront. * * @author Christian Johansen (christian@cjohansen.no) * @license BSD * * Copyright (c) 2010-2013 Christian Johansen */ if (typeof sinon == "undefined") { var sinon = {}; } sinon.fakeServer = (function () { var push = [].push; function F() {} function create(proto) { F.prototype = proto; return new F(); } function responseArray(handler) { var response = handler; if (Object.prototype.toString.call(handler) != "[object Array]") { response = [200, {}, handler]; } if (typeof response[2] != "string") { throw new TypeError("Fake server response body should be string, but was " + typeof response[2]); } return response; } var wloc = typeof window !== "undefined" ? window.location : {}; var rCurrLoc = new RegExp("^" + wloc.protocol + "//" + wloc.host); function matchOne(response, reqMethod, reqUrl) { var rmeth = response.method; var matchMethod = !rmeth || rmeth.toLowerCase() == reqMethod.toLowerCase(); var url = response.url; var matchUrl = !url || url == reqUrl || (typeof url.test == "function" && url.test(reqUrl)); return matchMethod && matchUrl; } function match(response, request) { var requestMethod = this.getHTTPMethod(request); var requestUrl = request.url; if (!/^https?:\/\//.test(requestUrl) || rCurrLoc.test(requestUrl)) { requestUrl = requestUrl.replace(rCurrLoc, ""); } if (matchOne(response, this.getHTTPMethod(request), requestUrl)) { if (typeof response.response == "function") { var ru = response.url; var args = [request].concat(!ru ? [] : requestUrl.match(ru).slice(1)); return response.response.apply(response, args); } return true; } return false; } function log(response, request) { var str; str = "Request:\n" + sinon.format(request) + "\n\n"; str += "Response:\n" + sinon.format(response) + "\n\n"; sinon.log(str); } return { create: function () { var server = create(this); this.xhr = sinon.useFakeXMLHttpRequest(); server.requests = []; this.xhr.onCreate = function (xhrObj) { server.addRequest(xhrObj); }; return server; }, addRequest: function addRequest(xhrObj) { var server = this; push.call(this.requests, xhrObj); xhrObj.onSend = function () { server.handleRequest(this); }; if (this.autoRespond && !this.responding) { setTimeout(function () { server.responding = false; server.respond(); }, this.autoRespondAfter || 10); this.responding = true; } }, getHTTPMethod: function getHTTPMethod(request) { if (this.fakeHTTPMethods && /post/i.test(request.method)) { var matches = (request.requestBody || "").match(/_method=([^\b;]+)/); return !!matches ? matches[1] : request.method; } return request.method; }, handleRequest: function handleRequest(xhr) { if (xhr.async) { if (!this.queue) { this.queue = []; } push.call(this.queue, xhr); } else { this.processRequest(xhr); } }, respondWith: function respondWith(method, url, body) { if (arguments.length == 1 && typeof method != "function") { this.response = responseArray(method); return; } if (!this.responses) { this.responses = []; } if (arguments.length == 1) { body = method; url = method = null; } if (arguments.length == 2) { body = url; url = method; method = null; } push.call(this.responses, { method: method, url: url, response: typeof body == "function" ? body : responseArray(body) }); }, respond: function respond() { if (arguments.length > 0) this.respondWith.apply(this, arguments); var queue = this.queue || []; var request; while(request = queue.shift()) { this.processRequest(request); } }, processRequest: function processRequest(request) { try { if (request.aborted) { return; } var response = this.response || [404, {}, ""]; if (this.responses) { for (var i = 0, l = this.responses.length; i < l; i++) { if (match.call(this, this.responses[i], request)) { response = this.responses[i].response; break; } } } if (request.readyState != 4) { log(response, request); request.respond(response[0], response[1], response[2]); } } catch (e) { sinon.logError("Fake server request processing", e); } }, restore: function restore() { return this.xhr.restore && this.xhr.restore.apply(this.xhr, arguments); } }; }()); if (typeof module == "object" && typeof require == "function") { module.exports = sinon; } /** * @depend fake_server.js * @depend fake_timers.js */ /*jslint browser: true, eqeqeq: false, onevar: false*/ /*global sinon*/ /** * Add-on for sinon.fakeServer that automatically handles a fake timer along with * the FakeXMLHttpRequest. The direct inspiration for this add-on is jQuery * 1.3.x, which does not use xhr object's onreadystatehandler at all - instead, * it polls the object for completion with setInterval. Dispite the direct * motivation, there is nothing jQuery-specific in this file, so it can be used * in any environment where the ajax implementation depends on setInterval or * setTimeout. * * @author Christian Johansen (christian@cjohansen.no) * @license BSD * * Copyright (c) 2010-2013 Christian Johansen */ (function () { function Server() {} Server.prototype = sinon.fakeServer; sinon.fakeServerWithClock = new Server(); sinon.fakeServerWithClock.addRequest = function addRequest(xhr) { if (xhr.async) { if (typeof setTimeout.clock == "object") { this.clock = setTimeout.clock; } else { this.clock = sinon.useFakeTimers(); this.resetClock = true; } if (!this.longestTimeout) { var clockSetTimeout = this.clock.setTimeout; var clockSetInterval = this.clock.setInterval; var server = this; this.clock.setTimeout = function (fn, timeout) { server.longestTimeout = Math.max(timeout, server.longestTimeout || 0); return clockSetTimeout.apply(this, arguments); }; this.clock.setInterval = function (fn, timeout) { server.longestTimeout = Math.max(timeout, server.longestTimeout || 0); return clockSetInterval.apply(this, arguments); }; } } return sinon.fakeServer.addRequest.call(this, xhr); }; sinon.fakeServerWithClock.respond = function respond() { var returnVal = sinon.fakeServer.respond.apply(this, arguments); if (this.clock) { this.clock.tick(this.longestTimeout || 0); this.longestTimeout = 0; if (this.resetClock) { this.clock.restore(); this.resetClock = false; } } return returnVal; }; sinon.fakeServerWithClock.restore = function restore() { if (this.clock) { this.clock.restore(); } return sinon.fakeServer.restore.apply(this, arguments); }; }()); /** * @depend ../sinon.js * @depend collection.js * @depend util/fake_timers.js * @depend util/fake_server_with_clock.js */ /*jslint eqeqeq: false, onevar: false, plusplus: false*/ /*global require, module*/ /** * Manages fake collections as well as fake utilities such as Sinon's * timers and fake XHR implementation in one convenient object. * * @author Christian Johansen (christian@cjohansen.no) * @license BSD * * Copyright (c) 2010-2013 Christian Johansen */ if (typeof module == "object" && typeof require == "function") { var sinon = require("../sinon"); sinon.extend(sinon, require("./util/fake_timers")); } (function () { var push = [].push; function exposeValue(sandbox, config, key, value) { if (!value) { return; } if (config.injectInto) { config.injectInto[key] = value; } else { push.call(sandbox.args, value); } } function prepareSandboxFromConfig(config) { var sandbox = sinon.create(sinon.sandbox); if (config.useFakeServer) { if (typeof config.useFakeServer == "object") { sandbox.serverPrototype = config.useFakeServer; } sandbox.useFakeServer(); } if (config.useFakeTimers) { if (typeof config.useFakeTimers == "object") { sandbox.useFakeTimers.apply(sandbox, config.useFakeTimers); } else { sandbox.useFakeTimers(); } } return sandbox; } sinon.sandbox = sinon.extend(sinon.create(sinon.collection), { useFakeTimers: function useFakeTimers() { this.clock = sinon.useFakeTimers.apply(sinon, arguments); return this.add(this.clock); }, serverPrototype: sinon.fakeServer, useFakeServer: function useFakeServer() { var proto = this.serverPrototype || sinon.fakeServer; if (!proto || !proto.create) { return null; } this.server = proto.create(); return this.add(this.server); }, inject: function (obj) { sinon.collection.inject.call(this, obj); if (this.clock) { obj.clock = this.clock; } if (this.server) { obj.server = this.server; obj.requests = this.server.requests; } return obj; }, create: function (config) { if (!config) { return sinon.create(sinon.sandbox); } var sandbox = prepareSandboxFromConfig(config); sandbox.args = sandbox.args || []; var prop, value, exposed = sandbox.inject({}); if (config.properties) { for (var i = 0, l = config.properties.length; i < l; i++) { prop = config.properties[i]; value = exposed[prop] || prop == "sandbox" && sandbox; exposeValue(sandbox, config, prop, value); } } else { exposeValue(sandbox, config, "sandbox", value); } return sandbox; } }); sinon.sandbox.useFakeXMLHttpRequest = sinon.sandbox.useFakeServer; if (typeof module == "object" && typeof require == "function") { module.exports = sinon.sandbox; } }()); /** * @depend ../sinon.js * @depend stub.js * @depend mock.js * @depend sandbox.js */ /*jslint eqeqeq: false, onevar: false, forin: true, plusplus: false*/ /*global module, require, sinon*/ /** * Test function, sandboxes fakes * * @author Christian Johansen (christian@cjohansen.no) * @license BSD * * Copyright (c) 2010-2013 Christian Johansen */ (function (sinon) { var commonJSModule = typeof module == "object" && typeof require == "function"; if (!sinon && commonJSModule) { sinon = require("../sinon"); } if (!sinon) { return; } function test(callback) { var type = typeof callback; if (type != "function") { throw new TypeError("sinon.test needs to wrap a test function, got " + type); } return function () { var config = sinon.getConfig(sinon.config); config.injectInto = config.injectIntoThis && this || config.injectInto; var sandbox = sinon.sandbox.create(config); var exception, result; var args = Array.prototype.slice.call(arguments).concat(sandbox.args); try { result = callback.apply(this, args); } catch (e) { exception = e; } if (typeof exception !== "undefined") { sandbox.restore(); throw exception; } else { sandbox.verifyAndRestore(); } return result; }; } test.config = { injectIntoThis: true, injectInto: null, properties: ["spy", "stub", "mock", "clock", "server", "requests"], useFakeTimers: true, useFakeServer: true }; if (commonJSModule) { module.exports = test; } else { sinon.test = test; } }(typeof sinon == "object" && sinon || null)); /** * @depend ../sinon.js * @depend test.js */ /*jslint eqeqeq: false, onevar: false, eqeqeq: false*/ /*global module, require, sinon*/ /** * Test case, sandboxes all test functions * * @author Christian Johansen (christian@cjohansen.no) * @license BSD * * Copyright (c) 2010-2013 Christian Johansen */ (function (sinon) { var commonJSModule = typeof module == "object" && typeof require == "function"; if (!sinon && commonJSModule) { sinon = require("../sinon"); } if (!sinon || !Object.prototype.hasOwnProperty) { return; } function createTest(property, setUp, tearDown) { return function () { if (setUp) { setUp.apply(this, arguments); } var exception, result; try { result = property.apply(this, arguments); } catch (e) { exception = e; } if (tearDown) { tearDown.apply(this, arguments); } if (exception) { throw exception; } return result; }; } function testCase(tests, prefix) { /*jsl:ignore*/ if (!tests || typeof tests != "object") { throw new TypeError("sinon.testCase needs an object with test functions"); } /*jsl:end*/ prefix = prefix || "test"; var rPrefix = new RegExp("^" + prefix); var methods = {}, testName, property, method; var setUp = tests.setUp; var tearDown = tests.tearDown; for (testName in tests) { if (tests.hasOwnProperty(testName)) { property = tests[testName]; if (/^(setUp|tearDown)$/.test(testName)) { continue; } if (typeof property == "function" && rPrefix.test(testName)) { method = property; if (setUp || tearDown) { method = createTest(property, setUp, tearDown); } methods[testName] = sinon.test(method); } else { methods[testName] = tests[testName]; } } } return methods; } if (commonJSModule) { module.exports = testCase; } else { sinon.testCase = testCase; } }(typeof sinon == "object" && sinon || null)); /** * @depend ../sinon.js * @depend stub.js */ /*jslint eqeqeq: false, onevar: false, nomen: false, plusplus: false*/ /*global module, require, sinon*/ /** * Assertions matching the test spy retrieval interface. * * @author Christian Johansen (christian@cjohansen.no) * @license BSD * * Copyright (c) 2010-2013 Christian Johansen */ (function (sinon, global) { var commonJSModule = typeof module == "object" && typeof require == "function"; var slice = Array.prototype.slice; var assert; if (!sinon && commonJSModule) { sinon = require("../sinon"); } if (!sinon) { return; } function verifyIsStub() { var method; for (var i = 0, l = arguments.length; i < l; ++i) { method = arguments[i]; if (!method) { assert.fail("fake is not a spy"); } if (typeof method != "function") { assert.fail(method + " is not a function"); } if (typeof method.getCall != "function") { assert.fail(method + " is not stubbed"); } } } function failAssertion(object, msg) { object = object || global; var failMethod = object.fail || assert.fail; failMethod.call(object, msg); } function mirrorPropAsAssertion(name, method, message) { if (arguments.length == 2) { message = method; method = name; } assert[name] = function (fake) { verifyIsStub(fake); var args = slice.call(arguments, 1); var failed = false; if (typeof method == "function") { failed = !method(fake); } else { failed = typeof fake[method] == "function" ? !fake[method].apply(fake, args) : !fake[method]; } if (failed) { failAssertion(this, fake.printf.apply(fake, [message].concat(args))); } else { assert.pass(name); } }; } function exposedName(prefix, prop) { return !prefix || /^fail/.test(prop) ? prop : prefix + prop.slice(0, 1).toUpperCase() + prop.slice(1); }; assert = { failException: "AssertError", fail: function fail(message) { var error = new Error(message); error.name = this.failException || assert.failException; throw error; }, pass: function pass(assertion) {}, callOrder: function assertCallOrder() { verifyIsStub.apply(null, arguments); var expected = "", actual = ""; if (!sinon.calledInOrder(arguments)) { try { expected = [].join.call(arguments, ", "); var calls = slice.call(arguments); var i = calls.length; while (i) { if (!calls[--i].called) { calls.splice(i, 1); } } actual = sinon.orderByFirstCall(calls).join(", "); } catch (e) { // If this fails, we'll just fall back to the blank string } failAssertion(this, "expected " + expected + " to be " + "called in order but were called as " + actual); } else { assert.pass("callOrder"); } }, callCount: function assertCallCount(method, count) { verifyIsStub(method); if (method.callCount != count) { var msg = "expected %n to be called " + sinon.timesInWords(count) + " but was called %c%C"; failAssertion(this, method.printf(msg)); } else { assert.pass("callCount"); } }, expose: function expose(target, options) { if (!target) { throw new TypeError("target is null or undefined"); } var o = options || {}; var prefix = typeof o.prefix == "undefined" && "assert" || o.prefix; var includeFail = typeof o.includeFail == "undefined" || !!o.includeFail; for (var method in this) { if (method != "export" && (includeFail || !/^(fail)/.test(method))) { target[exposedName(prefix, method)] = this[method]; } } return target; } }; mirrorPropAsAssertion("called", "expected %n to have been called at least once but was never called"); mirrorPropAsAssertion("notCalled", function (spy) { return !spy.called; }, "expected %n to not have been called but was called %c%C"); mirrorPropAsAssertion("calledOnce", "expected %n to be called once but was called %c%C"); mirrorPropAsAssertion("calledTwice", "expected %n to be called twice but was called %c%C"); mirrorPropAsAssertion("calledThrice", "expected %n to be called thrice but was called %c%C"); mirrorPropAsAssertion("calledOn", "expected %n to be called with %1 as this but was called with %t"); mirrorPropAsAssertion("alwaysCalledOn", "expected %n to always be called with %1 as this but was called with %t"); mirrorPropAsAssertion("calledWithNew", "expected %n to be called with new"); mirrorPropAsAssertion("alwaysCalledWithNew", "expected %n to always be called with new"); mirrorPropAsAssertion("calledWith", "expected %n to be called with arguments %*%C"); mirrorPropAsAssertion("calledWithMatch", "expected %n to be called with match %*%C"); mirrorPropAsAssertion("alwaysCalledWith", "expected %n to always be called with arguments %*%C"); mirrorPropAsAssertion("alwaysCalledWithMatch", "expected %n to always be called with match %*%C"); mirrorPropAsAssertion("calledWithExactly", "expected %n to be called with exact arguments %*%C"); mirrorPropAsAssertion("alwaysCalledWithExactly", "expected %n to always be called with exact arguments %*%C"); mirrorPropAsAssertion("neverCalledWith", "expected %n to never be called with arguments %*%C"); mirrorPropAsAssertion("neverCalledWithMatch", "expected %n to never be called with match %*%C"); mirrorPropAsAssertion("threw", "%n did not throw exception%C"); mirrorPropAsAssertion("alwaysThrew", "%n did not always throw exception%C"); if (commonJSModule) { module.exports = assert; } else { sinon.assert = assert; } }(typeof sinon == "object" && sinon || null, typeof window != "undefined" ? window : (typeof self != "undefined") ? self : global)); return sinon;}.call(typeof window != 'undefined' && window || {})); apache-couchdb-1.5.0/src/fauxton/test/mocha/mocha.js0000755000175000001440000033365212230722213017237 00000000000000;(function(){ // CommonJS require() function require(p){ var path = require.resolve(p) , mod = require.modules[path]; if (!mod) throw new Error('failed to require "' + p + '"'); if (!mod.exports) { mod.exports = {}; mod.call(mod.exports, mod, mod.exports, require.relative(path)); } return mod.exports; } require.modules = {}; require.resolve = function (path){ var orig = path , reg = path + '.js' , index = path + '/index.js'; return require.modules[reg] && reg || require.modules[index] && index || orig; }; require.register = function (path, fn){ require.modules[path] = fn; }; require.relative = function (parent) { return function(p){ if ('.' != p.charAt(0)) return require(p); var path = parent.split('/') , segs = p.split('/'); path.pop(); for (var i = 0; i < segs.length; i++) { var seg = segs[i]; if ('..' == seg) path.pop(); else if ('.' != seg) path.push(seg); } return require(path.join('/')); }; }; require.register("browser/debug.js", function(module, exports, require){ module.exports = function(type){ return function(){ } }; }); // module: browser/debug.js require.register("browser/diff.js", function(module, exports, require){ /* See license.txt for terms of usage */ /* * Text diff implementation. * * This library supports the following APIS: * JsDiff.diffChars: Character by character diff * JsDiff.diffWords: Word (as defined by \b regex) diff which ignores whitespace * JsDiff.diffLines: Line based diff * * JsDiff.diffCss: Diff targeted at CSS content * * These methods are based on the implementation proposed in * "An O(ND) Difference Algorithm and its Variations" (Myers, 1986). * http://citeseerx.ist.psu.edu/viewdoc/summary?doi=10.1.1.4.6927 */ var JsDiff = (function() { function clonePath(path) { return { newPos: path.newPos, components: path.components.slice(0) }; } function removeEmpty(array) { var ret = []; for (var i = 0; i < array.length; i++) { if (array[i]) { ret.push(array[i]); } } return ret; } function escapeHTML(s) { var n = s; n = n.replace(/&/g, "&"); n = n.replace(//g, ">"); n = n.replace(/"/g, """); return n; } var fbDiff = function(ignoreWhitespace) { this.ignoreWhitespace = ignoreWhitespace; }; fbDiff.prototype = { diff: function(oldString, newString) { // Handle the identity case (this is due to unrolling editLength == 0 if (newString == oldString) { return [{ value: newString }]; } if (!newString) { return [{ value: oldString, removed: true }]; } if (!oldString) { return [{ value: newString, added: true }]; } newString = this.tokenize(newString); oldString = this.tokenize(oldString); var newLen = newString.length, oldLen = oldString.length; var maxEditLength = newLen + oldLen; var bestPath = [{ newPos: -1, components: [] }]; // Seed editLength = 0 var oldPos = this.extractCommon(bestPath[0], newString, oldString, 0); if (bestPath[0].newPos+1 >= newLen && oldPos+1 >= oldLen) { return bestPath[0].components; } for (var editLength = 1; editLength <= maxEditLength; editLength++) { for (var diagonalPath = -1*editLength; diagonalPath <= editLength; diagonalPath+=2) { var basePath; var addPath = bestPath[diagonalPath-1], removePath = bestPath[diagonalPath+1]; oldPos = (removePath ? removePath.newPos : 0) - diagonalPath; if (addPath) { // No one else is going to attempt to use this value, clear it bestPath[diagonalPath-1] = undefined; } var canAdd = addPath && addPath.newPos+1 < newLen; var canRemove = removePath && 0 <= oldPos && oldPos < oldLen; if (!canAdd && !canRemove) { bestPath[diagonalPath] = undefined; continue; } // Select the diagonal that we want to branch from. We select the prior // path whose position in the new string is the farthest from the origin // and does not pass the bounds of the diff graph if (!canAdd || (canRemove && addPath.newPos < removePath.newPos)) { basePath = clonePath(removePath); this.pushComponent(basePath.components, oldString[oldPos], undefined, true); } else { basePath = clonePath(addPath); basePath.newPos++; this.pushComponent(basePath.components, newString[basePath.newPos], true, undefined); } var oldPos = this.extractCommon(basePath, newString, oldString, diagonalPath); if (basePath.newPos+1 >= newLen && oldPos+1 >= oldLen) { return basePath.components; } else { bestPath[diagonalPath] = basePath; } } } }, pushComponent: function(components, value, added, removed) { var last = components[components.length-1]; if (last && last.added === added && last.removed === removed) { // We need to clone here as the component clone operation is just // as shallow array clone components[components.length-1] = {value: this.join(last.value, value), added: added, removed: removed }; } else { components.push({value: value, added: added, removed: removed }); } }, extractCommon: function(basePath, newString, oldString, diagonalPath) { var newLen = newString.length, oldLen = oldString.length, newPos = basePath.newPos, oldPos = newPos - diagonalPath; while (newPos+1 < newLen && oldPos+1 < oldLen && this.equals(newString[newPos+1], oldString[oldPos+1])) { newPos++; oldPos++; this.pushComponent(basePath.components, newString[newPos], undefined, undefined); } basePath.newPos = newPos; return oldPos; }, equals: function(left, right) { var reWhitespace = /\S/; if (this.ignoreWhitespace && !reWhitespace.test(left) && !reWhitespace.test(right)) { return true; } else { return left == right; } }, join: function(left, right) { return left + right; }, tokenize: function(value) { return value; } }; var CharDiff = new fbDiff(); var WordDiff = new fbDiff(true); WordDiff.tokenize = function(value) { return removeEmpty(value.split(/(\s+|\b)/)); }; var CssDiff = new fbDiff(true); CssDiff.tokenize = function(value) { return removeEmpty(value.split(/([{}:;,]|\s+)/)); }; var LineDiff = new fbDiff(); LineDiff.tokenize = function(value) { return value.split(/^/m); }; return { diffChars: function(oldStr, newStr) { return CharDiff.diff(oldStr, newStr); }, diffWords: function(oldStr, newStr) { return WordDiff.diff(oldStr, newStr); }, diffLines: function(oldStr, newStr) { return LineDiff.diff(oldStr, newStr); }, diffCss: function(oldStr, newStr) { return CssDiff.diff(oldStr, newStr); }, createPatch: function(fileName, oldStr, newStr, oldHeader, newHeader) { var ret = []; ret.push("Index: " + fileName); ret.push("==================================================================="); ret.push("--- " + fileName + (typeof oldHeader === "undefined" ? "" : "\t" + oldHeader)); ret.push("+++ " + fileName + (typeof newHeader === "undefined" ? "" : "\t" + newHeader)); var diff = LineDiff.diff(oldStr, newStr); if (!diff[diff.length-1].value) { diff.pop(); // Remove trailing newline add } diff.push({value: "", lines: []}); // Append an empty value to make cleanup easier function contextLines(lines) { return lines.map(function(entry) { return ' ' + entry; }); } function eofNL(curRange, i, current) { var last = diff[diff.length-2], isLast = i === diff.length-2, isLastOfType = i === diff.length-3 && (current.added === !last.added || current.removed === !last.removed); // Figure out if this is the last line for the given file and missing NL if (!/\n$/.test(current.value) && (isLast || isLastOfType)) { curRange.push('\\ No newline at end of file'); } } var oldRangeStart = 0, newRangeStart = 0, curRange = [], oldLine = 1, newLine = 1; for (var i = 0; i < diff.length; i++) { var current = diff[i], lines = current.lines || current.value.replace(/\n$/, "").split("\n"); current.lines = lines; if (current.added || current.removed) { if (!oldRangeStart) { var prev = diff[i-1]; oldRangeStart = oldLine; newRangeStart = newLine; if (prev) { curRange = contextLines(prev.lines.slice(-4)); oldRangeStart -= curRange.length; newRangeStart -= curRange.length; } } curRange.push.apply(curRange, lines.map(function(entry) { return (current.added?"+":"-") + entry; })); eofNL(curRange, i, current); if (current.added) { newLine += lines.length; } else { oldLine += lines.length; } } else { if (oldRangeStart) { // Close out any changes that have been output (or join overlapping) if (lines.length <= 8 && i < diff.length-2) { // Overlapping curRange.push.apply(curRange, contextLines(lines)); } else { // end the range and output var contextSize = Math.min(lines.length, 4); ret.push( "@@ -" + oldRangeStart + "," + (oldLine-oldRangeStart+contextSize) + " +" + newRangeStart + "," + (newLine-newRangeStart+contextSize) + " @@"); ret.push.apply(ret, curRange); ret.push.apply(ret, contextLines(lines.slice(0, contextSize))); if (lines.length <= 4) { eofNL(ret, i, current); } oldRangeStart = 0; newRangeStart = 0; curRange = []; } } oldLine += lines.length; newLine += lines.length; } } return ret.join('\n') + '\n'; }, convertChangesToXML: function(changes){ var ret = []; for ( var i = 0; i < changes.length; i++) { var change = changes[i]; if (change.added) { ret.push(""); } else if (change.removed) { ret.push(""); } ret.push(escapeHTML(change.value)); if (change.added) { ret.push(""); } else if (change.removed) { ret.push(""); } } return ret.join(""); } }; })(); if (typeof module !== "undefined") { module.exports = JsDiff; } }); // module: browser/diff.js require.register("browser/events.js", function(module, exports, require){ /** * Module exports. */ exports.EventEmitter = EventEmitter; /** * Check if `obj` is an array. */ function isArray(obj) { return '[object Array]' == {}.toString.call(obj); } /** * Event emitter constructor. * * @api public */ function EventEmitter(){}; /** * Adds a listener. * * @api public */ EventEmitter.prototype.on = function (name, fn) { if (!this.$events) { this.$events = {}; } if (!this.$events[name]) { this.$events[name] = fn; } else if (isArray(this.$events[name])) { this.$events[name].push(fn); } else { this.$events[name] = [this.$events[name], fn]; } return this; }; EventEmitter.prototype.addListener = EventEmitter.prototype.on; /** * Adds a volatile listener. * * @api public */ EventEmitter.prototype.once = function (name, fn) { var self = this; function on () { self.removeListener(name, on); fn.apply(this, arguments); }; on.listener = fn; this.on(name, on); return this; }; /** * Removes a listener. * * @api public */ EventEmitter.prototype.removeListener = function (name, fn) { if (this.$events && this.$events[name]) { var list = this.$events[name]; if (isArray(list)) { var pos = -1; for (var i = 0, l = list.length; i < l; i++) { if (list[i] === fn || (list[i].listener && list[i].listener === fn)) { pos = i; break; } } if (pos < 0) { return this; } list.splice(pos, 1); if (!list.length) { delete this.$events[name]; } } else if (list === fn || (list.listener && list.listener === fn)) { delete this.$events[name]; } } return this; }; /** * Removes all listeners for an event. * * @api public */ EventEmitter.prototype.removeAllListeners = function (name) { if (name === undefined) { this.$events = {}; return this; } if (this.$events && this.$events[name]) { this.$events[name] = null; } return this; }; /** * Gets all listeners for a certain event. * * @api public */ EventEmitter.prototype.listeners = function (name) { if (!this.$events) { this.$events = {}; } if (!this.$events[name]) { this.$events[name] = []; } if (!isArray(this.$events[name])) { this.$events[name] = [this.$events[name]]; } return this.$events[name]; }; /** * Emits an event. * * @api public */ EventEmitter.prototype.emit = function (name) { if (!this.$events) { return false; } var handler = this.$events[name]; if (!handler) { return false; } var args = [].slice.call(arguments, 1); if ('function' == typeof handler) { handler.apply(this, args); } else if (isArray(handler)) { var listeners = handler.slice(); for (var i = 0, l = listeners.length; i < l; i++) { listeners[i].apply(this, args); } } else { return false; } return true; }; }); // module: browser/events.js require.register("browser/fs.js", function(module, exports, require){ }); // module: browser/fs.js require.register("browser/path.js", function(module, exports, require){ }); // module: browser/path.js require.register("browser/progress.js", function(module, exports, require){ /** * Expose `Progress`. */ module.exports = Progress; /** * Initialize a new `Progress` indicator. */ function Progress() { this.percent = 0; this.size(0); this.fontSize(11); this.font('helvetica, arial, sans-serif'); } /** * Set progress size to `n`. * * @param {Number} n * @return {Progress} for chaining * @api public */ Progress.prototype.size = function(n){ this._size = n; return this; }; /** * Set text to `str`. * * @param {String} str * @return {Progress} for chaining * @api public */ Progress.prototype.text = function(str){ this._text = str; return this; }; /** * Set font size to `n`. * * @param {Number} n * @return {Progress} for chaining * @api public */ Progress.prototype.fontSize = function(n){ this._fontSize = n; return this; }; /** * Set font `family`. * * @param {String} family * @return {Progress} for chaining */ Progress.prototype.font = function(family){ this._font = family; return this; }; /** * Update percentage to `n`. * * @param {Number} n * @return {Progress} for chaining */ Progress.prototype.update = function(n){ this.percent = n; return this; }; /** * Draw on `ctx`. * * @param {CanvasRenderingContext2d} ctx * @return {Progress} for chaining */ Progress.prototype.draw = function(ctx){ var percent = Math.min(this.percent, 100) , size = this._size , half = size / 2 , x = half , y = half , rad = half - 1 , fontSize = this._fontSize; ctx.font = fontSize + 'px ' + this._font; var angle = Math.PI * 2 * (percent / 100); ctx.clearRect(0, 0, size, size); // outer circle ctx.strokeStyle = '#9f9f9f'; ctx.beginPath(); ctx.arc(x, y, rad, 0, angle, false); ctx.stroke(); // inner circle ctx.strokeStyle = '#eee'; ctx.beginPath(); ctx.arc(x, y, rad - 1, 0, angle, true); ctx.stroke(); // text var text = this._text || (percent | 0) + '%' , w = ctx.measureText(text).width; ctx.fillText( text , x - w / 2 + 1 , y + fontSize / 2 - 1); return this; }; }); // module: browser/progress.js require.register("browser/tty.js", function(module, exports, require){ exports.isatty = function(){ return true; }; exports.getWindowSize = function(){ if ('innerHeight' in global) { return [global.innerHeight, global.innerWidth]; } else { // In a Web Worker, the DOM Window is not available. return [640, 480]; } }; }); // module: browser/tty.js require.register("context.js", function(module, exports, require){ /** * Expose `Context`. */ module.exports = Context; /** * Initialize a new `Context`. * * @api private */ function Context(){} /** * Set or get the context `Runnable` to `runnable`. * * @param {Runnable} runnable * @return {Context} * @api private */ Context.prototype.runnable = function(runnable){ if (0 == arguments.length) return this._runnable; this.test = this._runnable = runnable; return this; }; /** * Set test timeout `ms`. * * @param {Number} ms * @return {Context} self * @api private */ Context.prototype.timeout = function(ms){ this.runnable().timeout(ms); return this; }; /** * Set test slowness threshold `ms`. * * @param {Number} ms * @return {Context} self * @api private */ Context.prototype.slow = function(ms){ this.runnable().slow(ms); return this; }; /** * Inspect the context void of `._runnable`. * * @return {String} * @api private */ Context.prototype.inspect = function(){ return JSON.stringify(this, function(key, val){ if ('_runnable' == key) return; if ('test' == key) return; return val; }, 2); }; }); // module: context.js require.register("hook.js", function(module, exports, require){ /** * Module dependencies. */ var Runnable = require('./runnable'); /** * Expose `Hook`. */ module.exports = Hook; /** * Initialize a new `Hook` with the given `title` and callback `fn`. * * @param {String} title * @param {Function} fn * @api private */ function Hook(title, fn) { Runnable.call(this, title, fn); this.type = 'hook'; } /** * Inherit from `Runnable.prototype`. */ function F(){}; F.prototype = Runnable.prototype; Hook.prototype = new F; Hook.prototype.constructor = Hook; /** * Get or set the test `err`. * * @param {Error} err * @return {Error} * @api public */ Hook.prototype.error = function(err){ if (0 == arguments.length) { var err = this._error; this._error = null; return err; } this._error = err; }; }); // module: hook.js require.register("interfaces/bdd.js", function(module, exports, require){ /** * Module dependencies. */ var Suite = require('../suite') , Test = require('../test'); /** * BDD-style interface: * * describe('Array', function(){ * describe('#indexOf()', function(){ * it('should return -1 when not present', function(){ * * }); * * it('should return the index when present', function(){ * * }); * }); * }); * */ module.exports = function(suite){ var suites = [suite]; suite.on('pre-require', function(context, file, mocha){ /** * Execute before running tests. */ context.before = function(fn){ suites[0].beforeAll(fn); }; /** * Execute after running tests. */ context.after = function(fn){ suites[0].afterAll(fn); }; /** * Execute before each test case. */ context.beforeEach = function(fn){ suites[0].beforeEach(fn); }; /** * Execute after each test case. */ context.afterEach = function(fn){ suites[0].afterEach(fn); }; /** * Describe a "suite" with the given `title` * and callback `fn` containing nested suites * and/or tests. */ context.describe = context.context = function(title, fn){ var suite = Suite.create(suites[0], title); suites.unshift(suite); fn.call(suite); suites.shift(); return suite; }; /** * Pending describe. */ context.xdescribe = context.xcontext = context.describe.skip = function(title, fn){ var suite = Suite.create(suites[0], title); suite.pending = true; suites.unshift(suite); fn.call(suite); suites.shift(); }; /** * Exclusive suite. */ context.describe.only = function(title, fn){ var suite = context.describe(title, fn); mocha.grep(suite.fullTitle()); }; /** * Describe a specification or test-case * with the given `title` and callback `fn` * acting as a thunk. */ context.it = context.specify = function(title, fn){ var suite = suites[0]; if (suite.pending) var fn = null; var test = new Test(title, fn); suite.addTest(test); return test; }; /** * Exclusive test-case. */ context.it.only = function(title, fn){ var test = context.it(title, fn); mocha.grep(test.fullTitle()); }; /** * Pending test case. */ context.xit = context.xspecify = context.it.skip = function(title){ context.it(title); }; }); }; }); // module: interfaces/bdd.js require.register("interfaces/exports.js", function(module, exports, require){ /** * Module dependencies. */ var Suite = require('../suite') , Test = require('../test'); /** * TDD-style interface: * * exports.Array = { * '#indexOf()': { * 'should return -1 when the value is not present': function(){ * * }, * * 'should return the correct index when the value is present': function(){ * * } * } * }; * */ module.exports = function(suite){ var suites = [suite]; suite.on('require', visit); function visit(obj) { var suite; for (var key in obj) { if ('function' == typeof obj[key]) { var fn = obj[key]; switch (key) { case 'before': suites[0].beforeAll(fn); break; case 'after': suites[0].afterAll(fn); break; case 'beforeEach': suites[0].beforeEach(fn); break; case 'afterEach': suites[0].afterEach(fn); break; default: suites[0].addTest(new Test(key, fn)); } } else { var suite = Suite.create(suites[0], key); suites.unshift(suite); visit(obj[key]); suites.shift(); } } } }; }); // module: interfaces/exports.js require.register("interfaces/index.js", function(module, exports, require){ exports.bdd = require('./bdd'); exports.tdd = require('./tdd'); exports.qunit = require('./qunit'); exports.exports = require('./exports'); }); // module: interfaces/index.js require.register("interfaces/qunit.js", function(module, exports, require){ /** * Module dependencies. */ var Suite = require('../suite') , Test = require('../test'); /** * QUnit-style interface: * * suite('Array'); * * test('#length', function(){ * var arr = [1,2,3]; * ok(arr.length == 3); * }); * * test('#indexOf()', function(){ * var arr = [1,2,3]; * ok(arr.indexOf(1) == 0); * ok(arr.indexOf(2) == 1); * ok(arr.indexOf(3) == 2); * }); * * suite('String'); * * test('#length', function(){ * ok('foo'.length == 3); * }); * */ module.exports = function(suite){ var suites = [suite]; suite.on('pre-require', function(context, file, mocha){ /** * Execute before running tests. */ context.before = function(fn){ suites[0].beforeAll(fn); }; /** * Execute after running tests. */ context.after = function(fn){ suites[0].afterAll(fn); }; /** * Execute before each test case. */ context.beforeEach = function(fn){ suites[0].beforeEach(fn); }; /** * Execute after each test case. */ context.afterEach = function(fn){ suites[0].afterEach(fn); }; /** * Describe a "suite" with the given `title`. */ context.suite = function(title){ if (suites.length > 1) suites.shift(); var suite = Suite.create(suites[0], title); suites.unshift(suite); return suite; }; /** * Exclusive test-case. */ context.suite.only = function(title, fn){ var suite = context.suite(title, fn); mocha.grep(suite.fullTitle()); }; /** * Describe a specification or test-case * with the given `title` and callback `fn` * acting as a thunk. */ context.test = function(title, fn){ var test = new Test(title, fn); suites[0].addTest(test); return test; }; /** * Exclusive test-case. */ context.test.only = function(title, fn){ var test = context.test(title, fn); mocha.grep(test.fullTitle()); }; /** * Pending test case. */ context.test.skip = function(title){ context.test(title); }; }); }; }); // module: interfaces/qunit.js require.register("interfaces/tdd.js", function(module, exports, require){ /** * Module dependencies. */ var Suite = require('../suite') , Test = require('../test'); /** * TDD-style interface: * * suite('Array', function(){ * suite('#indexOf()', function(){ * suiteSetup(function(){ * * }); * * test('should return -1 when not present', function(){ * * }); * * test('should return the index when present', function(){ * * }); * * suiteTeardown(function(){ * * }); * }); * }); * */ module.exports = function(suite){ var suites = [suite]; suite.on('pre-require', function(context, file, mocha){ /** * Execute before each test case. */ context.setup = function(fn){ suites[0].beforeEach(fn); }; /** * Execute after each test case. */ context.teardown = function(fn){ suites[0].afterEach(fn); }; /** * Execute before the suite. */ context.suiteSetup = function(fn){ suites[0].beforeAll(fn); }; /** * Execute after the suite. */ context.suiteTeardown = function(fn){ suites[0].afterAll(fn); }; /** * Describe a "suite" with the given `title` * and callback `fn` containing nested suites * and/or tests. */ context.suite = function(title, fn){ var suite = Suite.create(suites[0], title); suites.unshift(suite); fn.call(suite); suites.shift(); return suite; }; /** * Pending suite. */ context.suite.skip = function(title, fn) { var suite = Suite.create(suites[0], title); suite.pending = true; suites.unshift(suite); fn.call(suite); suites.shift(); }; /** * Exclusive test-case. */ context.suite.only = function(title, fn){ var suite = context.suite(title, fn); mocha.grep(suite.fullTitle()); }; /** * Describe a specification or test-case * with the given `title` and callback `fn` * acting as a thunk. */ context.test = function(title, fn){ var suite = suites[0]; if (suite.pending) var fn = null; var test = new Test(title, fn); suite.addTest(test); return test; }; /** * Exclusive test-case. */ context.test.only = function(title, fn){ var test = context.test(title, fn); mocha.grep(test.fullTitle()); }; /** * Pending test case. */ context.test.skip = function(title){ context.test(title); }; }); }; }); // module: interfaces/tdd.js require.register("mocha.js", function(module, exports, require){ /*! * mocha * Copyright(c) 2011 TJ Holowaychuk * MIT Licensed */ /** * Module dependencies. */ var path = require('browser/path') , utils = require('./utils'); /** * Expose `Mocha`. */ exports = module.exports = Mocha; /** * Expose internals. */ exports.utils = utils; exports.interfaces = require('./interfaces'); exports.reporters = require('./reporters'); exports.Runnable = require('./runnable'); exports.Context = require('./context'); exports.Runner = require('./runner'); exports.Suite = require('./suite'); exports.Hook = require('./hook'); exports.Test = require('./test'); /** * Return image `name` path. * * @param {String} name * @return {String} * @api private */ function image(name) { return __dirname + '/../images/' + name + '.png'; } /** * Setup mocha with `options`. * * Options: * * - `ui` name "bdd", "tdd", "exports" etc * - `reporter` reporter instance, defaults to `mocha.reporters.Dot` * - `globals` array of accepted globals * - `timeout` timeout in milliseconds * - `bail` bail on the first test failure * - `slow` milliseconds to wait before considering a test slow * - `ignoreLeaks` ignore global leaks * - `grep` string or regexp to filter tests with * * @param {Object} options * @api public */ function Mocha(options) { options = options || {}; this.files = []; this.options = options; this.grep(options.grep); this.suite = new exports.Suite('', new exports.Context); this.ui(options.ui); this.bail(options.bail); this.reporter(options.reporter); if (options.timeout) this.timeout(options.timeout); if (options.slow) this.slow(options.slow); } /** * Enable or disable bailing on the first failure. * * @param {Boolean} [bail] * @api public */ Mocha.prototype.bail = function(bail){ if (0 == arguments.length) bail = true; this.suite.bail(bail); return this; }; /** * Add test `file`. * * @param {String} file * @api public */ Mocha.prototype.addFile = function(file){ this.files.push(file); return this; }; /** * Set reporter to `reporter`, defaults to "dot". * * @param {String|Function} reporter name or constructor * @api public */ Mocha.prototype.reporter = function(reporter){ if ('function' == typeof reporter) { this._reporter = reporter; } else { reporter = reporter || 'dot'; try { this._reporter = require('./reporters/' + reporter); } catch (err) { this._reporter = require(reporter); } if (!this._reporter) throw new Error('invalid reporter "' + reporter + '"'); } return this; }; /** * Set test UI `name`, defaults to "bdd". * * @param {String} bdd * @api public */ Mocha.prototype.ui = function(name){ name = name || 'bdd'; this._ui = exports.interfaces[name]; if (!this._ui) throw new Error('invalid interface "' + name + '"'); this._ui = this._ui(this.suite); return this; }; /** * Load registered files. * * @api private */ Mocha.prototype.loadFiles = function(fn){ var self = this; var suite = this.suite; var pending = this.files.length; this.files.forEach(function(file){ file = path.resolve(file); suite.emit('pre-require', global, file, self); suite.emit('require', require(file), file, self); suite.emit('post-require', global, file, self); --pending || (fn && fn()); }); }; /** * Enable growl support. * * @api private */ Mocha.prototype._growl = function(runner, reporter) { var notify = require('growl'); runner.on('end', function(){ var stats = reporter.stats; if (stats.failures) { var msg = stats.failures + ' of ' + runner.total + ' tests failed'; notify(msg, { name: 'mocha', title: 'Failed', image: image('error') }); } else { notify(stats.passes + ' tests passed in ' + stats.duration + 'ms', { name: 'mocha' , title: 'Passed' , image: image('ok') }); } }); }; /** * Add regexp to grep, if `re` is a string it is escaped. * * @param {RegExp|String} re * @return {Mocha} * @api public */ Mocha.prototype.grep = function(re){ this.options.grep = 'string' == typeof re ? new RegExp(utils.escapeRegexp(re)) : re; return this; }; /** * Invert `.grep()` matches. * * @return {Mocha} * @api public */ Mocha.prototype.invert = function(){ this.options.invert = true; return this; }; /** * Ignore global leaks. * * @param {Boolean} ignore * @return {Mocha} * @api public */ Mocha.prototype.ignoreLeaks = function(ignore){ this.options.ignoreLeaks = !!ignore; return this; }; /** * Enable global leak checking. * * @return {Mocha} * @api public */ Mocha.prototype.checkLeaks = function(){ this.options.ignoreLeaks = false; return this; }; /** * Enable growl support. * * @return {Mocha} * @api public */ Mocha.prototype.growl = function(){ this.options.growl = true; return this; }; /** * Ignore `globals` array or string. * * @param {Array|String} globals * @return {Mocha} * @api public */ Mocha.prototype.globals = function(globals){ this.options.globals = (this.options.globals || []).concat(globals); return this; }; /** * Set the timeout in milliseconds. * * @param {Number} timeout * @return {Mocha} * @api public */ Mocha.prototype.timeout = function(timeout){ this.suite.timeout(timeout); return this; }; /** * Set slowness threshold in milliseconds. * * @param {Number} slow * @return {Mocha} * @api public */ Mocha.prototype.slow = function(slow){ this.suite.slow(slow); return this; }; /** * Makes all tests async (accepting a callback) * * @return {Mocha} * @api public */ Mocha.prototype.asyncOnly = function(){ this.options.asyncOnly = true; return this; }; /** * Run tests and invoke `fn()` when complete. * * @param {Function} fn * @return {Runner} * @api public */ Mocha.prototype.run = function(fn){ if (this.files.length) this.loadFiles(); var suite = this.suite; var options = this.options; var runner = new exports.Runner(suite); var reporter = new this._reporter(runner); runner.ignoreLeaks = false !== options.ignoreLeaks; runner.asyncOnly = options.asyncOnly; if (options.grep) runner.grep(options.grep, options.invert); if (options.globals) runner.globals(options.globals); if (options.growl) this._growl(runner, reporter); return runner.run(fn); }; }); // module: mocha.js require.register("ms.js", function(module, exports, require){ /** * Helpers. */ var s = 1000; var m = s * 60; var h = m * 60; var d = h * 24; /** * Parse or format the given `val`. * * @param {String|Number} val * @return {String|Number} * @api public */ module.exports = function(val){ if ('string' == typeof val) return parse(val); return format(val); } /** * Parse the given `str` and return milliseconds. * * @param {String} str * @return {Number} * @api private */ function parse(str) { var m = /^((?:\d+)?\.?\d+) *(ms|seconds?|s|minutes?|m|hours?|h|days?|d|years?|y)?$/i.exec(str); if (!m) return; var n = parseFloat(m[1]); var type = (m[2] || 'ms').toLowerCase(); switch (type) { case 'years': case 'year': case 'y': return n * 31557600000; case 'days': case 'day': case 'd': return n * 86400000; case 'hours': case 'hour': case 'h': return n * 3600000; case 'minutes': case 'minute': case 'm': return n * 60000; case 'seconds': case 'second': case 's': return n * 1000; case 'ms': return n; } } /** * Format the given `ms`. * * @param {Number} ms * @return {String} * @api public */ function format(ms) { if (ms == d) return Math.round(ms / d) + ' day'; if (ms > d) return Math.round(ms / d) + ' days'; if (ms == h) return Math.round(ms / h) + ' hour'; if (ms > h) return Math.round(ms / h) + ' hours'; if (ms == m) return Math.round(ms / m) + ' minute'; if (ms > m) return Math.round(ms / m) + ' minutes'; if (ms == s) return Math.round(ms / s) + ' second'; if (ms > s) return Math.round(ms / s) + ' seconds'; return ms + ' ms'; } }); // module: ms.js require.register("reporters/base.js", function(module, exports, require){ /** * Module dependencies. */ var tty = require('browser/tty') , diff = require('browser/diff') , ms = require('../ms'); /** * Save timer references to avoid Sinon interfering (see GH-237). */ var Date = global.Date , setTimeout = global.setTimeout , setInterval = global.setInterval , clearTimeout = global.clearTimeout , clearInterval = global.clearInterval; /** * Check if both stdio streams are associated with a tty. */ var isatty = tty.isatty(1) && tty.isatty(2); /** * Expose `Base`. */ exports = module.exports = Base; /** * Enable coloring by default. */ exports.useColors = isatty; /** * Default color map. */ exports.colors = { 'pass': 90 , 'fail': 31 , 'bright pass': 92 , 'bright fail': 91 , 'bright yellow': 93 , 'pending': 36 , 'suite': 0 , 'error title': 0 , 'error message': 31 , 'error stack': 90 , 'checkmark': 32 , 'fast': 90 , 'medium': 33 , 'slow': 31 , 'green': 32 , 'light': 90 , 'diff gutter': 90 , 'diff added': 42 , 'diff removed': 41 }; /** * Default symbol map. */ exports.symbols = { ok: 'āœ“', err: 'āœ–', dot: '․' }; // With node.js on Windows: use symbols available in terminal default fonts if ('win32' == process.platform) { exports.symbols.ok = '\u221A'; exports.symbols.err = '\u00D7'; exports.symbols.dot = '.'; } /** * Color `str` with the given `type`, * allowing colors to be disabled, * as well as user-defined color * schemes. * * @param {String} type * @param {String} str * @return {String} * @api private */ var color = exports.color = function(type, str) { if (!exports.useColors) return str; return '\u001b[' + exports.colors[type] + 'm' + str + '\u001b[0m'; }; /** * Expose term window size, with some * defaults for when stderr is not a tty. */ exports.window = { width: isatty ? process.stdout.getWindowSize ? process.stdout.getWindowSize(1)[0] : tty.getWindowSize()[1] : 75 }; /** * Expose some basic cursor interactions * that are common among reporters. */ exports.cursor = { hide: function(){ process.stdout.write('\u001b[?25l'); }, show: function(){ process.stdout.write('\u001b[?25h'); }, deleteLine: function(){ process.stdout.write('\u001b[2K'); }, beginningOfLine: function(){ process.stdout.write('\u001b[0G'); }, CR: function(){ exports.cursor.deleteLine(); exports.cursor.beginningOfLine(); } }; /** * Outut the given `failures` as a list. * * @param {Array} failures * @api public */ exports.list = function(failures){ console.error(); failures.forEach(function(test, i){ // format var fmt = color('error title', ' %s) %s:\n') + color('error message', ' %s') + color('error stack', '\n%s\n'); // msg var err = test.err , message = err.message || '' , stack = err.stack || message , index = stack.indexOf(message) + message.length , msg = stack.slice(0, index) , actual = err.actual , expected = err.expected , escape = true; // uncaught if (err.uncaught) { msg = 'Uncaught ' + msg; } // explicitly show diff if (err.showDiff && sameType(actual, expected)) { escape = false; err.actual = actual = stringify(actual); err.expected = expected = stringify(expected); } // actual / expected diff if ('string' == typeof actual && 'string' == typeof expected) { msg = errorDiff(err, 'Words', escape); // linenos var lines = msg.split('\n'); if (lines.length > 4) { var width = String(lines.length).length; msg = lines.map(function(str, i){ return pad(++i, width) + ' |' + ' ' + str; }).join('\n'); } // legend msg = '\n' + color('diff removed', 'actual') + ' ' + color('diff added', 'expected') + '\n\n' + msg + '\n'; // indent msg = msg.replace(/^/gm, ' '); fmt = color('error title', ' %s) %s:\n%s') + color('error stack', '\n%s\n'); } // indent stack trace without msg stack = stack.slice(index ? index + 1 : index) .replace(/^/gm, ' '); console.error(fmt, (i + 1), test.fullTitle(), msg, stack); }); }; /** * Initialize a new `Base` reporter. * * All other reporters generally * inherit from this reporter, providing * stats such as test duration, number * of tests passed / failed etc. * * @param {Runner} runner * @api public */ function Base(runner) { var self = this , stats = this.stats = { suites: 0, tests: 0, passes: 0, pending: 0, failures: 0 } , failures = this.failures = []; if (!runner) return; this.runner = runner; runner.stats = stats; runner.on('start', function(){ stats.start = new Date; }); runner.on('suite', function(suite){ stats.suites = stats.suites || 0; suite.root || stats.suites++; }); runner.on('test end', function(test){ stats.tests = stats.tests || 0; stats.tests++; }); runner.on('pass', function(test){ stats.passes = stats.passes || 0; var medium = test.slow() / 2; test.speed = test.duration > test.slow() ? 'slow' : test.duration > medium ? 'medium' : 'fast'; stats.passes++; }); runner.on('fail', function(test, err){ stats.failures = stats.failures || 0; stats.failures++; test.err = err; failures.push(test); }); runner.on('end', function(){ stats.end = new Date; stats.duration = new Date - stats.start; }); runner.on('pending', function(){ stats.pending++; }); } /** * Output common epilogue used by many of * the bundled reporters. * * @api public */ Base.prototype.epilogue = function(){ var stats = this.stats; var tests; var fmt; console.log(); // passes fmt = color('bright pass', ' ') + color('green', ' %d passing') + color('light', ' (%s)'); console.log(fmt, stats.passes || 0, ms(stats.duration)); // pending if (stats.pending) { fmt = color('pending', ' ') + color('pending', ' %d pending'); console.log(fmt, stats.pending); } // failures if (stats.failures) { fmt = color('fail', ' %d failing'); console.error(fmt, stats.failures); Base.list(this.failures); console.error(); } console.log(); }; /** * Pad the given `str` to `len`. * * @param {String} str * @param {String} len * @return {String} * @api private */ function pad(str, len) { str = String(str); return Array(len - str.length + 1).join(' ') + str; } /** * Return a character diff for `err`. * * @param {Error} err * @return {String} * @api private */ function errorDiff(err, type, escape) { return diff['diff' + type](err.actual, err.expected).map(function(str){ if (escape) { str.value = str.value .replace(/\t/g, '') .replace(/\r/g, '') .replace(/\n/g, '\n'); } if (str.added) return colorLines('diff added', str.value); if (str.removed) return colorLines('diff removed', str.value); return str.value; }).join(''); } /** * Color lines for `str`, using the color `name`. * * @param {String} name * @param {String} str * @return {String} * @api private */ function colorLines(name, str) { return str.split('\n').map(function(str){ return color(name, str); }).join('\n'); } /** * Stringify `obj`. * * @param {Mixed} obj * @return {String} * @api private */ function stringify(obj) { if (obj instanceof RegExp) return obj.toString(); return JSON.stringify(obj, null, 2); } /** * Check that a / b have the same type. * * @param {Object} a * @param {Object} b * @return {Boolean} * @api private */ function sameType(a, b) { a = Object.prototype.toString.call(a); b = Object.prototype.toString.call(b); return a == b; } }); // module: reporters/base.js require.register("reporters/doc.js", function(module, exports, require){ /** * Module dependencies. */ var Base = require('./base') , utils = require('../utils'); /** * Expose `Doc`. */ exports = module.exports = Doc; /** * Initialize a new `Doc` reporter. * * @param {Runner} runner * @api public */ function Doc(runner) { Base.call(this, runner); var self = this , stats = this.stats , total = runner.total , indents = 2; function indent() { return Array(indents).join(' '); } runner.on('suite', function(suite){ if (suite.root) return; ++indents; console.log('%s
', indent()); ++indents; console.log('%s

%s

', indent(), utils.escape(suite.title)); console.log('%s
', indent()); }); runner.on('suite end', function(suite){ if (suite.root) return; console.log('%s
', indent()); --indents; console.log('%s
', indent()); --indents; }); runner.on('pass', function(test){ console.log('%s
%s
', indent(), utils.escape(test.title)); var code = utils.escape(utils.clean(test.fn.toString())); console.log('%s
%s
', indent(), code); }); } }); // module: reporters/doc.js require.register("reporters/dot.js", function(module, exports, require){ /** * Module dependencies. */ var Base = require('./base') , color = Base.color; /** * Expose `Dot`. */ exports = module.exports = Dot; /** * Initialize a new `Dot` matrix test reporter. * * @param {Runner} runner * @api public */ function Dot(runner) { Base.call(this, runner); var self = this , stats = this.stats , width = Base.window.width * .75 | 0 , n = 0; runner.on('start', function(){ process.stdout.write('\n '); }); runner.on('pending', function(test){ process.stdout.write(color('pending', Base.symbols.dot)); }); runner.on('pass', function(test){ if (++n % width == 0) process.stdout.write('\n '); if ('slow' == test.speed) { process.stdout.write(color('bright yellow', Base.symbols.dot)); } else { process.stdout.write(color(test.speed, Base.symbols.dot)); } }); runner.on('fail', function(test, err){ if (++n % width == 0) process.stdout.write('\n '); process.stdout.write(color('fail', Base.symbols.dot)); }); runner.on('end', function(){ console.log(); self.epilogue(); }); } /** * Inherit from `Base.prototype`. */ function F(){}; F.prototype = Base.prototype; Dot.prototype = new F; Dot.prototype.constructor = Dot; }); // module: reporters/dot.js require.register("reporters/html-cov.js", function(module, exports, require){ /** * Module dependencies. */ var JSONCov = require('./json-cov') , fs = require('browser/fs'); /** * Expose `HTMLCov`. */ exports = module.exports = HTMLCov; /** * Initialize a new `JsCoverage` reporter. * * @param {Runner} runner * @api public */ function HTMLCov(runner) { var jade = require('jade') , file = __dirname + '/templates/coverage.jade' , str = fs.readFileSync(file, 'utf8') , fn = jade.compile(str, { filename: file }) , self = this; JSONCov.call(this, runner, false); runner.on('end', function(){ process.stdout.write(fn({ cov: self.cov , coverageClass: coverageClass })); }); } /** * Return coverage class for `n`. * * @return {String} * @api private */ function coverageClass(n) { if (n >= 75) return 'high'; if (n >= 50) return 'medium'; if (n >= 25) return 'low'; return 'terrible'; } }); // module: reporters/html-cov.js require.register("reporters/html.js", function(module, exports, require){ /** * Module dependencies. */ var Base = require('./base') , utils = require('../utils') , Progress = require('../browser/progress') , escape = utils.escape; /** * Save timer references to avoid Sinon interfering (see GH-237). */ var Date = global.Date , setTimeout = global.setTimeout , setInterval = global.setInterval , clearTimeout = global.clearTimeout , clearInterval = global.clearInterval; /** * Expose `Doc`. */ exports = module.exports = HTML; /** * Stats template. */ var statsTemplate = '
    ' + '
  • ' + '
  • passes: 0
  • ' + '
  • failures: 0
  • ' + '
  • duration: 0s
  • ' + '
'; /** * Initialize a new `Doc` reporter. * * @param {Runner} runner * @api public */ function HTML(runner, root) { Base.call(this, runner); var self = this , stats = this.stats , total = runner.total , stat = fragment(statsTemplate) , items = stat.getElementsByTagName('li') , passes = items[1].getElementsByTagName('em')[0] , passesLink = items[1].getElementsByTagName('a')[0] , failures = items[2].getElementsByTagName('em')[0] , failuresLink = items[2].getElementsByTagName('a')[0] , duration = items[3].getElementsByTagName('em')[0] , canvas = stat.getElementsByTagName('canvas')[0] , report = fragment('
    ') , stack = [report] , progress , ctx root = root || document.getElementById('mocha'); if (canvas.getContext) { var ratio = window.devicePixelRatio || 1; canvas.style.width = canvas.width; canvas.style.height = canvas.height; canvas.width *= ratio; canvas.height *= ratio; ctx = canvas.getContext('2d'); ctx.scale(ratio, ratio); progress = new Progress; } if (!root) return error('#mocha div missing, add it to your document'); // pass toggle on(passesLink, 'click', function(){ unhide(); var name = /pass/.test(report.className) ? '' : ' pass'; report.className = report.className.replace(/fail|pass/g, '') + name; if (report.className.trim()) hideSuitesWithout('test pass'); }); // failure toggle on(failuresLink, 'click', function(){ unhide(); var name = /fail/.test(report.className) ? '' : ' fail'; report.className = report.className.replace(/fail|pass/g, '') + name; if (report.className.trim()) hideSuitesWithout('test fail'); }); root.appendChild(stat); root.appendChild(report); if (progress) progress.size(40); runner.on('suite', function(suite){ if (suite.root) return; // suite var url = '?grep=' + encodeURIComponent(suite.fullTitle()); var el = fragment('
  • %s

  • ', url, escape(suite.title)); // container stack[0].appendChild(el); stack.unshift(document.createElement('ul')); el.appendChild(stack[0]); }); runner.on('suite end', function(suite){ if (suite.root) return; stack.shift(); }); runner.on('fail', function(test, err){ if ('hook' == test.type) runner.emit('test end', test); }); runner.on('test end', function(test){ // TODO: add to stats var percent = stats.tests / this.total * 100 | 0; if (progress) progress.update(percent).draw(ctx); // update stats var ms = new Date - stats.start; text(passes, stats.passes); text(failures, stats.failures); text(duration, (ms / 1000).toFixed(2)); // test if ('passed' == test.state) { var el = fragment('
  • %e%ems ‣

  • ', test.speed, test.title, test.duration, encodeURIComponent(test.fullTitle())); } else if (test.pending) { var el = fragment('
  • %e

  • ', test.title); } else { var el = fragment('
  • %e ‣

  • ', test.title, encodeURIComponent(test.fullTitle())); var str = test.err.stack || test.err.toString(); // FF / Opera do not add the message if (!~str.indexOf(test.err.message)) { str = test.err.message + '\n' + str; } // <=IE7 stringifies to [Object Error]. Since it can be overloaded, we // check for the result of the stringifying. if ('[object Error]' == str) str = test.err.message; // Safari doesn't give you a stack. Let's at least provide a source line. if (!test.err.stack && test.err.sourceURL && test.err.line !== undefined) { str += "\n(" + test.err.sourceURL + ":" + test.err.line + ")"; } el.appendChild(fragment('
    %e
    ', str)); } // toggle code // TODO: defer if (!test.pending) { var h2 = el.getElementsByTagName('h2')[0]; on(h2, 'click', function(){ pre.style.display = 'none' == pre.style.display ? 'block' : 'none'; }); var pre = fragment('
    %e
    ', utils.clean(test.fn.toString())); el.appendChild(pre); pre.style.display = 'none'; } // Don't call .appendChild if #mocha-report was already .shift()'ed off the stack. if (stack[0]) stack[0].appendChild(el); }); } /** * Display error `msg`. */ function error(msg) { document.body.appendChild(fragment('
    %s
    ', msg)); } /** * Return a DOM fragment from `html`. */ function fragment(html) { var args = arguments , div = document.createElement('div') , i = 1; div.innerHTML = html.replace(/%([se])/g, function(_, type){ switch (type) { case 's': return String(args[i++]); case 'e': return escape(args[i++]); } }); return div.firstChild; } /** * Check for suites that do not have elements * with `classname`, and hide them. */ function hideSuitesWithout(classname) { var suites = document.getElementsByClassName('suite'); for (var i = 0; i < suites.length; i++) { var els = suites[i].getElementsByClassName(classname); if (0 == els.length) suites[i].className += ' hidden'; } } /** * Unhide .hidden suites. */ function unhide() { var els = document.getElementsByClassName('suite hidden'); for (var i = 0; i < els.length; ++i) { els[i].className = els[i].className.replace('suite hidden', 'suite'); } } /** * Set `el` text to `str`. */ function text(el, str) { if (el.textContent) { el.textContent = str; } else { el.innerText = str; } } /** * Listen on `event` with callback `fn`. */ function on(el, event, fn) { if (el.addEventListener) { el.addEventListener(event, fn, false); } else { el.attachEvent('on' + event, fn); } } }); // module: reporters/html.js require.register("reporters/index.js", function(module, exports, require){ exports.Base = require('./base'); exports.Dot = require('./dot'); exports.Doc = require('./doc'); exports.TAP = require('./tap'); exports.JSON = require('./json'); exports.HTML = require('./html'); exports.List = require('./list'); exports.Min = require('./min'); exports.Spec = require('./spec'); exports.Nyan = require('./nyan'); exports.XUnit = require('./xunit'); exports.Markdown = require('./markdown'); exports.Progress = require('./progress'); exports.Landing = require('./landing'); exports.JSONCov = require('./json-cov'); exports.HTMLCov = require('./html-cov'); exports.JSONStream = require('./json-stream'); exports.Teamcity = require('./teamcity'); }); // module: reporters/index.js require.register("reporters/json-cov.js", function(module, exports, require){ /** * Module dependencies. */ var Base = require('./base'); /** * Expose `JSONCov`. */ exports = module.exports = JSONCov; /** * Initialize a new `JsCoverage` reporter. * * @param {Runner} runner * @param {Boolean} output * @api public */ function JSONCov(runner, output) { var self = this , output = 1 == arguments.length ? true : output; Base.call(this, runner); var tests = [] , failures = [] , passes = []; runner.on('test end', function(test){ tests.push(test); }); runner.on('pass', function(test){ passes.push(test); }); runner.on('fail', function(test){ failures.push(test); }); runner.on('end', function(){ var cov = global._$jscoverage || {}; var result = self.cov = map(cov); result.stats = self.stats; result.tests = tests.map(clean); result.failures = failures.map(clean); result.passes = passes.map(clean); if (!output) return; process.stdout.write(JSON.stringify(result, null, 2 )); }); } /** * Map jscoverage data to a JSON structure * suitable for reporting. * * @param {Object} cov * @return {Object} * @api private */ function map(cov) { var ret = { instrumentation: 'node-jscoverage' , sloc: 0 , hits: 0 , misses: 0 , coverage: 0 , files: [] }; for (var filename in cov) { var data = coverage(filename, cov[filename]); ret.files.push(data); ret.hits += data.hits; ret.misses += data.misses; ret.sloc += data.sloc; } ret.files.sort(function(a, b) { return a.filename.localeCompare(b.filename); }); if (ret.sloc > 0) { ret.coverage = (ret.hits / ret.sloc) * 100; } return ret; }; /** * Map jscoverage data for a single source file * to a JSON structure suitable for reporting. * * @param {String} filename name of the source file * @param {Object} data jscoverage coverage data * @return {Object} * @api private */ function coverage(filename, data) { var ret = { filename: filename, coverage: 0, hits: 0, misses: 0, sloc: 0, source: {} }; data.source.forEach(function(line, num){ num++; if (data[num] === 0) { ret.misses++; ret.sloc++; } else if (data[num] !== undefined) { ret.hits++; ret.sloc++; } ret.source[num] = { source: line , coverage: data[num] === undefined ? '' : data[num] }; }); ret.coverage = ret.hits / ret.sloc * 100; return ret; } /** * Return a plain-object representation of `test` * free of cyclic properties etc. * * @param {Object} test * @return {Object} * @api private */ function clean(test) { return { title: test.title , fullTitle: test.fullTitle() , duration: test.duration } } }); // module: reporters/json-cov.js require.register("reporters/json-stream.js", function(module, exports, require){ /** * Module dependencies. */ var Base = require('./base') , color = Base.color; /** * Expose `List`. */ exports = module.exports = List; /** * Initialize a new `List` test reporter. * * @param {Runner} runner * @api public */ function List(runner) { Base.call(this, runner); var self = this , stats = this.stats , total = runner.total; runner.on('start', function(){ console.log(JSON.stringify(['start', { total: total }])); }); runner.on('pass', function(test){ console.log(JSON.stringify(['pass', clean(test)])); }); runner.on('fail', function(test, err){ console.log(JSON.stringify(['fail', clean(test)])); }); runner.on('end', function(){ process.stdout.write(JSON.stringify(['end', self.stats])); }); } /** * Return a plain-object representation of `test` * free of cyclic properties etc. * * @param {Object} test * @return {Object} * @api private */ function clean(test) { return { title: test.title , fullTitle: test.fullTitle() , duration: test.duration } } }); // module: reporters/json-stream.js require.register("reporters/json.js", function(module, exports, require){ /** * Module dependencies. */ var Base = require('./base') , cursor = Base.cursor , color = Base.color; /** * Expose `JSON`. */ exports = module.exports = JSONReporter; /** * Initialize a new `JSON` reporter. * * @param {Runner} runner * @api public */ function JSONReporter(runner) { var self = this; Base.call(this, runner); var tests = [] , failures = [] , passes = []; runner.on('test end', function(test){ tests.push(test); }); runner.on('pass', function(test){ passes.push(test); }); runner.on('fail', function(test){ failures.push(test); }); runner.on('end', function(){ var obj = { stats: self.stats , tests: tests.map(clean) , failures: failures.map(clean) , passes: passes.map(clean) }; process.stdout.write(JSON.stringify(obj, null, 2)); }); } /** * Return a plain-object representation of `test` * free of cyclic properties etc. * * @param {Object} test * @return {Object} * @api private */ function clean(test) { return { title: test.title , fullTitle: test.fullTitle() , duration: test.duration } } }); // module: reporters/json.js require.register("reporters/landing.js", function(module, exports, require){ /** * Module dependencies. */ var Base = require('./base') , cursor = Base.cursor , color = Base.color; /** * Expose `Landing`. */ exports = module.exports = Landing; /** * Airplane color. */ Base.colors.plane = 0; /** * Airplane crash color. */ Base.colors['plane crash'] = 31; /** * Runway color. */ Base.colors.runway = 90; /** * Initialize a new `Landing` reporter. * * @param {Runner} runner * @api public */ function Landing(runner) { Base.call(this, runner); var self = this , stats = this.stats , width = Base.window.width * .75 | 0 , total = runner.total , stream = process.stdout , plane = color('plane', '✈') , crashed = -1 , n = 0; function runway() { var buf = Array(width).join('-'); return ' ' + color('runway', buf); } runner.on('start', function(){ stream.write('\n '); cursor.hide(); }); runner.on('test end', function(test){ // check if the plane crashed var col = -1 == crashed ? width * ++n / total | 0 : crashed; // show the crash if ('failed' == test.state) { plane = color('plane crash', '✈'); crashed = col; } // render landing strip stream.write('\u001b[4F\n\n'); stream.write(runway()); stream.write('\n '); stream.write(color('runway', Array(col).join('ā‹…'))); stream.write(plane) stream.write(color('runway', Array(width - col).join('ā‹…') + '\n')); stream.write(runway()); stream.write('\u001b[0m'); }); runner.on('end', function(){ cursor.show(); console.log(); self.epilogue(); }); } /** * Inherit from `Base.prototype`. */ function F(){}; F.prototype = Base.prototype; Landing.prototype = new F; Landing.prototype.constructor = Landing; }); // module: reporters/landing.js require.register("reporters/list.js", function(module, exports, require){ /** * Module dependencies. */ var Base = require('./base') , cursor = Base.cursor , color = Base.color; /** * Expose `List`. */ exports = module.exports = List; /** * Initialize a new `List` test reporter. * * @param {Runner} runner * @api public */ function List(runner) { Base.call(this, runner); var self = this , stats = this.stats , n = 0; runner.on('start', function(){ console.log(); }); runner.on('test', function(test){ process.stdout.write(color('pass', ' ' + test.fullTitle() + ': ')); }); runner.on('pending', function(test){ var fmt = color('checkmark', ' -') + color('pending', ' %s'); console.log(fmt, test.fullTitle()); }); runner.on('pass', function(test){ var fmt = color('checkmark', ' '+Base.symbols.dot) + color('pass', ' %s: ') + color(test.speed, '%dms'); cursor.CR(); console.log(fmt, test.fullTitle(), test.duration); }); runner.on('fail', function(test, err){ cursor.CR(); console.log(color('fail', ' %d) %s'), ++n, test.fullTitle()); }); runner.on('end', self.epilogue.bind(self)); } /** * Inherit from `Base.prototype`. */ function F(){}; F.prototype = Base.prototype; List.prototype = new F; List.prototype.constructor = List; }); // module: reporters/list.js require.register("reporters/markdown.js", function(module, exports, require){ /** * Module dependencies. */ var Base = require('./base') , utils = require('../utils'); /** * Expose `Markdown`. */ exports = module.exports = Markdown; /** * Initialize a new `Markdown` reporter. * * @param {Runner} runner * @api public */ function Markdown(runner) { Base.call(this, runner); var self = this , stats = this.stats , level = 0 , buf = ''; function title(str) { return Array(level).join('#') + ' ' + str; } function indent() { return Array(level).join(' '); } function mapTOC(suite, obj) { var ret = obj; obj = obj[suite.title] = obj[suite.title] || { suite: suite }; suite.suites.forEach(function(suite){ mapTOC(suite, obj); }); return ret; } function stringifyTOC(obj, level) { ++level; var buf = ''; var link; for (var key in obj) { if ('suite' == key) continue; if (key) link = ' - [' + key + '](#' + utils.slug(obj[key].suite.fullTitle()) + ')\n'; if (key) buf += Array(level).join(' ') + link; buf += stringifyTOC(obj[key], level); } --level; return buf; } function generateTOC(suite) { var obj = mapTOC(suite, {}); return stringifyTOC(obj, 0); } generateTOC(runner.suite); runner.on('suite', function(suite){ ++level; var slug = utils.slug(suite.fullTitle()); buf += '' + '\n'; buf += title(suite.title) + '\n'; }); runner.on('suite end', function(suite){ --level; }); runner.on('pass', function(test){ var code = utils.clean(test.fn.toString()); buf += test.title + '.\n'; buf += '\n```js\n'; buf += code + '\n'; buf += '```\n\n'; }); runner.on('end', function(){ process.stdout.write('# TOC\n'); process.stdout.write(generateTOC(runner.suite)); process.stdout.write(buf); }); } }); // module: reporters/markdown.js require.register("reporters/min.js", function(module, exports, require){ /** * Module dependencies. */ var Base = require('./base'); /** * Expose `Min`. */ exports = module.exports = Min; /** * Initialize a new `Min` minimal test reporter (best used with --watch). * * @param {Runner} runner * @api public */ function Min(runner) { Base.call(this, runner); runner.on('start', function(){ // clear screen process.stdout.write('\u001b[2J'); // set cursor position process.stdout.write('\u001b[1;3H'); }); runner.on('end', this.epilogue.bind(this)); } /** * Inherit from `Base.prototype`. */ function F(){}; F.prototype = Base.prototype; Min.prototype = new F; Min.prototype.constructor = Min; }); // module: reporters/min.js require.register("reporters/nyan.js", function(module, exports, require){ /** * Module dependencies. */ var Base = require('./base') , color = Base.color; /** * Expose `Dot`. */ exports = module.exports = NyanCat; /** * Initialize a new `Dot` matrix test reporter. * * @param {Runner} runner * @api public */ function NyanCat(runner) { Base.call(this, runner); var self = this , stats = this.stats , width = Base.window.width * .75 | 0 , rainbowColors = this.rainbowColors = self.generateColors() , colorIndex = this.colorIndex = 0 , numerOfLines = this.numberOfLines = 4 , trajectories = this.trajectories = [[], [], [], []] , nyanCatWidth = this.nyanCatWidth = 11 , trajectoryWidthMax = this.trajectoryWidthMax = (width - nyanCatWidth) , scoreboardWidth = this.scoreboardWidth = 5 , tick = this.tick = 0 , n = 0; runner.on('start', function(){ Base.cursor.hide(); self.draw('start'); }); runner.on('pending', function(test){ self.draw('pending'); }); runner.on('pass', function(test){ self.draw('pass'); }); runner.on('fail', function(test, err){ self.draw('fail'); }); runner.on('end', function(){ Base.cursor.show(); for (var i = 0; i < self.numberOfLines; i++) write('\n'); self.epilogue(); }); } /** * Draw the nyan cat with runner `status`. * * @param {String} status * @api private */ NyanCat.prototype.draw = function(status){ this.appendRainbow(); this.drawScoreboard(); this.drawRainbow(); this.drawNyanCat(status); this.tick = !this.tick; }; /** * Draw the "scoreboard" showing the number * of passes, failures and pending tests. * * @api private */ NyanCat.prototype.drawScoreboard = function(){ var stats = this.stats; var colors = Base.colors; function draw(color, n) { write(' '); write('\u001b[' + color + 'm' + n + '\u001b[0m'); write('\n'); } draw(colors.green, stats.passes); draw(colors.fail, stats.failures); draw(colors.pending, stats.pending); write('\n'); this.cursorUp(this.numberOfLines); }; /** * Append the rainbow. * * @api private */ NyanCat.prototype.appendRainbow = function(){ var segment = this.tick ? '_' : '-'; var rainbowified = this.rainbowify(segment); for (var index = 0; index < this.numberOfLines; index++) { var trajectory = this.trajectories[index]; if (trajectory.length >= this.trajectoryWidthMax) trajectory.shift(); trajectory.push(rainbowified); } }; /** * Draw the rainbow. * * @api private */ NyanCat.prototype.drawRainbow = function(){ var self = this; this.trajectories.forEach(function(line, index) { write('\u001b[' + self.scoreboardWidth + 'C'); write(line.join('')); write('\n'); }); this.cursorUp(this.numberOfLines); }; /** * Draw the nyan cat with `status`. * * @param {String} status * @api private */ NyanCat.prototype.drawNyanCat = function(status) { var self = this; var startWidth = this.scoreboardWidth + this.trajectories[0].length; var color = '\u001b[' + startWidth + 'C'; var padding = ''; write(color); write('_,------,'); write('\n'); write(color); padding = self.tick ? ' ' : ' '; write('_|' + padding + '/\\_/\\ '); write('\n'); write(color); padding = self.tick ? '_' : '__'; var tail = self.tick ? '~' : '^'; var face; switch (status) { case 'pass': face = '( ^ .^)'; break; case 'fail': face = '( o .o)'; break; default: face = '( - .-)'; } write(tail + '|' + padding + face + ' '); write('\n'); write(color); padding = self.tick ? ' ' : ' '; write(padding + '"" "" '); write('\n'); this.cursorUp(this.numberOfLines); }; /** * Move cursor up `n`. * * @param {Number} n * @api private */ NyanCat.prototype.cursorUp = function(n) { write('\u001b[' + n + 'A'); }; /** * Move cursor down `n`. * * @param {Number} n * @api private */ NyanCat.prototype.cursorDown = function(n) { write('\u001b[' + n + 'B'); }; /** * Generate rainbow colors. * * @return {Array} * @api private */ NyanCat.prototype.generateColors = function(){ var colors = []; for (var i = 0; i < (6 * 7); i++) { var pi3 = Math.floor(Math.PI / 3); var n = (i * (1.0 / 6)); var r = Math.floor(3 * Math.sin(n) + 3); var g = Math.floor(3 * Math.sin(n + 2 * pi3) + 3); var b = Math.floor(3 * Math.sin(n + 4 * pi3) + 3); colors.push(36 * r + 6 * g + b + 16); } return colors; }; /** * Apply rainbow to the given `str`. * * @param {String} str * @return {String} * @api private */ NyanCat.prototype.rainbowify = function(str){ var color = this.rainbowColors[this.colorIndex % this.rainbowColors.length]; this.colorIndex += 1; return '\u001b[38;5;' + color + 'm' + str + '\u001b[0m'; }; /** * Stdout helper. */ function write(string) { process.stdout.write(string); } /** * Inherit from `Base.prototype`. */ function F(){}; F.prototype = Base.prototype; NyanCat.prototype = new F; NyanCat.prototype.constructor = NyanCat; }); // module: reporters/nyan.js require.register("reporters/progress.js", function(module, exports, require){ /** * Module dependencies. */ var Base = require('./base') , cursor = Base.cursor , color = Base.color; /** * Expose `Progress`. */ exports = module.exports = Progress; /** * General progress bar color. */ Base.colors.progress = 90; /** * Initialize a new `Progress` bar test reporter. * * @param {Runner} runner * @param {Object} options * @api public */ function Progress(runner, options) { Base.call(this, runner); var self = this , options = options || {} , stats = this.stats , width = Base.window.width * .50 | 0 , total = runner.total , complete = 0 , max = Math.max; // default chars options.open = options.open || '['; options.complete = options.complete || 'ā–¬'; options.incomplete = options.incomplete || Base.symbols.dot; options.close = options.close || ']'; options.verbose = false; // tests started runner.on('start', function(){ console.log(); cursor.hide(); }); // tests complete runner.on('test end', function(){ complete++; var incomplete = total - complete , percent = complete / total , n = width * percent | 0 , i = width - n; cursor.CR(); process.stdout.write('\u001b[J'); process.stdout.write(color('progress', ' ' + options.open)); process.stdout.write(Array(n).join(options.complete)); process.stdout.write(Array(i).join(options.incomplete)); process.stdout.write(color('progress', options.close)); if (options.verbose) { process.stdout.write(color('progress', ' ' + complete + ' of ' + total)); } }); // tests are complete, output some stats // and the failures if any runner.on('end', function(){ cursor.show(); console.log(); self.epilogue(); }); } /** * Inherit from `Base.prototype`. */ function F(){}; F.prototype = Base.prototype; Progress.prototype = new F; Progress.prototype.constructor = Progress; }); // module: reporters/progress.js require.register("reporters/spec.js", function(module, exports, require){ /** * Module dependencies. */ var Base = require('./base') , cursor = Base.cursor , color = Base.color; /** * Expose `Spec`. */ exports = module.exports = Spec; /** * Initialize a new `Spec` test reporter. * * @param {Runner} runner * @api public */ function Spec(runner) { Base.call(this, runner); var self = this , stats = this.stats , indents = 0 , n = 0; function indent() { return Array(indents).join(' ') } runner.on('start', function(){ console.log(); }); runner.on('suite', function(suite){ ++indents; console.log(color('suite', '%s%s'), indent(), suite.title); }); runner.on('suite end', function(suite){ --indents; if (1 == indents) console.log(); }); runner.on('test', function(test){ process.stdout.write(indent() + color('pass', ' ā—¦ ' + test.title + ': ')); }); runner.on('pending', function(test){ var fmt = indent() + color('pending', ' - %s'); console.log(fmt, test.title); }); runner.on('pass', function(test){ if ('fast' == test.speed) { var fmt = indent() + color('checkmark', ' ' + Base.symbols.ok) + color('pass', ' %s '); cursor.CR(); console.log(fmt, test.title); } else { var fmt = indent() + color('checkmark', ' ' + Base.symbols.ok) + color('pass', ' %s ') + color(test.speed, '(%dms)'); cursor.CR(); console.log(fmt, test.title, test.duration); } }); runner.on('fail', function(test, err){ cursor.CR(); console.log(indent() + color('fail', ' %d) %s'), ++n, test.title); }); runner.on('end', self.epilogue.bind(self)); } /** * Inherit from `Base.prototype`. */ function F(){}; F.prototype = Base.prototype; Spec.prototype = new F; Spec.prototype.constructor = Spec; }); // module: reporters/spec.js require.register("reporters/tap.js", function(module, exports, require){ /** * Module dependencies. */ var Base = require('./base') , cursor = Base.cursor , color = Base.color; /** * Expose `TAP`. */ exports = module.exports = TAP; /** * Initialize a new `TAP` reporter. * * @param {Runner} runner * @api public */ function TAP(runner) { Base.call(this, runner); var self = this , stats = this.stats , n = 1 , passes = 0 , failures = 0; runner.on('start', function(){ var total = runner.grepTotal(runner.suite); console.log('%d..%d', 1, total); }); runner.on('test end', function(){ ++n; }); runner.on('pending', function(test){ console.log('ok %d %s # SKIP -', n, title(test)); }); runner.on('pass', function(test){ passes++; console.log('ok %d %s', n, title(test)); }); runner.on('fail', function(test, err){ failures++; console.log('not ok %d %s', n, title(test)); if (err.stack) console.log(err.stack.replace(/^/gm, ' ')); }); runner.on('end', function(){ console.log('# tests ' + (passes + failures)); console.log('# pass ' + passes); console.log('# fail ' + failures); }); } /** * Return a TAP-safe title of `test` * * @param {Object} test * @return {String} * @api private */ function title(test) { return test.fullTitle().replace(/#/g, ''); } }); // module: reporters/tap.js require.register("reporters/teamcity.js", function(module, exports, require){ /** * Module dependencies. */ var Base = require('./base'); /** * Expose `Teamcity`. */ exports = module.exports = Teamcity; /** * Initialize a new `Teamcity` reporter. * * @param {Runner} runner * @api public */ function Teamcity(runner) { Base.call(this, runner); var stats = this.stats; runner.on('start', function() { console.log("##teamcity[testSuiteStarted name='mocha.suite']"); }); runner.on('test', function(test) { console.log("##teamcity[testStarted name='" + escape(test.fullTitle()) + "']"); }); runner.on('fail', function(test, err) { console.log("##teamcity[testFailed name='" + escape(test.fullTitle()) + "' message='" + escape(err.message) + "']"); }); runner.on('pending', function(test) { console.log("##teamcity[testIgnored name='" + escape(test.fullTitle()) + "' message='pending']"); }); runner.on('test end', function(test) { console.log("##teamcity[testFinished name='" + escape(test.fullTitle()) + "' duration='" + test.duration + "']"); }); runner.on('end', function() { console.log("##teamcity[testSuiteFinished name='mocha.suite' duration='" + stats.duration + "']"); }); } /** * Escape the given `str`. */ function escape(str) { return str .replace(/\|/g, "||") .replace(/\n/g, "|n") .replace(/\r/g, "|r") .replace(/\[/g, "|[") .replace(/\]/g, "|]") .replace(/\u0085/g, "|x") .replace(/\u2028/g, "|l") .replace(/\u2029/g, "|p") .replace(/'/g, "|'"); } }); // module: reporters/teamcity.js require.register("reporters/xunit.js", function(module, exports, require){ /** * Module dependencies. */ var Base = require('./base') , utils = require('../utils') , escape = utils.escape; /** * Save timer references to avoid Sinon interfering (see GH-237). */ var Date = global.Date , setTimeout = global.setTimeout , setInterval = global.setInterval , clearTimeout = global.clearTimeout , clearInterval = global.clearInterval; /** * Expose `XUnit`. */ exports = module.exports = XUnit; /** * Initialize a new `XUnit` reporter. * * @param {Runner} runner * @api public */ function XUnit(runner) { Base.call(this, runner); var stats = this.stats , tests = [] , self = this; runner.on('pass', function(test){ tests.push(test); }); runner.on('fail', function(test){ tests.push(test); }); runner.on('end', function(){ console.log(tag('testsuite', { name: 'Mocha Tests' , tests: stats.tests , failures: stats.failures , errors: stats.failures , skipped: stats.tests - stats.failures - stats.passes , timestamp: (new Date).toUTCString() , time: (stats.duration / 1000) || 0 }, false)); tests.forEach(test); console.log(''); }); } /** * Inherit from `Base.prototype`. */ function F(){}; F.prototype = Base.prototype; XUnit.prototype = new F; XUnit.prototype.constructor = XUnit; /** * Output tag for the given `test.` */ function test(test) { var attrs = { classname: test.parent.fullTitle() , name: test.title , time: test.duration / 1000 }; if ('failed' == test.state) { var err = test.err; attrs.message = escape(err.message); console.log(tag('testcase', attrs, false, tag('failure', attrs, false, cdata(err.stack)))); } else if (test.pending) { console.log(tag('testcase', attrs, false, tag('skipped', {}, true))); } else { console.log(tag('testcase', attrs, true) ); } } /** * HTML tag helper. */ function tag(name, attrs, close, content) { var end = close ? '/>' : '>' , pairs = [] , tag; for (var key in attrs) { pairs.push(key + '="' + escape(attrs[key]) + '"'); } tag = '<' + name + (pairs.length ? ' ' + pairs.join(' ') : '') + end; if (content) tag += content + ''; } }); // module: reporters/xunit.js require.register("runnable.js", function(module, exports, require){ /** * Module dependencies. */ var EventEmitter = require('browser/events').EventEmitter , debug = require('browser/debug')('mocha:runnable') , milliseconds = require('./ms'); /** * Save timer references to avoid Sinon interfering (see GH-237). */ var Date = global.Date , setTimeout = global.setTimeout , setInterval = global.setInterval , clearTimeout = global.clearTimeout , clearInterval = global.clearInterval; /** * Object#toString(). */ var toString = Object.prototype.toString; /** * Expose `Runnable`. */ module.exports = Runnable; /** * Initialize a new `Runnable` with the given `title` and callback `fn`. * * @param {String} title * @param {Function} fn * @api private */ function Runnable(title, fn) { this.title = title; this.fn = fn; this.async = fn && fn.length; this.sync = ! this.async; this._timeout = 2000; this._slow = 75; this.timedOut = false; } /** * Inherit from `EventEmitter.prototype`. */ function F(){}; F.prototype = EventEmitter.prototype; Runnable.prototype = new F; Runnable.prototype.constructor = Runnable; /** * Set & get timeout `ms`. * * @param {Number|String} ms * @return {Runnable|Number} ms or self * @api private */ Runnable.prototype.timeout = function(ms){ if (0 == arguments.length) return this._timeout; if ('string' == typeof ms) ms = milliseconds(ms); debug('timeout %d', ms); this._timeout = ms; if (this.timer) this.resetTimeout(); return this; }; /** * Set & get slow `ms`. * * @param {Number|String} ms * @return {Runnable|Number} ms or self * @api private */ Runnable.prototype.slow = function(ms){ if (0 === arguments.length) return this._slow; if ('string' == typeof ms) ms = milliseconds(ms); debug('timeout %d', ms); this._slow = ms; return this; }; /** * Return the full title generated by recursively * concatenating the parent's full title. * * @return {String} * @api public */ Runnable.prototype.fullTitle = function(){ return this.parent.fullTitle() + ' ' + this.title; }; /** * Clear the timeout. * * @api private */ Runnable.prototype.clearTimeout = function(){ clearTimeout(this.timer); }; /** * Inspect the runnable void of private properties. * * @return {String} * @api private */ Runnable.prototype.inspect = function(){ return JSON.stringify(this, function(key, val){ if ('_' == key[0]) return; if ('parent' == key) return '#'; if ('ctx' == key) return '#'; return val; }, 2); }; /** * Reset the timeout. * * @api private */ Runnable.prototype.resetTimeout = function(){ var self = this; var ms = this.timeout() || 1e9; this.clearTimeout(); this.timer = setTimeout(function(){ self.callback(new Error('timeout of ' + ms + 'ms exceeded')); self.timedOut = true; }, ms); }; /** * Run the test and invoke `fn(err)`. * * @param {Function} fn * @api private */ Runnable.prototype.run = function(fn){ var self = this , ms = this.timeout() , start = new Date , ctx = this.ctx , finished , emitted; if (ctx) ctx.runnable(this); // timeout if (this.async) { if (ms) { this.timer = setTimeout(function(){ done(new Error('timeout of ' + ms + 'ms exceeded')); self.timedOut = true; }, ms); } } // called multiple times function multiple(err) { if (emitted) return; emitted = true; self.emit('error', err || new Error('done() called multiple times')); } // finished function done(err) { if (self.timedOut) return; if (finished) return multiple(err); self.clearTimeout(); self.duration = new Date - start; finished = true; fn(err); } // for .resetTimeout() this.callback = done; // async if (this.async) { try { this.fn.call(ctx, function(err){ if (err instanceof Error || toString.call(err) === "[object Error]") return done(err); if (null != err) return done(new Error('done() invoked with non-Error: ' + err)); done(); }); } catch (err) { done(err); } return; } if (this.asyncOnly) { return done(new Error('--async-only option in use without declaring `done()`')); } // sync try { if (!this.pending) this.fn.call(ctx); this.duration = new Date - start; fn(); } catch (err) { fn(err); } }; }); // module: runnable.js require.register("runner.js", function(module, exports, require){ /** * Module dependencies. */ var EventEmitter = require('browser/events').EventEmitter , debug = require('browser/debug')('mocha:runner') , Test = require('./test') , utils = require('./utils') , filter = utils.filter , keys = utils.keys; /** * Non-enumerable globals. */ var globals = [ 'setTimeout', 'clearTimeout', 'setInterval', 'clearInterval', 'XMLHttpRequest', 'Date' ]; /** * Expose `Runner`. */ module.exports = Runner; /** * Initialize a `Runner` for the given `suite`. * * Events: * * - `start` execution started * - `end` execution complete * - `suite` (suite) test suite execution started * - `suite end` (suite) all tests (and sub-suites) have finished * - `test` (test) test execution started * - `test end` (test) test completed * - `hook` (hook) hook execution started * - `hook end` (hook) hook complete * - `pass` (test) test passed * - `fail` (test, err) test failed * - `pending` (test) test pending * * @api public */ function Runner(suite) { var self = this; this._globals = []; this.suite = suite; this.total = suite.total(); this.failures = 0; this.on('test end', function(test){ self.checkGlobals(test); }); this.on('hook end', function(hook){ self.checkGlobals(hook); }); this.grep(/.*/); this.globals(this.globalProps().concat(['errno'])); } /** * Wrapper for setImmediate, process.nextTick, or browser polyfill. * * @param {Function} fn * @api private */ Runner.immediately = global.setImmediate || process.nextTick; /** * Inherit from `EventEmitter.prototype`. */ function F(){}; F.prototype = EventEmitter.prototype; Runner.prototype = new F; Runner.prototype.constructor = Runner; /** * Run tests with full titles matching `re`. Updates runner.total * with number of tests matched. * * @param {RegExp} re * @param {Boolean} invert * @return {Runner} for chaining * @api public */ Runner.prototype.grep = function(re, invert){ debug('grep %s', re); this._grep = re; this._invert = invert; this.total = this.grepTotal(this.suite); return this; }; /** * Returns the number of tests matching the grep search for the * given suite. * * @param {Suite} suite * @return {Number} * @api public */ Runner.prototype.grepTotal = function(suite) { var self = this; var total = 0; suite.eachTest(function(test){ var match = self._grep.test(test.fullTitle()); if (self._invert) match = !match; if (match) total++; }); return total; }; /** * Return a list of global properties. * * @return {Array} * @api private */ Runner.prototype.globalProps = function() { var props = utils.keys(global); // non-enumerables for (var i = 0; i < globals.length; ++i) { if (~utils.indexOf(props, globals[i])) continue; props.push(globals[i]); } return props; }; /** * Allow the given `arr` of globals. * * @param {Array} arr * @return {Runner} for chaining * @api public */ Runner.prototype.globals = function(arr){ if (0 == arguments.length) return this._globals; debug('globals %j', arr); utils.forEach(arr, function(arr){ this._globals.push(arr); }, this); return this; }; /** * Check for global variable leaks. * * @api private */ Runner.prototype.checkGlobals = function(test){ if (this.ignoreLeaks) return; var ok = this._globals; var globals = this.globalProps(); var isNode = process.kill; var leaks; // check length - 2 ('errno' and 'location' globals) if (isNode && 1 == ok.length - globals.length) return else if (2 == ok.length - globals.length) return; leaks = filterLeaks(ok, globals); this._globals = this._globals.concat(leaks); if (leaks.length > 1) { this.fail(test, new Error('global leaks detected: ' + leaks.join(', ') + '')); } else if (leaks.length) { this.fail(test, new Error('global leak detected: ' + leaks[0])); } }; /** * Fail the given `test`. * * @param {Test} test * @param {Error} err * @api private */ Runner.prototype.fail = function(test, err){ ++this.failures; test.state = 'failed'; if ('string' == typeof err) { err = new Error('the string "' + err + '" was thrown, throw an Error :)'); } this.emit('fail', test, err); }; /** * Fail the given `hook` with `err`. * * Hook failures (currently) hard-end due * to that fact that a failing hook will * surely cause subsequent tests to fail, * causing jumbled reporting. * * @param {Hook} hook * @param {Error} err * @api private */ Runner.prototype.failHook = function(hook, err){ this.fail(hook, err); this.emit('end'); }; /** * Run hook `name` callbacks and then invoke `fn()`. * * @param {String} name * @param {Function} function * @api private */ Runner.prototype.hook = function(name, fn){ var suite = this.suite , hooks = suite['_' + name] , self = this , timer; function next(i) { var hook = hooks[i]; if (!hook) return fn(); if (self.failures && suite.bail()) return fn(); self.currentRunnable = hook; hook.ctx.currentTest = self.test; self.emit('hook', hook); hook.on('error', function(err){ self.failHook(hook, err); }); hook.run(function(err){ hook.removeAllListeners('error'); var testError = hook.error(); if (testError) self.fail(self.test, testError); if (err) return self.failHook(hook, err); self.emit('hook end', hook); delete hook.ctx.currentTest; next(++i); }); } Runner.immediately(function(){ next(0); }); }; /** * Run hook `name` for the given array of `suites` * in order, and callback `fn(err)`. * * @param {String} name * @param {Array} suites * @param {Function} fn * @api private */ Runner.prototype.hooks = function(name, suites, fn){ var self = this , orig = this.suite; function next(suite) { self.suite = suite; if (!suite) { self.suite = orig; return fn(); } self.hook(name, function(err){ if (err) { self.suite = orig; return fn(err); } next(suites.pop()); }); } next(suites.pop()); }; /** * Run hooks from the top level down. * * @param {String} name * @param {Function} fn * @api private */ Runner.prototype.hookUp = function(name, fn){ var suites = [this.suite].concat(this.parents()).reverse(); this.hooks(name, suites, fn); }; /** * Run hooks from the bottom up. * * @param {String} name * @param {Function} fn * @api private */ Runner.prototype.hookDown = function(name, fn){ var suites = [this.suite].concat(this.parents()); this.hooks(name, suites, fn); }; /** * Return an array of parent Suites from * closest to furthest. * * @return {Array} * @api private */ Runner.prototype.parents = function(){ var suite = this.suite , suites = []; while (suite = suite.parent) suites.push(suite); return suites; }; /** * Run the current test and callback `fn(err)`. * * @param {Function} fn * @api private */ Runner.prototype.runTest = function(fn){ var test = this.test , self = this; if (this.asyncOnly) test.asyncOnly = true; try { test.on('error', function(err){ self.fail(test, err); }); test.run(fn); } catch (err) { fn(err); } }; /** * Run tests in the given `suite` and invoke * the callback `fn()` when complete. * * @param {Suite} suite * @param {Function} fn * @api private */ Runner.prototype.runTests = function(suite, fn){ var self = this , tests = suite.tests.slice() , test; function next(err) { // if we bail after first err if (self.failures && suite._bail) return fn(); // next test test = tests.shift(); // all done if (!test) return fn(); // grep var match = self._grep.test(test.fullTitle()); if (self._invert) match = !match; if (!match) return next(); // pending if (test.pending) { self.emit('pending', test); self.emit('test end', test); return next(); } // execute test and hook(s) self.emit('test', self.test = test); self.hookDown('beforeEach', function(){ self.currentRunnable = self.test; self.runTest(function(err){ test = self.test; if (err) { self.fail(test, err); self.emit('test end', test); return self.hookUp('afterEach', next); } test.state = 'passed'; self.emit('pass', test); self.emit('test end', test); self.hookUp('afterEach', next); }); }); } this.next = next; next(); }; /** * Run the given `suite` and invoke the * callback `fn()` when complete. * * @param {Suite} suite * @param {Function} fn * @api private */ Runner.prototype.runSuite = function(suite, fn){ var total = this.grepTotal(suite) , self = this , i = 0; debug('run suite %s', suite.fullTitle()); if (!total) return fn(); this.emit('suite', this.suite = suite); function next() { var curr = suite.suites[i++]; if (!curr) return done(); self.runSuite(curr, next); } function done() { self.suite = suite; self.hook('afterAll', function(){ self.emit('suite end', suite); fn(); }); } this.hook('beforeAll', function(){ self.runTests(suite, next); }); }; /** * Handle uncaught exceptions. * * @param {Error} err * @api private */ Runner.prototype.uncaught = function(err){ debug('uncaught exception %s', err.message); var runnable = this.currentRunnable; if (!runnable || 'failed' == runnable.state) return; runnable.clearTimeout(); err.uncaught = true; this.fail(runnable, err); // recover from test if ('test' == runnable.type) { this.emit('test end', runnable); this.hookUp('afterEach', this.next); return; } // bail on hooks this.emit('end'); }; /** * Run the root suite and invoke `fn(failures)` * on completion. * * @param {Function} fn * @return {Runner} for chaining * @api public */ Runner.prototype.run = function(fn){ var self = this , fn = fn || function(){}; function uncaught(err){ self.uncaught(err); } debug('start'); // callback this.on('end', function(){ debug('end'); process.removeListener('uncaughtException', uncaught); fn(self.failures); }); // run suites this.emit('start'); this.runSuite(this.suite, function(){ debug('finished running'); self.emit('end'); }); // uncaught exception process.on('uncaughtException', uncaught); return this; }; /** * Filter leaks with the given globals flagged as `ok`. * * @param {Array} ok * @param {Array} globals * @return {Array} * @api private */ function filterLeaks(ok, globals) { return filter(globals, function(key){ // Firefox and Chrome exposes iframes as index inside the window object if (/^d+/.test(key)) return false; var matched = filter(ok, function(ok){ if (~ok.indexOf('*')) return 0 == key.indexOf(ok.split('*')[0]); // Opera and IE expose global variables for HTML element IDs (issue #243) if (/^mocha-/.test(key)) return true; return key == ok; }); return matched.length == 0 && (!global.navigator || 'onerror' !== key); }); } }); // module: runner.js require.register("suite.js", function(module, exports, require){ /** * Module dependencies. */ var EventEmitter = require('browser/events').EventEmitter , debug = require('browser/debug')('mocha:suite') , milliseconds = require('./ms') , utils = require('./utils') , Hook = require('./hook'); /** * Expose `Suite`. */ exports = module.exports = Suite; /** * Create a new `Suite` with the given `title` * and parent `Suite`. When a suite with the * same title is already present, that suite * is returned to provide nicer reporter * and more flexible meta-testing. * * @param {Suite} parent * @param {String} title * @return {Suite} * @api public */ exports.create = function(parent, title){ var suite = new Suite(title, parent.ctx); suite.parent = parent; if (parent.pending) suite.pending = true; title = suite.fullTitle(); parent.addSuite(suite); return suite; }; /** * Initialize a new `Suite` with the given * `title` and `ctx`. * * @param {String} title * @param {Context} ctx * @api private */ function Suite(title, ctx) { this.title = title; this.ctx = ctx; this.suites = []; this.tests = []; this.pending = false; this._beforeEach = []; this._beforeAll = []; this._afterEach = []; this._afterAll = []; this.root = !title; this._timeout = 2000; this._slow = 75; this._bail = false; } /** * Inherit from `EventEmitter.prototype`. */ function F(){}; F.prototype = EventEmitter.prototype; Suite.prototype = new F; Suite.prototype.constructor = Suite; /** * Return a clone of this `Suite`. * * @return {Suite} * @api private */ Suite.prototype.clone = function(){ var suite = new Suite(this.title); debug('clone'); suite.ctx = this.ctx; suite.timeout(this.timeout()); suite.slow(this.slow()); suite.bail(this.bail()); return suite; }; /** * Set timeout `ms` or short-hand such as "2s". * * @param {Number|String} ms * @return {Suite|Number} for chaining * @api private */ Suite.prototype.timeout = function(ms){ if (0 == arguments.length) return this._timeout; if ('string' == typeof ms) ms = milliseconds(ms); debug('timeout %d', ms); this._timeout = parseInt(ms, 10); return this; }; /** * Set slow `ms` or short-hand such as "2s". * * @param {Number|String} ms * @return {Suite|Number} for chaining * @api private */ Suite.prototype.slow = function(ms){ if (0 === arguments.length) return this._slow; if ('string' == typeof ms) ms = milliseconds(ms); debug('slow %d', ms); this._slow = ms; return this; }; /** * Sets whether to bail after first error. * * @parma {Boolean} bail * @return {Suite|Number} for chaining * @api private */ Suite.prototype.bail = function(bail){ if (0 == arguments.length) return this._bail; debug('bail %s', bail); this._bail = bail; return this; }; /** * Run `fn(test[, done])` before running tests. * * @param {Function} fn * @return {Suite} for chaining * @api private */ Suite.prototype.beforeAll = function(fn){ if (this.pending) return this; var hook = new Hook('"before all" hook', fn); hook.parent = this; hook.timeout(this.timeout()); hook.slow(this.slow()); hook.ctx = this.ctx; this._beforeAll.push(hook); this.emit('beforeAll', hook); return this; }; /** * Run `fn(test[, done])` after running tests. * * @param {Function} fn * @return {Suite} for chaining * @api private */ Suite.prototype.afterAll = function(fn){ if (this.pending) return this; var hook = new Hook('"after all" hook', fn); hook.parent = this; hook.timeout(this.timeout()); hook.slow(this.slow()); hook.ctx = this.ctx; this._afterAll.push(hook); this.emit('afterAll', hook); return this; }; /** * Run `fn(test[, done])` before each test case. * * @param {Function} fn * @return {Suite} for chaining * @api private */ Suite.prototype.beforeEach = function(fn){ if (this.pending) return this; var hook = new Hook('"before each" hook', fn); hook.parent = this; hook.timeout(this.timeout()); hook.slow(this.slow()); hook.ctx = this.ctx; this._beforeEach.push(hook); this.emit('beforeEach', hook); return this; }; /** * Run `fn(test[, done])` after each test case. * * @param {Function} fn * @return {Suite} for chaining * @api private */ Suite.prototype.afterEach = function(fn){ if (this.pending) return this; var hook = new Hook('"after each" hook', fn); hook.parent = this; hook.timeout(this.timeout()); hook.slow(this.slow()); hook.ctx = this.ctx; this._afterEach.push(hook); this.emit('afterEach', hook); return this; }; /** * Add a test `suite`. * * @param {Suite} suite * @return {Suite} for chaining * @api private */ Suite.prototype.addSuite = function(suite){ suite.parent = this; suite.timeout(this.timeout()); suite.slow(this.slow()); suite.bail(this.bail()); this.suites.push(suite); this.emit('suite', suite); return this; }; /** * Add a `test` to this suite. * * @param {Test} test * @return {Suite} for chaining * @api private */ Suite.prototype.addTest = function(test){ test.parent = this; test.timeout(this.timeout()); test.slow(this.slow()); test.ctx = this.ctx; this.tests.push(test); this.emit('test', test); return this; }; /** * Return the full title generated by recursively * concatenating the parent's full title. * * @return {String} * @api public */ Suite.prototype.fullTitle = function(){ if (this.parent) { var full = this.parent.fullTitle(); if (full) return full + ' ' + this.title; } return this.title; }; /** * Return the total number of tests. * * @return {Number} * @api public */ Suite.prototype.total = function(){ return utils.reduce(this.suites, function(sum, suite){ return sum + suite.total(); }, 0) + this.tests.length; }; /** * Iterates through each suite recursively to find * all tests. Applies a function in the format * `fn(test)`. * * @param {Function} fn * @return {Suite} * @api private */ Suite.prototype.eachTest = function(fn){ utils.forEach(this.tests, fn); utils.forEach(this.suites, function(suite){ suite.eachTest(fn); }); return this; }; }); // module: suite.js require.register("test.js", function(module, exports, require){ /** * Module dependencies. */ var Runnable = require('./runnable'); /** * Expose `Test`. */ module.exports = Test; /** * Initialize a new `Test` with the given `title` and callback `fn`. * * @param {String} title * @param {Function} fn * @api private */ function Test(title, fn) { Runnable.call(this, title, fn); this.pending = !fn; this.type = 'test'; } /** * Inherit from `Runnable.prototype`. */ function F(){}; F.prototype = Runnable.prototype; Test.prototype = new F; Test.prototype.constructor = Test; }); // module: test.js require.register("utils.js", function(module, exports, require){ /** * Module dependencies. */ var fs = require('browser/fs') , path = require('browser/path') , join = path.join , debug = require('browser/debug')('mocha:watch'); /** * Ignored directories. */ var ignore = ['node_modules', '.git']; /** * Escape special characters in the given string of html. * * @param {String} html * @return {String} * @api private */ exports.escape = function(html){ return String(html) .replace(/&/g, '&') .replace(/"/g, '"') .replace(//g, '>'); }; /** * Array#forEach (<=IE8) * * @param {Array} array * @param {Function} fn * @param {Object} scope * @api private */ exports.forEach = function(arr, fn, scope){ for (var i = 0, l = arr.length; i < l; i++) fn.call(scope, arr[i], i); }; /** * Array#indexOf (<=IE8) * * @parma {Array} arr * @param {Object} obj to find index of * @param {Number} start * @api private */ exports.indexOf = function(arr, obj, start){ for (var i = start || 0, l = arr.length; i < l; i++) { if (arr[i] === obj) return i; } return -1; }; /** * Array#reduce (<=IE8) * * @param {Array} array * @param {Function} fn * @param {Object} initial value * @api private */ exports.reduce = function(arr, fn, val){ var rval = val; for (var i = 0, l = arr.length; i < l; i++) { rval = fn(rval, arr[i], i, arr); } return rval; }; /** * Array#filter (<=IE8) * * @param {Array} array * @param {Function} fn * @api private */ exports.filter = function(arr, fn){ var ret = []; for (var i = 0, l = arr.length; i < l; i++) { var val = arr[i]; if (fn(val, i, arr)) ret.push(val); } return ret; }; /** * Object.keys (<=IE8) * * @param {Object} obj * @return {Array} keys * @api private */ exports.keys = Object.keys || function(obj) { var keys = [] , has = Object.prototype.hasOwnProperty // for `window` on <=IE8 for (var key in obj) { if (has.call(obj, key)) { keys.push(key); } } return keys; }; /** * Watch the given `files` for changes * and invoke `fn(file)` on modification. * * @param {Array} files * @param {Function} fn * @api private */ exports.watch = function(files, fn){ var options = { interval: 100 }; files.forEach(function(file){ debug('file %s', file); fs.watchFile(file, options, function(curr, prev){ if (prev.mtime < curr.mtime) fn(file); }); }); }; /** * Ignored files. */ function ignored(path){ return !~ignore.indexOf(path); } /** * Lookup files in the given `dir`. * * @return {Array} * @api private */ exports.files = function(dir, ret){ ret = ret || []; fs.readdirSync(dir) .filter(ignored) .forEach(function(path){ path = join(dir, path); if (fs.statSync(path).isDirectory()) { exports.files(path, ret); } else if (path.match(/\.(js|coffee)$/)) { ret.push(path); } }); return ret; }; /** * Compute a slug from the given `str`. * * @param {String} str * @return {String} * @api private */ exports.slug = function(str){ return str .toLowerCase() .replace(/ +/g, '-') .replace(/[^-\w]/g, ''); }; /** * Strip the function definition from `str`, * and re-indent for pre whitespace. */ exports.clean = function(str) { str = str .replace(/^function *\(.*\) *{/, '') .replace(/\s+\}$/, ''); var whitespace = str.match(/^\n?(\s*)/)[1] , re = new RegExp('^' + whitespace, 'gm'); str = str.replace(re, ''); return exports.trim(str); }; /** * Escape regular expression characters in `str`. * * @param {String} str * @return {String} * @api private */ exports.escapeRegexp = function(str){ return str.replace(/[-\\^$*+?.()|[\]{}]/g, "\\$&"); }; /** * Trim the given `str`. * * @param {String} str * @return {String} * @api private */ exports.trim = function(str){ return str.replace(/^\s+|\s+$/g, ''); }; /** * Parse the given `qs`. * * @param {String} qs * @return {Object} * @api private */ exports.parseQuery = function(qs){ return exports.reduce(qs.replace('?', '').split('&'), function(obj, pair){ var i = pair.indexOf('=') , key = pair.slice(0, i) , val = pair.slice(++i); obj[key] = decodeURIComponent(val); return obj; }, {}); }; /** * Highlight the given string of `js`. * * @param {String} js * @return {String} * @api private */ function highlight(js) { return js .replace(//g, '>') .replace(/\/\/(.*)/gm, '//$1') .replace(/('.*?')/gm, '$1') .replace(/(\d+\.\d+)/gm, '$1') .replace(/(\d+)/gm, '$1') .replace(/\bnew *(\w+)/gm, 'new $1') .replace(/\b(function|new|throw|return|var|if|else)\b/gm, '$1') } /** * Highlight the contents of tag `name`. * * @param {String} name * @api private */ exports.highlightTags = function(name) { var code = document.getElementsByTagName(name); for (var i = 0, len = code.length; i < len; ++i) { code[i].innerHTML = highlight(code[i].innerHTML); } }; }); // module: utils.js // The global object is "self" in Web Workers. global = (function() { return this; })(); /** * Save timer references to avoid Sinon interfering (see GH-237). */ var Date = global.Date; var setTimeout = global.setTimeout; var setInterval = global.setInterval; var clearTimeout = global.clearTimeout; var clearInterval = global.clearInterval; /** * Node shims. * * These are meant only to allow * mocha.js to run untouched, not * to allow running node code in * the browser. */ var process = {}; process.exit = function(status){}; process.stdout = {}; /** * Remove uncaughtException listener. */ process.removeListener = function(e){ if ('uncaughtException' == e) { global.onerror = function() {}; } }; /** * Implements uncaughtException listener. */ process.on = function(e, fn){ if ('uncaughtException' == e) { global.onerror = function(err, url, line){ fn(new Error(err + ' (' + url + ':' + line + ')')); }; } }; /** * Expose mocha. */ var Mocha = global.Mocha = require('mocha'), mocha = global.mocha = new Mocha({ reporter: 'html' }); var immediateQueue = [] , immediateTimeout; function timeslice() { var immediateStart = new Date().getTime(); while (immediateQueue.length && (new Date().getTime() - immediateStart) < 100) { immediateQueue.shift()(); } if (immediateQueue.length) { immediateTimeout = setTimeout(timeslice, 0); } else { immediateTimeout = null; } } /** * High-performance override of Runner.immediately. */ Mocha.Runner.immediately = function(callback) { immediateQueue.push(callback); if (!immediateTimeout) { immediateTimeout = setTimeout(timeslice, 0); } }; /** * Override ui to ensure that the ui functions are initialized. * Normally this would happen in Mocha.prototype.loadFiles. */ mocha.ui = function(ui){ Mocha.prototype.ui.call(this, ui); this.suite.emit('pre-require', global, null, this); return this; }; /** * Setup mocha with the given setting options. */ mocha.setup = function(opts){ if ('string' == typeof opts) opts = { ui: opts }; for (var opt in opts) this[opt](opts[opt]); return this; }; /** * Run mocha, returning the Runner. */ mocha.run = function(fn){ var options = mocha.options; mocha.globals('location'); var query = Mocha.utils.parseQuery(global.location.search || ''); if (query.grep) mocha.grep(query.grep); if (query.invert) mocha.invert(); return Mocha.prototype.run.call(mocha, function(){ // The DOM Document is not available in Web Workers. if (global.document) { Mocha.utils.highlightTags('code'); } if (fn) fn(); }); }; /** * Expose the process shim. */ Mocha.process = process; })();apache-couchdb-1.5.0/src/fauxton/test/mocha/mocha.css0000755000175000001440000000737112230722213017407 00000000000000@charset "utf-8"; body { margin:0; } #mocha { font: 20px/1.5 "Helvetica Neue", Helvetica, Arial, sans-serif; margin: 60px 50px; } #mocha ul, #mocha li { margin: 0; padding: 0; } #mocha ul { list-style: none; } #mocha h1, #mocha h2 { margin: 0; } #mocha h1 { margin-top: 15px; font-size: 1em; font-weight: 200; } #mocha h1 a { text-decoration: none; color: inherit; } #mocha h1 a:hover { text-decoration: underline; } #mocha .suite .suite h1 { margin-top: 0; font-size: .8em; } #mocha .hidden { display: none; } #mocha h2 { font-size: 12px; font-weight: normal; cursor: pointer; } #mocha .suite { margin-left: 15px; } #mocha .test { margin-left: 15px; overflow: hidden; } #mocha .test.pending:hover h2::after { content: '(pending)'; font-family: arial, sans-serif; } #mocha .test.pass.medium .duration { background: #C09853; } #mocha .test.pass.slow .duration { background: #B94A48; } #mocha .test.pass::before { content: 'āœ“'; font-size: 12px; display: block; float: left; margin-right: 5px; color: #00d6b2; } #mocha .test.pass .duration { font-size: 9px; margin-left: 5px; padding: 2px 5px; color: white; -webkit-box-shadow: inset 0 1px 1px rgba(0,0,0,.2); -moz-box-shadow: inset 0 1px 1px rgba(0,0,0,.2); box-shadow: inset 0 1px 1px rgba(0,0,0,.2); -webkit-border-radius: 5px; -moz-border-radius: 5px; -ms-border-radius: 5px; -o-border-radius: 5px; border-radius: 5px; } #mocha .test.pass.fast .duration { display: none; } #mocha .test.pending { color: #0b97c4; } #mocha .test.pending::before { content: 'ā—¦'; color: #0b97c4; } #mocha .test.fail { color: #c00; } #mocha .test.fail pre { color: black; } #mocha .test.fail::before { content: 'āœ–'; font-size: 12px; display: block; float: left; margin-right: 5px; color: #c00; } #mocha .test pre.error { color: #c00; max-height: 300px; overflow: auto; } #mocha .test pre { display: block; float: left; clear: left; font: 12px/1.5 monaco, monospace; margin: 5px; padding: 15px; border: 1px solid #eee; border-bottom-color: #ddd; -webkit-border-radius: 3px; -webkit-box-shadow: 0 1px 3px #eee; -moz-border-radius: 3px; -moz-box-shadow: 0 1px 3px #eee; } #mocha .test h2 { position: relative; } #mocha .test a.replay { position: absolute; top: 3px; right: 0; text-decoration: none; vertical-align: middle; display: block; width: 15px; height: 15px; line-height: 15px; text-align: center; background: #eee; font-size: 15px; -moz-border-radius: 15px; border-radius: 15px; -webkit-transition: opacity 200ms; -moz-transition: opacity 200ms; transition: opacity 200ms; opacity: 0.3; color: #888; } #mocha .test:hover a.replay { opacity: 1; } #mocha-report.pass .test.fail { display: none; } #mocha-report.fail .test.pass { display: none; } #mocha-error { color: #c00; font-size: 1.5em; font-weight: 100; letter-spacing: 1px; } #mocha-stats { position: fixed; top: 15px; right: 10px; font-size: 12px; margin: 0; color: #888; z-index: 1; } #mocha-stats .progress { float: right; padding-top: 0; } #mocha-stats em { color: black; } #mocha-stats a { text-decoration: none; color: inherit; } #mocha-stats a:hover { border-bottom: 1px solid #eee; } #mocha-stats li { display: inline-block; margin: 0 5px; list-style: none; padding-top: 11px; } #mocha-stats canvas { width: 40px; height: 40px; } #mocha code .comment { color: #ddd } #mocha code .init { color: #2F6FAD } #mocha code .string { color: #5890AD } #mocha code .keyword { color: #8A6343 } #mocha code .number { color: #2F6FAD } @media screen and (max-device-width: 480px) { #mocha { margin: 60px 0px; } #mocha #stats { position: absolute; } } apache-couchdb-1.5.0/src/fauxton/test/mocha/testUtils.js0000644000175000001440000000236412230722213020136 00000000000000// 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. define([ "chai", "sinon-chai", "underscore" ], function(chai, sinonChai) { chai.use(sinonChai); var ViewSandbox = function () { this.initialize(); }; _.extend(ViewSandbox.prototype, { initialize: function () { this.$el = $('
    ').appendTo('body'); this.$ = this.$el.find; }, views: [], renderView: function (view) { this.views.push(view); this.$el.append(view.el); view.render(); }, remove: function () { _.each(this.views, function (view) { view.remove(); }, this); } }); return { chai: chai, assert: chai.assert, ViewSandbox: ViewSandbox }; }); apache-couchdb-1.5.0/src/fauxton/test/mocha/chai.js0000644000175000001440000032641612230722213017051 00000000000000;(function(){ /** * Require the given path. * * @param {String} path * @return {Object} exports * @api public */ function require(path, parent, orig) { var resolved = require.resolve(path); // lookup failed if (null == resolved) { orig = orig || path; parent = parent || 'root'; var err = new Error('Failed to require "' + orig + '" from "' + parent + '"'); err.path = orig; err.parent = parent; err.require = true; throw err; } var module = require.modules[resolved]; // perform real require() // by invoking the module's // registered function if (!module.exports) { module.exports = {}; module.client = module.component = true; module.call(this, module.exports, require.relative(resolved), module); } return module.exports; } /** * Registered modules. */ require.modules = {}; /** * Registered aliases. */ require.aliases = {}; /** * Resolve `path`. * * Lookup: * * - PATH/index.js * - PATH.js * - PATH * * @param {String} path * @return {String} path or null * @api private */ require.resolve = function(path) { if (path.charAt(0) === '/') path = path.slice(1); var paths = [ path, path + '.js', path + '.json', path + '/index.js', path + '/index.json' ]; for (var i = 0; i < paths.length; i++) { var path = paths[i]; if (require.modules.hasOwnProperty(path)) return path; if (require.aliases.hasOwnProperty(path)) return require.aliases[path]; } }; /** * Normalize `path` relative to the current path. * * @param {String} curr * @param {String} path * @return {String} * @api private */ require.normalize = function(curr, path) { var segs = []; if ('.' != path.charAt(0)) return path; curr = curr.split('/'); path = path.split('/'); for (var i = 0; i < path.length; ++i) { if ('..' == path[i]) { curr.pop(); } else if ('.' != path[i] && '' != path[i]) { segs.push(path[i]); } } return curr.concat(segs).join('/'); }; /** * Register module at `path` with callback `definition`. * * @param {String} path * @param {Function} definition * @api private */ require.register = function(path, definition) { require.modules[path] = definition; }; /** * Alias a module definition. * * @param {String} from * @param {String} to * @api private */ require.alias = function(from, to) { if (!require.modules.hasOwnProperty(from)) { throw new Error('Failed to alias "' + from + '", it does not exist'); } require.aliases[to] = from; }; /** * Return a require function relative to the `parent` path. * * @param {String} parent * @return {Function} * @api private */ require.relative = function(parent) { var p = require.normalize(parent, '..'); /** * lastIndexOf helper. */ function lastIndexOf(arr, obj) { var i = arr.length; while (i--) { if (arr[i] === obj) return i; } return -1; } /** * The relative require() itself. */ function localRequire(path) { var resolved = localRequire.resolve(path); return require(resolved, parent, path); } /** * Resolve relative to the parent. */ localRequire.resolve = function(path) { var c = path.charAt(0); if ('/' == c) return path.slice(1); if ('.' == c) return require.normalize(p, path); // resolve deps by returning // the dep in the nearest "deps" // directory var segs = parent.split('/'); var i = lastIndexOf(segs, 'deps') + 1; if (!i) i = 0; path = segs.slice(0, i + 1).join('/') + '/deps/' + path; return path; }; /** * Check if module is defined at `path`. */ localRequire.exists = function(path) { return require.modules.hasOwnProperty(localRequire.resolve(path)); }; return localRequire; }; require.register("chaijs-assertion-error/index.js", function(exports, require, module){ /*! * assertion-error * Copyright(c) 2013 Jake Luer * MIT Licensed */ /*! * Return a function that will copy properties from * one object to another excluding any originally * listed. Returned function will create a new `{}`. * * @param {String} excluded properties ... * @return {Function} */ function exclude () { var excludes = [].slice.call(arguments); function excludeProps (res, obj) { Object.keys(obj).forEach(function (key) { if (!~excludes.indexOf(key)) res[key] = obj[key]; }); } return function extendExclude () { var args = [].slice.call(arguments) , i = 0 , res = {}; for (; i < args.length; i++) { excludeProps(res, args[i]); } return res; }; }; /*! * Primary Exports */ module.exports = AssertionError; /** * ### AssertionError * * An extension of the JavaScript `Error` constructor for * assertion and validation scenarios. * * @param {String} message * @param {Object} properties to include (optional) * @param {callee} start stack function (optional) */ function AssertionError (message, _props, ssf) { var extend = exclude('name', 'message', 'stack', 'constructor', 'toJSON') , props = extend(_props || {}); // default values this.message = message || 'Unspecified AssertionError'; this.showDiff = false; // copy from properties for (var key in props) { this[key] = props[key]; } // capture stack trace ssf = ssf || arguments.callee; if (ssf && Error.captureStackTrace) { Error.captureStackTrace(this, ssf); } } /*! * Inherit from Error.prototype */ AssertionError.prototype = Object.create(Error.prototype); /*! * Statically set name */ AssertionError.prototype.name = 'AssertionError'; /*! * Ensure correct constructor */ AssertionError.prototype.constructor = AssertionError; /** * Allow errors to be converted to JSON for static transfer. * * @param {Boolean} include stack (default: `true`) * @return {Object} object that can be `JSON.stringify` */ AssertionError.prototype.toJSON = function (stack) { var extend = exclude('constructor', 'toJSON', 'stack') , props = extend({ name: this.name }, this); // include stack if exists and not turned off if (false !== stack && this.stack) { props.stack = this.stack; } return props; }; }); require.register("chai/index.js", function(exports, require, module){ module.exports = require('./lib/chai'); }); require.register("chai/lib/chai.js", function(exports, require, module){ /*! * chai * Copyright(c) 2011-2013 Jake Luer * MIT Licensed */ var used = [] , exports = module.exports = {}; /*! * Chai version */ exports.version = '1.7.2'; /*! * Assertion Error */ exports.AssertionError = require('assertion-error'); /*! * Utils for plugins (not exported) */ var util = require('./chai/utils'); /** * # .use(function) * * Provides a way to extend the internals of Chai * * @param {Function} * @returns {this} for chaining * @api public */ exports.use = function (fn) { if (!~used.indexOf(fn)) { fn(this, util); used.push(fn); } return this; }; /*! * Primary `Assertion` prototype */ var assertion = require('./chai/assertion'); exports.use(assertion); /*! * Core Assertions */ var core = require('./chai/core/assertions'); exports.use(core); /*! * Expect interface */ var expect = require('./chai/interface/expect'); exports.use(expect); /*! * Should interface */ var should = require('./chai/interface/should'); exports.use(should); /*! * Assert interface */ var assert = require('./chai/interface/assert'); exports.use(assert); }); require.register("chai/lib/chai/assertion.js", function(exports, require, module){ /*! * chai * http://chaijs.com * Copyright(c) 2011-2013 Jake Luer * MIT Licensed */ module.exports = function (_chai, util) { /*! * Module dependencies. */ var AssertionError = _chai.AssertionError , flag = util.flag; /*! * Module export. */ _chai.Assertion = Assertion; /*! * Assertion Constructor * * Creates object for chaining. * * @api private */ function Assertion (obj, msg, stack) { flag(this, 'ssfi', stack || arguments.callee); flag(this, 'object', obj); flag(this, 'message', msg); } /*! * ### Assertion.includeStack * * User configurable property, influences whether stack trace * is included in Assertion error message. Default of false * suppresses stack trace in the error message * * Assertion.includeStack = true; // enable stack on error * * @api public */ Assertion.includeStack = false; /*! * ### Assertion.showDiff * * User configurable property, influences whether or not * the `showDiff` flag should be included in the thrown * AssertionErrors. `false` will always be `false`; `true` * will be true when the assertion has requested a diff * be shown. * * @api public */ Assertion.showDiff = true; Assertion.addProperty = function (name, fn) { util.addProperty(this.prototype, name, fn); }; Assertion.addMethod = function (name, fn) { util.addMethod(this.prototype, name, fn); }; Assertion.addChainableMethod = function (name, fn, chainingBehavior) { util.addChainableMethod(this.prototype, name, fn, chainingBehavior); }; Assertion.overwriteProperty = function (name, fn) { util.overwriteProperty(this.prototype, name, fn); }; Assertion.overwriteMethod = function (name, fn) { util.overwriteMethod(this.prototype, name, fn); }; /*! * ### .assert(expression, message, negateMessage, expected, actual) * * Executes an expression and check expectations. Throws AssertionError for reporting if test doesn't pass. * * @name assert * @param {Philosophical} expression to be tested * @param {String} message to display if fails * @param {String} negatedMessage to display if negated expression fails * @param {Mixed} expected value (remember to check for negation) * @param {Mixed} actual (optional) will default to `this.obj` * @api private */ Assertion.prototype.assert = function (expr, msg, negateMsg, expected, _actual, showDiff) { var ok = util.test(this, arguments); if (true !== showDiff) showDiff = false; if (true !== Assertion.showDiff) showDiff = false; if (!ok) { var msg = util.getMessage(this, arguments) , actual = util.getActual(this, arguments); throw new AssertionError(msg, { actual: actual , expected: expected , showDiff: showDiff }, (Assertion.includeStack) ? this.assert : flag(this, 'ssfi')); } }; /*! * ### ._obj * * Quick reference to stored `actual` value for plugin developers. * * @api private */ Object.defineProperty(Assertion.prototype, '_obj', { get: function () { return flag(this, 'object'); } , set: function (val) { flag(this, 'object', val); } }); }; }); require.register("chai/lib/chai/core/assertions.js", function(exports, require, module){ /*! * chai * http://chaijs.com * Copyright(c) 2011-2013 Jake Luer * MIT Licensed */ module.exports = function (chai, _) { var Assertion = chai.Assertion , toString = Object.prototype.toString , flag = _.flag; /** * ### Language Chains * * The following are provide as chainable getters to * improve the readability of your assertions. They * do not provide an testing capability unless they * have been overwritten by a plugin. * * **Chains** * * - to * - be * - been * - is * - that * - and * - have * - with * - at * - of * - same * * @name language chains * @api public */ [ 'to', 'be', 'been' , 'is', 'and', 'have' , 'with', 'that', 'at' , 'of', 'same' ].forEach(function (chain) { Assertion.addProperty(chain, function () { return this; }); }); /** * ### .not * * Negates any of assertions following in the chain. * * expect(foo).to.not.equal('bar'); * expect(goodFn).to.not.throw(Error); * expect({ foo: 'baz' }).to.have.property('foo') * .and.not.equal('bar'); * * @name not * @api public */ Assertion.addProperty('not', function () { flag(this, 'negate', true); }); /** * ### .deep * * Sets the `deep` flag, later used by the `equal` and * `property` assertions. * * expect(foo).to.deep.equal({ bar: 'baz' }); * expect({ foo: { bar: { baz: 'quux' } } }) * .to.have.deep.property('foo.bar.baz', 'quux'); * * @name deep * @api public */ Assertion.addProperty('deep', function () { flag(this, 'deep', true); }); /** * ### .a(type) * * The `a` and `an` assertions are aliases that can be * used either as language chains or to assert a value's * type. * * // typeof * expect('test').to.be.a('string'); * expect({ foo: 'bar' }).to.be.an('object'); * expect(null).to.be.a('null'); * expect(undefined).to.be.an('undefined'); * * // language chain * expect(foo).to.be.an.instanceof(Foo); * * @name a * @alias an * @param {String} type * @param {String} message _optional_ * @api public */ function an (type, msg) { if (msg) flag(this, 'message', msg); type = type.toLowerCase(); var obj = flag(this, 'object') , article = ~[ 'a', 'e', 'i', 'o', 'u' ].indexOf(type.charAt(0)) ? 'an ' : 'a '; this.assert( type === _.type(obj) , 'expected #{this} to be ' + article + type , 'expected #{this} not to be ' + article + type ); } Assertion.addChainableMethod('an', an); Assertion.addChainableMethod('a', an); /** * ### .include(value) * * The `include` and `contain` assertions can be used as either property * based language chains or as methods to assert the inclusion of an object * in an array or a substring in a string. When used as language chains, * they toggle the `contain` flag for the `keys` assertion. * * expect([1,2,3]).to.include(2); * expect('foobar').to.contain('foo'); * expect({ foo: 'bar', hello: 'universe' }).to.include.keys('foo'); * * @name include * @alias contain * @param {Object|String|Number} obj * @param {String} message _optional_ * @api public */ function includeChainingBehavior () { flag(this, 'contains', true); } function include (val, msg) { if (msg) flag(this, 'message', msg); var obj = flag(this, 'object') this.assert( ~obj.indexOf(val) , 'expected #{this} to include ' + _.inspect(val) , 'expected #{this} to not include ' + _.inspect(val)); } Assertion.addChainableMethod('include', include, includeChainingBehavior); Assertion.addChainableMethod('contain', include, includeChainingBehavior); /** * ### .ok * * Asserts that the target is truthy. * * expect('everthing').to.be.ok; * expect(1).to.be.ok; * expect(false).to.not.be.ok; * expect(undefined).to.not.be.ok; * expect(null).to.not.be.ok; * * @name ok * @api public */ Assertion.addProperty('ok', function () { this.assert( flag(this, 'object') , 'expected #{this} to be truthy' , 'expected #{this} to be falsy'); }); /** * ### .true * * Asserts that the target is `true`. * * expect(true).to.be.true; * expect(1).to.not.be.true; * * @name true * @api public */ Assertion.addProperty('true', function () { this.assert( true === flag(this, 'object') , 'expected #{this} to be true' , 'expected #{this} to be false' , this.negate ? false : true ); }); /** * ### .false * * Asserts that the target is `false`. * * expect(false).to.be.false; * expect(0).to.not.be.false; * * @name false * @api public */ Assertion.addProperty('false', function () { this.assert( false === flag(this, 'object') , 'expected #{this} to be false' , 'expected #{this} to be true' , this.negate ? true : false ); }); /** * ### .null * * Asserts that the target is `null`. * * expect(null).to.be.null; * expect(undefined).not.to.be.null; * * @name null * @api public */ Assertion.addProperty('null', function () { this.assert( null === flag(this, 'object') , 'expected #{this} to be null' , 'expected #{this} not to be null' ); }); /** * ### .undefined * * Asserts that the target is `undefined`. * * expect(undefined).to.be.undefined; * expect(null).to.not.be.undefined; * * @name undefined * @api public */ Assertion.addProperty('undefined', function () { this.assert( undefined === flag(this, 'object') , 'expected #{this} to be undefined' , 'expected #{this} not to be undefined' ); }); /** * ### .exist * * Asserts that the target is neither `null` nor `undefined`. * * var foo = 'hi' * , bar = null * , baz; * * expect(foo).to.exist; * expect(bar).to.not.exist; * expect(baz).to.not.exist; * * @name exist * @api public */ Assertion.addProperty('exist', function () { this.assert( null != flag(this, 'object') , 'expected #{this} to exist' , 'expected #{this} to not exist' ); }); /** * ### .empty * * Asserts that the target's length is `0`. For arrays, it checks * the `length` property. For objects, it gets the count of * enumerable keys. * * expect([]).to.be.empty; * expect('').to.be.empty; * expect({}).to.be.empty; * * @name empty * @api public */ Assertion.addProperty('empty', function () { var obj = flag(this, 'object') , expected = obj; if (Array.isArray(obj) || 'string' === typeof object) { expected = obj.length; } else if (typeof obj === 'object') { expected = Object.keys(obj).length; } this.assert( !expected , 'expected #{this} to be empty' , 'expected #{this} not to be empty' ); }); /** * ### .arguments * * Asserts that the target is an arguments object. * * function test () { * expect(arguments).to.be.arguments; * } * * @name arguments * @alias Arguments * @api public */ function checkArguments () { var obj = flag(this, 'object') , type = Object.prototype.toString.call(obj); this.assert( '[object Arguments]' === type , 'expected #{this} to be arguments but got ' + type , 'expected #{this} to not be arguments' ); } Assertion.addProperty('arguments', checkArguments); Assertion.addProperty('Arguments', checkArguments); /** * ### .equal(value) * * Asserts that the target is strictly equal (`===`) to `value`. * Alternately, if the `deep` flag is set, asserts that * the target is deeply equal to `value`. * * expect('hello').to.equal('hello'); * expect(42).to.equal(42); * expect(1).to.not.equal(true); * expect({ foo: 'bar' }).to.not.equal({ foo: 'bar' }); * expect({ foo: 'bar' }).to.deep.equal({ foo: 'bar' }); * * @name equal * @alias equals * @alias eq * @alias deep.equal * @param {Mixed} value * @param {String} message _optional_ * @api public */ function assertEqual (val, msg) { if (msg) flag(this, 'message', msg); var obj = flag(this, 'object'); if (flag(this, 'deep')) { return this.eql(val); } else { this.assert( val === obj , 'expected #{this} to equal #{exp}' , 'expected #{this} to not equal #{exp}' , val , this._obj , true ); } } Assertion.addMethod('equal', assertEqual); Assertion.addMethod('equals', assertEqual); Assertion.addMethod('eq', assertEqual); /** * ### .eql(value) * * Asserts that the target is deeply equal to `value`. * * expect({ foo: 'bar' }).to.eql({ foo: 'bar' }); * expect([ 1, 2, 3 ]).to.eql([ 1, 2, 3 ]); * * @name eql * @alias eqls * @param {Mixed} value * @param {String} message _optional_ * @api public */ function assertEql(obj, msg) { if (msg) flag(this, 'message', msg); this.assert( _.eql(obj, flag(this, 'object')) , 'expected #{this} to deeply equal #{exp}' , 'expected #{this} to not deeply equal #{exp}' , obj , this._obj , true ); } Assertion.addMethod('eql', assertEql); Assertion.addMethod('eqls', assertEql); /** * ### .above(value) * * Asserts that the target is greater than `value`. * * expect(10).to.be.above(5); * * Can also be used in conjunction with `length` to * assert a minimum length. The benefit being a * more informative error message than if the length * was supplied directly. * * expect('foo').to.have.length.above(2); * expect([ 1, 2, 3 ]).to.have.length.above(2); * * @name above * @alias gt * @alias greaterThan * @param {Number} value * @param {String} message _optional_ * @api public */ function assertAbove (n, msg) { if (msg) flag(this, 'message', msg); var obj = flag(this, 'object'); if (flag(this, 'doLength')) { new Assertion(obj, msg).to.have.property('length'); var len = obj.length; this.assert( len > n , 'expected #{this} to have a length above #{exp} but got #{act}' , 'expected #{this} to not have a length above #{exp}' , n , len ); } else { this.assert( obj > n , 'expected #{this} to be above ' + n , 'expected #{this} to be at most ' + n ); } } Assertion.addMethod('above', assertAbove); Assertion.addMethod('gt', assertAbove); Assertion.addMethod('greaterThan', assertAbove); /** * ### .least(value) * * Asserts that the target is greater than or equal to `value`. * * expect(10).to.be.at.least(10); * * Can also be used in conjunction with `length` to * assert a minimum length. The benefit being a * more informative error message than if the length * was supplied directly. * * expect('foo').to.have.length.of.at.least(2); * expect([ 1, 2, 3 ]).to.have.length.of.at.least(3); * * @name least * @alias gte * @param {Number} value * @param {String} message _optional_ * @api public */ function assertLeast (n, msg) { if (msg) flag(this, 'message', msg); var obj = flag(this, 'object'); if (flag(this, 'doLength')) { new Assertion(obj, msg).to.have.property('length'); var len = obj.length; this.assert( len >= n , 'expected #{this} to have a length at least #{exp} but got #{act}' , 'expected #{this} to have a length below #{exp}' , n , len ); } else { this.assert( obj >= n , 'expected #{this} to be at least ' + n , 'expected #{this} to be below ' + n ); } } Assertion.addMethod('least', assertLeast); Assertion.addMethod('gte', assertLeast); /** * ### .below(value) * * Asserts that the target is less than `value`. * * expect(5).to.be.below(10); * * Can also be used in conjunction with `length` to * assert a maximum length. The benefit being a * more informative error message than if the length * was supplied directly. * * expect('foo').to.have.length.below(4); * expect([ 1, 2, 3 ]).to.have.length.below(4); * * @name below * @alias lt * @alias lessThan * @param {Number} value * @param {String} message _optional_ * @api public */ function assertBelow (n, msg) { if (msg) flag(this, 'message', msg); var obj = flag(this, 'object'); if (flag(this, 'doLength')) { new Assertion(obj, msg).to.have.property('length'); var len = obj.length; this.assert( len < n , 'expected #{this} to have a length below #{exp} but got #{act}' , 'expected #{this} to not have a length below #{exp}' , n , len ); } else { this.assert( obj < n , 'expected #{this} to be below ' + n , 'expected #{this} to be at least ' + n ); } } Assertion.addMethod('below', assertBelow); Assertion.addMethod('lt', assertBelow); Assertion.addMethod('lessThan', assertBelow); /** * ### .most(value) * * Asserts that the target is less than or equal to `value`. * * expect(5).to.be.at.most(5); * * Can also be used in conjunction with `length` to * assert a maximum length. The benefit being a * more informative error message than if the length * was supplied directly. * * expect('foo').to.have.length.of.at.most(4); * expect([ 1, 2, 3 ]).to.have.length.of.at.most(3); * * @name most * @alias lte * @param {Number} value * @param {String} message _optional_ * @api public */ function assertMost (n, msg) { if (msg) flag(this, 'message', msg); var obj = flag(this, 'object'); if (flag(this, 'doLength')) { new Assertion(obj, msg).to.have.property('length'); var len = obj.length; this.assert( len <= n , 'expected #{this} to have a length at most #{exp} but got #{act}' , 'expected #{this} to have a length above #{exp}' , n , len ); } else { this.assert( obj <= n , 'expected #{this} to be at most ' + n , 'expected #{this} to be above ' + n ); } } Assertion.addMethod('most', assertMost); Assertion.addMethod('lte', assertMost); /** * ### .within(start, finish) * * Asserts that the target is within a range. * * expect(7).to.be.within(5,10); * * Can also be used in conjunction with `length` to * assert a length range. The benefit being a * more informative error message than if the length * was supplied directly. * * expect('foo').to.have.length.within(2,4); * expect([ 1, 2, 3 ]).to.have.length.within(2,4); * * @name within * @param {Number} start lowerbound inclusive * @param {Number} finish upperbound inclusive * @param {String} message _optional_ * @api public */ Assertion.addMethod('within', function (start, finish, msg) { if (msg) flag(this, 'message', msg); var obj = flag(this, 'object') , range = start + '..' + finish; if (flag(this, 'doLength')) { new Assertion(obj, msg).to.have.property('length'); var len = obj.length; this.assert( len >= start && len <= finish , 'expected #{this} to have a length within ' + range , 'expected #{this} to not have a length within ' + range ); } else { this.assert( obj >= start && obj <= finish , 'expected #{this} to be within ' + range , 'expected #{this} to not be within ' + range ); } }); /** * ### .instanceof(constructor) * * Asserts that the target is an instance of `constructor`. * * var Tea = function (name) { this.name = name; } * , Chai = new Tea('chai'); * * expect(Chai).to.be.an.instanceof(Tea); * expect([ 1, 2, 3 ]).to.be.instanceof(Array); * * @name instanceof * @param {Constructor} constructor * @param {String} message _optional_ * @alias instanceOf * @api public */ function assertInstanceOf (constructor, msg) { if (msg) flag(this, 'message', msg); var name = _.getName(constructor); this.assert( flag(this, 'object') instanceof constructor , 'expected #{this} to be an instance of ' + name , 'expected #{this} to not be an instance of ' + name ); }; Assertion.addMethod('instanceof', assertInstanceOf); Assertion.addMethod('instanceOf', assertInstanceOf); /** * ### .property(name, [value]) * * Asserts that the target has a property `name`, optionally asserting that * the value of that property is strictly equal to `value`. * If the `deep` flag is set, you can use dot- and bracket-notation for deep * references into objects and arrays. * * // simple referencing * var obj = { foo: 'bar' }; * expect(obj).to.have.property('foo'); * expect(obj).to.have.property('foo', 'bar'); * * // deep referencing * var deepObj = { * green: { tea: 'matcha' } * , teas: [ 'chai', 'matcha', { tea: 'konacha' } ] * }; * expect(deepObj).to.have.deep.property('green.tea', 'matcha'); * expect(deepObj).to.have.deep.property('teas[1]', 'matcha'); * expect(deepObj).to.have.deep.property('teas[2].tea', 'konacha'); * * You can also use an array as the starting point of a `deep.property` * assertion, or traverse nested arrays. * * var arr = [ * [ 'chai', 'matcha', 'konacha' ] * , [ { tea: 'chai' } * , { tea: 'matcha' } * , { tea: 'konacha' } ] * ]; * * expect(arr).to.have.deep.property('[0][1]', 'matcha'); * expect(arr).to.have.deep.property('[1][2].tea', 'konacha'); * * Furthermore, `property` changes the subject of the assertion * to be the value of that property from the original object. This * permits for further chainable assertions on that property. * * expect(obj).to.have.property('foo') * .that.is.a('string'); * expect(deepObj).to.have.property('green') * .that.is.an('object') * .that.deep.equals({ tea: 'matcha' }); * expect(deepObj).to.have.property('teas') * .that.is.an('array') * .with.deep.property('[2]') * .that.deep.equals({ tea: 'konacha' }); * * @name property * @alias deep.property * @param {String} name * @param {Mixed} value (optional) * @param {String} message _optional_ * @returns value of property for chaining * @api public */ Assertion.addMethod('property', function (name, val, msg) { if (msg) flag(this, 'message', msg); var descriptor = flag(this, 'deep') ? 'deep property ' : 'property ' , negate = flag(this, 'negate') , obj = flag(this, 'object') , value = flag(this, 'deep') ? _.getPathValue(name, obj) : obj[name]; if (negate && undefined !== val) { if (undefined === value) { msg = (msg != null) ? msg + ': ' : ''; throw new Error(msg + _.inspect(obj) + ' has no ' + descriptor + _.inspect(name)); } } else { this.assert( undefined !== value , 'expected #{this} to have a ' + descriptor + _.inspect(name) , 'expected #{this} to not have ' + descriptor + _.inspect(name)); } if (undefined !== val) { this.assert( val === value , 'expected #{this} to have a ' + descriptor + _.inspect(name) + ' of #{exp}, but got #{act}' , 'expected #{this} to not have a ' + descriptor + _.inspect(name) + ' of #{act}' , val , value ); } flag(this, 'object', value); }); /** * ### .ownProperty(name) * * Asserts that the target has an own property `name`. * * expect('test').to.have.ownProperty('length'); * * @name ownProperty * @alias haveOwnProperty * @param {String} name * @param {String} message _optional_ * @api public */ function assertOwnProperty (name, msg) { if (msg) flag(this, 'message', msg); var obj = flag(this, 'object'); this.assert( obj.hasOwnProperty(name) , 'expected #{this} to have own property ' + _.inspect(name) , 'expected #{this} to not have own property ' + _.inspect(name) ); } Assertion.addMethod('ownProperty', assertOwnProperty); Assertion.addMethod('haveOwnProperty', assertOwnProperty); /** * ### .length(value) * * Asserts that the target's `length` property has * the expected value. * * expect([ 1, 2, 3]).to.have.length(3); * expect('foobar').to.have.length(6); * * Can also be used as a chain precursor to a value * comparison for the length property. * * expect('foo').to.have.length.above(2); * expect([ 1, 2, 3 ]).to.have.length.above(2); * expect('foo').to.have.length.below(4); * expect([ 1, 2, 3 ]).to.have.length.below(4); * expect('foo').to.have.length.within(2,4); * expect([ 1, 2, 3 ]).to.have.length.within(2,4); * * @name length * @alias lengthOf * @param {Number} length * @param {String} message _optional_ * @api public */ function assertLengthChain () { flag(this, 'doLength', true); } function assertLength (n, msg) { if (msg) flag(this, 'message', msg); var obj = flag(this, 'object'); new Assertion(obj, msg).to.have.property('length'); var len = obj.length; this.assert( len == n , 'expected #{this} to have a length of #{exp} but got #{act}' , 'expected #{this} to not have a length of #{act}' , n , len ); } Assertion.addChainableMethod('length', assertLength, assertLengthChain); Assertion.addMethod('lengthOf', assertLength, assertLengthChain); /** * ### .match(regexp) * * Asserts that the target matches a regular expression. * * expect('foobar').to.match(/^foo/); * * @name match * @param {RegExp} RegularExpression * @param {String} message _optional_ * @api public */ Assertion.addMethod('match', function (re, msg) { if (msg) flag(this, 'message', msg); var obj = flag(this, 'object'); this.assert( re.exec(obj) , 'expected #{this} to match ' + re , 'expected #{this} not to match ' + re ); }); /** * ### .string(string) * * Asserts that the string target contains another string. * * expect('foobar').to.have.string('bar'); * * @name string * @param {String} string * @param {String} message _optional_ * @api public */ Assertion.addMethod('string', function (str, msg) { if (msg) flag(this, 'message', msg); var obj = flag(this, 'object'); new Assertion(obj, msg).is.a('string'); this.assert( ~obj.indexOf(str) , 'expected #{this} to contain ' + _.inspect(str) , 'expected #{this} to not contain ' + _.inspect(str) ); }); /** * ### .keys(key1, [key2], [...]) * * Asserts that the target has exactly the given keys, or * asserts the inclusion of some keys when using the * `include` or `contain` modifiers. * * expect({ foo: 1, bar: 2 }).to.have.keys(['foo', 'bar']); * expect({ foo: 1, bar: 2, baz: 3 }).to.contain.keys('foo', 'bar'); * * @name keys * @alias key * @param {String...|Array} keys * @api public */ function assertKeys (keys) { var obj = flag(this, 'object') , str , ok = true; keys = keys instanceof Array ? keys : Array.prototype.slice.call(arguments); if (!keys.length) throw new Error('keys required'); var actual = Object.keys(obj) , len = keys.length; // Inclusion ok = keys.every(function(key){ return ~actual.indexOf(key); }); // Strict if (!flag(this, 'negate') && !flag(this, 'contains')) { ok = ok && keys.length == actual.length; } // Key string if (len > 1) { keys = keys.map(function(key){ return _.inspect(key); }); var last = keys.pop(); str = keys.join(', ') + ', and ' + last; } else { str = _.inspect(keys[0]); } // Form str = (len > 1 ? 'keys ' : 'key ') + str; // Have / include str = (flag(this, 'contains') ? 'contain ' : 'have ') + str; // Assertion this.assert( ok , 'expected #{this} to ' + str , 'expected #{this} to not ' + str ); } Assertion.addMethod('keys', assertKeys); Assertion.addMethod('key', assertKeys); /** * ### .throw(constructor) * * Asserts that the function target will throw a specific error, or specific type of error * (as determined using `instanceof`), optionally with a RegExp or string inclusion test * for the error's message. * * var err = new ReferenceError('This is a bad function.'); * var fn = function () { throw err; } * expect(fn).to.throw(ReferenceError); * expect(fn).to.throw(Error); * expect(fn).to.throw(/bad function/); * expect(fn).to.not.throw('good function'); * expect(fn).to.throw(ReferenceError, /bad function/); * expect(fn).to.throw(err); * expect(fn).to.not.throw(new RangeError('Out of range.')); * * Please note that when a throw expectation is negated, it will check each * parameter independently, starting with error constructor type. The appropriate way * to check for the existence of a type of error but for a message that does not match * is to use `and`. * * expect(fn).to.throw(ReferenceError) * .and.not.throw(/good function/); * * @name throw * @alias throws * @alias Throw * @param {ErrorConstructor} constructor * @param {String|RegExp} expected error message * @param {String} message _optional_ * @see https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Error#Error_types * @api public */ function assertThrows (constructor, errMsg, msg) { if (msg) flag(this, 'message', msg); var obj = flag(this, 'object'); new Assertion(obj, msg).is.a('function'); var thrown = false , desiredError = null , name = null , thrownError = null; if (arguments.length === 0) { errMsg = null; constructor = null; } else if (constructor && (constructor instanceof RegExp || 'string' === typeof constructor)) { errMsg = constructor; constructor = null; } else if (constructor && constructor instanceof Error) { desiredError = constructor; constructor = null; errMsg = null; } else if (typeof constructor === 'function') { name = (new constructor()).name; } else { constructor = null; } try { obj(); } catch (err) { // first, check desired error if (desiredError) { this.assert( err === desiredError , 'expected #{this} to throw #{exp} but #{act} was thrown' , 'expected #{this} to not throw #{exp}' , desiredError , err ); return this; } // next, check constructor if (constructor) { this.assert( err instanceof constructor , 'expected #{this} to throw #{exp} but #{act} was thrown' , 'expected #{this} to not throw #{exp} but #{act} was thrown' , name , err ); if (!errMsg) return this; } // next, check message var message = 'object' === _.type(err) && "message" in err ? err.message : '' + err; if ((message != null) && errMsg && errMsg instanceof RegExp) { this.assert( errMsg.exec(message) , 'expected #{this} to throw error matching #{exp} but got #{act}' , 'expected #{this} to throw error not matching #{exp}' , errMsg , message ); return this; } else if ((message != null) && errMsg && 'string' === typeof errMsg) { this.assert( ~message.indexOf(errMsg) , 'expected #{this} to throw error including #{exp} but got #{act}' , 'expected #{this} to throw error not including #{act}' , errMsg , message ); return this; } else { thrown = true; thrownError = err; } } var actuallyGot = '' , expectedThrown = name !== null ? name : desiredError ? '#{exp}' //_.inspect(desiredError) : 'an error'; if (thrown) { actuallyGot = ' but #{act} was thrown' } this.assert( thrown === true , 'expected #{this} to throw ' + expectedThrown + actuallyGot , 'expected #{this} to not throw ' + expectedThrown + actuallyGot , desiredError , thrownError ); }; Assertion.addMethod('throw', assertThrows); Assertion.addMethod('throws', assertThrows); Assertion.addMethod('Throw', assertThrows); /** * ### .respondTo(method) * * Asserts that the object or class target will respond to a method. * * Klass.prototype.bar = function(){}; * expect(Klass).to.respondTo('bar'); * expect(obj).to.respondTo('bar'); * * To check if a constructor will respond to a static function, * set the `itself` flag. * * Klass.baz = function(){}; * expect(Klass).itself.to.respondTo('baz'); * * @name respondTo * @param {String} method * @param {String} message _optional_ * @api public */ Assertion.addMethod('respondTo', function (method, msg) { if (msg) flag(this, 'message', msg); var obj = flag(this, 'object') , itself = flag(this, 'itself') , context = ('function' === _.type(obj) && !itself) ? obj.prototype[method] : obj[method]; this.assert( 'function' === typeof context , 'expected #{this} to respond to ' + _.inspect(method) , 'expected #{this} to not respond to ' + _.inspect(method) ); }); /** * ### .itself * * Sets the `itself` flag, later used by the `respondTo` assertion. * * function Foo() {} * Foo.bar = function() {} * Foo.prototype.baz = function() {} * * expect(Foo).itself.to.respondTo('bar'); * expect(Foo).itself.not.to.respondTo('baz'); * * @name itself * @api public */ Assertion.addProperty('itself', function () { flag(this, 'itself', true); }); /** * ### .satisfy(method) * * Asserts that the target passes a given truth test. * * expect(1).to.satisfy(function(num) { return num > 0; }); * * @name satisfy * @param {Function} matcher * @param {String} message _optional_ * @api public */ Assertion.addMethod('satisfy', function (matcher, msg) { if (msg) flag(this, 'message', msg); var obj = flag(this, 'object'); this.assert( matcher(obj) , 'expected #{this} to satisfy ' + _.objDisplay(matcher) , 'expected #{this} to not satisfy' + _.objDisplay(matcher) , this.negate ? false : true , matcher(obj) ); }); /** * ### .closeTo(expected, delta) * * Asserts that the target is equal `expected`, to within a +/- `delta` range. * * expect(1.5).to.be.closeTo(1, 0.5); * * @name closeTo * @param {Number} expected * @param {Number} delta * @param {String} message _optional_ * @api public */ Assertion.addMethod('closeTo', function (expected, delta, msg) { if (msg) flag(this, 'message', msg); var obj = flag(this, 'object'); this.assert( Math.abs(obj - expected) <= delta , 'expected #{this} to be close to ' + expected + ' +/- ' + delta , 'expected #{this} not to be close to ' + expected + ' +/- ' + delta ); }); function isSubsetOf(subset, superset) { return subset.every(function(elem) { return superset.indexOf(elem) !== -1; }) } /** * ### .members(set) * * Asserts that the target is a superset of `set`, * or that the target and `set` have the same members. * * expect([1, 2, 3]).to.include.members([3, 2]); * expect([1, 2, 3]).to.not.include.members([3, 2, 8]); * * expect([4, 2]).to.have.members([2, 4]); * expect([5, 2]).to.not.have.members([5, 2, 1]); * * @name members * @param {Array} set * @param {String} message _optional_ * @api public */ Assertion.addMethod('members', function (subset, msg) { if (msg) flag(this, 'message', msg); var obj = flag(this, 'object'); new Assertion(obj).to.be.an('array'); new Assertion(subset).to.be.an('array'); if (flag(this, 'contains')) { return this.assert( isSubsetOf(subset, obj) , 'expected #{this} to be a superset of #{act}' , 'expected #{this} to not be a superset of #{act}' , obj , subset ); } this.assert( isSubsetOf(obj, subset) && isSubsetOf(subset, obj) , 'expected #{this} to have the same members as #{act}' , 'expected #{this} to not have the same members as #{act}' , obj , subset ); }); }; }); require.register("chai/lib/chai/interface/assert.js", function(exports, require, module){ /*! * chai * Copyright(c) 2011-2013 Jake Luer * MIT Licensed */ module.exports = function (chai, util) { /*! * Chai dependencies. */ var Assertion = chai.Assertion , flag = util.flag; /*! * Module export. */ /** * ### assert(expression, message) * * Write your own test expressions. * * assert('foo' !== 'bar', 'foo is not bar'); * assert(Array.isArray([]), 'empty arrays are arrays'); * * @param {Mixed} expression to test for truthiness * @param {String} message to display on error * @name assert * @api public */ var assert = chai.assert = function (express, errmsg) { var test = new Assertion(null); test.assert( express , errmsg , '[ negation message unavailable ]' ); }; /** * ### .fail(actual, expected, [message], [operator]) * * Throw a failure. Node.js `assert` module-compatible. * * @name fail * @param {Mixed} actual * @param {Mixed} expected * @param {String} message * @param {String} operator * @api public */ assert.fail = function (actual, expected, message, operator) { throw new chai.AssertionError({ actual: actual , expected: expected , message: message , operator: operator , stackStartFunction: assert.fail }); }; /** * ### .ok(object, [message]) * * Asserts that `object` is truthy. * * assert.ok('everything', 'everything is ok'); * assert.ok(false, 'this will fail'); * * @name ok * @param {Mixed} object to test * @param {String} message * @api public */ assert.ok = function (val, msg) { new Assertion(val, msg).is.ok; }; /** * ### .notOk(object, [message]) * * Asserts that `object` is falsy. * * assert.notOk('everything', 'this will fail'); * assert.notOk(false, 'this will pass'); * * @name notOk * @param {Mixed} object to test * @param {String} message * @api public */ assert.notOk = function (val, msg) { new Assertion(val, msg).is.not.ok; }; /** * ### .equal(actual, expected, [message]) * * Asserts non-strict equality (`==`) of `actual` and `expected`. * * assert.equal(3, '3', '== coerces values to strings'); * * @name equal * @param {Mixed} actual * @param {Mixed} expected * @param {String} message * @api public */ assert.equal = function (act, exp, msg) { var test = new Assertion(act, msg); test.assert( exp == flag(test, 'object') , 'expected #{this} to equal #{exp}' , 'expected #{this} to not equal #{act}' , exp , act ); }; /** * ### .notEqual(actual, expected, [message]) * * Asserts non-strict inequality (`!=`) of `actual` and `expected`. * * assert.notEqual(3, 4, 'these numbers are not equal'); * * @name notEqual * @param {Mixed} actual * @param {Mixed} expected * @param {String} message * @api public */ assert.notEqual = function (act, exp, msg) { var test = new Assertion(act, msg); test.assert( exp != flag(test, 'object') , 'expected #{this} to not equal #{exp}' , 'expected #{this} to equal #{act}' , exp , act ); }; /** * ### .strictEqual(actual, expected, [message]) * * Asserts strict equality (`===`) of `actual` and `expected`. * * assert.strictEqual(true, true, 'these booleans are strictly equal'); * * @name strictEqual * @param {Mixed} actual * @param {Mixed} expected * @param {String} message * @api public */ assert.strictEqual = function (act, exp, msg) { new Assertion(act, msg).to.equal(exp); }; /** * ### .notStrictEqual(actual, expected, [message]) * * Asserts strict inequality (`!==`) of `actual` and `expected`. * * assert.notStrictEqual(3, '3', 'no coercion for strict equality'); * * @name notStrictEqual * @param {Mixed} actual * @param {Mixed} expected * @param {String} message * @api public */ assert.notStrictEqual = function (act, exp, msg) { new Assertion(act, msg).to.not.equal(exp); }; /** * ### .deepEqual(actual, expected, [message]) * * Asserts that `actual` is deeply equal to `expected`. * * assert.deepEqual({ tea: 'green' }, { tea: 'green' }); * * @name deepEqual * @param {Mixed} actual * @param {Mixed} expected * @param {String} message * @api public */ assert.deepEqual = function (act, exp, msg) { new Assertion(act, msg).to.eql(exp); }; /** * ### .notDeepEqual(actual, expected, [message]) * * Assert that `actual` is not deeply equal to `expected`. * * assert.notDeepEqual({ tea: 'green' }, { tea: 'jasmine' }); * * @name notDeepEqual * @param {Mixed} actual * @param {Mixed} expected * @param {String} message * @api public */ assert.notDeepEqual = function (act, exp, msg) { new Assertion(act, msg).to.not.eql(exp); }; /** * ### .isTrue(value, [message]) * * Asserts that `value` is true. * * var teaServed = true; * assert.isTrue(teaServed, 'the tea has been served'); * * @name isTrue * @param {Mixed} value * @param {String} message * @api public */ assert.isTrue = function (val, msg) { new Assertion(val, msg).is['true']; }; /** * ### .isFalse(value, [message]) * * Asserts that `value` is false. * * var teaServed = false; * assert.isFalse(teaServed, 'no tea yet? hmm...'); * * @name isFalse * @param {Mixed} value * @param {String} message * @api public */ assert.isFalse = function (val, msg) { new Assertion(val, msg).is['false']; }; /** * ### .isNull(value, [message]) * * Asserts that `value` is null. * * assert.isNull(err, 'there was no error'); * * @name isNull * @param {Mixed} value * @param {String} message * @api public */ assert.isNull = function (val, msg) { new Assertion(val, msg).to.equal(null); }; /** * ### .isNotNull(value, [message]) * * Asserts that `value` is not null. * * var tea = 'tasty chai'; * assert.isNotNull(tea, 'great, time for tea!'); * * @name isNotNull * @param {Mixed} value * @param {String} message * @api public */ assert.isNotNull = function (val, msg) { new Assertion(val, msg).to.not.equal(null); }; /** * ### .isUndefined(value, [message]) * * Asserts that `value` is `undefined`. * * var tea; * assert.isUndefined(tea, 'no tea defined'); * * @name isUndefined * @param {Mixed} value * @param {String} message * @api public */ assert.isUndefined = function (val, msg) { new Assertion(val, msg).to.equal(undefined); }; /** * ### .isDefined(value, [message]) * * Asserts that `value` is not `undefined`. * * var tea = 'cup of chai'; * assert.isDefined(tea, 'tea has been defined'); * * @name isDefined * @param {Mixed} value * @param {String} message * @api public */ assert.isDefined = function (val, msg) { new Assertion(val, msg).to.not.equal(undefined); }; /** * ### .isFunction(value, [message]) * * Asserts that `value` is a function. * * function serveTea() { return 'cup of tea'; }; * assert.isFunction(serveTea, 'great, we can have tea now'); * * @name isFunction * @param {Mixed} value * @param {String} message * @api public */ assert.isFunction = function (val, msg) { new Assertion(val, msg).to.be.a('function'); }; /** * ### .isNotFunction(value, [message]) * * Asserts that `value` is _not_ a function. * * var serveTea = [ 'heat', 'pour', 'sip' ]; * assert.isNotFunction(serveTea, 'great, we have listed the steps'); * * @name isNotFunction * @param {Mixed} value * @param {String} message * @api public */ assert.isNotFunction = function (val, msg) { new Assertion(val, msg).to.not.be.a('function'); }; /** * ### .isObject(value, [message]) * * Asserts that `value` is an object (as revealed by * `Object.prototype.toString`). * * var selection = { name: 'Chai', serve: 'with spices' }; * assert.isObject(selection, 'tea selection is an object'); * * @name isObject * @param {Mixed} value * @param {String} message * @api public */ assert.isObject = function (val, msg) { new Assertion(val, msg).to.be.a('object'); }; /** * ### .isNotObject(value, [message]) * * Asserts that `value` is _not_ an object. * * var selection = 'chai' * assert.isObject(selection, 'tea selection is not an object'); * assert.isObject(null, 'null is not an object'); * * @name isNotObject * @param {Mixed} value * @param {String} message * @api public */ assert.isNotObject = function (val, msg) { new Assertion(val, msg).to.not.be.a('object'); }; /** * ### .isArray(value, [message]) * * Asserts that `value` is an array. * * var menu = [ 'green', 'chai', 'oolong' ]; * assert.isArray(menu, 'what kind of tea do we want?'); * * @name isArray * @param {Mixed} value * @param {String} message * @api public */ assert.isArray = function (val, msg) { new Assertion(val, msg).to.be.an('array'); }; /** * ### .isNotArray(value, [message]) * * Asserts that `value` is _not_ an array. * * var menu = 'green|chai|oolong'; * assert.isNotArray(menu, 'what kind of tea do we want?'); * * @name isNotArray * @param {Mixed} value * @param {String} message * @api public */ assert.isNotArray = function (val, msg) { new Assertion(val, msg).to.not.be.an('array'); }; /** * ### .isString(value, [message]) * * Asserts that `value` is a string. * * var teaOrder = 'chai'; * assert.isString(teaOrder, 'order placed'); * * @name isString * @param {Mixed} value * @param {String} message * @api public */ assert.isString = function (val, msg) { new Assertion(val, msg).to.be.a('string'); }; /** * ### .isNotString(value, [message]) * * Asserts that `value` is _not_ a string. * * var teaOrder = 4; * assert.isNotString(teaOrder, 'order placed'); * * @name isNotString * @param {Mixed} value * @param {String} message * @api public */ assert.isNotString = function (val, msg) { new Assertion(val, msg).to.not.be.a('string'); }; /** * ### .isNumber(value, [message]) * * Asserts that `value` is a number. * * var cups = 2; * assert.isNumber(cups, 'how many cups'); * * @name isNumber * @param {Number} value * @param {String} message * @api public */ assert.isNumber = function (val, msg) { new Assertion(val, msg).to.be.a('number'); }; /** * ### .isNotNumber(value, [message]) * * Asserts that `value` is _not_ a number. * * var cups = '2 cups please'; * assert.isNotNumber(cups, 'how many cups'); * * @name isNotNumber * @param {Mixed} value * @param {String} message * @api public */ assert.isNotNumber = function (val, msg) { new Assertion(val, msg).to.not.be.a('number'); }; /** * ### .isBoolean(value, [message]) * * Asserts that `value` is a boolean. * * var teaReady = true * , teaServed = false; * * assert.isBoolean(teaReady, 'is the tea ready'); * assert.isBoolean(teaServed, 'has tea been served'); * * @name isBoolean * @param {Mixed} value * @param {String} message * @api public */ assert.isBoolean = function (val, msg) { new Assertion(val, msg).to.be.a('boolean'); }; /** * ### .isNotBoolean(value, [message]) * * Asserts that `value` is _not_ a boolean. * * var teaReady = 'yep' * , teaServed = 'nope'; * * assert.isNotBoolean(teaReady, 'is the tea ready'); * assert.isNotBoolean(teaServed, 'has tea been served'); * * @name isNotBoolean * @param {Mixed} value * @param {String} message * @api public */ assert.isNotBoolean = function (val, msg) { new Assertion(val, msg).to.not.be.a('boolean'); }; /** * ### .typeOf(value, name, [message]) * * Asserts that `value`'s type is `name`, as determined by * `Object.prototype.toString`. * * assert.typeOf({ tea: 'chai' }, 'object', 'we have an object'); * assert.typeOf(['chai', 'jasmine'], 'array', 'we have an array'); * assert.typeOf('tea', 'string', 'we have a string'); * assert.typeOf(/tea/, 'regexp', 'we have a regular expression'); * assert.typeOf(null, 'null', 'we have a null'); * assert.typeOf(undefined, 'undefined', 'we have an undefined'); * * @name typeOf * @param {Mixed} value * @param {String} name * @param {String} message * @api public */ assert.typeOf = function (val, type, msg) { new Assertion(val, msg).to.be.a(type); }; /** * ### .notTypeOf(value, name, [message]) * * Asserts that `value`'s type is _not_ `name`, as determined by * `Object.prototype.toString`. * * assert.notTypeOf('tea', 'number', 'strings are not numbers'); * * @name notTypeOf * @param {Mixed} value * @param {String} typeof name * @param {String} message * @api public */ assert.notTypeOf = function (val, type, msg) { new Assertion(val, msg).to.not.be.a(type); }; /** * ### .instanceOf(object, constructor, [message]) * * Asserts that `value` is an instance of `constructor`. * * var Tea = function (name) { this.name = name; } * , chai = new Tea('chai'); * * assert.instanceOf(chai, Tea, 'chai is an instance of tea'); * * @name instanceOf * @param {Object} object * @param {Constructor} constructor * @param {String} message * @api public */ assert.instanceOf = function (val, type, msg) { new Assertion(val, msg).to.be.instanceOf(type); }; /** * ### .notInstanceOf(object, constructor, [message]) * * Asserts `value` is not an instance of `constructor`. * * var Tea = function (name) { this.name = name; } * , chai = new String('chai'); * * assert.notInstanceOf(chai, Tea, 'chai is not an instance of tea'); * * @name notInstanceOf * @param {Object} object * @param {Constructor} constructor * @param {String} message * @api public */ assert.notInstanceOf = function (val, type, msg) { new Assertion(val, msg).to.not.be.instanceOf(type); }; /** * ### .include(haystack, needle, [message]) * * Asserts that `haystack` includes `needle`. Works * for strings and arrays. * * assert.include('foobar', 'bar', 'foobar contains string "bar"'); * assert.include([ 1, 2, 3 ], 3, 'array contains value'); * * @name include * @param {Array|String} haystack * @param {Mixed} needle * @param {String} message * @api public */ assert.include = function (exp, inc, msg) { var obj = new Assertion(exp, msg); if (Array.isArray(exp)) { obj.to.include(inc); } else if ('string' === typeof exp) { obj.to.contain.string(inc); } else { throw new chai.AssertionError( 'expected an array or string' , null , assert.include ); } }; /** * ### .notInclude(haystack, needle, [message]) * * Asserts that `haystack` does not include `needle`. Works * for strings and arrays. *i * assert.notInclude('foobar', 'baz', 'string not include substring'); * assert.notInclude([ 1, 2, 3 ], 4, 'array not include contain value'); * * @name notInclude * @param {Array|String} haystack * @param {Mixed} needle * @param {String} message * @api public */ assert.notInclude = function (exp, inc, msg) { var obj = new Assertion(exp, msg); if (Array.isArray(exp)) { obj.to.not.include(inc); } else if ('string' === typeof exp) { obj.to.not.contain.string(inc); } else { throw new chai.AssertionError( 'expected an array or string' , null , assert.notInclude ); } }; /** * ### .match(value, regexp, [message]) * * Asserts that `value` matches the regular expression `regexp`. * * assert.match('foobar', /^foo/, 'regexp matches'); * * @name match * @param {Mixed} value * @param {RegExp} regexp * @param {String} message * @api public */ assert.match = function (exp, re, msg) { new Assertion(exp, msg).to.match(re); }; /** * ### .notMatch(value, regexp, [message]) * * Asserts that `value` does not match the regular expression `regexp`. * * assert.notMatch('foobar', /^foo/, 'regexp does not match'); * * @name notMatch * @param {Mixed} value * @param {RegExp} regexp * @param {String} message * @api public */ assert.notMatch = function (exp, re, msg) { new Assertion(exp, msg).to.not.match(re); }; /** * ### .property(object, property, [message]) * * Asserts that `object` has a property named by `property`. * * assert.property({ tea: { green: 'matcha' }}, 'tea'); * * @name property * @param {Object} object * @param {String} property * @param {String} message * @api public */ assert.property = function (obj, prop, msg) { new Assertion(obj, msg).to.have.property(prop); }; /** * ### .notProperty(object, property, [message]) * * Asserts that `object` does _not_ have a property named by `property`. * * assert.notProperty({ tea: { green: 'matcha' }}, 'coffee'); * * @name notProperty * @param {Object} object * @param {String} property * @param {String} message * @api public */ assert.notProperty = function (obj, prop, msg) { new Assertion(obj, msg).to.not.have.property(prop); }; /** * ### .deepProperty(object, property, [message]) * * Asserts that `object` has a property named by `property`, which can be a * string using dot- and bracket-notation for deep reference. * * assert.deepProperty({ tea: { green: 'matcha' }}, 'tea.green'); * * @name deepProperty * @param {Object} object * @param {String} property * @param {String} message * @api public */ assert.deepProperty = function (obj, prop, msg) { new Assertion(obj, msg).to.have.deep.property(prop); }; /** * ### .notDeepProperty(object, property, [message]) * * Asserts that `object` does _not_ have a property named by `property`, which * can be a string using dot- and bracket-notation for deep reference. * * assert.notDeepProperty({ tea: { green: 'matcha' }}, 'tea.oolong'); * * @name notDeepProperty * @param {Object} object * @param {String} property * @param {String} message * @api public */ assert.notDeepProperty = function (obj, prop, msg) { new Assertion(obj, msg).to.not.have.deep.property(prop); }; /** * ### .propertyVal(object, property, value, [message]) * * Asserts that `object` has a property named by `property` with value given * by `value`. * * assert.propertyVal({ tea: 'is good' }, 'tea', 'is good'); * * @name propertyVal * @param {Object} object * @param {String} property * @param {Mixed} value * @param {String} message * @api public */ assert.propertyVal = function (obj, prop, val, msg) { new Assertion(obj, msg).to.have.property(prop, val); }; /** * ### .propertyNotVal(object, property, value, [message]) * * Asserts that `object` has a property named by `property`, but with a value * different from that given by `value`. * * assert.propertyNotVal({ tea: 'is good' }, 'tea', 'is bad'); * * @name propertyNotVal * @param {Object} object * @param {String} property * @param {Mixed} value * @param {String} message * @api public */ assert.propertyNotVal = function (obj, prop, val, msg) { new Assertion(obj, msg).to.not.have.property(prop, val); }; /** * ### .deepPropertyVal(object, property, value, [message]) * * Asserts that `object` has a property named by `property` with value given * by `value`. `property` can use dot- and bracket-notation for deep * reference. * * assert.deepPropertyVal({ tea: { green: 'matcha' }}, 'tea.green', 'matcha'); * * @name deepPropertyVal * @param {Object} object * @param {String} property * @param {Mixed} value * @param {String} message * @api public */ assert.deepPropertyVal = function (obj, prop, val, msg) { new Assertion(obj, msg).to.have.deep.property(prop, val); }; /** * ### .deepPropertyNotVal(object, property, value, [message]) * * Asserts that `object` has a property named by `property`, but with a value * different from that given by `value`. `property` can use dot- and * bracket-notation for deep reference. * * assert.deepPropertyNotVal({ tea: { green: 'matcha' }}, 'tea.green', 'konacha'); * * @name deepPropertyNotVal * @param {Object} object * @param {String} property * @param {Mixed} value * @param {String} message * @api public */ assert.deepPropertyNotVal = function (obj, prop, val, msg) { new Assertion(obj, msg).to.not.have.deep.property(prop, val); }; /** * ### .lengthOf(object, length, [message]) * * Asserts that `object` has a `length` property with the expected value. * * assert.lengthOf([1,2,3], 3, 'array has length of 3'); * assert.lengthOf('foobar', 5, 'string has length of 6'); * * @name lengthOf * @param {Mixed} object * @param {Number} length * @param {String} message * @api public */ assert.lengthOf = function (exp, len, msg) { new Assertion(exp, msg).to.have.length(len); }; /** * ### .throws(function, [constructor/string/regexp], [string/regexp], [message]) * * Asserts that `function` will throw an error that is an instance of * `constructor`, or alternately that it will throw an error with message * matching `regexp`. * * assert.throw(fn, 'function throws a reference error'); * assert.throw(fn, /function throws a reference error/); * assert.throw(fn, ReferenceError); * assert.throw(fn, ReferenceError, 'function throws a reference error'); * assert.throw(fn, ReferenceError, /function throws a reference error/); * * @name throws * @alias throw * @alias Throw * @param {Function} function * @param {ErrorConstructor} constructor * @param {RegExp} regexp * @param {String} message * @see https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Error#Error_types * @api public */ assert.Throw = function (fn, errt, errs, msg) { if ('string' === typeof errt || errt instanceof RegExp) { errs = errt; errt = null; } new Assertion(fn, msg).to.Throw(errt, errs); }; /** * ### .doesNotThrow(function, [constructor/regexp], [message]) * * Asserts that `function` will _not_ throw an error that is an instance of * `constructor`, or alternately that it will not throw an error with message * matching `regexp`. * * assert.doesNotThrow(fn, Error, 'function does not throw'); * * @name doesNotThrow * @param {Function} function * @param {ErrorConstructor} constructor * @param {RegExp} regexp * @param {String} message * @see https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Error#Error_types * @api public */ assert.doesNotThrow = function (fn, type, msg) { if ('string' === typeof type) { msg = type; type = null; } new Assertion(fn, msg).to.not.Throw(type); }; /** * ### .operator(val1, operator, val2, [message]) * * Compares two values using `operator`. * * assert.operator(1, '<', 2, 'everything is ok'); * assert.operator(1, '>', 2, 'this will fail'); * * @name operator * @param {Mixed} val1 * @param {String} operator * @param {Mixed} val2 * @param {String} message * @api public */ assert.operator = function (val, operator, val2, msg) { if (!~['==', '===', '>', '>=', '<', '<=', '!=', '!=='].indexOf(operator)) { throw new Error('Invalid operator "' + operator + '"'); } var test = new Assertion(eval(val + operator + val2), msg); test.assert( true === flag(test, 'object') , 'expected ' + util.inspect(val) + ' to be ' + operator + ' ' + util.inspect(val2) , 'expected ' + util.inspect(val) + ' to not be ' + operator + ' ' + util.inspect(val2) ); }; /** * ### .closeTo(actual, expected, delta, [message]) * * Asserts that the target is equal `expected`, to within a +/- `delta` range. * * assert.closeTo(1.5, 1, 0.5, 'numbers are close'); * * @name closeTo * @param {Number} actual * @param {Number} expected * @param {Number} delta * @param {String} message * @api public */ assert.closeTo = function (act, exp, delta, msg) { new Assertion(act, msg).to.be.closeTo(exp, delta); }; /** * ### .sameMembers(set1, set2, [message]) * * Asserts that `set1` and `set2` have the same members. * Order is not taken into account. * * assert.sameMembers([ 1, 2, 3 ], [ 2, 1, 3 ], 'same members'); * * @name sameMembers * @param {Array} superset * @param {Array} subset * @param {String} message * @api public */ assert.sameMembers = function (set1, set2, msg) { new Assertion(set1, msg).to.have.same.members(set2); } /** * ### .includeMembers(superset, subset, [message]) * * Asserts that `subset` is included in `superset`. * Order is not taken into account. * * assert.includeMembers([ 1, 2, 3 ], [ 2, 1 ], 'include members'); * * @name includeMembers * @param {Array} superset * @param {Array} subset * @param {String} message * @api public */ assert.includeMembers = function (superset, subset, msg) { new Assertion(superset, msg).to.include.members(subset); } /*! * Undocumented / untested */ assert.ifError = function (val, msg) { new Assertion(val, msg).to.not.be.ok; }; /*! * Aliases. */ (function alias(name, as){ assert[as] = assert[name]; return alias; }) ('Throw', 'throw') ('Throw', 'throws'); }; }); require.register("chai/lib/chai/interface/expect.js", function(exports, require, module){ /*! * chai * Copyright(c) 2011-2013 Jake Luer * MIT Licensed */ module.exports = function (chai, util) { chai.expect = function (val, message) { return new chai.Assertion(val, message); }; }; }); require.register("chai/lib/chai/interface/should.js", function(exports, require, module){ /*! * chai * Copyright(c) 2011-2013 Jake Luer * MIT Licensed */ module.exports = function (chai, util) { var Assertion = chai.Assertion; function loadShould () { // modify Object.prototype to have `should` Object.defineProperty(Object.prototype, 'should', { set: function (value) { // See https://github.com/chaijs/chai/issues/86: this makes // `whatever.should = someValue` actually set `someValue`, which is // especially useful for `global.should = require('chai').should()`. // // Note that we have to use [[DefineProperty]] instead of [[Put]] // since otherwise we would trigger this very setter! Object.defineProperty(this, 'should', { value: value, enumerable: true, configurable: true, writable: true }); } , get: function(){ if (this instanceof String || this instanceof Number) { return new Assertion(this.constructor(this)); } else if (this instanceof Boolean) { return new Assertion(this == true); } return new Assertion(this); } , configurable: true }); var should = {}; should.equal = function (val1, val2, msg) { new Assertion(val1, msg).to.equal(val2); }; should.Throw = function (fn, errt, errs, msg) { new Assertion(fn, msg).to.Throw(errt, errs); }; should.exist = function (val, msg) { new Assertion(val, msg).to.exist; } // negation should.not = {} should.not.equal = function (val1, val2, msg) { new Assertion(val1, msg).to.not.equal(val2); }; should.not.Throw = function (fn, errt, errs, msg) { new Assertion(fn, msg).to.not.Throw(errt, errs); }; should.not.exist = function (val, msg) { new Assertion(val, msg).to.not.exist; } should['throw'] = should['Throw']; should.not['throw'] = should.not['Throw']; return should; }; chai.should = loadShould; chai.Should = loadShould; }; }); require.register("chai/lib/chai/utils/addChainableMethod.js", function(exports, require, module){ /*! * Chai - addChainingMethod utility * Copyright(c) 2012-2013 Jake Luer * MIT Licensed */ /*! * Module dependencies */ var transferFlags = require('./transferFlags'); /*! * Module variables */ // Check whether `__proto__` is supported var hasProtoSupport = '__proto__' in Object; // Without `__proto__` support, this module will need to add properties to a function. // However, some Function.prototype methods cannot be overwritten, // and there seems no easy cross-platform way to detect them (@see chaijs/chai/issues/69). var excludeNames = /^(?:length|name|arguments|caller)$/; // Cache `Function` properties var call = Function.prototype.call, apply = Function.prototype.apply; /** * ### addChainableMethod (ctx, name, method, chainingBehavior) * * Adds a method to an object, such that the method can also be chained. * * utils.addChainableMethod(chai.Assertion.prototype, 'foo', function (str) { * var obj = utils.flag(this, 'object'); * new chai.Assertion(obj).to.be.equal(str); * }); * * Can also be accessed directly from `chai.Assertion`. * * chai.Assertion.addChainableMethod('foo', fn, chainingBehavior); * * The result can then be used as both a method assertion, executing both `method` and * `chainingBehavior`, or as a language chain, which only executes `chainingBehavior`. * * expect(fooStr).to.be.foo('bar'); * expect(fooStr).to.be.foo.equal('foo'); * * @param {Object} ctx object to which the method is added * @param {String} name of method to add * @param {Function} method function to be used for `name`, when called * @param {Function} chainingBehavior function to be called every time the property is accessed * @name addChainableMethod * @api public */ module.exports = function (ctx, name, method, chainingBehavior) { if (typeof chainingBehavior !== 'function') chainingBehavior = function () { }; Object.defineProperty(ctx, name, { get: function () { chainingBehavior.call(this); var assert = function () { var result = method.apply(this, arguments); return result === undefined ? this : result; }; // Use `__proto__` if available if (hasProtoSupport) { // Inherit all properties from the object by replacing the `Function` prototype var prototype = assert.__proto__ = Object.create(this); // Restore the `call` and `apply` methods from `Function` prototype.call = call; prototype.apply = apply; } // Otherwise, redefine all properties (slow!) else { var asserterNames = Object.getOwnPropertyNames(ctx); asserterNames.forEach(function (asserterName) { if (!excludeNames.test(asserterName)) { var pd = Object.getOwnPropertyDescriptor(ctx, asserterName); Object.defineProperty(assert, asserterName, pd); } }); } transferFlags(this, assert); return assert; } , configurable: true }); }; }); require.register("chai/lib/chai/utils/addMethod.js", function(exports, require, module){ /*! * Chai - addMethod utility * Copyright(c) 2012-2013 Jake Luer * MIT Licensed */ /** * ### .addMethod (ctx, name, method) * * Adds a method to the prototype of an object. * * utils.addMethod(chai.Assertion.prototype, 'foo', function (str) { * var obj = utils.flag(this, 'object'); * new chai.Assertion(obj).to.be.equal(str); * }); * * Can also be accessed directly from `chai.Assertion`. * * chai.Assertion.addMethod('foo', fn); * * Then can be used as any other assertion. * * expect(fooStr).to.be.foo('bar'); * * @param {Object} ctx object to which the method is added * @param {String} name of method to add * @param {Function} method function to be used for name * @name addMethod * @api public */ module.exports = function (ctx, name, method) { ctx[name] = function () { var result = method.apply(this, arguments); return result === undefined ? this : result; }; }; }); require.register("chai/lib/chai/utils/addProperty.js", function(exports, require, module){ /*! * Chai - addProperty utility * Copyright(c) 2012-2013 Jake Luer * MIT Licensed */ /** * ### addProperty (ctx, name, getter) * * Adds a property to the prototype of an object. * * utils.addProperty(chai.Assertion.prototype, 'foo', function () { * var obj = utils.flag(this, 'object'); * new chai.Assertion(obj).to.be.instanceof(Foo); * }); * * Can also be accessed directly from `chai.Assertion`. * * chai.Assertion.addProperty('foo', fn); * * Then can be used as any other assertion. * * expect(myFoo).to.be.foo; * * @param {Object} ctx object to which the property is added * @param {String} name of property to add * @param {Function} getter function to be used for name * @name addProperty * @api public */ module.exports = function (ctx, name, getter) { Object.defineProperty(ctx, name, { get: function () { var result = getter.call(this); return result === undefined ? this : result; } , configurable: true }); }; }); require.register("chai/lib/chai/utils/eql.js", function(exports, require, module){ // This is (almost) directly from Node.js assert // https://github.com/joyent/node/blob/f8c335d0caf47f16d31413f89aa28eda3878e3aa/lib/assert.js module.exports = _deepEqual; var getEnumerableProperties = require('./getEnumerableProperties'); // for the browser var Buffer; try { Buffer = require('buffer').Buffer; } catch (ex) { Buffer = { isBuffer: function () { return false; } }; } function _deepEqual(actual, expected, memos) { // 7.1. All identical values are equivalent, as determined by ===. if (actual === expected) { return true; } else if (Buffer.isBuffer(actual) && Buffer.isBuffer(expected)) { if (actual.length != expected.length) return false; for (var i = 0; i < actual.length; i++) { if (actual[i] !== expected[i]) return false; } return true; // 7.2. If the expected value is a Date object, the actual value is // equivalent if it is also a Date object that refers to the same time. } else if (expected instanceof Date) { if (!(actual instanceof Date)) return false; return actual.getTime() === expected.getTime(); // 7.3. Other pairs that do not both pass typeof value == 'object', // equivalence is determined by ==. } else if (typeof actual != 'object' && typeof expected != 'object') { return actual === expected; } else if (expected instanceof RegExp) { if (!(actual instanceof RegExp)) return false; return actual.toString() === expected.toString(); // 7.4. For all other Object pairs, including Array objects, equivalence is // determined by having the same number of owned properties (as verified // with Object.prototype.hasOwnProperty.call), the same set of keys // (although not necessarily the same order), equivalent values for every // corresponding key, and an identical 'prototype' property. Note: this // accounts for both named and indexed properties on Arrays. } else { return objEquiv(actual, expected, memos); } } function isUndefinedOrNull(value) { return value === null || value === undefined; } function isArguments(object) { return Object.prototype.toString.call(object) == '[object Arguments]'; } function objEquiv(a, b, memos) { if (isUndefinedOrNull(a) || isUndefinedOrNull(b)) return false; // an identical 'prototype' property. if (a.prototype !== b.prototype) return false; // check if we have already compared a and b var i; if (memos) { for(i = 0; i < memos.length; i++) { if ((memos[i][0] === a && memos[i][1] === b) || (memos[i][0] === b && memos[i][1] === a)) return true; } } else { memos = []; } //~~~I've managed to break Object.keys through screwy arguments passing. // Converting to array solves the problem. if (isArguments(a)) { if (!isArguments(b)) { return false; } a = pSlice.call(a); b = pSlice.call(b); return _deepEqual(a, b, memos); } try { var ka = getEnumerableProperties(a), kb = getEnumerableProperties(b), key; } catch (e) {//happens when one is a string literal and the other isn't return false; } // having the same number of owned properties (keys incorporates // hasOwnProperty) if (ka.length != kb.length) return false; //the same set of keys (although not necessarily the same order), ka.sort(); kb.sort(); //~~~cheap key test for (i = ka.length - 1; i >= 0; i--) { if (ka[i] != kb[i]) return false; } // remember objects we have compared to guard against circular references memos.push([ a, b ]); //equivalent values for every corresponding key, and //~~~possibly expensive deep test for (i = ka.length - 1; i >= 0; i--) { key = ka[i]; if (!_deepEqual(a[key], b[key], memos)) return false; } return true; } }); require.register("chai/lib/chai/utils/flag.js", function(exports, require, module){ /*! * Chai - flag utility * Copyright(c) 2012-2013 Jake Luer * MIT Licensed */ /** * ### flag(object ,key, [value]) * * Get or set a flag value on an object. If a * value is provided it will be set, else it will * return the currently set value or `undefined` if * the value is not set. * * utils.flag(this, 'foo', 'bar'); // setter * utils.flag(this, 'foo'); // getter, returns `bar` * * @param {Object} object (constructed Assertion * @param {String} key * @param {Mixed} value (optional) * @name flag * @api private */ module.exports = function (obj, key, value) { var flags = obj.__flags || (obj.__flags = Object.create(null)); if (arguments.length === 3) { flags[key] = value; } else { return flags[key]; } }; }); require.register("chai/lib/chai/utils/getActual.js", function(exports, require, module){ /*! * Chai - getActual utility * Copyright(c) 2012-2013 Jake Luer * MIT Licensed */ /** * # getActual(object, [actual]) * * Returns the `actual` value for an Assertion * * @param {Object} object (constructed Assertion) * @param {Arguments} chai.Assertion.prototype.assert arguments */ module.exports = function (obj, args) { var actual = args[4]; return 'undefined' !== typeof actual ? actual : obj._obj; }; }); require.register("chai/lib/chai/utils/getEnumerableProperties.js", function(exports, require, module){ /*! * Chai - getEnumerableProperties utility * Copyright(c) 2012-2013 Jake Luer * MIT Licensed */ /** * ### .getEnumerableProperties(object) * * This allows the retrieval of enumerable property names of an object, * inherited or not. * * @param {Object} object * @returns {Array} * @name getEnumerableProperties * @api public */ module.exports = function getEnumerableProperties(object) { var result = []; for (var name in object) { result.push(name); } return result; }; }); require.register("chai/lib/chai/utils/getMessage.js", function(exports, require, module){ /*! * Chai - message composition utility * Copyright(c) 2012-2013 Jake Luer * MIT Licensed */ /*! * Module dependancies */ var flag = require('./flag') , getActual = require('./getActual') , inspect = require('./inspect') , objDisplay = require('./objDisplay'); /** * ### .getMessage(object, message, negateMessage) * * Construct the error message based on flags * and template tags. Template tags will return * a stringified inspection of the object referenced. * * Message template tags: * - `#{this}` current asserted object * - `#{act}` actual value * - `#{exp}` expected value * * @param {Object} object (constructed Assertion) * @param {Arguments} chai.Assertion.prototype.assert arguments * @name getMessage * @api public */ module.exports = function (obj, args) { var negate = flag(obj, 'negate') , val = flag(obj, 'object') , expected = args[3] , actual = getActual(obj, args) , msg = negate ? args[2] : args[1] , flagMsg = flag(obj, 'message'); msg = msg || ''; msg = msg .replace(/#{this}/g, objDisplay(val)) .replace(/#{act}/g, objDisplay(actual)) .replace(/#{exp}/g, objDisplay(expected)); return flagMsg ? flagMsg + ': ' + msg : msg; }; }); require.register("chai/lib/chai/utils/getName.js", function(exports, require, module){ /*! * Chai - getName utility * Copyright(c) 2012-2013 Jake Luer * MIT Licensed */ /** * # getName(func) * * Gets the name of a function, in a cross-browser way. * * @param {Function} a function (usually a constructor) */ module.exports = function (func) { if (func.name) return func.name; var match = /^\s?function ([^(]*)\(/.exec(func); return match && match[1] ? match[1] : ""; }; }); require.register("chai/lib/chai/utils/getPathValue.js", function(exports, require, module){ /*! * Chai - getPathValue utility * Copyright(c) 2012-2013 Jake Luer * @see https://github.com/logicalparadox/filtr * MIT Licensed */ /** * ### .getPathValue(path, object) * * This allows the retrieval of values in an * object given a string path. * * var obj = { * prop1: { * arr: ['a', 'b', 'c'] * , str: 'Hello' * } * , prop2: { * arr: [ { nested: 'Universe' } ] * , str: 'Hello again!' * } * } * * The following would be the results. * * getPathValue('prop1.str', obj); // Hello * getPathValue('prop1.att[2]', obj); // b * getPathValue('prop2.arr[0].nested', obj); // Universe * * @param {String} path * @param {Object} object * @returns {Object} value or `undefined` * @name getPathValue * @api public */ var getPathValue = module.exports = function (path, obj) { var parsed = parsePath(path); return _getPathValue(parsed, obj); }; /*! * ## parsePath(path) * * Helper function used to parse string object * paths. Use in conjunction with `_getPathValue`. * * var parsed = parsePath('myobject.property.subprop'); * * ### Paths: * * * Can be as near infinitely deep and nested * * Arrays are also valid using the formal `myobject.document[3].property`. * * @param {String} path * @returns {Object} parsed * @api private */ function parsePath (path) { var str = path.replace(/\[/g, '.[') , parts = str.match(/(\\\.|[^.]+?)+/g); return parts.map(function (value) { var re = /\[(\d+)\]$/ , mArr = re.exec(value) if (mArr) return { i: parseFloat(mArr[1]) }; else return { p: value }; }); }; /*! * ## _getPathValue(parsed, obj) * * Helper companion function for `.parsePath` that returns * the value located at the parsed address. * * var value = getPathValue(parsed, obj); * * @param {Object} parsed definition from `parsePath`. * @param {Object} object to search against * @returns {Object|Undefined} value * @api private */ function _getPathValue (parsed, obj) { var tmp = obj , res; for (var i = 0, l = parsed.length; i < l; i++) { var part = parsed[i]; if (tmp) { if ('undefined' !== typeof part.p) tmp = tmp[part.p]; else if ('undefined' !== typeof part.i) tmp = tmp[part.i]; if (i == (l - 1)) res = tmp; } else { res = undefined; } } return res; }; }); require.register("chai/lib/chai/utils/getProperties.js", function(exports, require, module){ /*! * Chai - getProperties utility * Copyright(c) 2012-2013 Jake Luer * MIT Licensed */ /** * ### .getProperties(object) * * This allows the retrieval of property names of an object, enumerable or not, * inherited or not. * * @param {Object} object * @returns {Array} * @name getProperties * @api public */ module.exports = function getProperties(object) { var result = Object.getOwnPropertyNames(subject); function addProperty(property) { if (result.indexOf(property) === -1) { result.push(property); } } var proto = Object.getPrototypeOf(subject); while (proto !== null) { Object.getOwnPropertyNames(proto).forEach(addProperty); proto = Object.getPrototypeOf(proto); } return result; }; }); require.register("chai/lib/chai/utils/index.js", function(exports, require, module){ /*! * chai * Copyright(c) 2011 Jake Luer * MIT Licensed */ /*! * Main exports */ var exports = module.exports = {}; /*! * test utility */ exports.test = require('./test'); /*! * type utility */ exports.type = require('./type'); /*! * message utility */ exports.getMessage = require('./getMessage'); /*! * actual utility */ exports.getActual = require('./getActual'); /*! * Inspect util */ exports.inspect = require('./inspect'); /*! * Object Display util */ exports.objDisplay = require('./objDisplay'); /*! * Flag utility */ exports.flag = require('./flag'); /*! * Flag transferring utility */ exports.transferFlags = require('./transferFlags'); /*! * Deep equal utility */ exports.eql = require('./eql'); /*! * Deep path value */ exports.getPathValue = require('./getPathValue'); /*! * Function name */ exports.getName = require('./getName'); /*! * add Property */ exports.addProperty = require('./addProperty'); /*! * add Method */ exports.addMethod = require('./addMethod'); /*! * overwrite Property */ exports.overwriteProperty = require('./overwriteProperty'); /*! * overwrite Method */ exports.overwriteMethod = require('./overwriteMethod'); /*! * Add a chainable method */ exports.addChainableMethod = require('./addChainableMethod'); }); require.register("chai/lib/chai/utils/inspect.js", function(exports, require, module){ // This is (almost) directly from Node.js utils // https://github.com/joyent/node/blob/f8c335d0caf47f16d31413f89aa28eda3878e3aa/lib/util.js var getName = require('./getName'); var getProperties = require('./getProperties'); var getEnumerableProperties = require('./getEnumerableProperties'); module.exports = inspect; /** * Echos the value of a value. Trys to print the value out * in the best way possible given the different types. * * @param {Object} obj The object to print out. * @param {Boolean} showHidden Flag that shows hidden (not enumerable) * properties of objects. * @param {Number} depth Depth in which to descend in object. Default is 2. * @param {Boolean} colors Flag to turn on ANSI escape codes to color the * output. Default is false (no coloring). */ function inspect(obj, showHidden, depth, colors) { var ctx = { showHidden: showHidden, seen: [], stylize: function (str) { return str; } }; return formatValue(ctx, obj, (typeof depth === 'undefined' ? 2 : depth)); } // https://gist.github.com/1044128/ var getOuterHTML = function(element) { if ('outerHTML' in element) return element.outerHTML; var ns = "http://www.w3.org/1999/xhtml"; var container = document.createElementNS(ns, '_'); var elemProto = (window.HTMLElement || window.Element).prototype; var xmlSerializer = new XMLSerializer(); var html; if (document.xmlVersion) { return xmlSerializer.serializeToString(element); } else { container.appendChild(element.cloneNode(false)); html = container.innerHTML.replace('><', '>' + element.innerHTML + '<'); container.innerHTML = ''; return html; } }; // Returns true if object is a DOM element. var isDOMElement = function (object) { if (typeof HTMLElement === 'object') { return object instanceof HTMLElement; } else { return object && typeof object === 'object' && object.nodeType === 1 && typeof object.nodeName === 'string'; } }; function formatValue(ctx, value, recurseTimes) { // Provide a hook for user-specified inspect functions. // Check that value is an object with an inspect function on it if (value && typeof value.inspect === 'function' && // Filter out the util module, it's inspect function is special value.inspect !== exports.inspect && // Also filter out any prototype objects using the circular check. !(value.constructor && value.constructor.prototype === value)) { var ret = value.inspect(recurseTimes); if (typeof ret !== 'string') { ret = formatValue(ctx, ret, recurseTimes); } return ret; } // Primitive types cannot have properties var primitive = formatPrimitive(ctx, value); if (primitive) { return primitive; } // If it's DOM elem, get outer HTML. if (isDOMElement(value)) { return getOuterHTML(value); } // Look up the keys of the object. var visibleKeys = getEnumerableProperties(value); var keys = ctx.showHidden ? getProperties(value) : visibleKeys; // Some type of object without properties can be shortcutted. // In IE, errors have a single `stack` property, or if they are vanilla `Error`, // a `stack` plus `description` property; ignore those for consistency. if (keys.length === 0 || (isError(value) && ( (keys.length === 1 && keys[0] === 'stack') || (keys.length === 2 && keys[0] === 'description' && keys[1] === 'stack') ))) { if (typeof value === 'function') { var name = getName(value); var nameSuffix = name ? ': ' + name : ''; return ctx.stylize('[Function' + nameSuffix + ']', 'special'); } if (isRegExp(value)) { return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp'); } if (isDate(value)) { return ctx.stylize(Date.prototype.toUTCString.call(value), 'date'); } if (isError(value)) { return formatError(value); } } var base = '', array = false, braces = ['{', '}']; // Make Array say that they are Array if (isArray(value)) { array = true; braces = ['[', ']']; } // Make functions say that they are functions if (typeof value === 'function') { var name = getName(value); var nameSuffix = name ? ': ' + name : ''; base = ' [Function' + nameSuffix + ']'; } // Make RegExps say that they are RegExps if (isRegExp(value)) { base = ' ' + RegExp.prototype.toString.call(value); } // Make dates with properties first say the date if (isDate(value)) { base = ' ' + Date.prototype.toUTCString.call(value); } // Make error with message first say the error if (isError(value)) { return formatError(value); } if (keys.length === 0 && (!array || value.length == 0)) { return braces[0] + base + braces[1]; } if (recurseTimes < 0) { if (isRegExp(value)) { return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp'); } else { return ctx.stylize('[Object]', 'special'); } } ctx.seen.push(value); var output; if (array) { output = formatArray(ctx, value, recurseTimes, visibleKeys, keys); } else { output = keys.map(function(key) { return formatProperty(ctx, value, recurseTimes, visibleKeys, key, array); }); } ctx.seen.pop(); return reduceToSingleString(output, base, braces); } function formatPrimitive(ctx, value) { switch (typeof value) { case 'undefined': return ctx.stylize('undefined', 'undefined'); case 'string': var simple = '\'' + JSON.stringify(value).replace(/^"|"$/g, '') .replace(/'/g, "\\'") .replace(/\\"/g, '"') + '\''; return ctx.stylize(simple, 'string'); case 'number': return ctx.stylize('' + value, 'number'); case 'boolean': return ctx.stylize('' + value, 'boolean'); } // For some reason typeof null is "object", so special case here. if (value === null) { return ctx.stylize('null', 'null'); } } function formatError(value) { return '[' + Error.prototype.toString.call(value) + ']'; } function formatArray(ctx, value, recurseTimes, visibleKeys, keys) { var output = []; for (var i = 0, l = value.length; i < l; ++i) { if (Object.prototype.hasOwnProperty.call(value, String(i))) { output.push(formatProperty(ctx, value, recurseTimes, visibleKeys, String(i), true)); } else { output.push(''); } } keys.forEach(function(key) { if (!key.match(/^\d+$/)) { output.push(formatProperty(ctx, value, recurseTimes, visibleKeys, key, true)); } }); return output; } function formatProperty(ctx, value, recurseTimes, visibleKeys, key, array) { var name, str; if (value.__lookupGetter__) { if (value.__lookupGetter__(key)) { if (value.__lookupSetter__(key)) { str = ctx.stylize('[Getter/Setter]', 'special'); } else { str = ctx.stylize('[Getter]', 'special'); } } else { if (value.__lookupSetter__(key)) { str = ctx.stylize('[Setter]', 'special'); } } } if (visibleKeys.indexOf(key) < 0) { name = '[' + key + ']'; } if (!str) { if (ctx.seen.indexOf(value[key]) < 0) { if (recurseTimes === null) { str = formatValue(ctx, value[key], null); } else { str = formatValue(ctx, value[key], recurseTimes - 1); } if (str.indexOf('\n') > -1) { if (array) { str = str.split('\n').map(function(line) { return ' ' + line; }).join('\n').substr(2); } else { str = '\n' + str.split('\n').map(function(line) { return ' ' + line; }).join('\n'); } } } else { str = ctx.stylize('[Circular]', 'special'); } } if (typeof name === 'undefined') { if (array && key.match(/^\d+$/)) { return str; } name = JSON.stringify('' + key); if (name.match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)) { name = name.substr(1, name.length - 2); name = ctx.stylize(name, 'name'); } else { name = name.replace(/'/g, "\\'") .replace(/\\"/g, '"') .replace(/(^"|"$)/g, "'"); name = ctx.stylize(name, 'string'); } } return name + ': ' + str; } function reduceToSingleString(output, base, braces) { var numLinesEst = 0; var length = output.reduce(function(prev, cur) { numLinesEst++; if (cur.indexOf('\n') >= 0) numLinesEst++; return prev + cur.length + 1; }, 0); if (length > 60) { return braces[0] + (base === '' ? '' : base + '\n ') + ' ' + output.join(',\n ') + ' ' + braces[1]; } return braces[0] + base + ' ' + output.join(', ') + ' ' + braces[1]; } function isArray(ar) { return Array.isArray(ar) || (typeof ar === 'object' && objectToString(ar) === '[object Array]'); } function isRegExp(re) { return typeof re === 'object' && objectToString(re) === '[object RegExp]'; } function isDate(d) { return typeof d === 'object' && objectToString(d) === '[object Date]'; } function isError(e) { return typeof e === 'object' && objectToString(e) === '[object Error]'; } function objectToString(o) { return Object.prototype.toString.call(o); } }); require.register("chai/lib/chai/utils/objDisplay.js", function(exports, require, module){ /*! * Chai - flag utility * Copyright(c) 2012-2013 Jake Luer * MIT Licensed */ /*! * Module dependancies */ var inspect = require('./inspect'); /** * ### .objDisplay (object) * * Determines if an object or an array matches * criteria to be inspected in-line for error * messages or should be truncated. * * @param {Mixed} javascript object to inspect * @name objDisplay * @api public */ module.exports = function (obj) { var str = inspect(obj) , type = Object.prototype.toString.call(obj); if (str.length >= 40) { if (type === '[object Function]') { return !obj.name || obj.name === '' ? '[Function]' : '[Function: ' + obj.name + ']'; } else if (type === '[object Array]') { return '[ Array(' + obj.length + ') ]'; } else if (type === '[object Object]') { var keys = Object.keys(obj) , kstr = keys.length > 2 ? keys.splice(0, 2).join(', ') + ', ...' : keys.join(', '); return '{ Object (' + kstr + ') }'; } else { return str; } } else { return str; } }; }); require.register("chai/lib/chai/utils/overwriteMethod.js", function(exports, require, module){ /*! * Chai - overwriteMethod utility * Copyright(c) 2012-2013 Jake Luer * MIT Licensed */ /** * ### overwriteMethod (ctx, name, fn) * * Overwites an already existing method and provides * access to previous function. Must return function * to be used for name. * * utils.overwriteMethod(chai.Assertion.prototype, 'equal', function (_super) { * return function (str) { * var obj = utils.flag(this, 'object'); * if (obj instanceof Foo) { * new chai.Assertion(obj.value).to.equal(str); * } else { * _super.apply(this, arguments); * } * } * }); * * Can also be accessed directly from `chai.Assertion`. * * chai.Assertion.overwriteMethod('foo', fn); * * Then can be used as any other assertion. * * expect(myFoo).to.equal('bar'); * * @param {Object} ctx object whose method is to be overwritten * @param {String} name of method to overwrite * @param {Function} method function that returns a function to be used for name * @name overwriteMethod * @api public */ module.exports = function (ctx, name, method) { var _method = ctx[name] , _super = function () { return this; }; if (_method && 'function' === typeof _method) _super = _method; ctx[name] = function () { var result = method(_super).apply(this, arguments); return result === undefined ? this : result; } }; }); require.register("chai/lib/chai/utils/overwriteProperty.js", function(exports, require, module){ /*! * Chai - overwriteProperty utility * Copyright(c) 2012-2013 Jake Luer * MIT Licensed */ /** * ### overwriteProperty (ctx, name, fn) * * Overwites an already existing property getter and provides * access to previous value. Must return function to use as getter. * * utils.overwriteProperty(chai.Assertion.prototype, 'ok', function (_super) { * return function () { * var obj = utils.flag(this, 'object'); * if (obj instanceof Foo) { * new chai.Assertion(obj.name).to.equal('bar'); * } else { * _super.call(this); * } * } * }); * * * Can also be accessed directly from `chai.Assertion`. * * chai.Assertion.overwriteProperty('foo', fn); * * Then can be used as any other assertion. * * expect(myFoo).to.be.ok; * * @param {Object} ctx object whose property is to be overwritten * @param {String} name of property to overwrite * @param {Function} getter function that returns a getter function to be used for name * @name overwriteProperty * @api public */ module.exports = function (ctx, name, getter) { var _get = Object.getOwnPropertyDescriptor(ctx, name) , _super = function () {}; if (_get && 'function' === typeof _get.get) _super = _get.get Object.defineProperty(ctx, name, { get: function () { var result = getter(_super).call(this); return result === undefined ? this : result; } , configurable: true }); }; }); require.register("chai/lib/chai/utils/test.js", function(exports, require, module){ /*! * Chai - test utility * Copyright(c) 2012-2013 Jake Luer * MIT Licensed */ /*! * Module dependancies */ var flag = require('./flag'); /** * # test(object, expression) * * Test and object for expression. * * @param {Object} object (constructed Assertion) * @param {Arguments} chai.Assertion.prototype.assert arguments */ module.exports = function (obj, args) { var negate = flag(obj, 'negate') , expr = args[0]; return negate ? !expr : expr; }; }); require.register("chai/lib/chai/utils/transferFlags.js", function(exports, require, module){ /*! * Chai - transferFlags utility * Copyright(c) 2012-2013 Jake Luer * MIT Licensed */ /** * ### transferFlags(assertion, object, includeAll = true) * * Transfer all the flags for `assertion` to `object`. If * `includeAll` is set to `false`, then the base Chai * assertion flags (namely `object`, `ssfi`, and `message`) * will not be transferred. * * * var newAssertion = new Assertion(); * utils.transferFlags(assertion, newAssertion); * * var anotherAsseriton = new Assertion(myObj); * utils.transferFlags(assertion, anotherAssertion, false); * * @param {Assertion} assertion the assertion to transfer the flags from * @param {Object} object the object to transfer the flags too; usually a new assertion * @param {Boolean} includeAll * @name getAllFlags * @api private */ module.exports = function (assertion, object, includeAll) { var flags = assertion.__flags || (assertion.__flags = Object.create(null)); if (!object.__flags) { object.__flags = Object.create(null); } includeAll = arguments.length === 3 ? includeAll : true; for (var flag in flags) { if (includeAll || (flag !== 'object' && flag !== 'ssfi' && flag != 'message')) { object.__flags[flag] = flags[flag]; } } }; }); require.register("chai/lib/chai/utils/type.js", function(exports, require, module){ /*! * Chai - type utility * Copyright(c) 2012-2013 Jake Luer * MIT Licensed */ /*! * Detectable javascript natives */ var natives = { '[object Arguments]': 'arguments' , '[object Array]': 'array' , '[object Date]': 'date' , '[object Function]': 'function' , '[object Number]': 'number' , '[object RegExp]': 'regexp' , '[object String]': 'string' }; /** * ### type(object) * * Better implementation of `typeof` detection that can * be used cross-browser. Handles the inconsistencies of * Array, `null`, and `undefined` detection. * * utils.type({}) // 'object' * utils.type(null) // `null' * utils.type(undefined) // `undefined` * utils.type([]) // `array` * * @param {Mixed} object to detect type of * @name type * @api private */ module.exports = function (obj) { var str = Object.prototype.toString.call(obj); if (natives[str]) return natives[str]; if (obj === null) return 'null'; if (obj === undefined) return 'undefined'; if (obj === Object(obj)) return 'object'; return typeof obj; }; }); require.alias("chaijs-assertion-error/index.js", "chai/deps/assertion-error/index.js"); require.alias("chaijs-assertion-error/index.js", "chai/deps/assertion-error/index.js"); require.alias("chaijs-assertion-error/index.js", "assertion-error/index.js"); require.alias("chaijs-assertion-error/index.js", "chaijs-assertion-error/index.js"); require.alias("chai/index.js", "chai/index.js"); if (typeof exports == "object") { module.exports = require("chai"); } else if (typeof define == "function" && define.amd) { define(function(){ return require("chai"); }); } else { this["chai"] = require("chai"); }})(); apache-couchdb-1.5.0/src/fauxton/test/mocha/sinon-chai.js0000644000175000001440000001066112230722213020165 00000000000000(function (sinonChai) { "use strict"; // Module systems magic dance. if (typeof require === "function" && typeof exports === "object" && typeof module === "object") { // NodeJS module.exports = sinonChai; } else if (typeof define === "function" && define.amd) { // AMD define(function () { return sinonChai; }); } else { // Other environment (usually apache-couchdb-1.5.0/src/fauxton/test/test.config.underscore0000644000175000001440000000054312230722213021024 00000000000000// vim: set ft=javascript: // Set the require.js configuration for your test setup. require.config( <%= JSON.stringify(configInfo, null, '\t') %> ); require([ <% _.each(testFiles, function (test) {%> '../<%= test %>', <% }) %> ], function() { if (window.mochaPhantomJS) { mochaPhantomJS.run(); } else { mocha.run(); } }); apache-couchdb-1.5.0/src/fauxton/Gruntfile.js0000644000175000001440000003232312230722213016025 00000000000000// 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. // This is the main application configuration file. It is a Grunt // configuration file, which you can learn more about here: // https://github.com/cowboy/grunt/blob/master/docs/configuring.md module.exports = function(grunt) { var helper = require('./tasks/helper').init(grunt), _ = grunt.util._, path = require('path'); var couch_config = function () { var default_couch_config = { fauxton: { db: 'http://localhost:5984/fauxton', app: './couchapp.js', options: { okay_if_missing: true } } }; var settings_couch_config = helper.readSettingsFile().couch_config; return settings_couch_config || default_couch_config; }(); var cleanableAddons = function () { var theListToClean = []; helper.processAddons(function(addon){ // Only clean addons that are included from a local dir if (addon.path){ theListToClean.push("app/addons/" + addon.name); } }); return theListToClean; }(); var cleanable = function(){ // Whitelist files and directories to be cleaned // You'll always want to clean these two directories // Now find the external addons you have and add them for cleaning up return _.union(["dist/", "app/load_addons.js"], cleanableAddons); }(); var assets = function(){ // Base assets var theAssets = { less:{ paths: ["assets/less"], files: { "dist/debug/css/fauxton.css": "assets/less/fauxton.less" } }, img: ["assets/img/**"] }; helper.processAddons(function(addon){ // Less files from addons var root = addon.path || "app/addons/" + addon.name; var lessPath = root + "/assets/less"; if(path.existsSync(lessPath)){ // .less files exist for this addon theAssets.less.paths.push(lessPath); theAssets.less.files["dist/debug/css/" + addon.name + ".css"] = lessPath + "/" + addon.name + ".less"; } // Images root = addon.path || "app/addons/" + addon.name; var imgPath = root + "/assets/img"; if(path.existsSync(imgPath)){ theAssets.img.push(imgPath + "/**"); } }); return theAssets; }(); var templateSettings = function(){ var defaultSettings = { "development": { "src": "assets/index.underscore", "dest": "dist/debug/index.html", "variables": { "requirejs": "/assets/js/libs/require.js", "css": "./css/index.css", "base": null } }, "release": { "src": "assets/index.underscore", "dest": "dist/debug/index.html", "variables": { "requirejs": "./js/require.js", "css": "./css/index.css", "base": null } } }; var settings = helper.readSettingsFile(); return settings.template || defaultSettings; }(); grunt.initConfig({ // The clean task ensures all files are removed from the dist/ directory so // that no files linger from previous builds. clean: { release: cleanable, watch: cleanableAddons }, // The lint task will run the build configuration and the application // JavaScript through JSHint and report any errors. You can change the // options for this task, by reading this: // https://github.com/cowboy/grunt/blob/master/docs/task_lint.md lint: { files: [ "build/config.js", "app/**/*.js" ] }, less: { compile: { options: { paths: assets.less.paths }, files: assets.less.files } }, // The jshint option for scripturl is set to lax, because the anchor // override inside main.js needs to test for them so as to not accidentally // route. jshint: { all: ['app/**/*.js', 'Gruntfile.js', "test/core/*.js"], options: { scripturl: true, evil: true } }, // The jst task compiles all application templates into JavaScript // functions with the underscore.js template function from 1.2.4. You can // change the namespace and the template options, by reading this: // https://github.com/gruntjs/grunt-contrib/blob/master/docs/jst.md // // The concat task depends on this file to exist, so if you decide to // remove this, ensure concat is updated accordingly. jst: { "dist/debug/templates.js": [ "app/templates/**/*.html", "app/addons/**/templates/**/*.html" ] }, template: templateSettings, // The concatenate task is used here to merge the almond require/define // shim and the templates into the application code. It's named // dist/debug/require.js, because we want to only load one script file in // index.html. concat: { requirejs: { src: [ "assets/js/libs/require.js", "dist/debug/templates.js", "dist/debug/require.js"], dest: "dist/debug/js/require.js" }, index_css: { src: ["dist/debug/css/*.css", 'assets/css/*.css'], dest: 'dist/debug/css/index.css' }, test_config_js: { src: ["dist/debug/templates.js", "test/test.config.js"], dest: 'test/test.config.js' } }, cssmin: { compress: { files: { "dist/release/css/index.css": [ "dist/debug/css/index.css", 'assets/css/*.css', "app/addons/**/assets/css/*.css" ] }, options: { report: 'min' } } }, uglify: { release: { files: { "dist/release/js/require.js": [ "dist/debug/js/require.js" ] } } }, // Runs a proxy server for easier development, no need to keep deploying to couchdb couchserver: { dist: './dist/debug/', port: 8000, proxy: { target: { host: 'localhost', port: 5984, https: false }, // This sets the Host header in the proxy so that you can use external // CouchDB instances and not have the Host set to 'localhost' changeOrigin: true } }, watch: { js: { files: helper.watchFiles(['.js'], ["./app/**/*.js", '!./app/load_addons.js',"./assets/**/*.js", "./test/**/*.js"]), tasks: ['watchRun'], }, style: { files: helper.watchFiles(['.less','.css'],["./app/**/*.css","./app/**/*.less","./assets/**/*.css", "./assets/**/*.less"]), tasks: ['clean:watch', 'dependencies','less', 'concat:index_css'], }, html: { // the index.html is added in as a dummy file incase there is no // html dependancies this will break. So we need one include pattern files: helper.watchFiles(['.html'], ['./index.html']), tasks: ['clean:watch', 'dependencies'] }, options: { nospawn: true, debounceDelay: 500 } }, requirejs: { compile: { options: { baseUrl: 'app', // Include the main configuration file. mainConfigFile: "app/config.js", // Output file. out: "dist/debug/require.js", // Root application module. name: "config", // Do not wrap everything in an IIFE. wrap: false, optimize: "none", } } }, // Copy build artifacts and library code into the distribution // see - http://gruntjs.com/configuring-tasks#building-the-files-object-dynamically copy: { couchdb: { files: [ // this gets built in the template task {src: "dist/release/index.html", dest: "../../share/www/fauxton/index.html"}, {src: ["**"], dest: "../../share/www/fauxton/js/", cwd:'dist/release/js/', expand: true}, {src: ["**"], dest: "../../share/www/fauxton/img/", cwd:'dist/release/img/', expand: true}, {src: ["**"], dest: "../../share/www/fauxton/css/", cwd:"dist/release/css/", expand: true} ] }, couchdebug: { files: [ // this gets built in the template task {src: "dist/debug/index.html", dest: "../../share/www/fauxton/index.html"}, {src: ["**"], dest: "../../share/www/fauxton/js/", cwd:'dist/debug/js/', expand: true}, {src: ["**"], dest: "../../share/www/fauxton/img/", cwd:'dist/debug/img/', expand: true}, {src: ["**"], dest: "../../share/www/fauxton/css/", cwd:"dist/debug/css/", expand: true} ] }, dist:{ files:[ {src: "dist/debug/index.html", dest: "dist/release/index.html"}, {src: assets.img, dest: "dist/release/img/", flatten: true, expand: true} ] }, debug:{ files:[ {src: assets.img, dest: "dist/debug/img/", flatten: true, expand: true} ] } }, get_deps: { "default": { src: "settings.json" } }, gen_load_addons: { "default": { src: "settings.json" } }, mkcouchdb: couch_config, rmcouchdb: couch_config, couchapp: couch_config, mochaSetup: { default: { files: { src: helper.watchFiles(['[Ss]pec.js'], ['./test/core/**/*[Ss]pec.js', './app/**/*[Ss]pec.js'])}, template: 'test/test.config.underscore', config: './app/config.js' } }, mocha_phantomjs: { all: ['test/runner.html'] } }); // on watch events configure jshint:all to only run on changed file grunt.event.on('watch', function(action, filepath) { if (!!filepath.match(/.js$/) && filepath.indexOf('test.config.js') === -1) { grunt.config(['jshint', 'all'], filepath); } if (!!filepath.match(/[Ss]pec.js$/)) { grunt.task.run(['mochaSetup','jst', 'concat:test_config_js', 'mocha_phantomjs']); } }); /* * Load Grunt plugins */ // Load fauxton specific tasks grunt.loadTasks('tasks'); // Load the couchapp task grunt.loadNpmTasks('grunt-couchapp'); // Load the copy task grunt.loadNpmTasks('grunt-contrib-watch'); // Load the exec task grunt.loadNpmTasks('grunt-exec'); // Load Require.js task grunt.loadNpmTasks('grunt-contrib-requirejs'); // Load Copy task grunt.loadNpmTasks('grunt-contrib-copy'); // Load Clean task grunt.loadNpmTasks('grunt-contrib-clean'); // Load jshint task grunt.loadNpmTasks('grunt-contrib-jshint'); // Load jst task grunt.loadNpmTasks('grunt-contrib-jst'); // Load less task grunt.loadNpmTasks('grunt-contrib-less'); // Load concat task grunt.loadNpmTasks('grunt-contrib-concat'); // Load UglifyJS task grunt.loadNpmTasks('grunt-contrib-uglify'); // Load CSSMin task grunt.loadNpmTasks('grunt-contrib-cssmin'); grunt.loadNpmTasks('grunt-mocha-phantomjs'); /* * Default task */ // defult task - install minified app to local CouchDB grunt.registerTask('default', 'couchdb'); /* * Transformation tasks */ // clean out previous build artefactsa and lint grunt.registerTask('lint', ['clean', 'jshint']); grunt.registerTask('test', ['lint', 'mochaSetup','jst', 'concat:test_config_js', 'mocha_phantomjs']); // Fetch dependencies (from git or local dir), lint them and make load_addons grunt.registerTask('dependencies', ['get_deps', 'gen_load_addons:default']); // build templates, js and css grunt.registerTask('build', ['less', 'concat:index_css', 'jst', 'requirejs', 'concat:requirejs', 'template:release']); // minify code and css, ready for release. grunt.registerTask('minify', ['uglify', 'cssmin:compress']); /* * Build the app in either dev, debug, or release mode */ // dev server grunt.registerTask('dev', ['debugDev', 'couchserver']); // build a debug release grunt.registerTask('debug', ['lint', 'dependencies', 'concat:requirejs','less', 'concat:index_css', 'template:development', 'copy:debug']); grunt.registerTask('debugDev', ['clean', 'dependencies','jshint','less', 'concat:index_css', 'template:development', 'copy:debug']); grunt.registerTask('watchRun', ['clean:watch', 'dependencies', 'jshint']); // build a release grunt.registerTask('release', ['clean' ,'dependencies','jshint', 'build', 'minify', 'copy:dist']); /* * Install into CouchDB in either debug, release, or couchapp mode */ // make a development install that is server by mochiweb under _utils grunt.registerTask('couchdebug', ['debug', 'copy:couchdebug']); // make a minimized install that is server by mochiweb under _utils grunt.registerTask('couchdb', ['release', 'copy:couchdb']); // make an install that can be deployed as a couchapp grunt.registerTask('couchapp_setup', ['release']); // install fauxton as couchapp grunt.registerTask('couchapp_install', ['rmcouchdb:fauxton', 'mkcouchdb:fauxton', 'couchapp:fauxton']); // setup and install fauxton as couchapp grunt.registerTask('couchapp_deploy', ['couchapp_setup', 'couchapp_install']); }; apache-couchdb-1.5.0/src/fauxton/favicon.ico0000644000175000001440000000217612230722213015654 00000000000000 h(  @’’’’’’’’’’’’’’’#õīę‰īęŠĶźąÄ’źąÄ’īęŠĶõīꉒ’’#’’’’’’’’’’’’’’’’’’’’’õīꉼąÄ’źąÄ’źąÄ’źąÄ’źąÄ’źąÄ’źąÄ’źąÄ’õīꉒ’’’’’’’’’’’’’’īęŠĶźąÄ’źąÄ’źąÄ’źąÄ’Ō»•’Ā•`’œZ’œZ’Ļ«|’åŲ»’īęŠĶ’’’’’’’’’õīę‰åŲ»’Ťy’²†S’¼|7’¶€E’¤k/’Ær3’¹y6’¼|7’²t3’²†S’źąÄ’õīꉒ’’’’’#źąÄ’Ťy’¤k/’²t3’¼|7’Ær3’¤k/’Ær3’¹y6’¼|7’²t3’­k1’źąÄ’źąÄ’’’’#ōīŽ™źąÄ’²†S’¤k/’²t3’¼|7’Ær3’¤k/’Ær3’¹y6’¼|7’²t3’­k1’źąÄ’źąÄ’ōīŽ™īęŠĶźąÄ’²†S’¤k/’²t3’¼|7’Ær3’¤k/’Ær3’¹y6’¼|7’²t3’­k1’źąÄ’źąÄ’īęŠĶźąÄ’źąÄ’²†S’¤k/’²t3’¼|7’Ær3’¤k/’Ær3’Ģ™f’¶€E’²t3’­k1’źąÄ’źąÄ’źąÄ’źąÄ’źąÄ’²†S’¤k/’œZ’͜h’Ąs’āѾ’’’’’’’’’’’’’õīę’²†S’źąÄ’źąÄ’źąÄ’īęŠĶźąÄ’Ąs’õīę’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’üśų’źąÄ’źąÄ’īęŠĶōīŽ™źąÄ’šēŪ’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’õīę’źąÄ’źąÄ’ōīŽ™’’’#źąÄ’ļčÓ’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’üśų’Ōø“’źąÄ’źąÄ’’’’#’’’õīꉼąÄ’ėāČ’ōīŽ’õīę’’’’’’’’’’’’’’’’’’’’’’’’’ōīŽ’źąÄ’õīꉒ’’’’’’’’īęŠĶźąÄ’źąÄ’źąÄ’ōīŽ’’’’’’’’’’’’’’’’’õīę’ėāČ’īęŠĶ’’’’’’’’’’’’’’’õīꉼąÄ’źąÄ’źąÄ’źąÄ’ļčÓ’ļčÓ’ėāČ’źąÄ’õīꉒ’’’’’’’’’’’’’’’’’’’’’’’#õīę‰īęŠĶźąÄ’źąÄ’īęŠĶõīꉒ’’#’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’apache-couchdb-1.5.0/src/fauxton/writing_addons.md0000644000175000001440000001100112230722213017053 00000000000000# Addons Addons allow you to extend Fauxton for a specific use case. Addons will usually have the following structure: * templates/ * my_addon.html - _underscore template fragments_ * base.js - _entry point to the addon_ * resources.js - _models and collections of the addon_ * routes.js - _URL routing for the addon_ * views.js - _views that the model provides_ [optional] * assets/less * my_addon.less ## Generating an addon We have a `grunt-init` template that lets you create a skeleton addon, including all the boiler plate code. Run `./node_modules/.bin/grunt-init tasks/addon` and answer the questions it asks to create an addon: $ ./node_modules/.bin/grunt-init tasks/addon path.existsSync is now called `fs.existsSync`. Running "addon" task Please answer the following: [?] Add on Name (WickedCool) SuperAddon [?] Location of add ons (app/addons) [?] Do you need an assets folder?(for .less) (y/N) [?] Do you need to make any changes to the above before continuing? (y/N) Created addon SuperAddon in app/addons Done, without errors. Once the addon is created add the name to the settings.json file to get it compiled and added on the next install. ## Routes and hooks An addon can insert itself into fauxton in two ways; via a route or via a hook. ### Routes An addon will override an existing route should one exist, but in all other ways is just a normal backbone route/view. This is how you would add a whole new feature. ### Hooks Hooks let you modify/extend an existing feature. They modify a DOM element by selector for a named set of routes, for example: var Search = new FauxtonAPI.addon(); Search.hooks = { // Render additional content into the sidebar "#sidebar-content": { routes:[ "database/:database/_design/:ddoc/_search/:search", "database/:database/_design/:ddoc/_view/:view", "database/:database/_:handler"], callback: searchSidebar } }; return Search; adds the `searchSidebar` callback to `#sidebar-content` for three routes. ## Hello world addon First create the addon skeleton: ± bbb addon path.existsSync is now called `fs.existsSync`. Running "addon" task Please answer the following: [?] Add on Name (WickedCool) Hello [?] Location of add ons (app/addons) [?] Do you need to make any changes to the above before continuing? (y/N) Created addon Hello in app/addons Done, without errors. In `app/addons/hello/templates/hello.html` place:

    Hello!

    Next, we'll defined a simple view in `resources.js` (for more complex addons you may want to have a views.js) that renders that template: define([ "app", "api" ], function (app, FauxtonAPI) { var Resources = {}; Resources.Hello = FauxtonAPI.View.extend({ template: "addons/hello/templates/hello" }); return Resources; }); Then define a route in `routes.js` that the addon is accessible at: define([ "app", "api", "addons/hello/resources" ], function(app, FauxtonAPI, Resources) { var HelloRouteObject = FauxtonAPI.RouteObject.extend({ layout: "one_pane", crumbs: [ {"name": "Hello","link": "_hello"} ], routes: { "_hello": "helloRoute" }, selectedHeader: "Hello", roles: ["_admin"], apiUrl:'hello', initialize: function () { //put common views used on all your routes here (eg: sidebars ) }, helloRoute: function () { this.setView("#dashboard-content", new Resources.Hello({})); } }); Resources.RouteObjects = [HelloRouteObject]; return Resources; }); Then wire it all together in base.js: define([ "app", "api", "addons/hello/routes" ], function(app, FauxtonAPI, HelloRoutes) { HelloRoutes.initialize = function() { FauxtonAPI.addHeaderLink({title: "Hello", href: "#_hello"}); }; return HelloRoutes; }); Once the code is in place include the add on in your `settings.json` so that it gets included by the `require` task. Your addon is included in one of three ways; a local path, a git URL or a name. Named plugins assume the plugin is in the fauxton base directory, addons with a git URL will be cloned into the application, local paths will be copied. Addons included from a local path will be cleaned out by the clean task, others are left alone. **TODO:** addons via npm module apache-couchdb-1.5.0/src/fauxton/tasks/0000755000175000001440000000000012230722303014732 500000000000000apache-couchdb-1.5.0/src/fauxton/tasks/addon/0000755000175000001440000000000012230722303016017 500000000000000apache-couchdb-1.5.0/src/fauxton/tasks/addon/root/0000755000175000001440000000000012230722303017002 500000000000000apache-couchdb-1.5.0/src/fauxton/tasks/addon/root/resources.js.underscore0000644000175000001440000000124712230722213023446 00000000000000// 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. define([ "app", "api" ], function (app, FauxtonAPI) { var {%= name %} = FauxtonAPI.addon(); return {%= name %}; }); apache-couchdb-1.5.0/src/fauxton/tasks/addon/root/base.js.underscore0000644000175000001440000000127012230722213022342 00000000000000// 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. define([ "app", "api", "addons/{%= name.toLowerCase() %}/routes" ], function(app, FauxtonAPI, {%= name %}) { return {%= name %}; }); apache-couchdb-1.5.0/src/fauxton/tasks/addon/root/routes.js.underscore0000644000175000001440000000132512230722213022752 00000000000000// 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. define([ "app", "api", "addons/{%= name.toLowerCase() %}/resources" ], function(app, FauxtonAPI, {%= name %}) { {%= name %}.Routes = {}; return {%= name %}; }); apache-couchdb-1.5.0/src/fauxton/tasks/addon/template.js0000644000175000001440000000402212230722213020106 00000000000000// 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. 'use strict'; exports.description = 'Generate a skeleton for an addon.'; exports.notes = ''; exports.after = "Created your addon! Don't forget to update your"+ " settings.json for it to be compiled and deployed"; // Any existing file or directory matching this wildcard will cause a warning. // exports.warnOn = '*'; // The actual init template. exports.template = function(grunt, init, done) { // destpath init.process( {}, [ { name: "name", message: "Add on Name", validator: /^[\w\-\.]+$/, default: "WickedCool" }, { name: "path", message: "Location of add ons", default: "app/addons" }, { name: "assets", message: "Do you need an assets folder? (for .less)", default: 'y/N' } ], function (err, props) { // Files to copy (and process). var files = init.filesToCopy(props); // Actually copy and process (apply the template props) files. init.copyAndProcess(files, props); // Make the assets dir if requested if (props.assets == "y"){ var asspath = props.path + "/" + props.name.toLowerCase() + "/assets"; grunt.file.mkdir(asspath); grunt.log.writeln("Created " + asspath); } var tmplpath = props.path + "/" + props.name.toLowerCase() + "/templates"; grunt.file.mkdir(tmplpath); grunt.log.writeln("Created " + tmplpath); // All done! done(); } ) };apache-couchdb-1.5.0/src/fauxton/tasks/addon/rename.json0000644000175000001440000000035312230722213020102 00000000000000{ "routes.js.underscore": "{%= path %}/{%= name.toLowerCase() %}/routes.js", "resources.js.underscore": "{%= path %}/{%= name.toLowerCase() %}/resources.js", "base.js.underscore": "{%= path %}/{%= name.toLowerCase() %}/base.js" }apache-couchdb-1.5.0/src/fauxton/tasks/fauxton.js0000644000175000001440000001053312230722213016676 00000000000000// 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. module.exports = function(grunt) { var _ = grunt.util._; grunt.registerMultiTask('template', 'generates an html file from a specified template', function(){ var data = this.data; var _ = grunt.util._; var tmpl = _.template(grunt.file.read(data.src), null, data.variables); grunt.file.write(data.dest, tmpl(data.variables)); }); grunt.registerMultiTask('get_deps', 'Fetch external dependencies', function(version) { grunt.log.writeln("Fetching external dependencies"); var path = require('path'); var done = this.async(); var data = this.data; var target = data.target || "app/addons/"; var settingsFile = path.existsSync(data.src) ? data.src : "settings.json.default"; var settings = grunt.file.readJSON(settingsFile); var _ = grunt.util._; // This should probably be a helper, though they seem to have been removed var fetch = function(deps, command){ var child_process = require('child_process'); var async = require('async'); async.forEach(deps, function(dep, cb) { var path = target + dep.name; var location = dep.url || dep.path; grunt.log.writeln("Fetching: " + dep.name + " (" + location + ")"); child_process.exec(command(dep, path), function(error, stdout, stderr) { grunt.log.writeln(stderr); grunt.log.writeln(stdout); cb(error); }); }, function(error) { if (error) { grunt.log.writeln("ERROR: " + error.message); return false; } else { return true; } }); }; var remoteDeps = _.filter(settings.deps, function(dep) { return !! dep.url; }); grunt.log.writeln(remoteDeps.length + " remote dependencies"); var remote = fetch(remoteDeps, function(dep, destination){ return "git clone " + dep.url + " " + destination; }); var localDeps = _.filter(settings.deps, function(dep) { return !! dep.path; }); grunt.log.writeln(localDeps.length + " local dependencies"); var local = fetch(localDeps, function(dep, destination){ // TODO: Windows var command = "cp -r " + dep.path + " " + destination; grunt.log.writeln(command); return command; }); done(remote && local); }); grunt.registerMultiTask('gen_load_addons', 'Generate the load_addons.js file', function() { var path = require('path'); var data = this.data; var _ = grunt.util._; var settingsFile = path.existsSync(data.src) ? data.src : "settings.json.default"; var settings = grunt.file.readJSON(settingsFile); var template = "app/load_addons.js.underscore"; var dest = "app/load_addons.js"; var deps = _.map(settings.deps, function(dep) { return "addons/" + dep.name + "/base"; }); var tmpl = _.template(grunt.file.read(template)); grunt.file.write(dest, tmpl({deps: deps})); }); grunt.registerMultiTask('mochaSetup','Generate a config.js and runner.html for tests', function(){ var data = this.data, configInfo, _ = grunt.util._, configTemplateSrc = data.template, testFiles = grunt.file.expand(data.files.src); var configTemplate = _.template(grunt.file.read(configTemplateSrc)); // a bit of a nasty hack to read our current config.js and get the info so we can change it // for our testing setup var require = { config: function (args) { configInfo = args; configInfo.paths['chai'] = "../test/mocha/chai"; configInfo.paths['sinon-chai'] = "../test/mocha/sinon-chai"; configInfo.paths['testUtils'] = "../test/mocha/testUtils"; configInfo.baseUrl = '../app'; delete configInfo.deps; } }; eval(grunt.file.read(data.config) +''); grunt.file.write('./test/test.config.js', configTemplate({configInfo: configInfo, testFiles: testFiles})); }); }; apache-couchdb-1.5.0/src/fauxton/tasks/couchserver.js0000644000175000001440000000700312230722213017540 00000000000000// 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. module.exports = function (grunt) { var log = grunt.log; grunt.registerTask("couchserver", 'Run a couch dev proxy server', function () { var fs = require("fs"), path = require("path"), http = require("http"), httpProxy = require('http-proxy'), send = require('send'), options = grunt.config('couchserver'); // Options var dist_dir = options.dist || './dist/debug/', app_dir = './app', port = options.port || 8000; // Proxy options with default localhost var proxy_settings = options.proxy || { target: { host: 'localhost', port: 5984, https: false } }; // inform grunt that this task is async var done = this.async(); // create proxy to couch for all couch requests var proxy = new httpProxy.HttpProxy(proxy_settings); http.createServer(function (req, res) { var url = req.url.replace('app/',''), accept = req.headers.accept.split(','), filePath; if (!!url.match(/assets/)) { // serve any javascript or css files from here assets dir filePath = path.join('./',url); } else if (!!url.match(/mocha|\/test\/core\/|test\.config/)) { filePath = path.join('./test', url.replace('/test/','')); } else if (!!url.match(/\.css|img/)) { filePath = path.join(dist_dir,url); /*} else if (!!url.match(/\/js\//)) { // serve any javascript or files from dist debug dir filePath = path.join(dist_dir,req.url);*/ } else if (!!url.match(/\.js$|\.html$/)) { // server js from app directory filePath = path.join(app_dir, url.replace('/_utils/fauxton/','')); } else if (!!url.match(/testrunner/)) { var testSetup = grunt.util.spawn({cmd: 'grunt', grunt: true, args: ['mochaSetup']}, function (error, result, code) {/* log.writeln(String(result));*/ }); testSetup.stdout.pipe(process.stdout); testSetup.stderr.pipe(process.stderr); filePath = path.join('./test/runner.html'); } else if (url === '/' && accept[0] !== 'application/json') { // serve main index file from here filePath = path.join(dist_dir, 'index.html'); }; if (filePath) { return send(req, filePath) .on('error', function (err) { if (err.status === 404) { log.writeln('Could not locate', filePath); } else { log.writeln('ERROR', filePath, err); } res.end(err.message); }) .pipe(res); } proxy.proxyRequest(req, res); }).listen(port); // Fail this task if any errors have been logged if (grunt.errors) { return false; } var watch = grunt.util.spawn({cmd: 'grunt', grunt: true, args: ['watch']}, function (error, result, code) {/* log.writeln(String(result));*/ }); watch.stdout.pipe(process.stdout); watch.stderr.pipe(process.stderr); log.writeln('Listening on ' + port); }); }; apache-couchdb-1.5.0/src/fauxton/tasks/helper.js0000644000175000001440000000266012230722213016473 00000000000000// 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. var fs = require('fs'), path = require('path'); exports.init = function(grunt) { var _ = grunt.util._; return { readSettingsFile: function () { if (fs.existsSync("settings.json")) { return grunt.file.readJSON("settings.json"); } else if (fs.existsSync("settings.json.default")) { return grunt.file.readJSON("settings.json.default"); } else { return {deps: []}; } }, processAddons: function (callback) { this.readSettingsFile().deps.forEach(callback); }, watchFiles: function (fileExtensions, defaults) { return _.reduce(this.readSettingsFile().deps, function (files, dep) { if (dep.path) { _.each(fileExtensions, function (fileExtension) { files.push(path.join(dep.path, '**/*' + fileExtension )); }); } return files }, defaults); } }; }; apache-couchdb-1.5.0/src/fauxton/index.html0000644000175000001440000000270612230722213015527 00000000000000 Project Fauxton

    © Project Fauxton 2012

    apache-couchdb-1.5.0/src/fauxton/TODO.md0000644000175000001440000000132712230722213014617 00000000000000# Fauxton todo In no particular order - [ ] docco docs - [ ] user management - [ ] view options - [ ] view editor - [ ] visual view builder - [ ] new db as modal - [ ] new view button - [ ] show design docs only - [ ] fix delete doc button UI bug - [ ] delete multiple docs via _bulk_docs - [x] show change events in database view - [ ] pouchdb addon - [ ] bespoke bootstrap style - [ ] responsive interface - [ ] sticky subnav for some UI components on _all_docs - [ ] "show me" button in API bar doesn't - [ ] edit index button doesn't - [ ] replicate UI - [x] delete database - [x] format dates better (e.g. in logs plugin) - [ ] format log entry better - [ ] filter logs by method - [ ] restore unfiltered data in logs UI apache-couchdb-1.5.0/src/fauxton/assets/0000755000175000001440000000000012230722303015107 500000000000000apache-couchdb-1.5.0/src/fauxton/assets/js/0000755000175000001440000000000012230722303015523 500000000000000apache-couchdb-1.5.0/src/fauxton/assets/js/libs/0000755000175000001440000000000012230722303016454 500000000000000apache-couchdb-1.5.0/src/fauxton/assets/js/libs/spin.min.js0000644000175000001440000000565312230722213020476 00000000000000(function(a,b,c){function O(a){H(arguments,function(b,d){a[b]===c&&(a[b]=d)});return a}function N(a){H(arguments,function(b,c){a[m][M(a,b)||b]=c});return a}function M(a,b){var d=a[m],f,g;if(d[b]!==c){return b}b=b.charAt(0).toUpperCase()+b.slice(1);for(g=0;g= 0 ? value.substring(i) : (i = value.length, ""), t = []; while (i > 0) t.push(value.substring(i -= 3, i + 3)); return t.reverse().join(",") + f; } function d3_formatPrefix(d, i) { var k = Math.pow(10, Math.abs(8 - i) * 3); return { scale: i > 8 ? function(d) { return d / k; } : function(d) { return d * k; }, symbol: d }; } function d3_ease_clamp(f) { return function(t) { return t <= 0 ? 0 : t >= 1 ? 1 : f(t); }; } function d3_ease_reverse(f) { return function(t) { return 1 - f(1 - t); }; } function d3_ease_reflect(f) { return function(t) { return .5 * (t < .5 ? f(2 * t) : 2 - f(2 - 2 * t)); }; } function d3_ease_identity(t) { return t; } function d3_ease_poly(e) { return function(t) { return Math.pow(t, e); }; } function d3_ease_sin(t) { return 1 - Math.cos(t * Math.PI / 2); } function d3_ease_exp(t) { return Math.pow(2, 10 * (t - 1)); } function d3_ease_circle(t) { return 1 - Math.sqrt(1 - t * t); } function d3_ease_elastic(a, p) { var s; if (arguments.length < 2) p = .45; if (arguments.length < 1) { a = 1; s = p / 4; } else s = p / (2 * Math.PI) * Math.asin(1 / a); return function(t) { return 1 + a * Math.pow(2, 10 * -t) * Math.sin((t - s) * 2 * Math.PI / p); }; } function d3_ease_back(s) { if (!s) s = 1.70158; return function(t) { return t * t * ((s + 1) * t - s); }; } function d3_ease_bounce(t) { return t < 1 / 2.75 ? 7.5625 * t * t : t < 2 / 2.75 ? 7.5625 * (t -= 1.5 / 2.75) * t + .75 : t < 2.5 / 2.75 ? 7.5625 * (t -= 2.25 / 2.75) * t + .9375 : 7.5625 * (t -= 2.625 / 2.75) * t + .984375; } function d3_eventCancel() { d3.event.stopPropagation(); d3.event.preventDefault(); } function d3_eventSource() { var e = d3.event, s; while (s = e.sourceEvent) e = s; return e; } function d3_eventDispatch(target) { var dispatch = new d3_dispatch, i = 0, n = arguments.length; while (++i < n) dispatch[arguments[i]] = d3_dispatch_event(dispatch); dispatch.of = function(thiz, argumentz) { return function(e1) { try { var e0 = e1.sourceEvent = d3.event; e1.target = target; d3.event = e1; dispatch[e1.type].apply(thiz, argumentz); } finally { d3.event = e0; } }; }; return dispatch; } function d3_transform(m) { var r0 = [ m.a, m.b ], r1 = [ m.c, m.d ], kx = d3_transformNormalize(r0), kz = d3_transformDot(r0, r1), ky = d3_transformNormalize(d3_transformCombine(r1, r0, -kz)) || 0; if (r0[0] * r1[1] < r1[0] * r0[1]) { r0[0] *= -1; r0[1] *= -1; kx *= -1; kz *= -1; } this.rotate = (kx ? Math.atan2(r0[1], r0[0]) : Math.atan2(-r1[0], r1[1])) * d3_transformDegrees; this.translate = [ m.e, m.f ]; this.scale = [ kx, ky ]; this.skew = ky ? Math.atan2(kz, ky) * d3_transformDegrees : 0; } function d3_transformDot(a, b) { return a[0] * b[0] + a[1] * b[1]; } function d3_transformNormalize(a) { var k = Math.sqrt(d3_transformDot(a, a)); if (k) { a[0] /= k; a[1] /= k; } return k; } function d3_transformCombine(a, b, k) { a[0] += k * b[0]; a[1] += k * b[1]; return a; } function d3_interpolateByName(name) { return name == "transform" ? d3.interpolateTransform : d3.interpolate; } function d3_uninterpolateNumber(a, b) { b = b - (a = +a) ? 1 / (b - a) : 0; return function(x) { return (x - a) * b; }; } function d3_uninterpolateClamp(a, b) { b = b - (a = +a) ? 1 / (b - a) : 0; return function(x) { return Math.max(0, Math.min(1, (x - a) * b)); }; } function d3_Color() {} function d3_rgb(r, g, b) { return new d3_Rgb(r, g, b); } function d3_Rgb(r, g, b) { this.r = r; this.g = g; this.b = b; } function d3_rgb_hex(v) { return v < 16 ? "0" + Math.max(0, v).toString(16) : Math.min(255, v).toString(16); } function d3_rgb_parse(format, rgb, hsl) { var r = 0, g = 0, b = 0, m1, m2, name; m1 = /([a-z]+)\((.*)\)/i.exec(format); if (m1) { m2 = m1[2].split(","); switch (m1[1]) { case "hsl": { return hsl(parseFloat(m2[0]), parseFloat(m2[1]) / 100, parseFloat(m2[2]) / 100); } case "rgb": { return rgb(d3_rgb_parseNumber(m2[0]), d3_rgb_parseNumber(m2[1]), d3_rgb_parseNumber(m2[2])); } } } if (name = d3_rgb_names.get(format)) return rgb(name.r, name.g, name.b); if (format != null && format.charAt(0) === "#") { if (format.length === 4) { r = format.charAt(1); r += r; g = format.charAt(2); g += g; b = format.charAt(3); b += b; } else if (format.length === 7) { r = format.substring(1, 3); g = format.substring(3, 5); b = format.substring(5, 7); } r = parseInt(r, 16); g = parseInt(g, 16); b = parseInt(b, 16); } return rgb(r, g, b); } function d3_rgb_hsl(r, g, b) { var min = Math.min(r /= 255, g /= 255, b /= 255), max = Math.max(r, g, b), d = max - min, h, s, l = (max + min) / 2; if (d) { s = l < .5 ? d / (max + min) : d / (2 - max - min); if (r == max) h = (g - b) / d + (g < b ? 6 : 0); else if (g == max) h = (b - r) / d + 2; else h = (r - g) / d + 4; h *= 60; } else { s = h = 0; } return d3_hsl(h, s, l); } function d3_rgb_lab(r, g, b) { r = d3_rgb_xyz(r); g = d3_rgb_xyz(g); b = d3_rgb_xyz(b); var x = d3_xyz_lab((.4124564 * r + .3575761 * g + .1804375 * b) / d3_lab_X), y = d3_xyz_lab((.2126729 * r + .7151522 * g + .072175 * b) / d3_lab_Y), z = d3_xyz_lab((.0193339 * r + .119192 * g + .9503041 * b) / d3_lab_Z); return d3_lab(116 * y - 16, 500 * (x - y), 200 * (y - z)); } function d3_rgb_xyz(r) { return (r /= 255) <= .04045 ? r / 12.92 : Math.pow((r + .055) / 1.055, 2.4); } function d3_rgb_parseNumber(c) { var f = parseFloat(c); return c.charAt(c.length - 1) === "%" ? Math.round(f * 2.55) : f; } function d3_hsl(h, s, l) { return new d3_Hsl(h, s, l); } function d3_Hsl(h, s, l) { this.h = h; this.s = s; this.l = l; } function d3_hsl_rgb(h, s, l) { function v(h) { if (h > 360) h -= 360; else if (h < 0) h += 360; if (h < 60) return m1 + (m2 - m1) * h / 60; if (h < 180) return m2; if (h < 240) return m1 + (m2 - m1) * (240 - h) / 60; return m1; } function vv(h) { return Math.round(v(h) * 255); } var m1, m2; h = h % 360; if (h < 0) h += 360; s = s < 0 ? 0 : s > 1 ? 1 : s; l = l < 0 ? 0 : l > 1 ? 1 : l; m2 = l <= .5 ? l * (1 + s) : l + s - l * s; m1 = 2 * l - m2; return d3_rgb(vv(h + 120), vv(h), vv(h - 120)); } function d3_hcl(h, c, l) { return new d3_Hcl(h, c, l); } function d3_Hcl(h, c, l) { this.h = h; this.c = c; this.l = l; } function d3_hcl_lab(h, c, l) { return d3_lab(l, Math.cos(h *= Math.PI / 180) * c, Math.sin(h) * c); } function d3_lab(l, a, b) { return new d3_Lab(l, a, b); } function d3_Lab(l, a, b) { this.l = l; this.a = a; this.b = b; } function d3_lab_rgb(l, a, b) { var y = (l + 16) / 116, x = y + a / 500, z = y - b / 200; x = d3_lab_xyz(x) * d3_lab_X; y = d3_lab_xyz(y) * d3_lab_Y; z = d3_lab_xyz(z) * d3_lab_Z; return d3_rgb(d3_xyz_rgb(3.2404542 * x - 1.5371385 * y - .4985314 * z), d3_xyz_rgb(-.969266 * x + 1.8760108 * y + .041556 * z), d3_xyz_rgb(.0556434 * x - .2040259 * y + 1.0572252 * z)); } function d3_lab_hcl(l, a, b) { return d3_hcl(Math.atan2(b, a) / Math.PI * 180, Math.sqrt(a * a + b * b), l); } function d3_lab_xyz(x) { return x > .206893034 ? x * x * x : (x - 4 / 29) / 7.787037; } function d3_xyz_lab(x) { return x > .008856 ? Math.pow(x, 1 / 3) : 7.787037 * x + 4 / 29; } function d3_xyz_rgb(r) { return Math.round(255 * (r <= .00304 ? 12.92 * r : 1.055 * Math.pow(r, 1 / 2.4) - .055)); } function d3_selection(groups) { d3_arraySubclass(groups, d3_selectionPrototype); return groups; } function d3_selection_selector(selector) { return function() { return d3_select(selector, this); }; } function d3_selection_selectorAll(selector) { return function() { return d3_selectAll(selector, this); }; } function d3_selection_attr(name, value) { function attrNull() { this.removeAttribute(name); } function attrNullNS() { this.removeAttributeNS(name.space, name.local); } function attrConstant() { this.setAttribute(name, value); } function attrConstantNS() { this.setAttributeNS(name.space, name.local, value); } function attrFunction() { var x = value.apply(this, arguments); if (x == null) this.removeAttribute(name); else this.setAttribute(name, x); } function attrFunctionNS() { var x = value.apply(this, arguments); if (x == null) this.removeAttributeNS(name.space, name.local); else this.setAttributeNS(name.space, name.local, x); } name = d3.ns.qualify(name); return value == null ? name.local ? attrNullNS : attrNull : typeof value === "function" ? name.local ? attrFunctionNS : attrFunction : name.local ? attrConstantNS : attrConstant; } function d3_selection_classedRe(name) { return new RegExp("(?:^|\\s+)" + d3.requote(name) + "(?:\\s+|$)", "g"); } function d3_selection_classed(name, value) { function classedConstant() { var i = -1; while (++i < n) name[i](this, value); } function classedFunction() { var i = -1, x = value.apply(this, arguments); while (++i < n) name[i](this, x); } name = name.trim().split(/\s+/).map(d3_selection_classedName); var n = name.length; return typeof value === "function" ? classedFunction : classedConstant; } function d3_selection_classedName(name) { var re = d3_selection_classedRe(name); return function(node, value) { if (c = node.classList) return value ? c.add(name) : c.remove(name); var c = node.className, cb = c.baseVal != null, cv = cb ? c.baseVal : c; if (value) { re.lastIndex = 0; if (!re.test(cv)) { cv = d3_collapse(cv + " " + name); if (cb) c.baseVal = cv; else node.className = cv; } } else if (cv) { cv = d3_collapse(cv.replace(re, " ")); if (cb) c.baseVal = cv; else node.className = cv; } }; } function d3_selection_style(name, value, priority) { function styleNull() { this.style.removeProperty(name); } function styleConstant() { this.style.setProperty(name, value, priority); } function styleFunction() { var x = value.apply(this, arguments); if (x == null) this.style.removeProperty(name); else this.style.setProperty(name, x, priority); } return value == null ? styleNull : typeof value === "function" ? styleFunction : styleConstant; } function d3_selection_property(name, value) { function propertyNull() { delete this[name]; } function propertyConstant() { this[name] = value; } function propertyFunction() { var x = value.apply(this, arguments); if (x == null) delete this[name]; else this[name] = x; } return value == null ? propertyNull : typeof value === "function" ? propertyFunction : propertyConstant; } function d3_selection_dataNode(data) { return { __data__: data }; } function d3_selection_filter(selector) { return function() { return d3_selectMatches(this, selector); }; } function d3_selection_sortComparator(comparator) { if (!arguments.length) comparator = d3.ascending; return function(a, b) { return comparator(a && a.__data__, b && b.__data__); }; } function d3_selection_on(type, listener, capture) { function onRemove() { var wrapper = this[name]; if (wrapper) { this.removeEventListener(type, wrapper, wrapper.$); delete this[name]; } } function onAdd() { function wrapper(e) { var o = d3.event; d3.event = e; args[0] = node.__data__; try { listener.apply(node, args); } finally { d3.event = o; } } var node = this, args = arguments; onRemove.call(this); this.addEventListener(type, this[name] = wrapper, wrapper.$ = capture); wrapper._ = listener; } var name = "__on" + type, i = type.indexOf("."); if (i > 0) type = type.substring(0, i); return listener ? onAdd : onRemove; } function d3_selection_each(groups, callback) { for (var j = 0, m = groups.length; j < m; j++) { for (var group = groups[j], i = 0, n = group.length, node; i < n; i++) { if (node = group[i]) callback(node, i, j); } } return groups; } function d3_selection_enter(selection) { d3_arraySubclass(selection, d3_selection_enterPrototype); return selection; } function d3_transition(groups, id, time) { d3_arraySubclass(groups, d3_transitionPrototype); var tweens = new d3_Map, event = d3.dispatch("start", "end"), ease = d3_transitionEase; groups.id = id; groups.time = time; groups.tween = function(name, tween) { if (arguments.length < 2) return tweens.get(name); if (tween == null) tweens.remove(name); else tweens.set(name, tween); return groups; }; groups.ease = function(value) { if (!arguments.length) return ease; ease = typeof value === "function" ? value : d3.ease.apply(d3, arguments); return groups; }; groups.each = function(type, listener) { if (arguments.length < 2) return d3_transition_each.call(groups, type); event.on(type, listener); return groups; }; d3.timer(function(elapsed) { return d3_selection_each(groups, function(node, i, j) { function start(elapsed) { if (lock.active > id) return stop(); lock.active = id; tweens.forEach(function(key, value) { if (value = value.call(node, d, i)) { tweened.push(value); } }); event.start.call(node, d, i); if (!tick(elapsed)) d3.timer(tick, 0, time); return 1; } function tick(elapsed) { if (lock.active !== id) return stop(); var t = (elapsed - delay) / duration, e = ease(t), n = tweened.length; while (n > 0) { tweened[--n].call(node, e); } if (t >= 1) { stop(); d3_transitionId = id; event.end.call(node, d, i); d3_transitionId = 0; return 1; } } function stop() { if (!--lock.count) delete node.__transition__; return 1; } var tweened = [], delay = node.delay, duration = node.duration, lock = (node = node.node).__transition__ || (node.__transition__ = { active: 0, count: 0 }), d = node.__data__; ++lock.count; delay <= elapsed ? start(elapsed) : d3.timer(start, delay, time); }); }, 0, time); return groups; } function d3_transition_each(callback) { var id = d3_transitionId, ease = d3_transitionEase, delay = d3_transitionDelay, duration = d3_transitionDuration; d3_transitionId = this.id; d3_transitionEase = this.ease(); d3_selection_each(this, function(node, i, j) { d3_transitionDelay = node.delay; d3_transitionDuration = node.duration; callback.call(node = node.node, node.__data__, i, j); }); d3_transitionId = id; d3_transitionEase = ease; d3_transitionDelay = delay; d3_transitionDuration = duration; return this; } function d3_tweenNull(d, i, a) { return a != "" && d3_tweenRemove; } function d3_tweenByName(b, name) { return d3.tween(b, d3_interpolateByName(name)); } function d3_timer_step() { var elapsed, now = Date.now(), t1 = d3_timer_queue; while (t1) { elapsed = now - t1.then; if (elapsed >= t1.delay) t1.flush = t1.callback(elapsed); t1 = t1.next; } var delay = d3_timer_flush() - now; if (delay > 24) { if (isFinite(delay)) { clearTimeout(d3_timer_timeout); d3_timer_timeout = setTimeout(d3_timer_step, delay); } d3_timer_interval = 0; } else { d3_timer_interval = 1; d3_timer_frame(d3_timer_step); } } function d3_timer_flush() { var t0 = null, t1 = d3_timer_queue, then = Infinity; while (t1) { if (t1.flush) { delete d3_timer_byId[t1.callback.id]; t1 = t0 ? t0.next = t1.next : d3_timer_queue = t1.next; } else { then = Math.min(then, t1.then + t1.delay); t1 = (t0 = t1).next; } } return then; } function d3_mousePoint(container, e) { var svg = container.ownerSVGElement || container; if (svg.createSVGPoint) { var point = svg.createSVGPoint(); if (d3_mouse_bug44083 < 0 && (window.scrollX || window.scrollY)) { svg = d3.select(document.body).append("svg").style("position", "absolute").style("top", 0).style("left", 0); var ctm = svg[0][0].getScreenCTM(); d3_mouse_bug44083 = !(ctm.f || ctm.e); svg.remove(); } if (d3_mouse_bug44083) { point.x = e.pageX; point.y = e.pageY; } else { point.x = e.clientX; point.y = e.clientY; } point = point.matrixTransform(container.getScreenCTM().inverse()); return [ point.x, point.y ]; } var rect = container.getBoundingClientRect(); return [ e.clientX - rect.left - container.clientLeft, e.clientY - rect.top - container.clientTop ]; } function d3_noop() {} function d3_scaleExtent(domain) { var start = domain[0], stop = domain[domain.length - 1]; return start < stop ? [ start, stop ] : [ stop, start ]; } function d3_scaleRange(scale) { return scale.rangeExtent ? scale.rangeExtent() : d3_scaleExtent(scale.range()); } function d3_scale_nice(domain, nice) { var i0 = 0, i1 = domain.length - 1, x0 = domain[i0], x1 = domain[i1], dx; if (x1 < x0) { dx = i0, i0 = i1, i1 = dx; dx = x0, x0 = x1, x1 = dx; } if (nice = nice(x1 - x0)) { domain[i0] = nice.floor(x0); domain[i1] = nice.ceil(x1); } return domain; } function d3_scale_niceDefault() { return Math; } function d3_scale_linear(domain, range, interpolate, clamp) { function rescale() { var linear = Math.min(domain.length, range.length) > 2 ? d3_scale_polylinear : d3_scale_bilinear, uninterpolate = clamp ? d3_uninterpolateClamp : d3_uninterpolateNumber; output = linear(domain, range, uninterpolate, interpolate); input = linear(range, domain, uninterpolate, d3.interpolate); return scale; } function scale(x) { return output(x); } var output, input; scale.invert = function(y) { return input(y); }; scale.domain = function(x) { if (!arguments.length) return domain; domain = x.map(Number); return rescale(); }; scale.range = function(x) { if (!arguments.length) return range; range = x; return rescale(); }; scale.rangeRound = function(x) { return scale.range(x).interpolate(d3.interpolateRound); }; scale.clamp = function(x) { if (!arguments.length) return clamp; clamp = x; return rescale(); }; scale.interpolate = function(x) { if (!arguments.length) return interpolate; interpolate = x; return rescale(); }; scale.ticks = function(m) { return d3_scale_linearTicks(domain, m); }; scale.tickFormat = function(m) { return d3_scale_linearTickFormat(domain, m); }; scale.nice = function() { d3_scale_nice(domain, d3_scale_linearNice); return rescale(); }; scale.copy = function() { return d3_scale_linear(domain, range, interpolate, clamp); }; return rescale(); } function d3_scale_linearRebind(scale, linear) { return d3.rebind(scale, linear, "range", "rangeRound", "interpolate", "clamp"); } function d3_scale_linearNice(dx) { dx = Math.pow(10, Math.round(Math.log(dx) / Math.LN10) - 1); return dx && { floor: function(x) { return Math.floor(x / dx) * dx; }, ceil: function(x) { return Math.ceil(x / dx) * dx; } }; } function d3_scale_linearTickRange(domain, m) { var extent = d3_scaleExtent(domain), span = extent[1] - extent[0], step = Math.pow(10, Math.floor(Math.log(span / m) / Math.LN10)), err = m / span * step; if (err <= .15) step *= 10; else if (err <= .35) step *= 5; else if (err <= .75) step *= 2; extent[0] = Math.ceil(extent[0] / step) * step; extent[1] = Math.floor(extent[1] / step) * step + step * .5; extent[2] = step; return extent; } function d3_scale_linearTicks(domain, m) { return d3.range.apply(d3, d3_scale_linearTickRange(domain, m)); } function d3_scale_linearTickFormat(domain, m) { return d3.format(",." + Math.max(0, -Math.floor(Math.log(d3_scale_linearTickRange(domain, m)[2]) / Math.LN10 + .01)) + "f"); } function d3_scale_bilinear(domain, range, uninterpolate, interpolate) { var u = uninterpolate(domain[0], domain[1]), i = interpolate(range[0], range[1]); return function(x) { return i(u(x)); }; } function d3_scale_polylinear(domain, range, uninterpolate, interpolate) { var u = [], i = [], j = 0, k = Math.min(domain.length, range.length) - 1; if (domain[k] < domain[0]) { domain = domain.slice().reverse(); range = range.slice().reverse(); } while (++j <= k) { u.push(uninterpolate(domain[j - 1], domain[j])); i.push(interpolate(range[j - 1], range[j])); } return function(x) { var j = d3.bisect(domain, x, 1, k) - 1; return i[j](u[j](x)); }; } function d3_scale_log(linear, log) { function scale(x) { return linear(log(x)); } var pow = log.pow; scale.invert = function(x) { return pow(linear.invert(x)); }; scale.domain = function(x) { if (!arguments.length) return linear.domain().map(pow); log = x[0] < 0 ? d3_scale_logn : d3_scale_logp; pow = log.pow; linear.domain(x.map(log)); return scale; }; scale.nice = function() { linear.domain(d3_scale_nice(linear.domain(), d3_scale_niceDefault)); return scale; }; scale.ticks = function() { var extent = d3_scaleExtent(linear.domain()), ticks = []; if (extent.every(isFinite)) { var i = Math.floor(extent[0]), j = Math.ceil(extent[1]), u = pow(extent[0]), v = pow(extent[1]); if (log === d3_scale_logn) { ticks.push(pow(i)); for (; i++ < j; ) for (var k = 9; k > 0; k--) ticks.push(pow(i) * k); } else { for (; i < j; i++) for (var k = 1; k < 10; k++) ticks.push(pow(i) * k); ticks.push(pow(i)); } for (i = 0; ticks[i] < u; i++) {} for (j = ticks.length; ticks[j - 1] > v; j--) {} ticks = ticks.slice(i, j); } return ticks; }; scale.tickFormat = function(n, format) { if (arguments.length < 2) format = d3_scale_logFormat; if (arguments.length < 1) return format; var k = Math.max(.1, n / scale.ticks().length), f = log === d3_scale_logn ? (e = -1e-12, Math.floor) : (e = 1e-12, Math.ceil), e; return function(d) { return d / pow(f(log(d) + e)) <= k ? format(d) : ""; }; }; scale.copy = function() { return d3_scale_log(linear.copy(), log); }; return d3_scale_linearRebind(scale, linear); } function d3_scale_logp(x) { return Math.log(x < 0 ? 0 : x) / Math.LN10; } function d3_scale_logn(x) { return -Math.log(x > 0 ? 0 : -x) / Math.LN10; } function d3_scale_pow(linear, exponent) { function scale(x) { return linear(powp(x)); } var powp = d3_scale_powPow(exponent), powb = d3_scale_powPow(1 / exponent); scale.invert = function(x) { return powb(linear.invert(x)); }; scale.domain = function(x) { if (!arguments.length) return linear.domain().map(powb); linear.domain(x.map(powp)); return scale; }; scale.ticks = function(m) { return d3_scale_linearTicks(scale.domain(), m); }; scale.tickFormat = function(m) { return d3_scale_linearTickFormat(scale.domain(), m); }; scale.nice = function() { return scale.domain(d3_scale_nice(scale.domain(), d3_scale_linearNice)); }; scale.exponent = function(x) { if (!arguments.length) return exponent; var domain = scale.domain(); powp = d3_scale_powPow(exponent = x); powb = d3_scale_powPow(1 / exponent); return scale.domain(domain); }; scale.copy = function() { return d3_scale_pow(linear.copy(), exponent); }; return d3_scale_linearRebind(scale, linear); } function d3_scale_powPow(e) { return function(x) { return x < 0 ? -Math.pow(-x, e) : Math.pow(x, e); }; } function d3_scale_ordinal(domain, ranger) { function scale(x) { return range[((index.get(x) || index.set(x, domain.push(x))) - 1) % range.length]; } function steps(start, step) { return d3.range(domain.length).map(function(i) { return start + step * i; }); } var index, range, rangeBand; scale.domain = function(x) { if (!arguments.length) return domain; domain = []; index = new d3_Map; var i = -1, n = x.length, xi; while (++i < n) if (!index.has(xi = x[i])) index.set(xi, domain.push(xi)); return scale[ranger.t].apply(scale, ranger.a); }; scale.range = function(x) { if (!arguments.length) return range; range = x; rangeBand = 0; ranger = { t: "range", a: arguments }; return scale; }; scale.rangePoints = function(x, padding) { if (arguments.length < 2) padding = 0; var start = x[0], stop = x[1], step = (stop - start) / (Math.max(1, domain.length - 1) + padding); range = steps(domain.length < 2 ? (start + stop) / 2 : start + step * padding / 2, step); rangeBand = 0; ranger = { t: "rangePoints", a: arguments }; return scale; }; scale.rangeBands = function(x, padding, outerPadding) { if (arguments.length < 2) padding = 0; if (arguments.length < 3) outerPadding = padding; var reverse = x[1] < x[0], start = x[reverse - 0], stop = x[1 - reverse], step = (stop - start) / (domain.length - padding + 2 * outerPadding); range = steps(start + step * outerPadding, step); if (reverse) range.reverse(); rangeBand = step * (1 - padding); ranger = { t: "rangeBands", a: arguments }; return scale; }; scale.rangeRoundBands = function(x, padding, outerPadding) { if (arguments.length < 2) padding = 0; if (arguments.length < 3) outerPadding = padding; var reverse = x[1] < x[0], start = x[reverse - 0], stop = x[1 - reverse], step = Math.floor((stop - start) / (domain.length - padding + 2 * outerPadding)), error = stop - start - (domain.length - padding) * step; range = steps(start + Math.round(error / 2), step); if (reverse) range.reverse(); rangeBand = Math.round(step * (1 - padding)); ranger = { t: "rangeRoundBands", a: arguments }; return scale; }; scale.rangeBand = function() { return rangeBand; }; scale.rangeExtent = function() { return d3_scaleExtent(ranger.a[0]); }; scale.copy = function() { return d3_scale_ordinal(domain, ranger); }; return scale.domain(domain); } function d3_scale_quantile(domain, range) { function rescale() { var k = 0, n = domain.length, q = range.length; thresholds = []; while (++k < q) thresholds[k - 1] = d3.quantile(domain, k / q); return scale; } function scale(x) { if (isNaN(x = +x)) return NaN; return range[d3.bisect(thresholds, x)]; } var thresholds; scale.domain = function(x) { if (!arguments.length) return domain; domain = x.filter(function(d) { return !isNaN(d); }).sort(d3.ascending); return rescale(); }; scale.range = function(x) { if (!arguments.length) return range; range = x; return rescale(); }; scale.quantiles = function() { return thresholds; }; scale.copy = function() { return d3_scale_quantile(domain, range); }; return rescale(); } function d3_scale_quantize(x0, x1, range) { function scale(x) { return range[Math.max(0, Math.min(i, Math.floor(kx * (x - x0))))]; } function rescale() { kx = range.length / (x1 - x0); i = range.length - 1; return scale; } var kx, i; scale.domain = function(x) { if (!arguments.length) return [ x0, x1 ]; x0 = +x[0]; x1 = +x[x.length - 1]; return rescale(); }; scale.range = function(x) { if (!arguments.length) return range; range = x; return rescale(); }; scale.copy = function() { return d3_scale_quantize(x0, x1, range); }; return rescale(); } function d3_scale_threshold(domain, range) { function scale(x) { return range[d3.bisect(domain, x)]; } scale.domain = function(_) { if (!arguments.length) return domain; domain = _; return scale; }; scale.range = function(_) { if (!arguments.length) return range; range = _; return scale; }; scale.copy = function() { return d3_scale_threshold(domain, range); }; return scale; } function d3_scale_identity(domain) { function identity(x) { return +x; } identity.invert = identity; identity.domain = identity.range = function(x) { if (!arguments.length) return domain; domain = x.map(identity); return identity; }; identity.ticks = function(m) { return d3_scale_linearTicks(domain, m); }; identity.tickFormat = function(m) { return d3_scale_linearTickFormat(domain, m); }; identity.copy = function() { return d3_scale_identity(domain); }; return identity; } function d3_svg_arcInnerRadius(d) { return d.innerRadius; } function d3_svg_arcOuterRadius(d) { return d.outerRadius; } function d3_svg_arcStartAngle(d) { return d.startAngle; } function d3_svg_arcEndAngle(d) { return d.endAngle; } function d3_svg_line(projection) { function line(data) { function segment() { segments.push("M", interpolate(projection(points), tension)); } var segments = [], points = [], i = -1, n = data.length, d, fx = d3_functor(x), fy = d3_functor(y); while (++i < n) { if (defined.call(this, d = data[i], i)) { points.push([ +fx.call(this, d, i), +fy.call(this, d, i) ]); } else if (points.length) { segment(); points = []; } } if (points.length) segment(); return segments.length ? segments.join("") : null; } var x = d3_svg_lineX, y = d3_svg_lineY, defined = d3_true, interpolate = d3_svg_lineLinear, interpolateKey = interpolate.key, tension = .7; line.x = function(_) { if (!arguments.length) return x; x = _; return line; }; line.y = function(_) { if (!arguments.length) return y; y = _; return line; }; line.defined = function(_) { if (!arguments.length) return defined; defined = _; return line; }; line.interpolate = function(_) { if (!arguments.length) return interpolateKey; if (typeof _ === "function") interpolateKey = interpolate = _; else interpolateKey = (interpolate = d3_svg_lineInterpolators.get(_) || d3_svg_lineLinear).key; return line; }; line.tension = function(_) { if (!arguments.length) return tension; tension = _; return line; }; return line; } function d3_svg_lineX(d) { return d[0]; } function d3_svg_lineY(d) { return d[1]; } function d3_svg_lineLinear(points) { return points.join("L"); } function d3_svg_lineLinearClosed(points) { return d3_svg_lineLinear(points) + "Z"; } function d3_svg_lineStepBefore(points) { var i = 0, n = points.length, p = points[0], path = [ p[0], ",", p[1] ]; while (++i < n) path.push("V", (p = points[i])[1], "H", p[0]); return path.join(""); } function d3_svg_lineStepAfter(points) { var i = 0, n = points.length, p = points[0], path = [ p[0], ",", p[1] ]; while (++i < n) path.push("H", (p = points[i])[0], "V", p[1]); return path.join(""); } function d3_svg_lineCardinalOpen(points, tension) { return points.length < 4 ? d3_svg_lineLinear(points) : points[1] + d3_svg_lineHermite(points.slice(1, points.length - 1), d3_svg_lineCardinalTangents(points, tension)); } function d3_svg_lineCardinalClosed(points, tension) { return points.length < 3 ? d3_svg_lineLinear(points) : points[0] + d3_svg_lineHermite((points.push(points[0]), points), d3_svg_lineCardinalTangents([ points[points.length - 2] ].concat(points, [ points[1] ]), tension)); } function d3_svg_lineCardinal(points, tension, closed) { return points.length < 3 ? d3_svg_lineLinear(points) : points[0] + d3_svg_lineHermite(points, d3_svg_lineCardinalTangents(points, tension)); } function d3_svg_lineHermite(points, tangents) { if (tangents.length < 1 || points.length != tangents.length && points.length != tangents.length + 2) { return d3_svg_lineLinear(points); } var quad = points.length != tangents.length, path = "", p0 = points[0], p = points[1], t0 = tangents[0], t = t0, pi = 1; if (quad) { path += "Q" + (p[0] - t0[0] * 2 / 3) + "," + (p[1] - t0[1] * 2 / 3) + "," + p[0] + "," + p[1]; p0 = points[1]; pi = 2; } if (tangents.length > 1) { t = tangents[1]; p = points[pi]; pi++; path += "C" + (p0[0] + t0[0]) + "," + (p0[1] + t0[1]) + "," + (p[0] - t[0]) + "," + (p[1] - t[1]) + "," + p[0] + "," + p[1]; for (var i = 2; i < tangents.length; i++, pi++) { p = points[pi]; t = tangents[i]; path += "S" + (p[0] - t[0]) + "," + (p[1] - t[1]) + "," + p[0] + "," + p[1]; } } if (quad) { var lp = points[pi]; path += "Q" + (p[0] + t[0] * 2 / 3) + "," + (p[1] + t[1] * 2 / 3) + "," + lp[0] + "," + lp[1]; } return path; } function d3_svg_lineCardinalTangents(points, tension) { var tangents = [], a = (1 - tension) / 2, p0, p1 = points[0], p2 = points[1], i = 1, n = points.length; while (++i < n) { p0 = p1; p1 = p2; p2 = points[i]; tangents.push([ a * (p2[0] - p0[0]), a * (p2[1] - p0[1]) ]); } return tangents; } function d3_svg_lineBasis(points) { if (points.length < 3) return d3_svg_lineLinear(points); var i = 1, n = points.length, pi = points[0], x0 = pi[0], y0 = pi[1], px = [ x0, x0, x0, (pi = points[1])[0] ], py = [ y0, y0, y0, pi[1] ], path = [ x0, ",", y0 ]; d3_svg_lineBasisBezier(path, px, py); while (++i < n) { pi = points[i]; px.shift(); px.push(pi[0]); py.shift(); py.push(pi[1]); d3_svg_lineBasisBezier(path, px, py); } i = -1; while (++i < 2) { px.shift(); px.push(pi[0]); py.shift(); py.push(pi[1]); d3_svg_lineBasisBezier(path, px, py); } return path.join(""); } function d3_svg_lineBasisOpen(points) { if (points.length < 4) return d3_svg_lineLinear(points); var path = [], i = -1, n = points.length, pi, px = [ 0 ], py = [ 0 ]; while (++i < 3) { pi = points[i]; px.push(pi[0]); py.push(pi[1]); } path.push(d3_svg_lineDot4(d3_svg_lineBasisBezier3, px) + "," + d3_svg_lineDot4(d3_svg_lineBasisBezier3, py)); --i; while (++i < n) { pi = points[i]; px.shift(); px.push(pi[0]); py.shift(); py.push(pi[1]); d3_svg_lineBasisBezier(path, px, py); } return path.join(""); } function d3_svg_lineBasisClosed(points) { var path, i = -1, n = points.length, m = n + 4, pi, px = [], py = []; while (++i < 4) { pi = points[i % n]; px.push(pi[0]); py.push(pi[1]); } path = [ d3_svg_lineDot4(d3_svg_lineBasisBezier3, px), ",", d3_svg_lineDot4(d3_svg_lineBasisBezier3, py) ]; --i; while (++i < m) { pi = points[i % n]; px.shift(); px.push(pi[0]); py.shift(); py.push(pi[1]); d3_svg_lineBasisBezier(path, px, py); } return path.join(""); } function d3_svg_lineBundle(points, tension) { var n = points.length - 1; if (n) { var x0 = points[0][0], y0 = points[0][1], dx = points[n][0] - x0, dy = points[n][1] - y0, i = -1, p, t; while (++i <= n) { p = points[i]; t = i / n; p[0] = tension * p[0] + (1 - tension) * (x0 + t * dx); p[1] = tension * p[1] + (1 - tension) * (y0 + t * dy); } } return d3_svg_lineBasis(points); } function d3_svg_lineDot4(a, b) { return a[0] * b[0] + a[1] * b[1] + a[2] * b[2] + a[3] * b[3]; } function d3_svg_lineBasisBezier(path, x, y) { path.push("C", d3_svg_lineDot4(d3_svg_lineBasisBezier1, x), ",", d3_svg_lineDot4(d3_svg_lineBasisBezier1, y), ",", d3_svg_lineDot4(d3_svg_lineBasisBezier2, x), ",", d3_svg_lineDot4(d3_svg_lineBasisBezier2, y), ",", d3_svg_lineDot4(d3_svg_lineBasisBezier3, x), ",", d3_svg_lineDot4(d3_svg_lineBasisBezier3, y)); } function d3_svg_lineSlope(p0, p1) { return (p1[1] - p0[1]) / (p1[0] - p0[0]); } function d3_svg_lineFiniteDifferences(points) { var i = 0, j = points.length - 1, m = [], p0 = points[0], p1 = points[1], d = m[0] = d3_svg_lineSlope(p0, p1); while (++i < j) { m[i] = (d + (d = d3_svg_lineSlope(p0 = p1, p1 = points[i + 1]))) / 2; } m[i] = d; return m; } function d3_svg_lineMonotoneTangents(points) { var tangents = [], d, a, b, s, m = d3_svg_lineFiniteDifferences(points), i = -1, j = points.length - 1; while (++i < j) { d = d3_svg_lineSlope(points[i], points[i + 1]); if (Math.abs(d) < 1e-6) { m[i] = m[i + 1] = 0; } else { a = m[i] / d; b = m[i + 1] / d; s = a * a + b * b; if (s > 9) { s = d * 3 / Math.sqrt(s); m[i] = s * a; m[i + 1] = s * b; } } } i = -1; while (++i <= j) { s = (points[Math.min(j, i + 1)][0] - points[Math.max(0, i - 1)][0]) / (6 * (1 + m[i] * m[i])); tangents.push([ s || 0, m[i] * s || 0 ]); } return tangents; } function d3_svg_lineMonotone(points) { return points.length < 3 ? d3_svg_lineLinear(points) : points[0] + d3_svg_lineHermite(points, d3_svg_lineMonotoneTangents(points)); } function d3_svg_lineRadial(points) { var point, i = -1, n = points.length, r, a; while (++i < n) { point = points[i]; r = point[0]; a = point[1] + d3_svg_arcOffset; point[0] = r * Math.cos(a); point[1] = r * Math.sin(a); } return points; } function d3_svg_area(projection) { function area(data) { function segment() { segments.push("M", interpolate(projection(points1), tension), L, interpolateReverse(projection(points0.reverse()), tension), "Z"); } var segments = [], points0 = [], points1 = [], i = -1, n = data.length, d, fx0 = d3_functor(x0), fy0 = d3_functor(y0), fx1 = x0 === x1 ? function() { return x; } : d3_functor(x1), fy1 = y0 === y1 ? function() { return y; } : d3_functor(y1), x, y; while (++i < n) { if (defined.call(this, d = data[i], i)) { points0.push([ x = +fx0.call(this, d, i), y = +fy0.call(this, d, i) ]); points1.push([ +fx1.call(this, d, i), +fy1.call(this, d, i) ]); } else if (points0.length) { segment(); points0 = []; points1 = []; } } if (points0.length) segment(); return segments.length ? segments.join("") : null; } var x0 = d3_svg_lineX, x1 = d3_svg_lineX, y0 = 0, y1 = d3_svg_lineY, defined = d3_true, interpolate = d3_svg_lineLinear, interpolateKey = interpolate.key, interpolateReverse = interpolate, L = "L", tension = .7; area.x = function(_) { if (!arguments.length) return x1; x0 = x1 = _; return area; }; area.x0 = function(_) { if (!arguments.length) return x0; x0 = _; return area; }; area.x1 = function(_) { if (!arguments.length) return x1; x1 = _; return area; }; area.y = function(_) { if (!arguments.length) return y1; y0 = y1 = _; return area; }; area.y0 = function(_) { if (!arguments.length) return y0; y0 = _; return area; }; area.y1 = function(_) { if (!arguments.length) return y1; y1 = _; return area; }; area.defined = function(_) { if (!arguments.length) return defined; defined = _; return area; }; area.interpolate = function(_) { if (!arguments.length) return interpolateKey; if (typeof _ === "function") interpolateKey = interpolate = _; else interpolateKey = (interpolate = d3_svg_lineInterpolators.get(_) || d3_svg_lineLinear).key; interpolateReverse = interpolate.reverse || interpolate; L = interpolate.closed ? "M" : "L"; return area; }; area.tension = function(_) { if (!arguments.length) return tension; tension = _; return area; }; return area; } function d3_svg_chordSource(d) { return d.source; } function d3_svg_chordTarget(d) { return d.target; } function d3_svg_chordRadius(d) { return d.radius; } function d3_svg_chordStartAngle(d) { return d.startAngle; } function d3_svg_chordEndAngle(d) { return d.endAngle; } function d3_svg_diagonalProjection(d) { return [ d.x, d.y ]; } function d3_svg_diagonalRadialProjection(projection) { return function() { var d = projection.apply(this, arguments), r = d[0], a = d[1] + d3_svg_arcOffset; return [ r * Math.cos(a), r * Math.sin(a) ]; }; } function d3_svg_symbolSize() { return 64; } function d3_svg_symbolType() { return "circle"; } function d3_svg_symbolCircle(size) { var r = Math.sqrt(size / Math.PI); return "M0," + r + "A" + r + "," + r + " 0 1,1 0," + -r + "A" + r + "," + r + " 0 1,1 0," + r + "Z"; } function d3_svg_axisX(selection, x) { selection.attr("transform", function(d) { return "translate(" + x(d) + ",0)"; }); } function d3_svg_axisY(selection, y) { selection.attr("transform", function(d) { return "translate(0," + y(d) + ")"; }); } function d3_svg_axisSubdivide(scale, ticks, m) { subticks = []; if (m && ticks.length > 1) { var extent = d3_scaleExtent(scale.domain()), subticks, i = -1, n = ticks.length, d = (ticks[1] - ticks[0]) / ++m, j, v; while (++i < n) { for (j = m; --j > 0; ) { if ((v = +ticks[i] - j * d) >= extent[0]) { subticks.push(v); } } } for (--i, j = 0; ++j < m && (v = +ticks[i] + j * d) < extent[1]; ) { subticks.push(v); } } return subticks; } function d3_behavior_zoomDelta() { if (!d3_behavior_zoomDiv) { d3_behavior_zoomDiv = d3.select("body").append("div").style("visibility", "hidden").style("top", 0).style("height", 0).style("width", 0).style("overflow-y", "scroll").append("div").style("height", "2000px").node().parentNode; } var e = d3.event, delta; try { d3_behavior_zoomDiv.scrollTop = 1e3; d3_behavior_zoomDiv.dispatchEvent(e); delta = 1e3 - d3_behavior_zoomDiv.scrollTop; } catch (error) { delta = e.wheelDelta || -e.detail * 5; } return delta; } function d3_layout_bundlePath(link) { var start = link.source, end = link.target, lca = d3_layout_bundleLeastCommonAncestor(start, end), points = [ start ]; while (start !== lca) { start = start.parent; points.push(start); } var k = points.length; while (end !== lca) { points.splice(k, 0, end); end = end.parent; } return points; } function d3_layout_bundleAncestors(node) { var ancestors = [], parent = node.parent; while (parent != null) { ancestors.push(node); node = parent; parent = parent.parent; } ancestors.push(node); return ancestors; } function d3_layout_bundleLeastCommonAncestor(a, b) { if (a === b) return a; var aNodes = d3_layout_bundleAncestors(a), bNodes = d3_layout_bundleAncestors(b), aNode = aNodes.pop(), bNode = bNodes.pop(), sharedNode = null; while (aNode === bNode) { sharedNode = aNode; aNode = aNodes.pop(); bNode = bNodes.pop(); } return sharedNode; } function d3_layout_forceDragstart(d) { d.fixed |= 2; } function d3_layout_forceDragend(d) { d.fixed &= 1; } function d3_layout_forceMouseover(d) { d.fixed |= 4; } function d3_layout_forceMouseout(d) { d.fixed &= 3; } function d3_layout_forceAccumulate(quad, alpha, charges) { var cx = 0, cy = 0; quad.charge = 0; if (!quad.leaf) { var nodes = quad.nodes, n = nodes.length, i = -1, c; while (++i < n) { c = nodes[i]; if (c == null) continue; d3_layout_forceAccumulate(c, alpha, charges); quad.charge += c.charge; cx += c.charge * c.cx; cy += c.charge * c.cy; } } if (quad.point) { if (!quad.leaf) { quad.point.x += Math.random() - .5; quad.point.y += Math.random() - .5; } var k = alpha * charges[quad.point.index]; quad.charge += quad.pointCharge = k; cx += k * quad.point.x; cy += k * quad.point.y; } quad.cx = cx / quad.charge; quad.cy = cy / quad.charge; } function d3_layout_forceLinkDistance(link) { return 20; } function d3_layout_forceLinkStrength(link) { return 1; } function d3_layout_stackX(d) { return d.x; } function d3_layout_stackY(d) { return d.y; } function d3_layout_stackOut(d, y0, y) { d.y0 = y0; d.y = y; } function d3_layout_stackOrderDefault(data) { return d3.range(data.length); } function d3_layout_stackOffsetZero(data) { var j = -1, m = data[0].length, y0 = []; while (++j < m) y0[j] = 0; return y0; } function d3_layout_stackMaxIndex(array) { var i = 1, j = 0, v = array[0][1], k, n = array.length; for (; i < n; ++i) { if ((k = array[i][1]) > v) { j = i; v = k; } } return j; } function d3_layout_stackReduceSum(d) { return d.reduce(d3_layout_stackSum, 0); } function d3_layout_stackSum(p, d) { return p + d[1]; } function d3_layout_histogramBinSturges(range, values) { return d3_layout_histogramBinFixed(range, Math.ceil(Math.log(values.length) / Math.LN2 + 1)); } function d3_layout_histogramBinFixed(range, n) { var x = -1, b = +range[0], m = (range[1] - b) / n, f = []; while (++x <= n) f[x] = m * x + b; return f; } function d3_layout_histogramRange(values) { return [ d3.min(values), d3.max(values) ]; } function d3_layout_hierarchyRebind(object, hierarchy) { d3.rebind(object, hierarchy, "sort", "children", "value"); object.links = d3_layout_hierarchyLinks; object.nodes = function(d) { d3_layout_hierarchyInline = true; return (object.nodes = object)(d); }; return object; } function d3_layout_hierarchyChildren(d) { return d.children; } function d3_layout_hierarchyValue(d) { return d.value; } function d3_layout_hierarchySort(a, b) { return b.value - a.value; } function d3_layout_hierarchyLinks(nodes) { return d3.merge(nodes.map(function(parent) { return (parent.children || []).map(function(child) { return { source: parent, target: child }; }); })); } function d3_layout_packSort(a, b) { return a.value - b.value; } function d3_layout_packInsert(a, b) { var c = a._pack_next; a._pack_next = b; b._pack_prev = a; b._pack_next = c; c._pack_prev = b; } function d3_layout_packSplice(a, b) { a._pack_next = b; b._pack_prev = a; } function d3_layout_packIntersects(a, b) { var dx = b.x - a.x, dy = b.y - a.y, dr = a.r + b.r; return dr * dr - dx * dx - dy * dy > .001; } function d3_layout_packSiblings(node) { function bound(node) { xMin = Math.min(node.x - node.r, xMin); xMax = Math.max(node.x + node.r, xMax); yMin = Math.min(node.y - node.r, yMin); yMax = Math.max(node.y + node.r, yMax); } if (!(nodes = node.children) || !(n = nodes.length)) return; var nodes, xMin = Infinity, xMax = -Infinity, yMin = Infinity, yMax = -Infinity, a, b, c, i, j, k, n; nodes.forEach(d3_layout_packLink); a = nodes[0]; a.x = -a.r; a.y = 0; bound(a); if (n > 1) { b = nodes[1]; b.x = b.r; b.y = 0; bound(b); if (n > 2) { c = nodes[2]; d3_layout_packPlace(a, b, c); bound(c); d3_layout_packInsert(a, c); a._pack_prev = c; d3_layout_packInsert(c, b); b = a._pack_next; for (i = 3; i < n; i++) { d3_layout_packPlace(a, b, c = nodes[i]); var isect = 0, s1 = 1, s2 = 1; for (j = b._pack_next; j !== b; j = j._pack_next, s1++) { if (d3_layout_packIntersects(j, c)) { isect = 1; break; } } if (isect == 1) { for (k = a._pack_prev; k !== j._pack_prev; k = k._pack_prev, s2++) { if (d3_layout_packIntersects(k, c)) { break; } } } if (isect) { if (s1 < s2 || s1 == s2 && b.r < a.r) d3_layout_packSplice(a, b = j); else d3_layout_packSplice(a = k, b); i--; } else { d3_layout_packInsert(a, c); b = c; bound(c); } } } } var cx = (xMin + xMax) / 2, cy = (yMin + yMax) / 2, cr = 0; for (i = 0; i < n; i++) { c = nodes[i]; c.x -= cx; c.y -= cy; cr = Math.max(cr, c.r + Math.sqrt(c.x * c.x + c.y * c.y)); } node.r = cr; nodes.forEach(d3_layout_packUnlink); } function d3_layout_packLink(node) { node._pack_next = node._pack_prev = node; } function d3_layout_packUnlink(node) { delete node._pack_next; delete node._pack_prev; } function d3_layout_packTransform(node, x, y, k) { var children = node.children; node.x = x += k * node.x; node.y = y += k * node.y; node.r *= k; if (children) { var i = -1, n = children.length; while (++i < n) d3_layout_packTransform(children[i], x, y, k); } } function d3_layout_packPlace(a, b, c) { var db = a.r + c.r, dx = b.x - a.x, dy = b.y - a.y; if (db && (dx || dy)) { var da = b.r + c.r, dc = dx * dx + dy * dy; da *= da; db *= db; var x = .5 + (db - da) / (2 * dc), y = Math.sqrt(Math.max(0, 2 * da * (db + dc) - (db -= dc) * db - da * da)) / (2 * dc); c.x = a.x + x * dx + y * dy; c.y = a.y + x * dy - y * dx; } else { c.x = a.x + db; c.y = a.y; } } function d3_layout_clusterY(children) { return 1 + d3.max(children, function(child) { return child.y; }); } function d3_layout_clusterX(children) { return children.reduce(function(x, child) { return x + child.x; }, 0) / children.length; } function d3_layout_clusterLeft(node) { var children = node.children; return children && children.length ? d3_layout_clusterLeft(children[0]) : node; } function d3_layout_clusterRight(node) { var children = node.children, n; return children && (n = children.length) ? d3_layout_clusterRight(children[n - 1]) : node; } function d3_layout_treeSeparation(a, b) { return a.parent == b.parent ? 1 : 2; } function d3_layout_treeLeft(node) { var children = node.children; return children && children.length ? children[0] : node._tree.thread; } function d3_layout_treeRight(node) { var children = node.children, n; return children && (n = children.length) ? children[n - 1] : node._tree.thread; } function d3_layout_treeSearch(node, compare) { var children = node.children; if (children && (n = children.length)) { var child, n, i = -1; while (++i < n) { if (compare(child = d3_layout_treeSearch(children[i], compare), node) > 0) { node = child; } } } return node; } function d3_layout_treeRightmost(a, b) { return a.x - b.x; } function d3_layout_treeLeftmost(a, b) { return b.x - a.x; } function d3_layout_treeDeepest(a, b) { return a.depth - b.depth; } function d3_layout_treeVisitAfter(node, callback) { function visit(node, previousSibling) { var children = node.children; if (children && (n = children.length)) { var child, previousChild = null, i = -1, n; while (++i < n) { child = children[i]; visit(child, previousChild); previousChild = child; } } callback(node, previousSibling); } visit(node, null); } function d3_layout_treeShift(node) { var shift = 0, change = 0, children = node.children, i = children.length, child; while (--i >= 0) { child = children[i]._tree; child.prelim += shift; child.mod += shift; shift += child.shift + (change += child.change); } } function d3_layout_treeMove(ancestor, node, shift) { ancestor = ancestor._tree; node = node._tree; var change = shift / (node.number - ancestor.number); ancestor.change += change; node.change -= change; node.shift += shift; node.prelim += shift; node.mod += shift; } function d3_layout_treeAncestor(vim, node, ancestor) { return vim._tree.ancestor.parent == node.parent ? vim._tree.ancestor : ancestor; } function d3_layout_treemapPadNull(node) { return { x: node.x, y: node.y, dx: node.dx, dy: node.dy }; } function d3_layout_treemapPad(node, padding) { var x = node.x + padding[3], y = node.y + padding[0], dx = node.dx - padding[1] - padding[3], dy = node.dy - padding[0] - padding[2]; if (dx < 0) { x += dx / 2; dx = 0; } if (dy < 0) { y += dy / 2; dy = 0; } return { x: x, y: y, dx: dx, dy: dy }; } function d3_dsv(delimiter, mimeType) { function dsv(url, callback) { d3.text(url, mimeType, function(text) { callback(text && dsv.parse(text)); }); } function formatRow(row) { return row.map(formatValue).join(delimiter); } function formatValue(text) { return reFormat.test(text) ? '"' + text.replace(/\"/g, '""') + '"' : text; } var reParse = new RegExp("\r\n|[" + delimiter + "\r\n]", "g"), reFormat = new RegExp('["' + delimiter + "\n]"), delimiterCode = delimiter.charCodeAt(0); dsv.parse = function(text) { var header; return dsv.parseRows(text, function(row, i) { if (i) { var o = {}, j = -1, m = header.length; while (++j < m) o[header[j]] = row[j]; return o; } else { header = row; return null; } }); }; dsv.parseRows = function(text, f) { function token() { if (reParse.lastIndex >= text.length) return EOF; if (eol) { eol = false; return EOL; } var j = reParse.lastIndex; if (text.charCodeAt(j) === 34) { var i = j; while (i++ < text.length) { if (text.charCodeAt(i) === 34) { if (text.charCodeAt(i + 1) !== 34) break; i++; } } reParse.lastIndex = i + 2; var c = text.charCodeAt(i + 1); if (c === 13) { eol = true; if (text.charCodeAt(i + 2) === 10) reParse.lastIndex++; } else if (c === 10) { eol = true; } return text.substring(j + 1, i).replace(/""/g, '"'); } var m = reParse.exec(text); if (m) { eol = m[0].charCodeAt(0) !== delimiterCode; return text.substring(j, m.index); } reParse.lastIndex = text.length; return text.substring(j); } var EOL = {}, EOF = {}, rows = [], n = 0, t, eol; reParse.lastIndex = 0; while ((t = token()) !== EOF) { var a = []; while (t !== EOL && t !== EOF) { a.push(t); t = token(); } if (f && !(a = f(a, n++))) continue; rows.push(a); } return rows; }; dsv.format = function(rows) { return rows.map(formatRow).join("\n"); }; return dsv; } function d3_geo_type(types, defaultValue) { return function(object) { return object && types.hasOwnProperty(object.type) ? types[object.type](object) : defaultValue; }; } function d3_path_circle(radius) { return "m0," + radius + "a" + radius + "," + radius + " 0 1,1 0," + -2 * radius + "a" + radius + "," + radius + " 0 1,1 0," + +2 * radius + "z"; } function d3_geo_bounds(o, f) { if (d3_geo_boundsTypes.hasOwnProperty(o.type)) d3_geo_boundsTypes[o.type](o, f); } function d3_geo_boundsFeature(o, f) { d3_geo_bounds(o.geometry, f); } function d3_geo_boundsFeatureCollection(o, f) { for (var a = o.features, i = 0, n = a.length; i < n; i++) { d3_geo_bounds(a[i].geometry, f); } } function d3_geo_boundsGeometryCollection(o, f) { for (var a = o.geometries, i = 0, n = a.length; i < n; i++) { d3_geo_bounds(a[i], f); } } function d3_geo_boundsLineString(o, f) { for (var a = o.coordinates, i = 0, n = a.length; i < n; i++) { f.apply(null, a[i]); } } function d3_geo_boundsMultiLineString(o, f) { for (var a = o.coordinates, i = 0, n = a.length; i < n; i++) { for (var b = a[i], j = 0, m = b.length; j < m; j++) { f.apply(null, b[j]); } } } function d3_geo_boundsMultiPolygon(o, f) { for (var a = o.coordinates, i = 0, n = a.length; i < n; i++) { for (var b = a[i][0], j = 0, m = b.length; j < m; j++) { f.apply(null, b[j]); } } } function d3_geo_boundsPoint(o, f) { f.apply(null, o.coordinates); } function d3_geo_boundsPolygon(o, f) { for (var a = o.coordinates[0], i = 0, n = a.length; i < n; i++) { f.apply(null, a[i]); } } function d3_geo_greatArcSource(d) { return d.source; } function d3_geo_greatArcTarget(d) { return d.target; } function d3_geo_greatArcInterpolator() { function interpolate(t) { var B = Math.sin(t *= d) * k, A = Math.sin(d - t) * k, x = A * kx0 + B * kx1, y = A * ky0 + B * ky1, z = A * sy0 + B * sy1; return [ Math.atan2(y, x) / d3_geo_radians, Math.atan2(z, Math.sqrt(x * x + y * y)) / d3_geo_radians ]; } var x0, y0, cy0, sy0, kx0, ky0, x1, y1, cy1, sy1, kx1, ky1, d, k; interpolate.distance = function() { if (d == null) k = 1 / Math.sin(d = Math.acos(Math.max(-1, Math.min(1, sy0 * sy1 + cy0 * cy1 * Math.cos(x1 - x0))))); return d; }; interpolate.source = function(_) { var cx0 = Math.cos(x0 = _[0] * d3_geo_radians), sx0 = Math.sin(x0); cy0 = Math.cos(y0 = _[1] * d3_geo_radians); sy0 = Math.sin(y0); kx0 = cy0 * cx0; ky0 = cy0 * sx0; d = null; return interpolate; }; interpolate.target = function(_) { var cx1 = Math.cos(x1 = _[0] * d3_geo_radians), sx1 = Math.sin(x1); cy1 = Math.cos(y1 = _[1] * d3_geo_radians); sy1 = Math.sin(y1); kx1 = cy1 * cx1; ky1 = cy1 * sx1; d = null; return interpolate; }; return interpolate; } function d3_geo_greatArcInterpolate(a, b) { var i = d3_geo_greatArcInterpolator().source(a).target(b); i.distance(); return i; } function d3_geom_contourStart(grid) { var x = 0, y = 0; while (true) { if (grid(x, y)) { return [ x, y ]; } if (x === 0) { x = y + 1; y = 0; } else { x = x - 1; y = y + 1; } } } function d3_geom_hullCCW(i1, i2, i3, v) { var t, a, b, c, d, e, f; t = v[i1]; a = t[0]; b = t[1]; t = v[i2]; c = t[0]; d = t[1]; t = v[i3]; e = t[0]; f = t[1]; return (f - b) * (c - a) - (d - b) * (e - a) > 0; } function d3_geom_polygonInside(p, a, b) { return (b[0] - a[0]) * (p[1] - a[1]) < (b[1] - a[1]) * (p[0] - a[0]); } function d3_geom_polygonIntersect(c, d, a, b) { var x1 = c[0], x2 = d[0], x3 = a[0], x4 = b[0], y1 = c[1], y2 = d[1], y3 = a[1], y4 = b[1], x13 = x1 - x3, x21 = x2 - x1, x43 = x4 - x3, y13 = y1 - y3, y21 = y2 - y1, y43 = y4 - y3, ua = (x43 * y13 - y43 * x13) / (y43 * x21 - x43 * y21); return [ x1 + ua * x21, y1 + ua * y21 ]; } function d3_voronoi_tessellate(vertices, callback) { var Sites = { list: vertices.map(function(v, i) { return { index: i, x: v[0], y: v[1] }; }).sort(function(a, b) { return a.y < b.y ? -1 : a.y > b.y ? 1 : a.x < b.x ? -1 : a.x > b.x ? 1 : 0; }), bottomSite: null }; var EdgeList = { list: [], leftEnd: null, rightEnd: null, init: function() { EdgeList.leftEnd = EdgeList.createHalfEdge(null, "l"); EdgeList.rightEnd = EdgeList.createHalfEdge(null, "l"); EdgeList.leftEnd.r = EdgeList.rightEnd; EdgeList.rightEnd.l = EdgeList.leftEnd; EdgeList.list.unshift(EdgeList.leftEnd, EdgeList.rightEnd); }, createHalfEdge: function(edge, side) { return { edge: edge, side: side, vertex: null, l: null, r: null }; }, insert: function(lb, he) { he.l = lb; he.r = lb.r; lb.r.l = he; lb.r = he; }, leftBound: function(p) { var he = EdgeList.leftEnd; do { he = he.r; } while (he != EdgeList.rightEnd && Geom.rightOf(he, p)); he = he.l; return he; }, del: function(he) { he.l.r = he.r; he.r.l = he.l; he.edge = null; }, right: function(he) { return he.r; }, left: function(he) { return he.l; }, leftRegion: function(he) { return he.edge == null ? Sites.bottomSite : he.edge.region[he.side]; }, rightRegion: function(he) { return he.edge == null ? Sites.bottomSite : he.edge.region[d3_voronoi_opposite[he.side]]; } }; var Geom = { bisect: function(s1, s2) { var newEdge = { region: { l: s1, r: s2 }, ep: { l: null, r: null } }; var dx = s2.x - s1.x, dy = s2.y - s1.y, adx = dx > 0 ? dx : -dx, ady = dy > 0 ? dy : -dy; newEdge.c = s1.x * dx + s1.y * dy + (dx * dx + dy * dy) * .5; if (adx > ady) { newEdge.a = 1; newEdge.b = dy / dx; newEdge.c /= dx; } else { newEdge.b = 1; newEdge.a = dx / dy; newEdge.c /= dy; } return newEdge; }, intersect: function(el1, el2) { var e1 = el1.edge, e2 = el2.edge; if (!e1 || !e2 || e1.region.r == e2.region.r) { return null; } var d = e1.a * e2.b - e1.b * e2.a; if (Math.abs(d) < 1e-10) { return null; } var xint = (e1.c * e2.b - e2.c * e1.b) / d, yint = (e2.c * e1.a - e1.c * e2.a) / d, e1r = e1.region.r, e2r = e2.region.r, el, e; if (e1r.y < e2r.y || e1r.y == e2r.y && e1r.x < e2r.x) { el = el1; e = e1; } else { el = el2; e = e2; } var rightOfSite = xint >= e.region.r.x; if (rightOfSite && el.side === "l" || !rightOfSite && el.side === "r") { return null; } return { x: xint, y: yint }; }, rightOf: function(he, p) { var e = he.edge, topsite = e.region.r, rightOfSite = p.x > topsite.x; if (rightOfSite && he.side === "l") { return 1; } if (!rightOfSite && he.side === "r") { return 0; } if (e.a === 1) { var dyp = p.y - topsite.y, dxp = p.x - topsite.x, fast = 0, above = 0; if (!rightOfSite && e.b < 0 || rightOfSite && e.b >= 0) { above = fast = dyp >= e.b * dxp; } else { above = p.x + p.y * e.b > e.c; if (e.b < 0) { above = !above; } if (!above) { fast = 1; } } if (!fast) { var dxs = topsite.x - e.region.l.x; above = e.b * (dxp * dxp - dyp * dyp) < dxs * dyp * (1 + 2 * dxp / dxs + e.b * e.b); if (e.b < 0) { above = !above; } } } else { var yl = e.c - e.a * p.x, t1 = p.y - yl, t2 = p.x - topsite.x, t3 = yl - topsite.y; above = t1 * t1 > t2 * t2 + t3 * t3; } return he.side === "l" ? above : !above; }, endPoint: function(edge, side, site) { edge.ep[side] = site; if (!edge.ep[d3_voronoi_opposite[side]]) return; callback(edge); }, distance: function(s, t) { var dx = s.x - t.x, dy = s.y - t.y; return Math.sqrt(dx * dx + dy * dy); } }; var EventQueue = { list: [], insert: function(he, site, offset) { he.vertex = site; he.ystar = site.y + offset; for (var i = 0, list = EventQueue.list, l = list.length; i < l; i++) { var next = list[i]; if (he.ystar > next.ystar || he.ystar == next.ystar && site.x > next.vertex.x) { continue; } else { break; } } list.splice(i, 0, he); }, del: function(he) { for (var i = 0, ls = EventQueue.list, l = ls.length; i < l && ls[i] != he; ++i) {} ls.splice(i, 1); }, empty: function() { return EventQueue.list.length === 0; }, nextEvent: function(he) { for (var i = 0, ls = EventQueue.list, l = ls.length; i < l; ++i) { if (ls[i] == he) return ls[i + 1]; } return null; }, min: function() { var elem = EventQueue.list[0]; return { x: elem.vertex.x, y: elem.ystar }; }, extractMin: function() { return EventQueue.list.shift(); } }; EdgeList.init(); Sites.bottomSite = Sites.list.shift(); var newSite = Sites.list.shift(), newIntStar; var lbnd, rbnd, llbnd, rrbnd, bisector; var bot, top, temp, p, v; var e, pm; while (true) { if (!EventQueue.empty()) { newIntStar = EventQueue.min(); } if (newSite && (EventQueue.empty() || newSite.y < newIntStar.y || newSite.y == newIntStar.y && newSite.x < newIntStar.x)) { lbnd = EdgeList.leftBound(newSite); rbnd = EdgeList.right(lbnd); bot = EdgeList.rightRegion(lbnd); e = Geom.bisect(bot, newSite); bisector = EdgeList.createHalfEdge(e, "l"); EdgeList.insert(lbnd, bisector); p = Geom.intersect(lbnd, bisector); if (p) { EventQueue.del(lbnd); EventQueue.insert(lbnd, p, Geom.distance(p, newSite)); } lbnd = bisector; bisector = EdgeList.createHalfEdge(e, "r"); EdgeList.insert(lbnd, bisector); p = Geom.intersect(bisector, rbnd); if (p) { EventQueue.insert(bisector, p, Geom.distance(p, newSite)); } newSite = Sites.list.shift(); } else if (!EventQueue.empty()) { lbnd = EventQueue.extractMin(); llbnd = EdgeList.left(lbnd); rbnd = EdgeList.right(lbnd); rrbnd = EdgeList.right(rbnd); bot = EdgeList.leftRegion(lbnd); top = EdgeList.rightRegion(rbnd); v = lbnd.vertex; Geom.endPoint(lbnd.edge, lbnd.side, v); Geom.endPoint(rbnd.edge, rbnd.side, v); EdgeList.del(lbnd); EventQueue.del(rbnd); EdgeList.del(rbnd); pm = "l"; if (bot.y > top.y) { temp = bot; bot = top; top = temp; pm = "r"; } e = Geom.bisect(bot, top); bisector = EdgeList.createHalfEdge(e, pm); EdgeList.insert(llbnd, bisector); Geom.endPoint(e, d3_voronoi_opposite[pm], v); p = Geom.intersect(llbnd, bisector); if (p) { EventQueue.del(llbnd); EventQueue.insert(llbnd, p, Geom.distance(p, bot)); } p = Geom.intersect(bisector, rrbnd); if (p) { EventQueue.insert(bisector, p, Geom.distance(p, bot)); } } else { break; } } for (lbnd = EdgeList.right(EdgeList.leftEnd); lbnd != EdgeList.rightEnd; lbnd = EdgeList.right(lbnd)) { callback(lbnd.edge); } } function d3_geom_quadtreeNode() { return { leaf: true, nodes: [], point: null }; } function d3_geom_quadtreeVisit(f, node, x1, y1, x2, y2) { if (!f(node, x1, y1, x2, y2)) { var sx = (x1 + x2) * .5, sy = (y1 + y2) * .5, children = node.nodes; if (children[0]) d3_geom_quadtreeVisit(f, children[0], x1, y1, sx, sy); if (children[1]) d3_geom_quadtreeVisit(f, children[1], sx, y1, x2, sy); if (children[2]) d3_geom_quadtreeVisit(f, children[2], x1, sy, sx, y2); if (children[3]) d3_geom_quadtreeVisit(f, children[3], sx, sy, x2, y2); } } function d3_geom_quadtreePoint(p) { return { x: p[0], y: p[1] }; } function d3_time_utc() { this._ = new Date(arguments.length > 1 ? Date.UTC.apply(this, arguments) : arguments[0]); } function d3_time_formatAbbreviate(name) { return name.substring(0, 3); } function d3_time_parse(date, template, string, j) { var c, p, i = 0, n = template.length, m = string.length; while (i < n) { if (j >= m) return -1; c = template.charCodeAt(i++); if (c == 37) { p = d3_time_parsers[template.charAt(i++)]; if (!p || (j = p(date, string, j)) < 0) return -1; } else if (c != string.charCodeAt(j++)) { return -1; } } return j; } function d3_time_formatRe(names) { return new RegExp("^(?:" + names.map(d3.requote).join("|") + ")", "i"); } function d3_time_formatLookup(names) { var map = new d3_Map, i = -1, n = names.length; while (++i < n) map.set(names[i].toLowerCase(), i); return map; } function d3_time_parseWeekdayAbbrev(date, string, i) { d3_time_dayAbbrevRe.lastIndex = 0; var n = d3_time_dayAbbrevRe.exec(string.substring(i)); return n ? i += n[0].length : -1; } function d3_time_parseWeekday(date, string, i) { d3_time_dayRe.lastIndex = 0; var n = d3_time_dayRe.exec(string.substring(i)); return n ? i += n[0].length : -1; } function d3_time_parseMonthAbbrev(date, string, i) { d3_time_monthAbbrevRe.lastIndex = 0; var n = d3_time_monthAbbrevRe.exec(string.substring(i)); return n ? (date.m = d3_time_monthAbbrevLookup.get(n[0].toLowerCase()), i += n[0].length) : -1; } function d3_time_parseMonth(date, string, i) { d3_time_monthRe.lastIndex = 0; var n = d3_time_monthRe.exec(string.substring(i)); return n ? (date.m = d3_time_monthLookup.get(n[0].toLowerCase()), i += n[0].length) : -1; } function d3_time_parseLocaleFull(date, string, i) { return d3_time_parse(date, d3_time_formats.c.toString(), string, i); } function d3_time_parseLocaleDate(date, string, i) { return d3_time_parse(date, d3_time_formats.x.toString(), string, i); } function d3_time_parseLocaleTime(date, string, i) { return d3_time_parse(date, d3_time_formats.X.toString(), string, i); } function d3_time_parseFullYear(date, string, i) { d3_time_numberRe.lastIndex = 0; var n = d3_time_numberRe.exec(string.substring(i, i + 4)); return n ? (date.y = +n[0], i += n[0].length) : -1; } function d3_time_parseYear(date, string, i) { d3_time_numberRe.lastIndex = 0; var n = d3_time_numberRe.exec(string.substring(i, i + 2)); return n ? (date.y = d3_time_expandYear(+n[0]), i += n[0].length) : -1; } function d3_time_expandYear(d) { return d + (d > 68 ? 1900 : 2e3); } function d3_time_parseMonthNumber(date, string, i) { d3_time_numberRe.lastIndex = 0; var n = d3_time_numberRe.exec(string.substring(i, i + 2)); return n ? (date.m = n[0] - 1, i += n[0].length) : -1; } function d3_time_parseDay(date, string, i) { d3_time_numberRe.lastIndex = 0; var n = d3_time_numberRe.exec(string.substring(i, i + 2)); return n ? (date.d = +n[0], i += n[0].length) : -1; } function d3_time_parseHour24(date, string, i) { d3_time_numberRe.lastIndex = 0; var n = d3_time_numberRe.exec(string.substring(i, i + 2)); return n ? (date.H = +n[0], i += n[0].length) : -1; } function d3_time_parseMinutes(date, string, i) { d3_time_numberRe.lastIndex = 0; var n = d3_time_numberRe.exec(string.substring(i, i + 2)); return n ? (date.M = +n[0], i += n[0].length) : -1; } function d3_time_parseSeconds(date, string, i) { d3_time_numberRe.lastIndex = 0; var n = d3_time_numberRe.exec(string.substring(i, i + 2)); return n ? (date.S = +n[0], i += n[0].length) : -1; } function d3_time_parseMilliseconds(date, string, i) { d3_time_numberRe.lastIndex = 0; var n = d3_time_numberRe.exec(string.substring(i, i + 3)); return n ? (date.L = +n[0], i += n[0].length) : -1; } function d3_time_parseAmPm(date, string, i) { var n = d3_time_amPmLookup.get(string.substring(i, i += 2).toLowerCase()); return n == null ? -1 : (date.p = n, i); } function d3_time_zone(d) { var z = d.getTimezoneOffset(), zs = z > 0 ? "-" : "+", zh = ~~(Math.abs(z) / 60), zm = Math.abs(z) % 60; return zs + d3_time_zfill2(zh) + d3_time_zfill2(zm); } function d3_time_formatIsoNative(date) { return date.toISOString(); } function d3_time_interval(local, step, number) { function round(date) { var d0 = local(date), d1 = offset(d0, 1); return date - d0 < d1 - date ? d0 : d1; } function ceil(date) { step(date = local(new d3_time(date - 1)), 1); return date; } function offset(date, k) { step(date = new d3_time(+date), k); return date; } function range(t0, t1, dt) { var time = ceil(t0), times = []; if (dt > 1) { while (time < t1) { if (!(number(time) % dt)) times.push(new Date(+time)); step(time, 1); } } else { while (time < t1) times.push(new Date(+time)), step(time, 1); } return times; } function range_utc(t0, t1, dt) { try { d3_time = d3_time_utc; var utc = new d3_time_utc; utc._ = t0; return range(utc, t1, dt); } finally { d3_time = Date; } } local.floor = local; local.round = round; local.ceil = ceil; local.offset = offset; local.range = range; var utc = local.utc = d3_time_interval_utc(local); utc.floor = utc; utc.round = d3_time_interval_utc(round); utc.ceil = d3_time_interval_utc(ceil); utc.offset = d3_time_interval_utc(offset); utc.range = range_utc; return local; } function d3_time_interval_utc(method) { return function(date, k) { try { d3_time = d3_time_utc; var utc = new d3_time_utc; utc._ = date; return method(utc, k)._; } finally { d3_time = Date; } }; } function d3_time_scale(linear, methods, format) { function scale(x) { return linear(x); } scale.invert = function(x) { return d3_time_scaleDate(linear.invert(x)); }; scale.domain = function(x) { if (!arguments.length) return linear.domain().map(d3_time_scaleDate); linear.domain(x); return scale; }; scale.nice = function(m) { return scale.domain(d3_scale_nice(scale.domain(), function() { return m; })); }; scale.ticks = function(m, k) { var extent = d3_time_scaleExtent(scale.domain()); if (typeof m !== "function") { var span = extent[1] - extent[0], target = span / m, i = d3.bisect(d3_time_scaleSteps, target); if (i == d3_time_scaleSteps.length) return methods.year(extent, m); if (!i) return linear.ticks(m).map(d3_time_scaleDate); if (Math.log(target / d3_time_scaleSteps[i - 1]) < Math.log(d3_time_scaleSteps[i] / target)) --i; m = methods[i]; k = m[1]; m = m[0].range; } return m(extent[0], new Date(+extent[1] + 1), k); }; scale.tickFormat = function() { return format; }; scale.copy = function() { return d3_time_scale(linear.copy(), methods, format); }; return d3.rebind(scale, linear, "range", "rangeRound", "interpolate", "clamp"); } function d3_time_scaleExtent(domain) { var start = domain[0], stop = domain[domain.length - 1]; return start < stop ? [ start, stop ] : [ stop, start ]; } function d3_time_scaleDate(t) { return new Date(t); } function d3_time_scaleFormat(formats) { return function(date) { var i = formats.length - 1, f = formats[i]; while (!f[1](date)) f = formats[--i]; return f[0](date); }; } function d3_time_scaleSetYear(y) { var d = new Date(y, 0, 1); d.setFullYear(y); return d; } function d3_time_scaleGetYear(d) { var y = d.getFullYear(), d0 = d3_time_scaleSetYear(y), d1 = d3_time_scaleSetYear(y + 1); return y + (d - d0) / (d1 - d0); } function d3_time_scaleUTCSetYear(y) { var d = new Date(Date.UTC(y, 0, 1)); d.setUTCFullYear(y); return d; } function d3_time_scaleUTCGetYear(d) { var y = d.getUTCFullYear(), d0 = d3_time_scaleUTCSetYear(y), d1 = d3_time_scaleUTCSetYear(y + 1); return y + (d - d0) / (d1 - d0); } if (!Date.now) Date.now = function() { return +(new Date); }; try { document.createElement("div").style.setProperty("opacity", 0, ""); } catch (error) { var d3_style_prototype = CSSStyleDeclaration.prototype, d3_style_setProperty = d3_style_prototype.setProperty; d3_style_prototype.setProperty = function(name, value, priority) { d3_style_setProperty.call(this, name, value + "", priority); }; } d3 = { version: "2.10.3" }; var d3_array = d3_arraySlice; try { d3_array(document.documentElement.childNodes)[0].nodeType; } catch (e) { d3_array = d3_arrayCopy; } var d3_arraySubclass = [].__proto__ ? function(array, prototype) { array.__proto__ = prototype; } : function(array, prototype) { for (var property in prototype) array[property] = prototype[property]; }; d3.map = function(object) { var map = new d3_Map; for (var key in object) map.set(key, object[key]); return map; }; d3_class(d3_Map, { has: function(key) { return d3_map_prefix + key in this; }, get: function(key) { return this[d3_map_prefix + key]; }, set: function(key, value) { return this[d3_map_prefix + key] = value; }, remove: function(key) { key = d3_map_prefix + key; return key in this && delete this[key]; }, keys: function() { var keys = []; this.forEach(function(key) { keys.push(key); }); return keys; }, values: function() { var values = []; this.forEach(function(key, value) { values.push(value); }); return values; }, entries: function() { var entries = []; this.forEach(function(key, value) { entries.push({ key: key, value: value }); }); return entries; }, forEach: function(f) { for (var key in this) { if (key.charCodeAt(0) === d3_map_prefixCode) { f.call(this, key.substring(1), this[key]); } } } }); var d3_map_prefix = "\0", d3_map_prefixCode = d3_map_prefix.charCodeAt(0); d3.functor = d3_functor; d3.rebind = function(target, source) { var i = 1, n = arguments.length, method; while (++i < n) target[method = arguments[i]] = d3_rebind(target, source, source[method]); return target; }; d3.ascending = function(a, b) { return a < b ? -1 : a > b ? 1 : a >= b ? 0 : NaN; }; d3.descending = function(a, b) { return b < a ? -1 : b > a ? 1 : b >= a ? 0 : NaN; }; d3.mean = function(array, f) { var n = array.length, a, m = 0, i = -1, j = 0; if (arguments.length === 1) { while (++i < n) if (d3_number(a = array[i])) m += (a - m) / ++j; } else { while (++i < n) if (d3_number(a = f.call(array, array[i], i))) m += (a - m) / ++j; } return j ? m : undefined; }; d3.median = function(array, f) { if (arguments.length > 1) array = array.map(f); array = array.filter(d3_number); return array.length ? d3.quantile(array.sort(d3.ascending), .5) : undefined; }; d3.min = function(array, f) { var i = -1, n = array.length, a, b; if (arguments.length === 1) { while (++i < n && ((a = array[i]) == null || a != a)) a = undefined; while (++i < n) if ((b = array[i]) != null && a > b) a = b; } else { while (++i < n && ((a = f.call(array, array[i], i)) == null || a != a)) a = undefined; while (++i < n) if ((b = f.call(array, array[i], i)) != null && a > b) a = b; } return a; }; d3.max = function(array, f) { var i = -1, n = array.length, a, b; if (arguments.length === 1) { while (++i < n && ((a = array[i]) == null || a != a)) a = undefined; while (++i < n) if ((b = array[i]) != null && b > a) a = b; } else { while (++i < n && ((a = f.call(array, array[i], i)) == null || a != a)) a = undefined; while (++i < n) if ((b = f.call(array, array[i], i)) != null && b > a) a = b; } return a; }; d3.extent = function(array, f) { var i = -1, n = array.length, a, b, c; if (arguments.length === 1) { while (++i < n && ((a = c = array[i]) == null || a != a)) a = c = undefined; while (++i < n) if ((b = array[i]) != null) { if (a > b) a = b; if (c < b) c = b; } } else { while (++i < n && ((a = c = f.call(array, array[i], i)) == null || a != a)) a = undefined; while (++i < n) if ((b = f.call(array, array[i], i)) != null) { if (a > b) a = b; if (c < b) c = b; } } return [ a, c ]; }; d3.random = { normal: function(µ, σ) { var n = arguments.length; if (n < 2) σ = 1; if (n < 1) µ = 0; return function() { var x, y, r; do { x = Math.random() * 2 - 1; y = Math.random() * 2 - 1; r = x * x + y * y; } while (!r || r > 1); return µ + σ * x * Math.sqrt(-2 * Math.log(r) / r); }; }, logNormal: function(µ, σ) { var n = arguments.length; if (n < 2) σ = 1; if (n < 1) µ = 0; var random = d3.random.normal(); return function() { return Math.exp(µ + σ * random()); }; }, irwinHall: function(m) { return function() { for (var s = 0, j = 0; j < m; j++) s += Math.random(); return s / m; }; } }; d3.sum = function(array, f) { var s = 0, n = array.length, a, i = -1; if (arguments.length === 1) { while (++i < n) if (!isNaN(a = +array[i])) s += a; } else { while (++i < n) if (!isNaN(a = +f.call(array, array[i], i))) s += a; } return s; }; d3.quantile = function(values, p) { var H = (values.length - 1) * p + 1, h = Math.floor(H), v = values[h - 1], e = H - h; return e ? v + e * (values[h] - v) : v; }; d3.transpose = function(matrix) { return d3.zip.apply(d3, matrix); }; d3.zip = function() { if (!(n = arguments.length)) return []; for (var i = -1, m = d3.min(arguments, d3_zipLength), zips = new Array(m); ++i < m; ) { for (var j = -1, n, zip = zips[i] = new Array(n); ++j < n; ) { zip[j] = arguments[j][i]; } } return zips; }; d3.bisector = function(f) { return { left: function(a, x, lo, hi) { if (arguments.length < 3) lo = 0; if (arguments.length < 4) hi = a.length; while (lo < hi) { var mid = lo + hi >>> 1; if (f.call(a, a[mid], mid) < x) lo = mid + 1; else hi = mid; } return lo; }, right: function(a, x, lo, hi) { if (arguments.length < 3) lo = 0; if (arguments.length < 4) hi = a.length; while (lo < hi) { var mid = lo + hi >>> 1; if (x < f.call(a, a[mid], mid)) hi = mid; else lo = mid + 1; } return lo; } }; }; var d3_bisector = d3.bisector(function(d) { return d; }); d3.bisectLeft = d3_bisector.left; d3.bisect = d3.bisectRight = d3_bisector.right; d3.first = function(array, f) { var i = 0, n = array.length, a = array[0], b; if (arguments.length === 1) f = d3.ascending; while (++i < n) { if (f.call(array, a, b = array[i]) > 0) { a = b; } } return a; }; d3.last = function(array, f) { var i = 0, n = array.length, a = array[0], b; if (arguments.length === 1) f = d3.ascending; while (++i < n) { if (f.call(array, a, b = array[i]) <= 0) { a = b; } } return a; }; d3.nest = function() { function map(array, depth) { if (depth >= keys.length) return rollup ? rollup.call(nest, array) : sortValues ? array.sort(sortValues) : array; var i = -1, n = array.length, key = keys[depth++], keyValue, object, valuesByKey = new d3_Map, values, o = {}; while (++i < n) { if (values = valuesByKey.get(keyValue = key(object = array[i]))) { values.push(object); } else { valuesByKey.set(keyValue, [ object ]); } } valuesByKey.forEach(function(keyValue, values) { o[keyValue] = map(values, depth); }); return o; } function entries(map, depth) { if (depth >= keys.length) return map; var a = [], sortKey = sortKeys[depth++], key; for (key in map) { a.push({ key: key, values: entries(map[key], depth) }); } if (sortKey) a.sort(function(a, b) { return sortKey(a.key, b.key); }); return a; } var nest = {}, keys = [], sortKeys = [], sortValues, rollup; nest.map = function(array) { return map(array, 0); }; nest.entries = function(array) { return entries(map(array, 0), 0); }; nest.key = function(d) { keys.push(d); return nest; }; nest.sortKeys = function(order) { sortKeys[keys.length - 1] = order; return nest; }; nest.sortValues = function(order) { sortValues = order; return nest; }; nest.rollup = function(f) { rollup = f; return nest; }; return nest; }; d3.keys = function(map) { var keys = []; for (var key in map) keys.push(key); return keys; }; d3.values = function(map) { var values = []; for (var key in map) values.push(map[key]); return values; }; d3.entries = function(map) { var entries = []; for (var key in map) entries.push({ key: key, value: map[key] }); return entries; }; d3.permute = function(array, indexes) { var permutes = [], i = -1, n = indexes.length; while (++i < n) permutes[i] = array[indexes[i]]; return permutes; }; d3.merge = function(arrays) { return Array.prototype.concat.apply([], arrays); }; d3.split = function(array, f) { var arrays = [], values = [], value, i = -1, n = array.length; if (arguments.length < 2) f = d3_splitter; while (++i < n) { if (f.call(values, value = array[i], i)) { values = []; } else { if (!values.length) arrays.push(values); values.push(value); } } return arrays; }; d3.range = function(start, stop, step) { if (arguments.length < 3) { step = 1; if (arguments.length < 2) { stop = start; start = 0; } } if ((stop - start) / step === Infinity) throw new Error("infinite range"); var range = [], k = d3_range_integerScale(Math.abs(step)), i = -1, j; start *= k, stop *= k, step *= k; if (step < 0) while ((j = start + step * ++i) > stop) range.push(j / k); else while ((j = start + step * ++i) < stop) range.push(j / k); return range; }; d3.requote = function(s) { return s.replace(d3_requote_re, "\\$&"); }; var d3_requote_re = /[\\\^\$\*\+\?\|\[\]\(\)\.\{\}]/g; d3.round = function(x, n) { return n ? Math.round(x * (n = Math.pow(10, n))) / n : Math.round(x); }; d3.xhr = function(url, mime, callback) { var req = new XMLHttpRequest; if (arguments.length < 3) callback = mime, mime = null; else if (mime && req.overrideMimeType) req.overrideMimeType(mime); req.open("GET", url, true); if (mime) req.setRequestHeader("Accept", mime); req.onreadystatechange = function() { if (req.readyState === 4) { var s = req.status; callback(!s && req.response || s >= 200 && s < 300 || s === 304 ? req : null); } }; req.send(null); }; d3.text = function(url, mime, callback) { function ready(req) { callback(req && req.responseText); } if (arguments.length < 3) { callback = mime; mime = null; } d3.xhr(url, mime, ready); }; d3.json = function(url, callback) { d3.text(url, "application/json", function(text) { callback(text ? JSON.parse(text) : null); }); }; d3.html = function(url, callback) { d3.text(url, "text/html", function(text) { if (text != null) { var range = document.createRange(); range.selectNode(document.body); text = range.createContextualFragment(text); } callback(text); }); }; d3.xml = function(url, mime, callback) { function ready(req) { callback(req && req.responseXML); } if (arguments.length < 3) { callback = mime; mime = null; } d3.xhr(url, mime, ready); }; var d3_nsPrefix = { svg: "http://www.w3.org/2000/svg", xhtml: "http://www.w3.org/1999/xhtml", xlink: "http://www.w3.org/1999/xlink", xml: "http://www.w3.org/XML/1998/namespace", xmlns: "http://www.w3.org/2000/xmlns/" }; d3.ns = { prefix: d3_nsPrefix, qualify: function(name) { var i = name.indexOf(":"), prefix = name; if (i >= 0) { prefix = name.substring(0, i); name = name.substring(i + 1); } return d3_nsPrefix.hasOwnProperty(prefix) ? { space: d3_nsPrefix[prefix], local: name } : name; } }; d3.dispatch = function() { var dispatch = new d3_dispatch, i = -1, n = arguments.length; while (++i < n) dispatch[arguments[i]] = d3_dispatch_event(dispatch); return dispatch; }; d3_dispatch.prototype.on = function(type, listener) { var i = type.indexOf("."), name = ""; if (i > 0) { name = type.substring(i + 1); type = type.substring(0, i); } return arguments.length < 2 ? this[type].on(name) : this[type].on(name, listener); }; d3.format = function(specifier) { var match = d3_format_re.exec(specifier), fill = match[1] || " ", sign = match[3] || "", zfill = match[5], width = +match[6], comma = match[7], precision = match[8], type = match[9], scale = 1, suffix = "", integer = false; if (precision) precision = +precision.substring(1); if (zfill) { fill = "0"; if (comma) width -= Math.floor((width - 1) / 4); } switch (type) { case "n": comma = true; type = "g"; break; case "%": scale = 100; suffix = "%"; type = "f"; break; case "p": scale = 100; suffix = "%"; type = "r"; break; case "d": integer = true; precision = 0; break; case "s": scale = -1; type = "r"; break; } if (type == "r" && !precision) type = "g"; type = d3_format_types.get(type) || d3_format_typeDefault; return function(value) { if (integer && value % 1) return ""; var negative = value < 0 && (value = -value) ? "-" : sign; if (scale < 0) { var prefix = d3.formatPrefix(value, precision); value = prefix.scale(value); suffix = prefix.symbol; } else { value *= scale; } value = type(value, precision); if (zfill) { var length = value.length + negative.length; if (length < width) value = (new Array(width - length + 1)).join(fill) + value; if (comma) value = d3_format_group(value); value = negative + value; } else { if (comma) value = d3_format_group(value); value = negative + value; var length = value.length; if (length < width) value = (new Array(width - length + 1)).join(fill) + value; } return value + suffix; }; }; var d3_format_re = /(?:([^{])?([<>=^]))?([+\- ])?(#)?(0)?([0-9]+)?(,)?(\.[0-9]+)?([a-zA-Z%])?/; var d3_format_types = d3.map({ g: function(x, p) { return x.toPrecision(p); }, e: function(x, p) { return x.toExponential(p); }, f: function(x, p) { return x.toFixed(p); }, r: function(x, p) { return d3.round(x, p = d3_format_precision(x, p)).toFixed(Math.max(0, Math.min(20, p))); } }); var d3_formatPrefixes = [ "y", "z", "a", "f", "p", "n", "μ", "m", "", "k", "M", "G", "T", "P", "E", "Z", "Y" ].map(d3_formatPrefix); d3.formatPrefix = function(value, precision) { var i = 0; if (value) { if (value < 0) value *= -1; if (precision) value = d3.round(value, d3_format_precision(value, precision)); i = 1 + Math.floor(1e-12 + Math.log(value) / Math.LN10); i = Math.max(-24, Math.min(24, Math.floor((i <= 0 ? i + 1 : i - 1) / 3) * 3)); } return d3_formatPrefixes[8 + i / 3]; }; var d3_ease_quad = d3_ease_poly(2), d3_ease_cubic = d3_ease_poly(3), d3_ease_default = function() { return d3_ease_identity; }; var d3_ease = d3.map({ linear: d3_ease_default, poly: d3_ease_poly, quad: function() { return d3_ease_quad; }, cubic: function() { return d3_ease_cubic; }, sin: function() { return d3_ease_sin; }, exp: function() { return d3_ease_exp; }, circle: function() { return d3_ease_circle; }, elastic: d3_ease_elastic, back: d3_ease_back, bounce: function() { return d3_ease_bounce; } }); var d3_ease_mode = d3.map({ "in": d3_ease_identity, out: d3_ease_reverse, "in-out": d3_ease_reflect, "out-in": function(f) { return d3_ease_reflect(d3_ease_reverse(f)); } }); d3.ease = function(name) { var i = name.indexOf("-"), t = i >= 0 ? name.substring(0, i) : name, m = i >= 0 ? name.substring(i + 1) : "in"; t = d3_ease.get(t) || d3_ease_default; m = d3_ease_mode.get(m) || d3_ease_identity; return d3_ease_clamp(m(t.apply(null, Array.prototype.slice.call(arguments, 1)))); }; d3.event = null; d3.transform = function(string) { var g = document.createElementNS(d3.ns.prefix.svg, "g"); return (d3.transform = function(string) { g.setAttribute("transform", string); var t = g.transform.baseVal.consolidate(); return new d3_transform(t ? t.matrix : d3_transformIdentity); })(string); }; d3_transform.prototype.toString = function() { return "translate(" + this.translate + ")rotate(" + this.rotate + ")skewX(" + this.skew + ")scale(" + this.scale + ")"; }; var d3_transformDegrees = 180 / Math.PI, d3_transformIdentity = { a: 1, b: 0, c: 0, d: 1, e: 0, f: 0 }; d3.interpolate = function(a, b) { var i = d3.interpolators.length, f; while (--i >= 0 && !(f = d3.interpolators[i](a, b))) ; return f; }; d3.interpolateNumber = function(a, b) { b -= a; return function(t) { return a + b * t; }; }; d3.interpolateRound = function(a, b) { b -= a; return function(t) { return Math.round(a + b * t); }; }; d3.interpolateString = function(a, b) { var m, i, j, s0 = 0, s1 = 0, s = [], q = [], n, o; d3_interpolate_number.lastIndex = 0; for (i = 0; m = d3_interpolate_number.exec(b); ++i) { if (m.index) s.push(b.substring(s0, s1 = m.index)); q.push({ i: s.length, x: m[0] }); s.push(null); s0 = d3_interpolate_number.lastIndex; } if (s0 < b.length) s.push(b.substring(s0)); for (i = 0, n = q.length; (m = d3_interpolate_number.exec(a)) && i < n; ++i) { o = q[i]; if (o.x == m[0]) { if (o.i) { if (s[o.i + 1] == null) { s[o.i - 1] += o.x; s.splice(o.i, 1); for (j = i + 1; j < n; ++j) q[j].i--; } else { s[o.i - 1] += o.x + s[o.i + 1]; s.splice(o.i, 2); for (j = i + 1; j < n; ++j) q[j].i -= 2; } } else { if (s[o.i + 1] == null) { s[o.i] = o.x; } else { s[o.i] = o.x + s[o.i + 1]; s.splice(o.i + 1, 1); for (j = i + 1; j < n; ++j) q[j].i--; } } q.splice(i, 1); n--; i--; } else { o.x = d3.interpolateNumber(parseFloat(m[0]), parseFloat(o.x)); } } while (i < n) { o = q.pop(); if (s[o.i + 1] == null) { s[o.i] = o.x; } else { s[o.i] = o.x + s[o.i + 1]; s.splice(o.i + 1, 1); } n--; } if (s.length === 1) { return s[0] == null ? q[0].x : function() { return b; }; } return function(t) { for (i = 0; i < n; ++i) s[(o = q[i]).i] = o.x(t); return s.join(""); }; }; d3.interpolateTransform = function(a, b) { var s = [], q = [], n, A = d3.transform(a), B = d3.transform(b), ta = A.translate, tb = B.translate, ra = A.rotate, rb = B.rotate, wa = A.skew, wb = B.skew, ka = A.scale, kb = B.scale; if (ta[0] != tb[0] || ta[1] != tb[1]) { s.push("translate(", null, ",", null, ")"); q.push({ i: 1, x: d3.interpolateNumber(ta[0], tb[0]) }, { i: 3, x: d3.interpolateNumber(ta[1], tb[1]) }); } else if (tb[0] || tb[1]) { s.push("translate(" + tb + ")"); } else { s.push(""); } if (ra != rb) { if (ra - rb > 180) rb += 360; else if (rb - ra > 180) ra += 360; q.push({ i: s.push(s.pop() + "rotate(", null, ")") - 2, x: d3.interpolateNumber(ra, rb) }); } else if (rb) { s.push(s.pop() + "rotate(" + rb + ")"); } if (wa != wb) { q.push({ i: s.push(s.pop() + "skewX(", null, ")") - 2, x: d3.interpolateNumber(wa, wb) }); } else if (wb) { s.push(s.pop() + "skewX(" + wb + ")"); } if (ka[0] != kb[0] || ka[1] != kb[1]) { n = s.push(s.pop() + "scale(", null, ",", null, ")"); q.push({ i: n - 4, x: d3.interpolateNumber(ka[0], kb[0]) }, { i: n - 2, x: d3.interpolateNumber(ka[1], kb[1]) }); } else if (kb[0] != 1 || kb[1] != 1) { s.push(s.pop() + "scale(" + kb + ")"); } n = q.length; return function(t) { var i = -1, o; while (++i < n) s[(o = q[i]).i] = o.x(t); return s.join(""); }; }; d3.interpolateRgb = function(a, b) { a = d3.rgb(a); b = d3.rgb(b); var ar = a.r, ag = a.g, ab = a.b, br = b.r - ar, bg = b.g - ag, bb = b.b - ab; return function(t) { return "#" + d3_rgb_hex(Math.round(ar + br * t)) + d3_rgb_hex(Math.round(ag + bg * t)) + d3_rgb_hex(Math.round(ab + bb * t)); }; }; d3.interpolateHsl = function(a, b) { a = d3.hsl(a); b = d3.hsl(b); var h0 = a.h, s0 = a.s, l0 = a.l, h1 = b.h - h0, s1 = b.s - s0, l1 = b.l - l0; if (h1 > 180) h1 -= 360; else if (h1 < -180) h1 += 360; return function(t) { return d3_hsl_rgb(h0 + h1 * t, s0 + s1 * t, l0 + l1 * t) + ""; }; }; d3.interpolateLab = function(a, b) { a = d3.lab(a); b = d3.lab(b); var al = a.l, aa = a.a, ab = a.b, bl = b.l - al, ba = b.a - aa, bb = b.b - ab; return function(t) { return d3_lab_rgb(al + bl * t, aa + ba * t, ab + bb * t) + ""; }; }; d3.interpolateHcl = function(a, b) { a = d3.hcl(a); b = d3.hcl(b); var ah = a.h, ac = a.c, al = a.l, bh = b.h - ah, bc = b.c - ac, bl = b.l - al; if (bh > 180) bh -= 360; else if (bh < -180) bh += 360; return function(t) { return d3_hcl_lab(ah + bh * t, ac + bc * t, al + bl * t) + ""; }; }; d3.interpolateArray = function(a, b) { var x = [], c = [], na = a.length, nb = b.length, n0 = Math.min(a.length, b.length), i; for (i = 0; i < n0; ++i) x.push(d3.interpolate(a[i], b[i])); for (; i < na; ++i) c[i] = a[i]; for (; i < nb; ++i) c[i] = b[i]; return function(t) { for (i = 0; i < n0; ++i) c[i] = x[i](t); return c; }; }; d3.interpolateObject = function(a, b) { var i = {}, c = {}, k; for (k in a) { if (k in b) { i[k] = d3_interpolateByName(k)(a[k], b[k]); } else { c[k] = a[k]; } } for (k in b) { if (!(k in a)) { c[k] = b[k]; } } return function(t) { for (k in i) c[k] = i[k](t); return c; }; }; var d3_interpolate_number = /[-+]?(?:\d+\.?\d*|\.?\d+)(?:[eE][-+]?\d+)?/g; d3.interpolators = [ d3.interpolateObject, function(a, b) { return b instanceof Array && d3.interpolateArray(a, b); }, function(a, b) { return (typeof a === "string" || typeof b === "string") && d3.interpolateString(a + "", b + ""); }, function(a, b) { return (typeof b === "string" ? d3_rgb_names.has(b) || /^(#|rgb\(|hsl\()/.test(b) : b instanceof d3_Color) && d3.interpolateRgb(a, b); }, function(a, b) { return !isNaN(a = +a) && !isNaN(b = +b) && d3.interpolateNumber(a, b); } ]; d3_Color.prototype.toString = function() { return this.rgb() + ""; }; d3.rgb = function(r, g, b) { return arguments.length === 1 ? r instanceof d3_Rgb ? d3_rgb(r.r, r.g, r.b) : d3_rgb_parse("" + r, d3_rgb, d3_hsl_rgb) : d3_rgb(~~r, ~~g, ~~b); }; var d3_rgbPrototype = d3_Rgb.prototype = new d3_Color; d3_rgbPrototype.brighter = function(k) { k = Math.pow(.7, arguments.length ? k : 1); var r = this.r, g = this.g, b = this.b, i = 30; if (!r && !g && !b) return d3_rgb(i, i, i); if (r && r < i) r = i; if (g && g < i) g = i; if (b && b < i) b = i; return d3_rgb(Math.min(255, Math.floor(r / k)), Math.min(255, Math.floor(g / k)), Math.min(255, Math.floor(b / k))); }; d3_rgbPrototype.darker = function(k) { k = Math.pow(.7, arguments.length ? k : 1); return d3_rgb(Math.floor(k * this.r), Math.floor(k * this.g), Math.floor(k * this.b)); }; d3_rgbPrototype.hsl = function() { return d3_rgb_hsl(this.r, this.g, this.b); }; d3_rgbPrototype.toString = function() { return "#" + d3_rgb_hex(this.r) + d3_rgb_hex(this.g) + d3_rgb_hex(this.b); }; var d3_rgb_names = d3.map({ aliceblue: "#f0f8ff", antiquewhite: "#faebd7", aqua: "#00ffff", aquamarine: "#7fffd4", azure: "#f0ffff", beige: "#f5f5dc", bisque: "#ffe4c4", black: "#000000", blanchedalmond: "#ffebcd", blue: "#0000ff", blueviolet: "#8a2be2", brown: "#a52a2a", burlywood: "#deb887", cadetblue: "#5f9ea0", chartreuse: "#7fff00", chocolate: "#d2691e", coral: "#ff7f50", cornflowerblue: "#6495ed", cornsilk: "#fff8dc", crimson: "#dc143c", cyan: "#00ffff", darkblue: "#00008b", darkcyan: "#008b8b", darkgoldenrod: "#b8860b", darkgray: "#a9a9a9", darkgreen: "#006400", darkgrey: "#a9a9a9", darkkhaki: "#bdb76b", darkmagenta: "#8b008b", darkolivegreen: "#556b2f", darkorange: "#ff8c00", darkorchid: "#9932cc", darkred: "#8b0000", darksalmon: "#e9967a", darkseagreen: "#8fbc8f", darkslateblue: "#483d8b", darkslategray: "#2f4f4f", darkslategrey: "#2f4f4f", darkturquoise: "#00ced1", darkviolet: "#9400d3", deeppink: "#ff1493", deepskyblue: "#00bfff", dimgray: "#696969", dimgrey: "#696969", dodgerblue: "#1e90ff", firebrick: "#b22222", floralwhite: "#fffaf0", forestgreen: "#228b22", fuchsia: "#ff00ff", gainsboro: "#dcdcdc", ghostwhite: "#f8f8ff", gold: "#ffd700", goldenrod: "#daa520", gray: "#808080", green: "#008000", greenyellow: "#adff2f", grey: "#808080", honeydew: "#f0fff0", hotpink: "#ff69b4", indianred: "#cd5c5c", indigo: "#4b0082", ivory: "#fffff0", khaki: "#f0e68c", lavender: "#e6e6fa", lavenderblush: "#fff0f5", lawngreen: "#7cfc00", lemonchiffon: "#fffacd", lightblue: "#add8e6", lightcoral: "#f08080", lightcyan: "#e0ffff", lightgoldenrodyellow: "#fafad2", lightgray: "#d3d3d3", lightgreen: "#90ee90", lightgrey: "#d3d3d3", lightpink: "#ffb6c1", lightsalmon: "#ffa07a", lightseagreen: "#20b2aa", lightskyblue: "#87cefa", lightslategray: "#778899", lightslategrey: "#778899", lightsteelblue: "#b0c4de", lightyellow: "#ffffe0", lime: "#00ff00", limegreen: "#32cd32", linen: "#faf0e6", magenta: "#ff00ff", maroon: "#800000", mediumaquamarine: "#66cdaa", mediumblue: "#0000cd", mediumorchid: "#ba55d3", mediumpurple: "#9370db", mediumseagreen: "#3cb371", mediumslateblue: "#7b68ee", mediumspringgreen: "#00fa9a", mediumturquoise: "#48d1cc", mediumvioletred: "#c71585", midnightblue: "#191970", mintcream: "#f5fffa", mistyrose: "#ffe4e1", moccasin: "#ffe4b5", navajowhite: "#ffdead", navy: "#000080", oldlace: "#fdf5e6", olive: "#808000", olivedrab: "#6b8e23", orange: "#ffa500", orangered: "#ff4500", orchid: "#da70d6", palegoldenrod: "#eee8aa", palegreen: "#98fb98", paleturquoise: "#afeeee", palevioletred: "#db7093", papayawhip: "#ffefd5", peachpuff: "#ffdab9", peru: "#cd853f", pink: "#ffc0cb", plum: "#dda0dd", powderblue: "#b0e0e6", purple: "#800080", red: "#ff0000", rosybrown: "#bc8f8f", royalblue: "#4169e1", saddlebrown: "#8b4513", salmon: "#fa8072", sandybrown: "#f4a460", seagreen: "#2e8b57", seashell: "#fff5ee", sienna: "#a0522d", silver: "#c0c0c0", skyblue: "#87ceeb", slateblue: "#6a5acd", slategray: "#708090", slategrey: "#708090", snow: "#fffafa", springgreen: "#00ff7f", steelblue: "#4682b4", tan: "#d2b48c", teal: "#008080", thistle: "#d8bfd8", tomato: "#ff6347", turquoise: "#40e0d0", violet: "#ee82ee", wheat: "#f5deb3", white: "#ffffff", whitesmoke: "#f5f5f5", yellow: "#ffff00", yellowgreen: "#9acd32" }); d3_rgb_names.forEach(function(key, value) { d3_rgb_names.set(key, d3_rgb_parse(value, d3_rgb, d3_hsl_rgb)); }); d3.hsl = function(h, s, l) { return arguments.length === 1 ? h instanceof d3_Hsl ? d3_hsl(h.h, h.s, h.l) : d3_rgb_parse("" + h, d3_rgb_hsl, d3_hsl) : d3_hsl(+h, +s, +l); }; var d3_hslPrototype = d3_Hsl.prototype = new d3_Color; d3_hslPrototype.brighter = function(k) { k = Math.pow(.7, arguments.length ? k : 1); return d3_hsl(this.h, this.s, this.l / k); }; d3_hslPrototype.darker = function(k) { k = Math.pow(.7, arguments.length ? k : 1); return d3_hsl(this.h, this.s, k * this.l); }; d3_hslPrototype.rgb = function() { return d3_hsl_rgb(this.h, this.s, this.l); }; d3.hcl = function(h, c, l) { return arguments.length === 1 ? h instanceof d3_Hcl ? d3_hcl(h.h, h.c, h.l) : h instanceof d3_Lab ? d3_lab_hcl(h.l, h.a, h.b) : d3_lab_hcl((h = d3_rgb_lab((h = d3.rgb(h)).r, h.g, h.b)).l, h.a, h.b) : d3_hcl(+h, +c, +l); }; var d3_hclPrototype = d3_Hcl.prototype = new d3_Color; d3_hclPrototype.brighter = function(k) { return d3_hcl(this.h, this.c, Math.min(100, this.l + d3_lab_K * (arguments.length ? k : 1))); }; d3_hclPrototype.darker = function(k) { return d3_hcl(this.h, this.c, Math.max(0, this.l - d3_lab_K * (arguments.length ? k : 1))); }; d3_hclPrototype.rgb = function() { return d3_hcl_lab(this.h, this.c, this.l).rgb(); }; d3.lab = function(l, a, b) { return arguments.length === 1 ? l instanceof d3_Lab ? d3_lab(l.l, l.a, l.b) : l instanceof d3_Hcl ? d3_hcl_lab(l.l, l.c, l.h) : d3_rgb_lab((l = d3.rgb(l)).r, l.g, l.b) : d3_lab(+l, +a, +b); }; var d3_lab_K = 18; var d3_lab_X = .95047, d3_lab_Y = 1, d3_lab_Z = 1.08883; var d3_labPrototype = d3_Lab.prototype = new d3_Color; d3_labPrototype.brighter = function(k) { return d3_lab(Math.min(100, this.l + d3_lab_K * (arguments.length ? k : 1)), this.a, this.b); }; d3_labPrototype.darker = function(k) { return d3_lab(Math.max(0, this.l - d3_lab_K * (arguments.length ? k : 1)), this.a, this.b); }; d3_labPrototype.rgb = function() { return d3_lab_rgb(this.l, this.a, this.b); }; var d3_select = function(s, n) { return n.querySelector(s); }, d3_selectAll = function(s, n) { return n.querySelectorAll(s); }, d3_selectRoot = document.documentElement, d3_selectMatcher = d3_selectRoot.matchesSelector || d3_selectRoot.webkitMatchesSelector || d3_selectRoot.mozMatchesSelector || d3_selectRoot.msMatchesSelector || d3_selectRoot.oMatchesSelector, d3_selectMatches = function(n, s) { return d3_selectMatcher.call(n, s); }; if (typeof Sizzle === "function") { d3_select = function(s, n) { return Sizzle(s, n)[0] || null; }; d3_selectAll = function(s, n) { return Sizzle.uniqueSort(Sizzle(s, n)); }; d3_selectMatches = Sizzle.matchesSelector; } var d3_selectionPrototype = []; d3.selection = function() { return d3_selectionRoot; }; d3.selection.prototype = d3_selectionPrototype; d3_selectionPrototype.select = function(selector) { var subgroups = [], subgroup, subnode, group, node; if (typeof selector !== "function") selector = d3_selection_selector(selector); for (var j = -1, m = this.length; ++j < m; ) { subgroups.push(subgroup = []); subgroup.parentNode = (group = this[j]).parentNode; for (var i = -1, n = group.length; ++i < n; ) { if (node = group[i]) { subgroup.push(subnode = selector.call(node, node.__data__, i)); if (subnode && "__data__" in node) subnode.__data__ = node.__data__; } else { subgroup.push(null); } } } return d3_selection(subgroups); }; d3_selectionPrototype.selectAll = function(selector) { var subgroups = [], subgroup, node; if (typeof selector !== "function") selector = d3_selection_selectorAll(selector); for (var j = -1, m = this.length; ++j < m; ) { for (var group = this[j], i = -1, n = group.length; ++i < n; ) { if (node = group[i]) { subgroups.push(subgroup = d3_array(selector.call(node, node.__data__, i))); subgroup.parentNode = node; } } } return d3_selection(subgroups); }; d3_selectionPrototype.attr = function(name, value) { if (arguments.length < 2) { if (typeof name === "string") { var node = this.node(); name = d3.ns.qualify(name); return name.local ? node.getAttributeNS(name.space, name.local) : node.getAttribute(name); } for (value in name) this.each(d3_selection_attr(value, name[value])); return this; } return this.each(d3_selection_attr(name, value)); }; d3_selectionPrototype.classed = function(name, value) { if (arguments.length < 2) { if (typeof name === "string") { var node = this.node(), n = (name = name.trim().split(/^|\s+/g)).length, i = -1; if (value = node.classList) { while (++i < n) if (!value.contains(name[i])) return false; } else { value = node.className; if (value.baseVal != null) value = value.baseVal; while (++i < n) if (!d3_selection_classedRe(name[i]).test(value)) return false; } return true; } for (value in name) this.each(d3_selection_classed(value, name[value])); return this; } return this.each(d3_selection_classed(name, value)); }; d3_selectionPrototype.style = function(name, value, priority) { var n = arguments.length; if (n < 3) { if (typeof name !== "string") { if (n < 2) value = ""; for (priority in name) this.each(d3_selection_style(priority, name[priority], value)); return this; } if (n < 2) return window.getComputedStyle(this.node(), null).getPropertyValue(name); priority = ""; } return this.each(d3_selection_style(name, value, priority)); }; d3_selectionPrototype.property = function(name, value) { if (arguments.length < 2) { if (typeof name === "string") return this.node()[name]; for (value in name) this.each(d3_selection_property(value, name[value])); return this; } return this.each(d3_selection_property(name, value)); }; d3_selectionPrototype.text = function(value) { return arguments.length < 1 ? this.node().textContent : this.each(typeof value === "function" ? function() { var v = value.apply(this, arguments); this.textContent = v == null ? "" : v; } : value == null ? function() { this.textContent = ""; } : function() { this.textContent = value; }); }; d3_selectionPrototype.html = function(value) { return arguments.length < 1 ? this.node().innerHTML : this.each(typeof value === "function" ? function() { var v = value.apply(this, arguments); this.innerHTML = v == null ? "" : v; } : value == null ? function() { this.innerHTML = ""; } : function() { this.innerHTML = value; }); }; d3_selectionPrototype.append = function(name) { function append() { return this.appendChild(document.createElementNS(this.namespaceURI, name)); } function appendNS() { return this.appendChild(document.createElementNS(name.space, name.local)); } name = d3.ns.qualify(name); return this.select(name.local ? appendNS : append); }; d3_selectionPrototype.insert = function(name, before) { function insert() { return this.insertBefore(document.createElementNS(this.namespaceURI, name), d3_select(before, this)); } function insertNS() { return this.insertBefore(document.createElementNS(name.space, name.local), d3_select(before, this)); } name = d3.ns.qualify(name); return this.select(name.local ? insertNS : insert); }; d3_selectionPrototype.remove = function() { return this.each(function() { var parent = this.parentNode; if (parent) parent.removeChild(this); }); }; d3_selectionPrototype.data = function(value, key) { function bind(group, groupData) { var i, n = group.length, m = groupData.length, n0 = Math.min(n, m), n1 = Math.max(n, m), updateNodes = [], enterNodes = [], exitNodes = [], node, nodeData; if (key) { var nodeByKeyValue = new d3_Map, keyValues = [], keyValue, j = groupData.length; for (i = -1; ++i < n; ) { keyValue = key.call(node = group[i], node.__data__, i); if (nodeByKeyValue.has(keyValue)) { exitNodes[j++] = node; } else { nodeByKeyValue.set(keyValue, node); } keyValues.push(keyValue); } for (i = -1; ++i < m; ) { keyValue = key.call(groupData, nodeData = groupData[i], i); if (nodeByKeyValue.has(keyValue)) { updateNodes[i] = node = nodeByKeyValue.get(keyValue); node.__data__ = nodeData; enterNodes[i] = exitNodes[i] = null; } else { enterNodes[i] = d3_selection_dataNode(nodeData); updateNodes[i] = exitNodes[i] = null; } nodeByKeyValue.remove(keyValue); } for (i = -1; ++i < n; ) { if (nodeByKeyValue.has(keyValues[i])) { exitNodes[i] = group[i]; } } } else { for (i = -1; ++i < n0; ) { node = group[i]; nodeData = groupData[i]; if (node) { node.__data__ = nodeData; updateNodes[i] = node; enterNodes[i] = exitNodes[i] = null; } else { enterNodes[i] = d3_selection_dataNode(nodeData); updateNodes[i] = exitNodes[i] = null; } } for (; i < m; ++i) { enterNodes[i] = d3_selection_dataNode(groupData[i]); updateNodes[i] = exitNodes[i] = null; } for (; i < n1; ++i) { exitNodes[i] = group[i]; enterNodes[i] = updateNodes[i] = null; } } enterNodes.update = updateNodes; enterNodes.parentNode = updateNodes.parentNode = exitNodes.parentNode = group.parentNode; enter.push(enterNodes); update.push(updateNodes); exit.push(exitNodes); } var i = -1, n = this.length, group, node; if (!arguments.length) { value = new Array(n = (group = this[0]).length); while (++i < n) { if (node = group[i]) { value[i] = node.__data__; } } return value; } var enter = d3_selection_enter([]), update = d3_selection([]), exit = d3_selection([]); if (typeof value === "function") { while (++i < n) { bind(group = this[i], value.call(group, group.parentNode.__data__, i)); } } else { while (++i < n) { bind(group = this[i], value); } } update.enter = function() { return enter; }; update.exit = function() { return exit; }; return update; }; d3_selectionPrototype.datum = d3_selectionPrototype.map = function(value) { return arguments.length < 1 ? this.property("__data__") : this.property("__data__", value); }; d3_selectionPrototype.filter = function(filter) { var subgroups = [], subgroup, group, node; if (typeof filter !== "function") filter = d3_selection_filter(filter); for (var j = 0, m = this.length; j < m; j++) { subgroups.push(subgroup = []); subgroup.parentNode = (group = this[j]).parentNode; for (var i = 0, n = group.length; i < n; i++) { if ((node = group[i]) && filter.call(node, node.__data__, i)) { subgroup.push(node); } } } return d3_selection(subgroups); }; d3_selectionPrototype.order = function() { for (var j = -1, m = this.length; ++j < m; ) { for (var group = this[j], i = group.length - 1, next = group[i], node; --i >= 0; ) { if (node = group[i]) { if (next && next !== node.nextSibling) next.parentNode.insertBefore(node, next); next = node; } } } return this; }; d3_selectionPrototype.sort = function(comparator) { comparator = d3_selection_sortComparator.apply(this, arguments); for (var j = -1, m = this.length; ++j < m; ) this[j].sort(comparator); return this.order(); }; d3_selectionPrototype.on = function(type, listener, capture) { var n = arguments.length; if (n < 3) { if (typeof type !== "string") { if (n < 2) listener = false; for (capture in type) this.each(d3_selection_on(capture, type[capture], listener)); return this; } if (n < 2) return (n = this.node()["__on" + type]) && n._; capture = false; } return this.each(d3_selection_on(type, listener, capture)); }; d3_selectionPrototype.each = function(callback) { return d3_selection_each(this, function(node, i, j) { callback.call(node, node.__data__, i, j); }); }; d3_selectionPrototype.call = function(callback) { callback.apply(this, (arguments[0] = this, arguments)); return this; }; d3_selectionPrototype.empty = function() { return !this.node(); }; d3_selectionPrototype.node = function(callback) { for (var j = 0, m = this.length; j < m; j++) { for (var group = this[j], i = 0, n = group.length; i < n; i++) { var node = group[i]; if (node) return node; } } return null; }; d3_selectionPrototype.transition = function() { var subgroups = [], subgroup, node; for (var j = -1, m = this.length; ++j < m; ) { subgroups.push(subgroup = []); for (var group = this[j], i = -1, n = group.length; ++i < n; ) { subgroup.push((node = group[i]) ? { node: node, delay: d3_transitionDelay, duration: d3_transitionDuration } : null); } } return d3_transition(subgroups, d3_transitionId || ++d3_transitionNextId, Date.now()); }; var d3_selectionRoot = d3_selection([ [ document ] ]); d3_selectionRoot[0].parentNode = d3_selectRoot; d3.select = function(selector) { return typeof selector === "string" ? d3_selectionRoot.select(selector) : d3_selection([ [ selector ] ]); }; d3.selectAll = function(selector) { return typeof selector === "string" ? d3_selectionRoot.selectAll(selector) : d3_selection([ d3_array(selector) ]); }; var d3_selection_enterPrototype = []; d3.selection.enter = d3_selection_enter; d3.selection.enter.prototype = d3_selection_enterPrototype; d3_selection_enterPrototype.append = d3_selectionPrototype.append; d3_selection_enterPrototype.insert = d3_selectionPrototype.insert; d3_selection_enterPrototype.empty = d3_selectionPrototype.empty; d3_selection_enterPrototype.node = d3_selectionPrototype.node; d3_selection_enterPrototype.select = function(selector) { var subgroups = [], subgroup, subnode, upgroup, group, node; for (var j = -1, m = this.length; ++j < m; ) { upgroup = (group = this[j]).update; subgroups.push(subgroup = []); subgroup.parentNode = group.parentNode; for (var i = -1, n = group.length; ++i < n; ) { if (node = group[i]) { subgroup.push(upgroup[i] = subnode = selector.call(group.parentNode, node.__data__, i)); subnode.__data__ = node.__data__; } else { subgroup.push(null); } } } return d3_selection(subgroups); }; var d3_transitionPrototype = [], d3_transitionNextId = 0, d3_transitionId = 0, d3_transitionDefaultDelay = 0, d3_transitionDefaultDuration = 250, d3_transitionDefaultEase = d3.ease("cubic-in-out"), d3_transitionDelay = d3_transitionDefaultDelay, d3_transitionDuration = d3_transitionDefaultDuration, d3_transitionEase = d3_transitionDefaultEase; d3_transitionPrototype.call = d3_selectionPrototype.call; d3.transition = function(selection) { return arguments.length ? d3_transitionId ? selection.transition() : selection : d3_selectionRoot.transition(); }; d3.transition.prototype = d3_transitionPrototype; d3_transitionPrototype.select = function(selector) { var subgroups = [], subgroup, subnode, node; if (typeof selector !== "function") selector = d3_selection_selector(selector); for (var j = -1, m = this.length; ++j < m; ) { subgroups.push(subgroup = []); for (var group = this[j], i = -1, n = group.length; ++i < n; ) { if ((node = group[i]) && (subnode = selector.call(node.node, node.node.__data__, i))) { if ("__data__" in node.node) subnode.__data__ = node.node.__data__; subgroup.push({ node: subnode, delay: node.delay, duration: node.duration }); } else { subgroup.push(null); } } } return d3_transition(subgroups, this.id, this.time).ease(this.ease()); }; d3_transitionPrototype.selectAll = function(selector) { var subgroups = [], subgroup, subnodes, node; if (typeof selector !== "function") selector = d3_selection_selectorAll(selector); for (var j = -1, m = this.length; ++j < m; ) { for (var group = this[j], i = -1, n = group.length; ++i < n; ) { if (node = group[i]) { subnodes = selector.call(node.node, node.node.__data__, i); subgroups.push(subgroup = []); for (var k = -1, o = subnodes.length; ++k < o; ) { subgroup.push({ node: subnodes[k], delay: node.delay, duration: node.duration }); } } } } return d3_transition(subgroups, this.id, this.time).ease(this.ease()); }; d3_transitionPrototype.filter = function(filter) { var subgroups = [], subgroup, group, node; if (typeof filter !== "function") filter = d3_selection_filter(filter); for (var j = 0, m = this.length; j < m; j++) { subgroups.push(subgroup = []); for (var group = this[j], i = 0, n = group.length; i < n; i++) { if ((node = group[i]) && filter.call(node.node, node.node.__data__, i)) { subgroup.push(node); } } } return d3_transition(subgroups, this.id, this.time).ease(this.ease()); }; d3_transitionPrototype.attr = function(name, value) { if (arguments.length < 2) { for (value in name) this.attrTween(value, d3_tweenByName(name[value], value)); return this; } return this.attrTween(name, d3_tweenByName(value, name)); }; d3_transitionPrototype.attrTween = function(nameNS, tween) { function attrTween(d, i) { var f = tween.call(this, d, i, this.getAttribute(name)); return f === d3_tweenRemove ? (this.removeAttribute(name), null) : f && function(t) { this.setAttribute(name, f(t)); }; } function attrTweenNS(d, i) { var f = tween.call(this, d, i, this.getAttributeNS(name.space, name.local)); return f === d3_tweenRemove ? (this.removeAttributeNS(name.space, name.local), null) : f && function(t) { this.setAttributeNS(name.space, name.local, f(t)); }; } var name = d3.ns.qualify(nameNS); return this.tween("attr." + nameNS, name.local ? attrTweenNS : attrTween); }; d3_transitionPrototype.style = function(name, value, priority) { var n = arguments.length; if (n < 3) { if (typeof name !== "string") { if (n < 2) value = ""; for (priority in name) this.styleTween(priority, d3_tweenByName(name[priority], priority), value); return this; } priority = ""; } return this.styleTween(name, d3_tweenByName(value, name), priority); }; d3_transitionPrototype.styleTween = function(name, tween, priority) { if (arguments.length < 3) priority = ""; return this.tween("style." + name, function(d, i) { var f = tween.call(this, d, i, window.getComputedStyle(this, null).getPropertyValue(name)); return f === d3_tweenRemove ? (this.style.removeProperty(name), null) : f && function(t) { this.style.setProperty(name, f(t), priority); }; }); }; d3_transitionPrototype.text = function(value) { return this.tween("text", function(d, i) { this.textContent = typeof value === "function" ? value.call(this, d, i) : value; }); }; d3_transitionPrototype.remove = function() { return this.each("end.transition", function() { var p; if (!this.__transition__ && (p = this.parentNode)) p.removeChild(this); }); }; d3_transitionPrototype.delay = function(value) { return d3_selection_each(this, typeof value === "function" ? function(node, i, j) { node.delay = value.call(node = node.node, node.__data__, i, j) | 0; } : (value = value | 0, function(node) { node.delay = value; })); }; d3_transitionPrototype.duration = function(value) { return d3_selection_each(this, typeof value === "function" ? function(node, i, j) { node.duration = Math.max(1, value.call(node = node.node, node.__data__, i, j) | 0); } : (value = Math.max(1, value | 0), function(node) { node.duration = value; })); }; d3_transitionPrototype.transition = function() { return this.select(d3_this); }; d3.tween = function(b, interpolate) { function tweenFunction(d, i, a) { var v = b.call(this, d, i); return v == null ? a != "" && d3_tweenRemove : a != v && interpolate(a, v + ""); } function tweenString(d, i, a) { return a != b && interpolate(a, b); } return typeof b === "function" ? tweenFunction : b == null ? d3_tweenNull : (b += "", tweenString); }; var d3_tweenRemove = {}; var d3_timer_id = 0, d3_timer_byId = {}, d3_timer_queue = null, d3_timer_interval, d3_timer_timeout; d3.timer = function(callback, delay, then) { if (arguments.length < 3) { if (arguments.length < 2) delay = 0; else if (!isFinite(delay)) return; then = Date.now(); } var timer = d3_timer_byId[callback.id]; if (timer && timer.callback === callback) { timer.then = then; timer.delay = delay; } else d3_timer_byId[callback.id = ++d3_timer_id] = d3_timer_queue = { callback: callback, then: then, delay: delay, next: d3_timer_queue }; if (!d3_timer_interval) { d3_timer_timeout = clearTimeout(d3_timer_timeout); d3_timer_interval = 1; d3_timer_frame(d3_timer_step); } }; d3.timer.flush = function() { var elapsed, now = Date.now(), t1 = d3_timer_queue; while (t1) { elapsed = now - t1.then; if (!t1.delay) t1.flush = t1.callback(elapsed); t1 = t1.next; } d3_timer_flush(); }; var d3_timer_frame = window.requestAnimationFrame || window.webkitRequestAnimationFrame || window.mozRequestAnimationFrame || window.oRequestAnimationFrame || window.msRequestAnimationFrame || function(callback) { setTimeout(callback, 17); }; d3.mouse = function(container) { return d3_mousePoint(container, d3_eventSource()); }; var d3_mouse_bug44083 = /WebKit/.test(navigator.userAgent) ? -1 : 0; d3.touches = function(container, touches) { if (arguments.length < 2) touches = d3_eventSource().touches; return touches ? d3_array(touches).map(function(touch) { var point = d3_mousePoint(container, touch); point.identifier = touch.identifier; return point; }) : []; }; d3.scale = {}; d3.scale.linear = function() { return d3_scale_linear([ 0, 1 ], [ 0, 1 ], d3.interpolate, false); }; d3.scale.log = function() { return d3_scale_log(d3.scale.linear(), d3_scale_logp); }; var d3_scale_logFormat = d3.format(".0e"); d3_scale_logp.pow = function(x) { return Math.pow(10, x); }; d3_scale_logn.pow = function(x) { return -Math.pow(10, -x); }; d3.scale.pow = function() { return d3_scale_pow(d3.scale.linear(), 1); }; d3.scale.sqrt = function() { return d3.scale.pow().exponent(.5); }; d3.scale.ordinal = function() { return d3_scale_ordinal([], { t: "range", a: [ [] ] }); }; d3.scale.category10 = function() { return d3.scale.ordinal().range(d3_category10); }; d3.scale.category20 = function() { return d3.scale.ordinal().range(d3_category20); }; d3.scale.category20b = function() { return d3.scale.ordinal().range(d3_category20b); }; d3.scale.category20c = function() { return d3.scale.ordinal().range(d3_category20c); }; var d3_category10 = [ "#1f77b4", "#ff7f0e", "#2ca02c", "#d62728", "#9467bd", "#8c564b", "#e377c2", "#7f7f7f", "#bcbd22", "#17becf" ]; var d3_category20 = [ "#1f77b4", "#aec7e8", "#ff7f0e", "#ffbb78", "#2ca02c", "#98df8a", "#d62728", "#ff9896", "#9467bd", "#c5b0d5", "#8c564b", "#c49c94", "#e377c2", "#f7b6d2", "#7f7f7f", "#c7c7c7", "#bcbd22", "#dbdb8d", "#17becf", "#9edae5" ]; var d3_category20b = [ "#393b79", "#5254a3", "#6b6ecf", "#9c9ede", "#637939", "#8ca252", "#b5cf6b", "#cedb9c", "#8c6d31", "#bd9e39", "#e7ba52", "#e7cb94", "#843c39", "#ad494a", "#d6616b", "#e7969c", "#7b4173", "#a55194", "#ce6dbd", "#de9ed6" ]; var d3_category20c = [ "#3182bd", "#6baed6", "#9ecae1", "#c6dbef", "#e6550d", "#fd8d3c", "#fdae6b", "#fdd0a2", "#31a354", "#74c476", "#a1d99b", "#c7e9c0", "#756bb1", "#9e9ac8", "#bcbddc", "#dadaeb", "#636363", "#969696", "#bdbdbd", "#d9d9d9" ]; d3.scale.quantile = function() { return d3_scale_quantile([], []); }; d3.scale.quantize = function() { return d3_scale_quantize(0, 1, [ 0, 1 ]); }; d3.scale.threshold = function() { return d3_scale_threshold([ .5 ], [ 0, 1 ]); }; d3.scale.identity = function() { return d3_scale_identity([ 0, 1 ]); }; d3.svg = {}; d3.svg.arc = function() { function arc() { var r0 = innerRadius.apply(this, arguments), r1 = outerRadius.apply(this, arguments), a0 = startAngle.apply(this, arguments) + d3_svg_arcOffset, a1 = endAngle.apply(this, arguments) + d3_svg_arcOffset, da = (a1 < a0 && (da = a0, a0 = a1, a1 = da), a1 - a0), df = da < Math.PI ? "0" : "1", c0 = Math.cos(a0), s0 = Math.sin(a0), c1 = Math.cos(a1), s1 = Math.sin(a1); return da >= d3_svg_arcMax ? r0 ? "M0," + r1 + "A" + r1 + "," + r1 + " 0 1,1 0," + -r1 + "A" + r1 + "," + r1 + " 0 1,1 0," + r1 + "M0," + r0 + "A" + r0 + "," + r0 + " 0 1,0 0," + -r0 + "A" + r0 + "," + r0 + " 0 1,0 0," + r0 + "Z" : "M0," + r1 + "A" + r1 + "," + r1 + " 0 1,1 0," + -r1 + "A" + r1 + "," + r1 + " 0 1,1 0," + r1 + "Z" : r0 ? "M" + r1 * c0 + "," + r1 * s0 + "A" + r1 + "," + r1 + " 0 " + df + ",1 " + r1 * c1 + "," + r1 * s1 + "L" + r0 * c1 + "," + r0 * s1 + "A" + r0 + "," + r0 + " 0 " + df + ",0 " + r0 * c0 + "," + r0 * s0 + "Z" : "M" + r1 * c0 + "," + r1 * s0 + "A" + r1 + "," + r1 + " 0 " + df + ",1 " + r1 * c1 + "," + r1 * s1 + "L0,0" + "Z"; } var innerRadius = d3_svg_arcInnerRadius, outerRadius = d3_svg_arcOuterRadius, startAngle = d3_svg_arcStartAngle, endAngle = d3_svg_arcEndAngle; arc.innerRadius = function(v) { if (!arguments.length) return innerRadius; innerRadius = d3_functor(v); return arc; }; arc.outerRadius = function(v) { if (!arguments.length) return outerRadius; outerRadius = d3_functor(v); return arc; }; arc.startAngle = function(v) { if (!arguments.length) return startAngle; startAngle = d3_functor(v); return arc; }; arc.endAngle = function(v) { if (!arguments.length) return endAngle; endAngle = d3_functor(v); return arc; }; arc.centroid = function() { var r = (innerRadius.apply(this, arguments) + outerRadius.apply(this, arguments)) / 2, a = (startAngle.apply(this, arguments) + endAngle.apply(this, arguments)) / 2 + d3_svg_arcOffset; return [ Math.cos(a) * r, Math.sin(a) * r ]; }; return arc; }; var d3_svg_arcOffset = -Math.PI / 2, d3_svg_arcMax = 2 * Math.PI - 1e-6; d3.svg.line = function() { return d3_svg_line(d3_identity); }; var d3_svg_lineInterpolators = d3.map({ linear: d3_svg_lineLinear, "linear-closed": d3_svg_lineLinearClosed, "step-before": d3_svg_lineStepBefore, "step-after": d3_svg_lineStepAfter, basis: d3_svg_lineBasis, "basis-open": d3_svg_lineBasisOpen, "basis-closed": d3_svg_lineBasisClosed, bundle: d3_svg_lineBundle, cardinal: d3_svg_lineCardinal, "cardinal-open": d3_svg_lineCardinalOpen, "cardinal-closed": d3_svg_lineCardinalClosed, monotone: d3_svg_lineMonotone }); d3_svg_lineInterpolators.forEach(function(key, value) { value.key = key; value.closed = /-closed$/.test(key); }); var d3_svg_lineBasisBezier1 = [ 0, 2 / 3, 1 / 3, 0 ], d3_svg_lineBasisBezier2 = [ 0, 1 / 3, 2 / 3, 0 ], d3_svg_lineBasisBezier3 = [ 0, 1 / 6, 2 / 3, 1 / 6 ]; d3.svg.line.radial = function() { var line = d3_svg_line(d3_svg_lineRadial); line.radius = line.x, delete line.x; line.angle = line.y, delete line.y; return line; }; d3_svg_lineStepBefore.reverse = d3_svg_lineStepAfter; d3_svg_lineStepAfter.reverse = d3_svg_lineStepBefore; d3.svg.area = function() { return d3_svg_area(d3_identity); }; d3.svg.area.radial = function() { var area = d3_svg_area(d3_svg_lineRadial); area.radius = area.x, delete area.x; area.innerRadius = area.x0, delete area.x0; area.outerRadius = area.x1, delete area.x1; area.angle = area.y, delete area.y; area.startAngle = area.y0, delete area.y0; area.endAngle = area.y1, delete area.y1; return area; }; d3.svg.chord = function() { function chord(d, i) { var s = subgroup(this, source, d, i), t = subgroup(this, target, d, i); return "M" + s.p0 + arc(s.r, s.p1, s.a1 - s.a0) + (equals(s, t) ? curve(s.r, s.p1, s.r, s.p0) : curve(s.r, s.p1, t.r, t.p0) + arc(t.r, t.p1, t.a1 - t.a0) + curve(t.r, t.p1, s.r, s.p0)) + "Z"; } function subgroup(self, f, d, i) { var subgroup = f.call(self, d, i), r = radius.call(self, subgroup, i), a0 = startAngle.call(self, subgroup, i) + d3_svg_arcOffset, a1 = endAngle.call(self, subgroup, i) + d3_svg_arcOffset; return { r: r, a0: a0, a1: a1, p0: [ r * Math.cos(a0), r * Math.sin(a0) ], p1: [ r * Math.cos(a1), r * Math.sin(a1) ] }; } function equals(a, b) { return a.a0 == b.a0 && a.a1 == b.a1; } function arc(r, p, a) { return "A" + r + "," + r + " 0 " + +(a > Math.PI) + ",1 " + p; } function curve(r0, p0, r1, p1) { return "Q 0,0 " + p1; } var source = d3_svg_chordSource, target = d3_svg_chordTarget, radius = d3_svg_chordRadius, startAngle = d3_svg_arcStartAngle, endAngle = d3_svg_arcEndAngle; chord.radius = function(v) { if (!arguments.length) return radius; radius = d3_functor(v); return chord; }; chord.source = function(v) { if (!arguments.length) return source; source = d3_functor(v); return chord; }; chord.target = function(v) { if (!arguments.length) return target; target = d3_functor(v); return chord; }; chord.startAngle = function(v) { if (!arguments.length) return startAngle; startAngle = d3_functor(v); return chord; }; chord.endAngle = function(v) { if (!arguments.length) return endAngle; endAngle = d3_functor(v); return chord; }; return chord; }; d3.svg.diagonal = function() { function diagonal(d, i) { var p0 = source.call(this, d, i), p3 = target.call(this, d, i), m = (p0.y + p3.y) / 2, p = [ p0, { x: p0.x, y: m }, { x: p3.x, y: m }, p3 ]; p = p.map(projection); return "M" + p[0] + "C" + p[1] + " " + p[2] + " " + p[3]; } var source = d3_svg_chordSource, target = d3_svg_chordTarget, projection = d3_svg_diagonalProjection; diagonal.source = function(x) { if (!arguments.length) return source; source = d3_functor(x); return diagonal; }; diagonal.target = function(x) { if (!arguments.length) return target; target = d3_functor(x); return diagonal; }; diagonal.projection = function(x) { if (!arguments.length) return projection; projection = x; return diagonal; }; return diagonal; }; d3.svg.diagonal.radial = function() { var diagonal = d3.svg.diagonal(), projection = d3_svg_diagonalProjection, projection_ = diagonal.projection; diagonal.projection = function(x) { return arguments.length ? projection_(d3_svg_diagonalRadialProjection(projection = x)) : projection; }; return diagonal; }; d3.svg.mouse = d3.mouse; d3.svg.touches = d3.touches; d3.svg.symbol = function() { function symbol(d, i) { return (d3_svg_symbols.get(type.call(this, d, i)) || d3_svg_symbolCircle)(size.call(this, d, i)); } var type = d3_svg_symbolType, size = d3_svg_symbolSize; symbol.type = function(x) { if (!arguments.length) return type; type = d3_functor(x); return symbol; }; symbol.size = function(x) { if (!arguments.length) return size; size = d3_functor(x); return symbol; }; return symbol; }; var d3_svg_symbols = d3.map({ circle: d3_svg_symbolCircle, cross: function(size) { var r = Math.sqrt(size / 5) / 2; return "M" + -3 * r + "," + -r + "H" + -r + "V" + -3 * r + "H" + r + "V" + -r + "H" + 3 * r + "V" + r + "H" + r + "V" + 3 * r + "H" + -r + "V" + r + "H" + -3 * r + "Z"; }, diamond: function(size) { var ry = Math.sqrt(size / (2 * d3_svg_symbolTan30)), rx = ry * d3_svg_symbolTan30; return "M0," + -ry + "L" + rx + ",0" + " 0," + ry + " " + -rx + ",0" + "Z"; }, square: function(size) { var r = Math.sqrt(size) / 2; return "M" + -r + "," + -r + "L" + r + "," + -r + " " + r + "," + r + " " + -r + "," + r + "Z"; }, "triangle-down": function(size) { var rx = Math.sqrt(size / d3_svg_symbolSqrt3), ry = rx * d3_svg_symbolSqrt3 / 2; return "M0," + ry + "L" + rx + "," + -ry + " " + -rx + "," + -ry + "Z"; }, "triangle-up": function(size) { var rx = Math.sqrt(size / d3_svg_symbolSqrt3), ry = rx * d3_svg_symbolSqrt3 / 2; return "M0," + -ry + "L" + rx + "," + ry + " " + -rx + "," + ry + "Z"; } }); d3.svg.symbolTypes = d3_svg_symbols.keys(); var d3_svg_symbolSqrt3 = Math.sqrt(3), d3_svg_symbolTan30 = Math.tan(30 * Math.PI / 180); d3.svg.axis = function() { function axis(g) { g.each(function() { var g = d3.select(this); var ticks = tickValues == null ? scale.ticks ? scale.ticks.apply(scale, tickArguments_) : scale.domain() : tickValues, tickFormat = tickFormat_ == null ? scale.tickFormat ? scale.tickFormat.apply(scale, tickArguments_) : String : tickFormat_; var subticks = d3_svg_axisSubdivide(scale, ticks, tickSubdivide), subtick = g.selectAll(".minor").data(subticks, String), subtickEnter = subtick.enter().insert("line", "g").attr("class", "tick minor").style("opacity", 1e-6), subtickExit = d3.transition(subtick.exit()).style("opacity", 1e-6).remove(), subtickUpdate = d3.transition(subtick).style("opacity", 1); var tick = g.selectAll("g").data(ticks, String), tickEnter = tick.enter().insert("g", "path").style("opacity", 1e-6), tickExit = d3.transition(tick.exit()).style("opacity", 1e-6).remove(), tickUpdate = d3.transition(tick).style("opacity", 1), tickTransform; var range = d3_scaleRange(scale), path = g.selectAll(".domain").data([ 0 ]), pathEnter = path.enter().append("path").attr("class", "domain"), pathUpdate = d3.transition(path); var scale1 = scale.copy(), scale0 = this.__chart__ || scale1; this.__chart__ = scale1; tickEnter.append("line").attr("class", "tick"); tickEnter.append("text"); var lineEnter = tickEnter.select("line"), lineUpdate = tickUpdate.select("line"), text = tick.select("text").text(tickFormat), textEnter = tickEnter.select("text"), textUpdate = tickUpdate.select("text"); switch (orient) { case "bottom": { tickTransform = d3_svg_axisX; subtickEnter.attr("y2", tickMinorSize); subtickUpdate.attr("x2", 0).attr("y2", tickMinorSize); lineEnter.attr("y2", tickMajorSize); textEnter.attr("y", Math.max(tickMajorSize, 0) + tickPadding); lineUpdate.attr("x2", 0).attr("y2", tickMajorSize); textUpdate.attr("x", 0).attr("y", Math.max(tickMajorSize, 0) + tickPadding); text.attr("dy", ".71em").attr("text-anchor", "middle"); pathUpdate.attr("d", "M" + range[0] + "," + tickEndSize + "V0H" + range[1] + "V" + tickEndSize); break; } case "top": { tickTransform = d3_svg_axisX; subtickEnter.attr("y2", -tickMinorSize); subtickUpdate.attr("x2", 0).attr("y2", -tickMinorSize); lineEnter.attr("y2", -tickMajorSize); textEnter.attr("y", -(Math.max(tickMajorSize, 0) + tickPadding)); lineUpdate.attr("x2", 0).attr("y2", -tickMajorSize); textUpdate.attr("x", 0).attr("y", -(Math.max(tickMajorSize, 0) + tickPadding)); text.attr("dy", "0em").attr("text-anchor", "middle"); pathUpdate.attr("d", "M" + range[0] + "," + -tickEndSize + "V0H" + range[1] + "V" + -tickEndSize); break; } case "left": { tickTransform = d3_svg_axisY; subtickEnter.attr("x2", -tickMinorSize); subtickUpdate.attr("x2", -tickMinorSize).attr("y2", 0); lineEnter.attr("x2", -tickMajorSize); textEnter.attr("x", -(Math.max(tickMajorSize, 0) + tickPadding)); lineUpdate.attr("x2", -tickMajorSize).attr("y2", 0); textUpdate.attr("x", -(Math.max(tickMajorSize, 0) + tickPadding)).attr("y", 0); text.attr("dy", ".32em").attr("text-anchor", "end"); pathUpdate.attr("d", "M" + -tickEndSize + "," + range[0] + "H0V" + range[1] + "H" + -tickEndSize); break; } case "right": { tickTransform = d3_svg_axisY; subtickEnter.attr("x2", tickMinorSize); subtickUpdate.attr("x2", tickMinorSize).attr("y2", 0); lineEnter.attr("x2", tickMajorSize); textEnter.attr("x", Math.max(tickMajorSize, 0) + tickPadding); lineUpdate.attr("x2", tickMajorSize).attr("y2", 0); textUpdate.attr("x", Math.max(tickMajorSize, 0) + tickPadding).attr("y", 0); text.attr("dy", ".32em").attr("text-anchor", "start"); pathUpdate.attr("d", "M" + tickEndSize + "," + range[0] + "H0V" + range[1] + "H" + tickEndSize); break; } } if (scale.ticks) { tickEnter.call(tickTransform, scale0); tickUpdate.call(tickTransform, scale1); tickExit.call(tickTransform, scale1); subtickEnter.call(tickTransform, scale0); subtickUpdate.call(tickTransform, scale1); subtickExit.call(tickTransform, scale1); } else { var dx = scale1.rangeBand() / 2, x = function(d) { return scale1(d) + dx; }; tickEnter.call(tickTransform, x); tickUpdate.call(tickTransform, x); } }); } var scale = d3.scale.linear(), orient = "bottom", tickMajorSize = 6, tickMinorSize = 6, tickEndSize = 6, tickPadding = 3, tickArguments_ = [ 10 ], tickValues = null, tickFormat_, tickSubdivide = 0; axis.scale = function(x) { if (!arguments.length) return scale; scale = x; return axis; }; axis.orient = function(x) { if (!arguments.length) return orient; orient = x; return axis; }; axis.ticks = function() { if (!arguments.length) return tickArguments_; tickArguments_ = arguments; return axis; }; axis.tickValues = function(x) { if (!arguments.length) return tickValues; tickValues = x; return axis; }; axis.tickFormat = function(x) { if (!arguments.length) return tickFormat_; tickFormat_ = x; return axis; }; axis.tickSize = function(x, y, z) { if (!arguments.length) return tickMajorSize; var n = arguments.length - 1; tickMajorSize = +x; tickMinorSize = n > 1 ? +y : tickMajorSize; tickEndSize = n > 0 ? +arguments[n] : tickMajorSize; return axis; }; axis.tickPadding = function(x) { if (!arguments.length) return tickPadding; tickPadding = +x; return axis; }; axis.tickSubdivide = function(x) { if (!arguments.length) return tickSubdivide; tickSubdivide = +x; return axis; }; return axis; }; d3.svg.brush = function() { function brush(g) { g.each(function() { var g = d3.select(this), bg = g.selectAll(".background").data([ 0 ]), fg = g.selectAll(".extent").data([ 0 ]), tz = g.selectAll(".resize").data(resizes, String), e; g.style("pointer-events", "all").on("mousedown.brush", brushstart).on("touchstart.brush", brushstart); bg.enter().append("rect").attr("class", "background").style("visibility", "hidden").style("cursor", "crosshair"); fg.enter().append("rect").attr("class", "extent").style("cursor", "move"); tz.enter().append("g").attr("class", function(d) { return "resize " + d; }).style("cursor", function(d) { return d3_svg_brushCursor[d]; }).append("rect").attr("x", function(d) { return /[ew]$/.test(d) ? -3 : null; }).attr("y", function(d) { return /^[ns]/.test(d) ? -3 : null; }).attr("width", 6).attr("height", 6).style("visibility", "hidden"); tz.style("display", brush.empty() ? "none" : null); tz.exit().remove(); if (x) { e = d3_scaleRange(x); bg.attr("x", e[0]).attr("width", e[1] - e[0]); redrawX(g); } if (y) { e = d3_scaleRange(y); bg.attr("y", e[0]).attr("height", e[1] - e[0]); redrawY(g); } redraw(g); }); } function redraw(g) { g.selectAll(".resize").attr("transform", function(d) { return "translate(" + extent[+/e$/.test(d)][0] + "," + extent[+/^s/.test(d)][1] + ")"; }); } function redrawX(g) { g.select(".extent").attr("x", extent[0][0]); g.selectAll(".extent,.n>rect,.s>rect").attr("width", extent[1][0] - extent[0][0]); } function redrawY(g) { g.select(".extent").attr("y", extent[0][1]); g.selectAll(".extent,.e>rect,.w>rect").attr("height", extent[1][1] - extent[0][1]); } function brushstart() { function mouse() { var touches = d3.event.changedTouches; return touches ? d3.touches(target, touches)[0] : d3.mouse(target); } function keydown() { if (d3.event.keyCode == 32) { if (!dragging) { center = null; origin[0] -= extent[1][0]; origin[1] -= extent[1][1]; dragging = 2; } d3_eventCancel(); } } function keyup() { if (d3.event.keyCode == 32 && dragging == 2) { origin[0] += extent[1][0]; origin[1] += extent[1][1]; dragging = 0; d3_eventCancel(); } } function brushmove() { var point = mouse(), moved = false; if (offset) { point[0] += offset[0]; point[1] += offset[1]; } if (!dragging) { if (d3.event.altKey) { if (!center) center = [ (extent[0][0] + extent[1][0]) / 2, (extent[0][1] + extent[1][1]) / 2 ]; origin[0] = extent[+(point[0] < center[0])][0]; origin[1] = extent[+(point[1] < center[1])][1]; } else center = null; } if (resizingX && move1(point, x, 0)) { redrawX(g); moved = true; } if (resizingY && move1(point, y, 1)) { redrawY(g); moved = true; } if (moved) { redraw(g); event_({ type: "brush", mode: dragging ? "move" : "resize" }); } } function move1(point, scale, i) { var range = d3_scaleRange(scale), r0 = range[0], r1 = range[1], position = origin[i], size = extent[1][i] - extent[0][i], min, max; if (dragging) { r0 -= position; r1 -= size + position; } min = Math.max(r0, Math.min(r1, point[i])); if (dragging) { max = (min += position) + size; } else { if (center) position = Math.max(r0, Math.min(r1, 2 * center[i] - min)); if (position < min) { max = min; min = position; } else { max = position; } } if (extent[0][i] !== min || extent[1][i] !== max) { extentDomain = null; extent[0][i] = min; extent[1][i] = max; return true; } } function brushend() { brushmove(); g.style("pointer-events", "all").selectAll(".resize").style("display", brush.empty() ? "none" : null); d3.select("body").style("cursor", null); w.on("mousemove.brush", null).on("mouseup.brush", null).on("touchmove.brush", null).on("touchend.brush", null).on("keydown.brush", null).on("keyup.brush", null); event_({ type: "brushend" }); d3_eventCancel(); } var target = this, eventTarget = d3.select(d3.event.target), event_ = event.of(target, arguments), g = d3.select(target), resizing = eventTarget.datum(), resizingX = !/^(n|s)$/.test(resizing) && x, resizingY = !/^(e|w)$/.test(resizing) && y, dragging = eventTarget.classed("extent"), center, origin = mouse(), offset; var w = d3.select(window).on("mousemove.brush", brushmove).on("mouseup.brush", brushend).on("touchmove.brush", brushmove).on("touchend.brush", brushend).on("keydown.brush", keydown).on("keyup.brush", keyup); if (dragging) { origin[0] = extent[0][0] - origin[0]; origin[1] = extent[0][1] - origin[1]; } else if (resizing) { var ex = +/w$/.test(resizing), ey = +/^n/.test(resizing); offset = [ extent[1 - ex][0] - origin[0], extent[1 - ey][1] - origin[1] ]; origin[0] = extent[ex][0]; origin[1] = extent[ey][1]; } else if (d3.event.altKey) center = origin.slice(); g.style("pointer-events", "none").selectAll(".resize").style("display", null); d3.select("body").style("cursor", eventTarget.style("cursor")); event_({ type: "brushstart" }); brushmove(); d3_eventCancel(); } var event = d3_eventDispatch(brush, "brushstart", "brush", "brushend"), x = null, y = null, resizes = d3_svg_brushResizes[0], extent = [ [ 0, 0 ], [ 0, 0 ] ], extentDomain; brush.x = function(z) { if (!arguments.length) return x; x = z; resizes = d3_svg_brushResizes[!x << 1 | !y]; return brush; }; brush.y = function(z) { if (!arguments.length) return y; y = z; resizes = d3_svg_brushResizes[!x << 1 | !y]; return brush; }; brush.extent = function(z) { var x0, x1, y0, y1, t; if (!arguments.length) { z = extentDomain || extent; if (x) { x0 = z[0][0], x1 = z[1][0]; if (!extentDomain) { x0 = extent[0][0], x1 = extent[1][0]; if (x.invert) x0 = x.invert(x0), x1 = x.invert(x1); if (x1 < x0) t = x0, x0 = x1, x1 = t; } } if (y) { y0 = z[0][1], y1 = z[1][1]; if (!extentDomain) { y0 = extent[0][1], y1 = extent[1][1]; if (y.invert) y0 = y.invert(y0), y1 = y.invert(y1); if (y1 < y0) t = y0, y0 = y1, y1 = t; } } return x && y ? [ [ x0, y0 ], [ x1, y1 ] ] : x ? [ x0, x1 ] : y && [ y0, y1 ]; } extentDomain = [ [ 0, 0 ], [ 0, 0 ] ]; if (x) { x0 = z[0], x1 = z[1]; if (y) x0 = x0[0], x1 = x1[0]; extentDomain[0][0] = x0, extentDomain[1][0] = x1; if (x.invert) x0 = x(x0), x1 = x(x1); if (x1 < x0) t = x0, x0 = x1, x1 = t; extent[0][0] = x0 | 0, extent[1][0] = x1 | 0; } if (y) { y0 = z[0], y1 = z[1]; if (x) y0 = y0[1], y1 = y1[1]; extentDomain[0][1] = y0, extentDomain[1][1] = y1; if (y.invert) y0 = y(y0), y1 = y(y1); if (y1 < y0) t = y0, y0 = y1, y1 = t; extent[0][1] = y0 | 0, extent[1][1] = y1 | 0; } return brush; }; brush.clear = function() { extentDomain = null; extent[0][0] = extent[0][1] = extent[1][0] = extent[1][1] = 0; return brush; }; brush.empty = function() { return x && extent[0][0] === extent[1][0] || y && extent[0][1] === extent[1][1]; }; return d3.rebind(brush, event, "on"); }; var d3_svg_brushCursor = { n: "ns-resize", e: "ew-resize", s: "ns-resize", w: "ew-resize", nw: "nwse-resize", ne: "nesw-resize", se: "nwse-resize", sw: "nesw-resize" }; var d3_svg_brushResizes = [ [ "n", "e", "s", "w", "nw", "ne", "se", "sw" ], [ "e", "w" ], [ "n", "s" ], [] ]; d3.behavior = {}; d3.behavior.drag = function() { function drag() { this.on("mousedown.drag", mousedown).on("touchstart.drag", mousedown); } function mousedown() { function point() { var p = target.parentNode; return touchId ? d3.touches(p).filter(function(p) { return p.identifier === touchId; })[0] : d3.mouse(p); } function dragmove() { if (!target.parentNode) return dragend(); var p = point(), dx = p[0] - origin_[0], dy = p[1] - origin_[1]; moved |= dx | dy; origin_ = p; d3_eventCancel(); event_({ type: "drag", x: p[0] + offset[0], y: p[1] + offset[1], dx: dx, dy: dy }); } function dragend() { event_({ type: "dragend" }); if (moved) { d3_eventCancel(); if (d3.event.target === eventTarget) w.on("click.drag", click, true); } w.on(touchId ? "touchmove.drag-" + touchId : "mousemove.drag", null).on(touchId ? "touchend.drag-" + touchId : "mouseup.drag", null); } function click() { d3_eventCancel(); w.on("click.drag", null); } var target = this, event_ = event.of(target, arguments), eventTarget = d3.event.target, touchId = d3.event.touches && d3.event.changedTouches[0].identifier, offset, origin_ = point(), moved = 0; var w = d3.select(window).on(touchId ? "touchmove.drag-" + touchId : "mousemove.drag", dragmove).on(touchId ? "touchend.drag-" + touchId : "mouseup.drag", dragend, true); if (origin) { offset = origin.apply(target, arguments); offset = [ offset.x - origin_[0], offset.y - origin_[1] ]; } else { offset = [ 0, 0 ]; } if (!touchId) d3_eventCancel(); event_({ type: "dragstart" }); } var event = d3_eventDispatch(drag, "drag", "dragstart", "dragend"), origin = null; drag.origin = function(x) { if (!arguments.length) return origin; origin = x; return drag; }; return d3.rebind(drag, event, "on"); }; d3.behavior.zoom = function() { function zoom() { this.on("mousedown.zoom", mousedown).on("mousewheel.zoom", mousewheel).on("mousemove.zoom", mousemove).on("DOMMouseScroll.zoom", mousewheel).on("dblclick.zoom", dblclick).on("touchstart.zoom", touchstart).on("touchmove.zoom", touchmove).on("touchend.zoom", touchstart); } function location(p) { return [ (p[0] - translate[0]) / scale, (p[1] - translate[1]) / scale ]; } function point(l) { return [ l[0] * scale + translate[0], l[1] * scale + translate[1] ]; } function scaleTo(s) { scale = Math.max(scaleExtent[0], Math.min(scaleExtent[1], s)); } function translateTo(p, l) { l = point(l); translate[0] += p[0] - l[0]; translate[1] += p[1] - l[1]; } function dispatch(event) { if (x1) x1.domain(x0.range().map(function(x) { return (x - translate[0]) / scale; }).map(x0.invert)); if (y1) y1.domain(y0.range().map(function(y) { return (y - translate[1]) / scale; }).map(y0.invert)); d3.event.preventDefault(); event({ type: "zoom", scale: scale, translate: translate }); } function mousedown() { function mousemove() { moved = 1; translateTo(d3.mouse(target), l); dispatch(event_); } function mouseup() { if (moved) d3_eventCancel(); w.on("mousemove.zoom", null).on("mouseup.zoom", null); if (moved && d3.event.target === eventTarget) w.on("click.zoom", click, true); } function click() { d3_eventCancel(); w.on("click.zoom", null); } var target = this, event_ = event.of(target, arguments), eventTarget = d3.event.target, moved = 0, w = d3.select(window).on("mousemove.zoom", mousemove).on("mouseup.zoom", mouseup), l = location(d3.mouse(target)); window.focus(); d3_eventCancel(); } function mousewheel() { if (!translate0) translate0 = location(d3.mouse(this)); scaleTo(Math.pow(2, d3_behavior_zoomDelta() * .002) * scale); translateTo(d3.mouse(this), translate0); dispatch(event.of(this, arguments)); } function mousemove() { translate0 = null; } function dblclick() { var p = d3.mouse(this), l = location(p); scaleTo(d3.event.shiftKey ? scale / 2 : scale * 2); translateTo(p, l); dispatch(event.of(this, arguments)); } function touchstart() { var touches = d3.touches(this), now = Date.now(); scale0 = scale; translate0 = {}; touches.forEach(function(t) { translate0[t.identifier] = location(t); }); d3_eventCancel(); if (touches.length === 1) { if (now - touchtime < 500) { var p = touches[0], l = location(touches[0]); scaleTo(scale * 2); translateTo(p, l); dispatch(event.of(this, arguments)); } touchtime = now; } } function touchmove() { var touches = d3.touches(this), p0 = touches[0], l0 = translate0[p0.identifier]; if (p1 = touches[1]) { var p1, l1 = translate0[p1.identifier]; p0 = [ (p0[0] + p1[0]) / 2, (p0[1] + p1[1]) / 2 ]; l0 = [ (l0[0] + l1[0]) / 2, (l0[1] + l1[1]) / 2 ]; scaleTo(d3.event.scale * scale0); } translateTo(p0, l0); touchtime = null; dispatch(event.of(this, arguments)); } var translate = [ 0, 0 ], translate0, scale = 1, scale0, scaleExtent = d3_behavior_zoomInfinity, event = d3_eventDispatch(zoom, "zoom"), x0, x1, y0, y1, touchtime; zoom.translate = function(x) { if (!arguments.length) return translate; translate = x.map(Number); return zoom; }; zoom.scale = function(x) { if (!arguments.length) return scale; scale = +x; return zoom; }; zoom.scaleExtent = function(x) { if (!arguments.length) return scaleExtent; scaleExtent = x == null ? d3_behavior_zoomInfinity : x.map(Number); return zoom; }; zoom.x = function(z) { if (!arguments.length) return x1; x1 = z; x0 = z.copy(); return zoom; }; zoom.y = function(z) { if (!arguments.length) return y1; y1 = z; y0 = z.copy(); return zoom; }; return d3.rebind(zoom, event, "on"); }; var d3_behavior_zoomDiv, d3_behavior_zoomInfinity = [ 0, Infinity ]; d3.layout = {}; d3.layout.bundle = function() { return function(links) { var paths = [], i = -1, n = links.length; while (++i < n) paths.push(d3_layout_bundlePath(links[i])); return paths; }; }; d3.layout.chord = function() { function relayout() { var subgroups = {}, groupSums = [], groupIndex = d3.range(n), subgroupIndex = [], k, x, x0, i, j; chords = []; groups = []; k = 0, i = -1; while (++i < n) { x = 0, j = -1; while (++j < n) { x += matrix[i][j]; } groupSums.push(x); subgroupIndex.push(d3.range(n)); k += x; } if (sortGroups) { groupIndex.sort(function(a, b) { return sortGroups(groupSums[a], groupSums[b]); }); } if (sortSubgroups) { subgroupIndex.forEach(function(d, i) { d.sort(function(a, b) { return sortSubgroups(matrix[i][a], matrix[i][b]); }); }); } k = (2 * Math.PI - padding * n) / k; x = 0, i = -1; while (++i < n) { x0 = x, j = -1; while (++j < n) { var di = groupIndex[i], dj = subgroupIndex[di][j], v = matrix[di][dj], a0 = x, a1 = x += v * k; subgroups[di + "-" + dj] = { index: di, subindex: dj, startAngle: a0, endAngle: a1, value: v }; } groups[di] = { index: di, startAngle: x0, endAngle: x, value: (x - x0) / k }; x += padding; } i = -1; while (++i < n) { j = i - 1; while (++j < n) { var source = subgroups[i + "-" + j], target = subgroups[j + "-" + i]; if (source.value || target.value) { chords.push(source.value < target.value ? { source: target, target: source } : { source: source, target: target }); } } } if (sortChords) resort(); } function resort() { chords.sort(function(a, b) { return sortChords((a.source.value + a.target.value) / 2, (b.source.value + b.target.value) / 2); }); } var chord = {}, chords, groups, matrix, n, padding = 0, sortGroups, sortSubgroups, sortChords; chord.matrix = function(x) { if (!arguments.length) return matrix; n = (matrix = x) && matrix.length; chords = groups = null; return chord; }; chord.padding = function(x) { if (!arguments.length) return padding; padding = x; chords = groups = null; return chord; }; chord.sortGroups = function(x) { if (!arguments.length) return sortGroups; sortGroups = x; chords = groups = null; return chord; }; chord.sortSubgroups = function(x) { if (!arguments.length) return sortSubgroups; sortSubgroups = x; chords = null; return chord; }; chord.sortChords = function(x) { if (!arguments.length) return sortChords; sortChords = x; if (chords) resort(); return chord; }; chord.chords = function() { if (!chords) relayout(); return chords; }; chord.groups = function() { if (!groups) relayout(); return groups; }; return chord; }; d3.layout.force = function() { function repulse(node) { return function(quad, x1, y1, x2, y2) { if (quad.point !== node) { var dx = quad.cx - node.x, dy = quad.cy - node.y, dn = 1 / Math.sqrt(dx * dx + dy * dy); if ((x2 - x1) * dn < theta) { var k = quad.charge * dn * dn; node.px -= dx * k; node.py -= dy * k; return true; } if (quad.point && isFinite(dn)) { var k = quad.pointCharge * dn * dn; node.px -= dx * k; node.py -= dy * k; } } return !quad.charge; }; } function dragmove(d) { d.px = d3.event.x; d.py = d3.event.y; force.resume(); } var force = {}, event = d3.dispatch("start", "tick", "end"), size = [ 1, 1 ], drag, alpha, friction = .9, linkDistance = d3_layout_forceLinkDistance, linkStrength = d3_layout_forceLinkStrength, charge = -30, gravity = .1, theta = .8, interval, nodes = [], links = [], distances, strengths, charges; force.tick = function() { if ((alpha *= .99) < .005) { event.end({ type: "end", alpha: alpha = 0 }); return true; } var n = nodes.length, m = links.length, q, i, o, s, t, l, k, x, y; for (i = 0; i < m; ++i) { o = links[i]; s = o.source; t = o.target; x = t.x - s.x; y = t.y - s.y; if (l = x * x + y * y) { l = alpha * strengths[i] * ((l = Math.sqrt(l)) - distances[i]) / l; x *= l; y *= l; t.x -= x * (k = s.weight / (t.weight + s.weight)); t.y -= y * k; s.x += x * (k = 1 - k); s.y += y * k; } } if (k = alpha * gravity) { x = size[0] / 2; y = size[1] / 2; i = -1; if (k) while (++i < n) { o = nodes[i]; o.x += (x - o.x) * k; o.y += (y - o.y) * k; } } if (charge) { d3_layout_forceAccumulate(q = d3.geom.quadtree(nodes), alpha, charges); i = -1; while (++i < n) { if (!(o = nodes[i]).fixed) { q.visit(repulse(o)); } } } i = -1; while (++i < n) { o = nodes[i]; if (o.fixed) { o.x = o.px; o.y = o.py; } else { o.x -= (o.px - (o.px = o.x)) * friction; o.y -= (o.py - (o.py = o.y)) * friction; } } event.tick({ type: "tick", alpha: alpha }); }; force.nodes = function(x) { if (!arguments.length) return nodes; nodes = x; return force; }; force.links = function(x) { if (!arguments.length) return links; links = x; return force; }; force.size = function(x) { if (!arguments.length) return size; size = x; return force; }; force.linkDistance = function(x) { if (!arguments.length) return linkDistance; linkDistance = d3_functor(x); return force; }; force.distance = force.linkDistance; force.linkStrength = function(x) { if (!arguments.length) return linkStrength; linkStrength = d3_functor(x); return force; }; force.friction = function(x) { if (!arguments.length) return friction; friction = x; return force; }; force.charge = function(x) { if (!arguments.length) return charge; charge = typeof x === "function" ? x : +x; return force; }; force.gravity = function(x) { if (!arguments.length) return gravity; gravity = x; return force; }; force.theta = function(x) { if (!arguments.length) return theta; theta = x; return force; }; force.alpha = function(x) { if (!arguments.length) return alpha; if (alpha) { if (x > 0) alpha = x; else alpha = 0; } else if (x > 0) { event.start({ type: "start", alpha: alpha = x }); d3.timer(force.tick); } return force; }; force.start = function() { function position(dimension, size) { var neighbors = neighbor(i), j = -1, m = neighbors.length, x; while (++j < m) if (!isNaN(x = neighbors[j][dimension])) return x; return Math.random() * size; } function neighbor() { if (!neighbors) { neighbors = []; for (j = 0; j < n; ++j) { neighbors[j] = []; } for (j = 0; j < m; ++j) { var o = links[j]; neighbors[o.source.index].push(o.target); neighbors[o.target.index].push(o.source); } } return neighbors[i]; } var i, j, n = nodes.length, m = links.length, w = size[0], h = size[1], neighbors, o; for (i = 0; i < n; ++i) { (o = nodes[i]).index = i; o.weight = 0; } distances = []; strengths = []; for (i = 0; i < m; ++i) { o = links[i]; if (typeof o.source == "number") o.source = nodes[o.source]; if (typeof o.target == "number") o.target = nodes[o.target]; distances[i] = linkDistance.call(this, o, i); strengths[i] = linkStrength.call(this, o, i); ++o.source.weight; ++o.target.weight; } for (i = 0; i < n; ++i) { o = nodes[i]; if (isNaN(o.x)) o.x = position("x", w); if (isNaN(o.y)) o.y = position("y", h); if (isNaN(o.px)) o.px = o.x; if (isNaN(o.py)) o.py = o.y; } charges = []; if (typeof charge === "function") { for (i = 0; i < n; ++i) { charges[i] = +charge.call(this, nodes[i], i); } } else { for (i = 0; i < n; ++i) { charges[i] = charge; } } return force.resume(); }; force.resume = function() { return force.alpha(.1); }; force.stop = function() { return force.alpha(0); }; force.drag = function() { if (!drag) drag = d3.behavior.drag().origin(d3_identity).on("dragstart", d3_layout_forceDragstart).on("drag", dragmove).on("dragend", d3_layout_forceDragend); this.on("mouseover.force", d3_layout_forceMouseover).on("mouseout.force", d3_layout_forceMouseout).call(drag); }; return d3.rebind(force, event, "on"); }; d3.layout.partition = function() { function position(node, x, dx, dy) { var children = node.children; node.x = x; node.y = node.depth * dy; node.dx = dx; node.dy = dy; if (children && (n = children.length)) { var i = -1, n, c, d; dx = node.value ? dx / node.value : 0; while (++i < n) { position(c = children[i], x, d = c.value * dx, dy); x += d; } } } function depth(node) { var children = node.children, d = 0; if (children && (n = children.length)) { var i = -1, n; while (++i < n) d = Math.max(d, depth(children[i])); } return 1 + d; } function partition(d, i) { var nodes = hierarchy.call(this, d, i); position(nodes[0], 0, size[0], size[1] / depth(nodes[0])); return nodes; } var hierarchy = d3.layout.hierarchy(), size = [ 1, 1 ]; partition.size = function(x) { if (!arguments.length) return size; size = x; return partition; }; return d3_layout_hierarchyRebind(partition, hierarchy); }; d3.layout.pie = function() { function pie(data, i) { var values = data.map(function(d, i) { return +value.call(pie, d, i); }); var a = +(typeof startAngle === "function" ? startAngle.apply(this, arguments) : startAngle); var k = ((typeof endAngle === "function" ? endAngle.apply(this, arguments) : endAngle) - startAngle) / d3.sum(values); var index = d3.range(data.length); if (sort != null) index.sort(sort === d3_layout_pieSortByValue ? function(i, j) { return values[j] - values[i]; } : function(i, j) { return sort(data[i], data[j]); }); var arcs = []; index.forEach(function(i) { var d; arcs[i] = { data: data[i], value: d = values[i], startAngle: a, endAngle: a += d * k }; }); return arcs; } var value = Number, sort = d3_layout_pieSortByValue, startAngle = 0, endAngle = 2 * Math.PI; pie.value = function(x) { if (!arguments.length) return value; value = x; return pie; }; pie.sort = function(x) { if (!arguments.length) return sort; sort = x; return pie; }; pie.startAngle = function(x) { if (!arguments.length) return startAngle; startAngle = x; return pie; }; pie.endAngle = function(x) { if (!arguments.length) return endAngle; endAngle = x; return pie; }; return pie; }; var d3_layout_pieSortByValue = {}; d3.layout.stack = function() { function stack(data, index) { var series = data.map(function(d, i) { return values.call(stack, d, i); }); var points = series.map(function(d, i) { return d.map(function(v, i) { return [ x.call(stack, v, i), y.call(stack, v, i) ]; }); }); var orders = order.call(stack, points, index); series = d3.permute(series, orders); points = d3.permute(points, orders); var offsets = offset.call(stack, points, index); var n = series.length, m = series[0].length, i, j, o; for (j = 0; j < m; ++j) { out.call(stack, series[0][j], o = offsets[j], points[0][j][1]); for (i = 1; i < n; ++i) { out.call(stack, series[i][j], o += points[i - 1][j][1], points[i][j][1]); } } return data; } var values = d3_identity, order = d3_layout_stackOrderDefault, offset = d3_layout_stackOffsetZero, out = d3_layout_stackOut, x = d3_layout_stackX, y = d3_layout_stackY; stack.values = function(x) { if (!arguments.length) return values; values = x; return stack; }; stack.order = function(x) { if (!arguments.length) return order; order = typeof x === "function" ? x : d3_layout_stackOrders.get(x) || d3_layout_stackOrderDefault; return stack; }; stack.offset = function(x) { if (!arguments.length) return offset; offset = typeof x === "function" ? x : d3_layout_stackOffsets.get(x) || d3_layout_stackOffsetZero; return stack; }; stack.x = function(z) { if (!arguments.length) return x; x = z; return stack; }; stack.y = function(z) { if (!arguments.length) return y; y = z; return stack; }; stack.out = function(z) { if (!arguments.length) return out; out = z; return stack; }; return stack; }; var d3_layout_stackOrders = d3.map({ "inside-out": function(data) { var n = data.length, i, j, max = data.map(d3_layout_stackMaxIndex), sums = data.map(d3_layout_stackReduceSum), index = d3.range(n).sort(function(a, b) { return max[a] - max[b]; }), top = 0, bottom = 0, tops = [], bottoms = []; for (i = 0; i < n; ++i) { j = index[i]; if (top < bottom) { top += sums[j]; tops.push(j); } else { bottom += sums[j]; bottoms.push(j); } } return bottoms.reverse().concat(tops); }, reverse: function(data) { return d3.range(data.length).reverse(); }, "default": d3_layout_stackOrderDefault }); var d3_layout_stackOffsets = d3.map({ silhouette: function(data) { var n = data.length, m = data[0].length, sums = [], max = 0, i, j, o, y0 = []; for (j = 0; j < m; ++j) { for (i = 0, o = 0; i < n; i++) o += data[i][j][1]; if (o > max) max = o; sums.push(o); } for (j = 0; j < m; ++j) { y0[j] = (max - sums[j]) / 2; } return y0; }, wiggle: function(data) { var n = data.length, x = data[0], m = x.length, max = 0, i, j, k, s1, s2, s3, dx, o, o0, y0 = []; y0[0] = o = o0 = 0; for (j = 1; j < m; ++j) { for (i = 0, s1 = 0; i < n; ++i) s1 += data[i][j][1]; for (i = 0, s2 = 0, dx = x[j][0] - x[j - 1][0]; i < n; ++i) { for (k = 0, s3 = (data[i][j][1] - data[i][j - 1][1]) / (2 * dx); k < i; ++k) { s3 += (data[k][j][1] - data[k][j - 1][1]) / dx; } s2 += s3 * data[i][j][1]; } y0[j] = o -= s1 ? s2 / s1 * dx : 0; if (o < o0) o0 = o; } for (j = 0; j < m; ++j) y0[j] -= o0; return y0; }, expand: function(data) { var n = data.length, m = data[0].length, k = 1 / n, i, j, o, y0 = []; for (j = 0; j < m; ++j) { for (i = 0, o = 0; i < n; i++) o += data[i][j][1]; if (o) for (i = 0; i < n; i++) data[i][j][1] /= o; else for (i = 0; i < n; i++) data[i][j][1] = k; } for (j = 0; j < m; ++j) y0[j] = 0; return y0; }, zero: d3_layout_stackOffsetZero }); d3.layout.histogram = function() { function histogram(data, i) { var bins = [], values = data.map(valuer, this), range = ranger.call(this, values, i), thresholds = binner.call(this, range, values, i), bin, i = -1, n = values.length, m = thresholds.length - 1, k = frequency ? 1 : 1 / n, x; while (++i < m) { bin = bins[i] = []; bin.dx = thresholds[i + 1] - (bin.x = thresholds[i]); bin.y = 0; } if (m > 0) { i = -1; while (++i < n) { x = values[i]; if (x >= range[0] && x <= range[1]) { bin = bins[d3.bisect(thresholds, x, 1, m) - 1]; bin.y += k; bin.push(data[i]); } } } return bins; } var frequency = true, valuer = Number, ranger = d3_layout_histogramRange, binner = d3_layout_histogramBinSturges; histogram.value = function(x) { if (!arguments.length) return valuer; valuer = x; return histogram; }; histogram.range = function(x) { if (!arguments.length) return ranger; ranger = d3_functor(x); return histogram; }; histogram.bins = function(x) { if (!arguments.length) return binner; binner = typeof x === "number" ? function(range) { return d3_layout_histogramBinFixed(range, x); } : d3_functor(x); return histogram; }; histogram.frequency = function(x) { if (!arguments.length) return frequency; frequency = !!x; return histogram; }; return histogram; }; d3.layout.hierarchy = function() { function recurse(data, depth, nodes) { var childs = children.call(hierarchy, data, depth), node = d3_layout_hierarchyInline ? data : { data: data }; node.depth = depth; nodes.push(node); if (childs && (n = childs.length)) { var i = -1, n, c = node.children = [], v = 0, j = depth + 1, d; while (++i < n) { d = recurse(childs[i], j, nodes); d.parent = node; c.push(d); v += d.value; } if (sort) c.sort(sort); if (value) node.value = v; } else if (value) { node.value = +value.call(hierarchy, data, depth) || 0; } return node; } function revalue(node, depth) { var children = node.children, v = 0; if (children && (n = children.length)) { var i = -1, n, j = depth + 1; while (++i < n) v += revalue(children[i], j); } else if (value) { v = +value.call(hierarchy, d3_layout_hierarchyInline ? node : node.data, depth) || 0; } if (value) node.value = v; return v; } function hierarchy(d) { var nodes = []; recurse(d, 0, nodes); return nodes; } var sort = d3_layout_hierarchySort, children = d3_layout_hierarchyChildren, value = d3_layout_hierarchyValue; hierarchy.sort = function(x) { if (!arguments.length) return sort; sort = x; return hierarchy; }; hierarchy.children = function(x) { if (!arguments.length) return children; children = x; return hierarchy; }; hierarchy.value = function(x) { if (!arguments.length) return value; value = x; return hierarchy; }; hierarchy.revalue = function(root) { revalue(root, 0); return root; }; return hierarchy; }; var d3_layout_hierarchyInline = false; d3.layout.pack = function() { function pack(d, i) { var nodes = hierarchy.call(this, d, i), root = nodes[0]; root.x = 0; root.y = 0; d3_layout_treeVisitAfter(root, function(d) { d.r = Math.sqrt(d.value); }); d3_layout_treeVisitAfter(root, d3_layout_packSiblings); var w = size[0], h = size[1], k = Math.max(2 * root.r / w, 2 * root.r / h); if (padding > 0) { var dr = padding * k / 2; d3_layout_treeVisitAfter(root, function(d) { d.r += dr; }); d3_layout_treeVisitAfter(root, d3_layout_packSiblings); d3_layout_treeVisitAfter(root, function(d) { d.r -= dr; }); k = Math.max(2 * root.r / w, 2 * root.r / h); } d3_layout_packTransform(root, w / 2, h / 2, 1 / k); return nodes; } var hierarchy = d3.layout.hierarchy().sort(d3_layout_packSort), padding = 0, size = [ 1, 1 ]; pack.size = function(x) { if (!arguments.length) return size; size = x; return pack; }; pack.padding = function(_) { if (!arguments.length) return padding; padding = +_; return pack; }; return d3_layout_hierarchyRebind(pack, hierarchy); }; d3.layout.cluster = function() { function cluster(d, i) { var nodes = hierarchy.call(this, d, i), root = nodes[0], previousNode, x = 0, kx, ky; d3_layout_treeVisitAfter(root, function(node) { var children = node.children; if (children && children.length) { node.x = d3_layout_clusterX(children); node.y = d3_layout_clusterY(children); } else { node.x = previousNode ? x += separation(node, previousNode) : 0; node.y = 0; previousNode = node; } }); var left = d3_layout_clusterLeft(root), right = d3_layout_clusterRight(root), x0 = left.x - separation(left, right) / 2, x1 = right.x + separation(right, left) / 2; d3_layout_treeVisitAfter(root, function(node) { node.x = (node.x - x0) / (x1 - x0) * size[0]; node.y = (1 - (root.y ? node.y / root.y : 1)) * size[1]; }); return nodes; } var hierarchy = d3.layout.hierarchy().sort(null).value(null), separation = d3_layout_treeSeparation, size = [ 1, 1 ]; cluster.separation = function(x) { if (!arguments.length) return separation; separation = x; return cluster; }; cluster.size = function(x) { if (!arguments.length) return size; size = x; return cluster; }; return d3_layout_hierarchyRebind(cluster, hierarchy); }; d3.layout.tree = function() { function tree(d, i) { function firstWalk(node, previousSibling) { var children = node.children, layout = node._tree; if (children && (n = children.length)) { var n, firstChild = children[0], previousChild, ancestor = firstChild, child, i = -1; while (++i < n) { child = children[i]; firstWalk(child, previousChild); ancestor = apportion(child, previousChild, ancestor); previousChild = child; } d3_layout_treeShift(node); var midpoint = .5 * (firstChild._tree.prelim + child._tree.prelim); if (previousSibling) { layout.prelim = previousSibling._tree.prelim + separation(node, previousSibling); layout.mod = layout.prelim - midpoint; } else { layout.prelim = midpoint; } } else { if (previousSibling) { layout.prelim = previousSibling._tree.prelim + separation(node, previousSibling); } } } function secondWalk(node, x) { node.x = node._tree.prelim + x; var children = node.children; if (children && (n = children.length)) { var i = -1, n; x += node._tree.mod; while (++i < n) { secondWalk(children[i], x); } } } function apportion(node, previousSibling, ancestor) { if (previousSibling) { var vip = node, vop = node, vim = previousSibling, vom = node.parent.children[0], sip = vip._tree.mod, sop = vop._tree.mod, sim = vim._tree.mod, som = vom._tree.mod, shift; while (vim = d3_layout_treeRight(vim), vip = d3_layout_treeLeft(vip), vim && vip) { vom = d3_layout_treeLeft(vom); vop = d3_layout_treeRight(vop); vop._tree.ancestor = node; shift = vim._tree.prelim + sim - vip._tree.prelim - sip + separation(vim, vip); if (shift > 0) { d3_layout_treeMove(d3_layout_treeAncestor(vim, node, ancestor), node, shift); sip += shift; sop += shift; } sim += vim._tree.mod; sip += vip._tree.mod; som += vom._tree.mod; sop += vop._tree.mod; } if (vim && !d3_layout_treeRight(vop)) { vop._tree.thread = vim; vop._tree.mod += sim - sop; } if (vip && !d3_layout_treeLeft(vom)) { vom._tree.thread = vip; vom._tree.mod += sip - som; ancestor = node; } } return ancestor; } var nodes = hierarchy.call(this, d, i), root = nodes[0]; d3_layout_treeVisitAfter(root, function(node, previousSibling) { node._tree = { ancestor: node, prelim: 0, mod: 0, change: 0, shift: 0, number: previousSibling ? previousSibling._tree.number + 1 : 0 }; }); firstWalk(root); secondWalk(root, -root._tree.prelim); var left = d3_layout_treeSearch(root, d3_layout_treeLeftmost), right = d3_layout_treeSearch(root, d3_layout_treeRightmost), deep = d3_layout_treeSearch(root, d3_layout_treeDeepest), x0 = left.x - separation(left, right) / 2, x1 = right.x + separation(right, left) / 2, y1 = deep.depth || 1; d3_layout_treeVisitAfter(root, function(node) { node.x = (node.x - x0) / (x1 - x0) * size[0]; node.y = node.depth / y1 * size[1]; delete node._tree; }); return nodes; } var hierarchy = d3.layout.hierarchy().sort(null).value(null), separation = d3_layout_treeSeparation, size = [ 1, 1 ]; tree.separation = function(x) { if (!arguments.length) return separation; separation = x; return tree; }; tree.size = function(x) { if (!arguments.length) return size; size = x; return tree; }; return d3_layout_hierarchyRebind(tree, hierarchy); }; d3.layout.treemap = function() { function scale(children, k) { var i = -1, n = children.length, child, area; while (++i < n) { area = (child = children[i]).value * (k < 0 ? 0 : k); child.area = isNaN(area) || area <= 0 ? 0 : area; } } function squarify(node) { var children = node.children; if (children && children.length) { var rect = pad(node), row = [], remaining = children.slice(), child, best = Infinity, score, u = Math.min(rect.dx, rect.dy), n; scale(remaining, rect.dx * rect.dy / node.value); row.area = 0; while ((n = remaining.length) > 0) { row.push(child = remaining[n - 1]); row.area += child.area; if ((score = worst(row, u)) <= best) { remaining.pop(); best = score; } else { row.area -= row.pop().area; position(row, u, rect, false); u = Math.min(rect.dx, rect.dy); row.length = row.area = 0; best = Infinity; } } if (row.length) { position(row, u, rect, true); row.length = row.area = 0; } children.forEach(squarify); } } function stickify(node) { var children = node.children; if (children && children.length) { var rect = pad(node), remaining = children.slice(), child, row = []; scale(remaining, rect.dx * rect.dy / node.value); row.area = 0; while (child = remaining.pop()) { row.push(child); row.area += child.area; if (child.z != null) { position(row, child.z ? rect.dx : rect.dy, rect, !remaining.length); row.length = row.area = 0; } } children.forEach(stickify); } } function worst(row, u) { var s = row.area, r, rmax = 0, rmin = Infinity, i = -1, n = row.length; while (++i < n) { if (!(r = row[i].area)) continue; if (r < rmin) rmin = r; if (r > rmax) rmax = r; } s *= s; u *= u; return s ? Math.max(u * rmax * ratio / s, s / (u * rmin * ratio)) : Infinity; } function position(row, u, rect, flush) { var i = -1, n = row.length, x = rect.x, y = rect.y, v = u ? round(row.area / u) : 0, o; if (u == rect.dx) { if (flush || v > rect.dy) v = rect.dy; while (++i < n) { o = row[i]; o.x = x; o.y = y; o.dy = v; x += o.dx = Math.min(rect.x + rect.dx - x, v ? round(o.area / v) : 0); } o.z = true; o.dx += rect.x + rect.dx - x; rect.y += v; rect.dy -= v; } else { if (flush || v > rect.dx) v = rect.dx; while (++i < n) { o = row[i]; o.x = x; o.y = y; o.dx = v; y += o.dy = Math.min(rect.y + rect.dy - y, v ? round(o.area / v) : 0); } o.z = false; o.dy += rect.y + rect.dy - y; rect.x += v; rect.dx -= v; } } function treemap(d) { var nodes = stickies || hierarchy(d), root = nodes[0]; root.x = 0; root.y = 0; root.dx = size[0]; root.dy = size[1]; if (stickies) hierarchy.revalue(root); scale([ root ], root.dx * root.dy / root.value); (stickies ? stickify : squarify)(root); if (sticky) stickies = nodes; return nodes; } var hierarchy = d3.layout.hierarchy(), round = Math.round, size = [ 1, 1 ], padding = null, pad = d3_layout_treemapPadNull, sticky = false, stickies, ratio = .5 * (1 + Math.sqrt(5)); treemap.size = function(x) { if (!arguments.length) return size; size = x; return treemap; }; treemap.padding = function(x) { function padFunction(node) { var p = x.call(treemap, node, node.depth); return p == null ? d3_layout_treemapPadNull(node) : d3_layout_treemapPad(node, typeof p === "number" ? [ p, p, p, p ] : p); } function padConstant(node) { return d3_layout_treemapPad(node, x); } if (!arguments.length) return padding; var type; pad = (padding = x) == null ? d3_layout_treemapPadNull : (type = typeof x) === "function" ? padFunction : type === "number" ? (x = [ x, x, x, x ], padConstant) : padConstant; return treemap; }; treemap.round = function(x) { if (!arguments.length) return round != Number; round = x ? Math.round : Number; return treemap; }; treemap.sticky = function(x) { if (!arguments.length) return sticky; sticky = x; stickies = null; return treemap; }; treemap.ratio = function(x) { if (!arguments.length) return ratio; ratio = x; return treemap; }; return d3_layout_hierarchyRebind(treemap, hierarchy); }; d3.csv = d3_dsv(",", "text/csv"); d3.tsv = d3_dsv(" ", "text/tab-separated-values"); d3.geo = {}; var d3_geo_radians = Math.PI / 180; d3.geo.azimuthal = function() { function azimuthal(coordinates) { var x1 = coordinates[0] * d3_geo_radians - x0, y1 = coordinates[1] * d3_geo_radians, cx1 = Math.cos(x1), sx1 = Math.sin(x1), cy1 = Math.cos(y1), sy1 = Math.sin(y1), cc = mode !== "orthographic" ? sy0 * sy1 + cy0 * cy1 * cx1 : null, c, k = mode === "stereographic" ? 1 / (1 + cc) : mode === "gnomonic" ? 1 / cc : mode === "equidistant" ? (c = Math.acos(cc), c ? c / Math.sin(c) : 0) : mode === "equalarea" ? Math.sqrt(2 / (1 + cc)) : 1, x = k * cy1 * sx1, y = k * (sy0 * cy1 * cx1 - cy0 * sy1); return [ scale * x + translate[0], scale * y + translate[1] ]; } var mode = "orthographic", origin, scale = 200, translate = [ 480, 250 ], x0, y0, cy0, sy0; azimuthal.invert = function(coordinates) { var x = (coordinates[0] - translate[0]) / scale, y = (coordinates[1] - translate[1]) / scale, p = Math.sqrt(x * x + y * y), c = mode === "stereographic" ? 2 * Math.atan(p) : mode === "gnomonic" ? Math.atan(p) : mode === "equidistant" ? p : mode === "equalarea" ? 2 * Math.asin(.5 * p) : Math.asin(p), sc = Math.sin(c), cc = Math.cos(c); return [ (x0 + Math.atan2(x * sc, p * cy0 * cc + y * sy0 * sc)) / d3_geo_radians, Math.asin(cc * sy0 - (p ? y * sc * cy0 / p : 0)) / d3_geo_radians ]; }; azimuthal.mode = function(x) { if (!arguments.length) return mode; mode = x + ""; return azimuthal; }; azimuthal.origin = function(x) { if (!arguments.length) return origin; origin = x; x0 = origin[0] * d3_geo_radians; y0 = origin[1] * d3_geo_radians; cy0 = Math.cos(y0); sy0 = Math.sin(y0); return azimuthal; }; azimuthal.scale = function(x) { if (!arguments.length) return scale; scale = +x; return azimuthal; }; azimuthal.translate = function(x) { if (!arguments.length) return translate; translate = [ +x[0], +x[1] ]; return azimuthal; }; return azimuthal.origin([ 0, 0 ]); }; d3.geo.albers = function() { function albers(coordinates) { var t = n * (d3_geo_radians * coordinates[0] - lng0), p = Math.sqrt(C - 2 * n * Math.sin(d3_geo_radians * coordinates[1])) / n; return [ scale * p * Math.sin(t) + translate[0], scale * (p * Math.cos(t) - p0) + translate[1] ]; } function reload() { var phi1 = d3_geo_radians * parallels[0], phi2 = d3_geo_radians * parallels[1], lat0 = d3_geo_radians * origin[1], s = Math.sin(phi1), c = Math.cos(phi1); lng0 = d3_geo_radians * origin[0]; n = .5 * (s + Math.sin(phi2)); C = c * c + 2 * n * s; p0 = Math.sqrt(C - 2 * n * Math.sin(lat0)) / n; return albers; } var origin = [ -98, 38 ], parallels = [ 29.5, 45.5 ], scale = 1e3, translate = [ 480, 250 ], lng0, n, C, p0; albers.invert = function(coordinates) { var x = (coordinates[0] - translate[0]) / scale, y = (coordinates[1] - translate[1]) / scale, p0y = p0 + y, t = Math.atan2(x, p0y), p = Math.sqrt(x * x + p0y * p0y); return [ (lng0 + t / n) / d3_geo_radians, Math.asin((C - p * p * n * n) / (2 * n)) / d3_geo_radians ]; }; albers.origin = function(x) { if (!arguments.length) return origin; origin = [ +x[0], +x[1] ]; return reload(); }; albers.parallels = function(x) { if (!arguments.length) return parallels; parallels = [ +x[0], +x[1] ]; return reload(); }; albers.scale = function(x) { if (!arguments.length) return scale; scale = +x; return albers; }; albers.translate = function(x) { if (!arguments.length) return translate; translate = [ +x[0], +x[1] ]; return albers; }; return reload(); }; d3.geo.albersUsa = function() { function albersUsa(coordinates) { var lon = coordinates[0], lat = coordinates[1]; return (lat > 50 ? alaska : lon < -140 ? hawaii : lat < 21 ? puertoRico : lower48)(coordinates); } var lower48 = d3.geo.albers(); var alaska = d3.geo.albers().origin([ -160, 60 ]).parallels([ 55, 65 ]); var hawaii = d3.geo.albers().origin([ -160, 20 ]).parallels([ 8, 18 ]); var puertoRico = d3.geo.albers().origin([ -60, 10 ]).parallels([ 8, 18 ]); albersUsa.scale = function(x) { if (!arguments.length) return lower48.scale(); lower48.scale(x); alaska.scale(x * .6); hawaii.scale(x); puertoRico.scale(x * 1.5); return albersUsa.translate(lower48.translate()); }; albersUsa.translate = function(x) { if (!arguments.length) return lower48.translate(); var dz = lower48.scale() / 1e3, dx = x[0], dy = x[1]; lower48.translate(x); alaska.translate([ dx - 400 * dz, dy + 170 * dz ]); hawaii.translate([ dx - 190 * dz, dy + 200 * dz ]); puertoRico.translate([ dx + 580 * dz, dy + 430 * dz ]); return albersUsa; }; return albersUsa.scale(lower48.scale()); }; d3.geo.bonne = function() { function bonne(coordinates) { var x = coordinates[0] * d3_geo_radians - x0, y = coordinates[1] * d3_geo_radians - y0; if (y1) { var p = c1 + y1 - y, E = x * Math.cos(y) / p; x = p * Math.sin(E); y = p * Math.cos(E) - c1; } else { x *= Math.cos(y); y *= -1; } return [ scale * x + translate[0], scale * y + translate[1] ]; } var scale = 200, translate = [ 480, 250 ], x0, y0, y1, c1; bonne.invert = function(coordinates) { var x = (coordinates[0] - translate[0]) / scale, y = (coordinates[1] - translate[1]) / scale; if (y1) { var c = c1 + y, p = Math.sqrt(x * x + c * c); y = c1 + y1 - p; x = x0 + p * Math.atan2(x, c) / Math.cos(y); } else { y *= -1; x /= Math.cos(y); } return [ x / d3_geo_radians, y / d3_geo_radians ]; }; bonne.parallel = function(x) { if (!arguments.length) return y1 / d3_geo_radians; c1 = 1 / Math.tan(y1 = x * d3_geo_radians); return bonne; }; bonne.origin = function(x) { if (!arguments.length) return [ x0 / d3_geo_radians, y0 / d3_geo_radians ]; x0 = x[0] * d3_geo_radians; y0 = x[1] * d3_geo_radians; return bonne; }; bonne.scale = function(x) { if (!arguments.length) return scale; scale = +x; return bonne; }; bonne.translate = function(x) { if (!arguments.length) return translate; translate = [ +x[0], +x[1] ]; return bonne; }; return bonne.origin([ 0, 0 ]).parallel(45); }; d3.geo.equirectangular = function() { function equirectangular(coordinates) { var x = coordinates[0] / 360, y = -coordinates[1] / 360; return [ scale * x + translate[0], scale * y + translate[1] ]; } var scale = 500, translate = [ 480, 250 ]; equirectangular.invert = function(coordinates) { var x = (coordinates[0] - translate[0]) / scale, y = (coordinates[1] - translate[1]) / scale; return [ 360 * x, -360 * y ]; }; equirectangular.scale = function(x) { if (!arguments.length) return scale; scale = +x; return equirectangular; }; equirectangular.translate = function(x) { if (!arguments.length) return translate; translate = [ +x[0], +x[1] ]; return equirectangular; }; return equirectangular; }; d3.geo.mercator = function() { function mercator(coordinates) { var x = coordinates[0] / 360, y = -(Math.log(Math.tan(Math.PI / 4 + coordinates[1] * d3_geo_radians / 2)) / d3_geo_radians) / 360; return [ scale * x + translate[0], scale * Math.max(-.5, Math.min(.5, y)) + translate[1] ]; } var scale = 500, translate = [ 480, 250 ]; mercator.invert = function(coordinates) { var x = (coordinates[0] - translate[0]) / scale, y = (coordinates[1] - translate[1]) / scale; return [ 360 * x, 2 * Math.atan(Math.exp(-360 * y * d3_geo_radians)) / d3_geo_radians - 90 ]; }; mercator.scale = function(x) { if (!arguments.length) return scale; scale = +x; return mercator; }; mercator.translate = function(x) { if (!arguments.length) return translate; translate = [ +x[0], +x[1] ]; return mercator; }; return mercator; }; d3.geo.path = function() { function path(d, i) { if (typeof pointRadius === "function") pointCircle = d3_path_circle(pointRadius.apply(this, arguments)); pathType(d); var result = buffer.length ? buffer.join("") : null; buffer = []; return result; } function project(coordinates) { return projection(coordinates).join(","); } function polygonArea(coordinates) { var sum = area(coordinates[0]), i = 0, n = coordinates.length; while (++i < n) sum -= area(coordinates[i]); return sum; } function polygonCentroid(coordinates) { var polygon = d3.geom.polygon(coordinates[0].map(projection)), area = polygon.area(), centroid = polygon.centroid(area < 0 ? (area *= -1, 1) : -1), x = centroid[0], y = centroid[1], z = area, i = 0, n = coordinates.length; while (++i < n) { polygon = d3.geom.polygon(coordinates[i].map(projection)); area = polygon.area(); centroid = polygon.centroid(area < 0 ? (area *= -1, 1) : -1); x -= centroid[0]; y -= centroid[1]; z -= area; } return [ x, y, 6 * z ]; } function area(coordinates) { return Math.abs(d3.geom.polygon(coordinates.map(projection)).area()); } var pointRadius = 4.5, pointCircle = d3_path_circle(pointRadius), projection = d3.geo.albersUsa(), buffer = []; var pathType = d3_geo_type({ FeatureCollection: function(o) { var features = o.features, i = -1, n = features.length; while (++i < n) buffer.push(pathType(features[i].geometry)); }, Feature: function(o) { pathType(o.geometry); }, Point: function(o) { buffer.push("M", project(o.coordinates), pointCircle); }, MultiPoint: function(o) { var coordinates = o.coordinates, i = -1, n = coordinates.length; while (++i < n) buffer.push("M", project(coordinates[i]), pointCircle); }, LineString: function(o) { var coordinates = o.coordinates, i = -1, n = coordinates.length; buffer.push("M"); while (++i < n) buffer.push(project(coordinates[i]), "L"); buffer.pop(); }, MultiLineString: function(o) { var coordinates = o.coordinates, i = -1, n = coordinates.length, subcoordinates, j, m; while (++i < n) { subcoordinates = coordinates[i]; j = -1; m = subcoordinates.length; buffer.push("M"); while (++j < m) buffer.push(project(subcoordinates[j]), "L"); buffer.pop(); } }, Polygon: function(o) { var coordinates = o.coordinates, i = -1, n = coordinates.length, subcoordinates, j, m; while (++i < n) { subcoordinates = coordinates[i]; j = -1; if ((m = subcoordinates.length - 1) > 0) { buffer.push("M"); while (++j < m) buffer.push(project(subcoordinates[j]), "L"); buffer[buffer.length - 1] = "Z"; } } }, MultiPolygon: function(o) { var coordinates = o.coordinates, i = -1, n = coordinates.length, subcoordinates, j, m, subsubcoordinates, k, p; while (++i < n) { subcoordinates = coordinates[i]; j = -1; m = subcoordinates.length; while (++j < m) { subsubcoordinates = subcoordinates[j]; k = -1; if ((p = subsubcoordinates.length - 1) > 0) { buffer.push("M"); while (++k < p) buffer.push(project(subsubcoordinates[k]), "L"); buffer[buffer.length - 1] = "Z"; } } } }, GeometryCollection: function(o) { var geometries = o.geometries, i = -1, n = geometries.length; while (++i < n) buffer.push(pathType(geometries[i])); } }); var areaType = path.area = d3_geo_type({ FeatureCollection: function(o) { var area = 0, features = o.features, i = -1, n = features.length; while (++i < n) area += areaType(features[i]); return area; }, Feature: function(o) { return areaType(o.geometry); }, Polygon: function(o) { return polygonArea(o.coordinates); }, MultiPolygon: function(o) { var sum = 0, coordinates = o.coordinates, i = -1, n = coordinates.length; while (++i < n) sum += polygonArea(coordinates[i]); return sum; }, GeometryCollection: function(o) { var sum = 0, geometries = o.geometries, i = -1, n = geometries.length; while (++i < n) sum += areaType(geometries[i]); return sum; } }, 0); var centroidType = path.centroid = d3_geo_type({ Feature: function(o) { return centroidType(o.geometry); }, Polygon: function(o) { var centroid = polygonCentroid(o.coordinates); return [ centroid[0] / centroid[2], centroid[1] / centroid[2] ]; }, MultiPolygon: function(o) { var area = 0, coordinates = o.coordinates, centroid, x = 0, y = 0, z = 0, i = -1, n = coordinates.length; while (++i < n) { centroid = polygonCentroid(coordinates[i]); x += centroid[0]; y += centroid[1]; z += centroid[2]; } return [ x / z, y / z ]; } }); path.projection = function(x) { projection = x; return path; }; path.pointRadius = function(x) { if (typeof x === "function") pointRadius = x; else { pointRadius = +x; pointCircle = d3_path_circle(pointRadius); } return path; }; return path; }; d3.geo.bounds = function(feature) { var left = Infinity, bottom = Infinity, right = -Infinity, top = -Infinity; d3_geo_bounds(feature, function(x, y) { if (x < left) left = x; if (x > right) right = x; if (y < bottom) bottom = y; if (y > top) top = y; }); return [ [ left, bottom ], [ right, top ] ]; }; var d3_geo_boundsTypes = { Feature: d3_geo_boundsFeature, FeatureCollection: d3_geo_boundsFeatureCollection, GeometryCollection: d3_geo_boundsGeometryCollection, LineString: d3_geo_boundsLineString, MultiLineString: d3_geo_boundsMultiLineString, MultiPoint: d3_geo_boundsLineString, MultiPolygon: d3_geo_boundsMultiPolygon, Point: d3_geo_boundsPoint, Polygon: d3_geo_boundsPolygon }; d3.geo.circle = function() { function circle() {} function visible(point) { return arc.distance(point) < radians; } function clip(coordinates) { var i = -1, n = coordinates.length, clipped = [], p0, p1, p2, d0, d1; while (++i < n) { d1 = arc.distance(p2 = coordinates[i]); if (d1 < radians) { if (p1) clipped.push(d3_geo_greatArcInterpolate(p1, p2)((d0 - radians) / (d0 - d1))); clipped.push(p2); p0 = p1 = null; } else { p1 = p2; if (!p0 && clipped.length) { clipped.push(d3_geo_greatArcInterpolate(clipped[clipped.length - 1], p1)((radians - d0) / (d1 - d0))); p0 = p1; } } d0 = d1; } p0 = coordinates[0]; p1 = clipped[0]; if (p1 && p2[0] === p0[0] && p2[1] === p0[1] && !(p2[0] === p1[0] && p2[1] === p1[1])) { clipped.push(p1); } return resample(clipped); } function resample(coordinates) { var i = 0, n = coordinates.length, j, m, resampled = n ? [ coordinates[0] ] : coordinates, resamples, origin = arc.source(); while (++i < n) { resamples = arc.source(coordinates[i - 1])(coordinates[i]).coordinates; for (j = 0, m = resamples.length; ++j < m; ) resampled.push(resamples[j]); } arc.source(origin); return resampled; } var origin = [ 0, 0 ], degrees = 90 - .01, radians = degrees * d3_geo_radians, arc = d3.geo.greatArc().source(origin).target(d3_identity); circle.clip = function(d) { if (typeof origin === "function") arc.source(origin.apply(this, arguments)); return clipType(d) || null; }; var clipType = d3_geo_type({ FeatureCollection: function(o) { var features = o.features.map(clipType).filter(d3_identity); return features && (o = Object.create(o), o.features = features, o); }, Feature: function(o) { var geometry = clipType(o.geometry); return geometry && (o = Object.create(o), o.geometry = geometry, o); }, Point: function(o) { return visible(o.coordinates) && o; }, MultiPoint: function(o) { var coordinates = o.coordinates.filter(visible); return coordinates.length && { type: o.type, coordinates: coordinates }; }, LineString: function(o) { var coordinates = clip(o.coordinates); return coordinates.length && (o = Object.create(o), o.coordinates = coordinates, o); }, MultiLineString: function(o) { var coordinates = o.coordinates.map(clip).filter(function(d) { return d.length; }); return coordinates.length && (o = Object.create(o), o.coordinates = coordinates, o); }, Polygon: function(o) { var coordinates = o.coordinates.map(clip); return coordinates[0].length && (o = Object.create(o), o.coordinates = coordinates, o); }, MultiPolygon: function(o) { var coordinates = o.coordinates.map(function(d) { return d.map(clip); }).filter(function(d) { return d[0].length; }); return coordinates.length && (o = Object.create(o), o.coordinates = coordinates, o); }, GeometryCollection: function(o) { var geometries = o.geometries.map(clipType).filter(d3_identity); return geometries.length && (o = Object.create(o), o.geometries = geometries, o); } }); circle.origin = function(x) { if (!arguments.length) return origin; origin = x; if (typeof origin !== "function") arc.source(origin); return circle; }; circle.angle = function(x) { if (!arguments.length) return degrees; radians = (degrees = +x) * d3_geo_radians; return circle; }; return d3.rebind(circle, arc, "precision"); }; d3.geo.greatArc = function() { function greatArc() { var d = greatArc.distance.apply(this, arguments), t = 0, dt = precision / d, coordinates = [ p0 ]; while ((t += dt) < 1) coordinates.push(interpolate(t)); coordinates.push(p1); return { type: "LineString", coordinates: coordinates }; } var source = d3_geo_greatArcSource, p0, target = d3_geo_greatArcTarget, p1, precision = 6 * d3_geo_radians, interpolate = d3_geo_greatArcInterpolator(); greatArc.distance = function() { if (typeof source === "function") interpolate.source(p0 = source.apply(this, arguments)); if (typeof target === "function") interpolate.target(p1 = target.apply(this, arguments)); return interpolate.distance(); }; greatArc.source = function(_) { if (!arguments.length) return source; source = _; if (typeof source !== "function") interpolate.source(p0 = source); return greatArc; }; greatArc.target = function(_) { if (!arguments.length) return target; target = _; if (typeof target !== "function") interpolate.target(p1 = target); return greatArc; }; greatArc.precision = function(_) { if (!arguments.length) return precision / d3_geo_radians; precision = _ * d3_geo_radians; return greatArc; }; return greatArc; }; d3.geo.greatCircle = d3.geo.circle; d3.geom = {}; d3.geom.contour = function(grid, start) { var s = start || d3_geom_contourStart(grid), c = [], x = s[0], y = s[1], dx = 0, dy = 0, pdx = NaN, pdy = NaN, i = 0; do { i = 0; if (grid(x - 1, y - 1)) i += 1; if (grid(x, y - 1)) i += 2; if (grid(x - 1, y)) i += 4; if (grid(x, y)) i += 8; if (i === 6) { dx = pdy === -1 ? -1 : 1; dy = 0; } else if (i === 9) { dx = 0; dy = pdx === 1 ? -1 : 1; } else { dx = d3_geom_contourDx[i]; dy = d3_geom_contourDy[i]; } if (dx != pdx && dy != pdy) { c.push([ x, y ]); pdx = dx; pdy = dy; } x += dx; y += dy; } while (s[0] != x || s[1] != y); return c; }; var d3_geom_contourDx = [ 1, 0, 1, 1, -1, 0, -1, 1, 0, 0, 0, 0, -1, 0, -1, NaN ], d3_geom_contourDy = [ 0, -1, 0, 0, 0, -1, 0, 0, 1, -1, 1, 1, 0, -1, 0, NaN ]; d3.geom.hull = function(vertices) { if (vertices.length < 3) return []; var len = vertices.length, plen = len - 1, points = [], stack = [], i, j, h = 0, x1, y1, x2, y2, u, v, a, sp; for (i = 1; i < len; ++i) { if (vertices[i][1] < vertices[h][1]) { h = i; } else if (vertices[i][1] == vertices[h][1]) { h = vertices[i][0] < vertices[h][0] ? i : h; } } for (i = 0; i < len; ++i) { if (i === h) continue; y1 = vertices[i][1] - vertices[h][1]; x1 = vertices[i][0] - vertices[h][0]; points.push({ angle: Math.atan2(y1, x1), index: i }); } points.sort(function(a, b) { return a.angle - b.angle; }); a = points[0].angle; v = points[0].index; u = 0; for (i = 1; i < plen; ++i) { j = points[i].index; if (a == points[i].angle) { x1 = vertices[v][0] - vertices[h][0]; y1 = vertices[v][1] - vertices[h][1]; x2 = vertices[j][0] - vertices[h][0]; y2 = vertices[j][1] - vertices[h][1]; if (x1 * x1 + y1 * y1 >= x2 * x2 + y2 * y2) { points[i].index = -1; } else { points[u].index = -1; a = points[i].angle; u = i; v = j; } } else { a = points[i].angle; u = i; v = j; } } stack.push(h); for (i = 0, j = 0; i < 2; ++j) { if (points[j].index !== -1) { stack.push(points[j].index); i++; } } sp = stack.length; for (; j < plen; ++j) { if (points[j].index === -1) continue; while (!d3_geom_hullCCW(stack[sp - 2], stack[sp - 1], points[j].index, vertices)) { --sp; } stack[sp++] = points[j].index; } var poly = []; for (i = 0; i < sp; ++i) { poly.push(vertices[stack[i]]); } return poly; }; d3.geom.polygon = function(coordinates) { coordinates.area = function() { var i = 0, n = coordinates.length, a = coordinates[n - 1][0] * coordinates[0][1], b = coordinates[n - 1][1] * coordinates[0][0]; while (++i < n) { a += coordinates[i - 1][0] * coordinates[i][1]; b += coordinates[i - 1][1] * coordinates[i][0]; } return (b - a) * .5; }; coordinates.centroid = function(k) { var i = -1, n = coordinates.length, x = 0, y = 0, a, b = coordinates[n - 1], c; if (!arguments.length) k = -1 / (6 * coordinates.area()); while (++i < n) { a = b; b = coordinates[i]; c = a[0] * b[1] - b[0] * a[1]; x += (a[0] + b[0]) * c; y += (a[1] + b[1]) * c; } return [ x * k, y * k ]; }; coordinates.clip = function(subject) { var input, i = -1, n = coordinates.length, j, m, a = coordinates[n - 1], b, c, d; while (++i < n) { input = subject.slice(); subject.length = 0; b = coordinates[i]; c = input[(m = input.length) - 1]; j = -1; while (++j < m) { d = input[j]; if (d3_geom_polygonInside(d, a, b)) { if (!d3_geom_polygonInside(c, a, b)) { subject.push(d3_geom_polygonIntersect(c, d, a, b)); } subject.push(d); } else if (d3_geom_polygonInside(c, a, b)) { subject.push(d3_geom_polygonIntersect(c, d, a, b)); } c = d; } a = b; } return subject; }; return coordinates; }; d3.geom.voronoi = function(vertices) { var polygons = vertices.map(function() { return []; }); d3_voronoi_tessellate(vertices, function(e) { var s1, s2, x1, x2, y1, y2; if (e.a === 1 && e.b >= 0) { s1 = e.ep.r; s2 = e.ep.l; } else { s1 = e.ep.l; s2 = e.ep.r; } if (e.a === 1) { y1 = s1 ? s1.y : -1e6; x1 = e.c - e.b * y1; y2 = s2 ? s2.y : 1e6; x2 = e.c - e.b * y2; } else { x1 = s1 ? s1.x : -1e6; y1 = e.c - e.a * x1; x2 = s2 ? s2.x : 1e6; y2 = e.c - e.a * x2; } var v1 = [ x1, y1 ], v2 = [ x2, y2 ]; polygons[e.region.l.index].push(v1, v2); polygons[e.region.r.index].push(v1, v2); }); return polygons.map(function(polygon, i) { var cx = vertices[i][0], cy = vertices[i][1]; polygon.forEach(function(v) { v.angle = Math.atan2(v[0] - cx, v[1] - cy); }); return polygon.sort(function(a, b) { return a.angle - b.angle; }).filter(function(d, i) { return !i || d.angle - polygon[i - 1].angle > 1e-10; }); }); }; var d3_voronoi_opposite = { l: "r", r: "l" }; d3.geom.delaunay = function(vertices) { var edges = vertices.map(function() { return []; }), triangles = []; d3_voronoi_tessellate(vertices, function(e) { edges[e.region.l.index].push(vertices[e.region.r.index]); }); edges.forEach(function(edge, i) { var v = vertices[i], cx = v[0], cy = v[1]; edge.forEach(function(v) { v.angle = Math.atan2(v[0] - cx, v[1] - cy); }); edge.sort(function(a, b) { return a.angle - b.angle; }); for (var j = 0, m = edge.length - 1; j < m; j++) { triangles.push([ v, edge[j], edge[j + 1] ]); } }); return triangles; }; d3.geom.quadtree = function(points, x1, y1, x2, y2) { function insert(n, p, x1, y1, x2, y2) { if (isNaN(p.x) || isNaN(p.y)) return; if (n.leaf) { var v = n.point; if (v) { if (Math.abs(v.x - p.x) + Math.abs(v.y - p.y) < .01) { insertChild(n, p, x1, y1, x2, y2); } else { n.point = null; insertChild(n, v, x1, y1, x2, y2); insertChild(n, p, x1, y1, x2, y2); } } else { n.point = p; } } else { insertChild(n, p, x1, y1, x2, y2); } } function insertChild(n, p, x1, y1, x2, y2) { var sx = (x1 + x2) * .5, sy = (y1 + y2) * .5, right = p.x >= sx, bottom = p.y >= sy, i = (bottom << 1) + right; n.leaf = false; n = n.nodes[i] || (n.nodes[i] = d3_geom_quadtreeNode()); if (right) x1 = sx; else x2 = sx; if (bottom) y1 = sy; else y2 = sy; insert(n, p, x1, y1, x2, y2); } var p, i = -1, n = points.length; if (n && isNaN(points[0].x)) points = points.map(d3_geom_quadtreePoint); if (arguments.length < 5) { if (arguments.length === 3) { y2 = x2 = y1; y1 = x1; } else { x1 = y1 = Infinity; x2 = y2 = -Infinity; while (++i < n) { p = points[i]; if (p.x < x1) x1 = p.x; if (p.y < y1) y1 = p.y; if (p.x > x2) x2 = p.x; if (p.y > y2) y2 = p.y; } var dx = x2 - x1, dy = y2 - y1; if (dx > dy) y2 = y1 + dx; else x2 = x1 + dy; } } var root = d3_geom_quadtreeNode(); root.add = function(p) { insert(root, p, x1, y1, x2, y2); }; root.visit = function(f) { d3_geom_quadtreeVisit(f, root, x1, y1, x2, y2); }; points.forEach(root.add); return root; }; d3.time = {}; var d3_time = Date, d3_time_daySymbols = [ "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday" ]; d3_time_utc.prototype = { getDate: function() { return this._.getUTCDate(); }, getDay: function() { return this._.getUTCDay(); }, getFullYear: function() { return this._.getUTCFullYear(); }, getHours: function() { return this._.getUTCHours(); }, getMilliseconds: function() { return this._.getUTCMilliseconds(); }, getMinutes: function() { return this._.getUTCMinutes(); }, getMonth: function() { return this._.getUTCMonth(); }, getSeconds: function() { return this._.getUTCSeconds(); }, getTime: function() { return this._.getTime(); }, getTimezoneOffset: function() { return 0; }, valueOf: function() { return this._.valueOf(); }, setDate: function() { d3_time_prototype.setUTCDate.apply(this._, arguments); }, setDay: function() { d3_time_prototype.setUTCDay.apply(this._, arguments); }, setFullYear: function() { d3_time_prototype.setUTCFullYear.apply(this._, arguments); }, setHours: function() { d3_time_prototype.setUTCHours.apply(this._, arguments); }, setMilliseconds: function() { d3_time_prototype.setUTCMilliseconds.apply(this._, arguments); }, setMinutes: function() { d3_time_prototype.setUTCMinutes.apply(this._, arguments); }, setMonth: function() { d3_time_prototype.setUTCMonth.apply(this._, arguments); }, setSeconds: function() { d3_time_prototype.setUTCSeconds.apply(this._, arguments); }, setTime: function() { d3_time_prototype.setTime.apply(this._, arguments); } }; var d3_time_prototype = Date.prototype; var d3_time_formatDateTime = "%a %b %e %H:%M:%S %Y", d3_time_formatDate = "%m/%d/%y", d3_time_formatTime = "%H:%M:%S"; var d3_time_days = d3_time_daySymbols, d3_time_dayAbbreviations = d3_time_days.map(d3_time_formatAbbreviate), d3_time_months = [ "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December" ], d3_time_monthAbbreviations = d3_time_months.map(d3_time_formatAbbreviate); d3.time.format = function(template) { function format(date) { var string = [], i = -1, j = 0, c, f; while (++i < n) { if (template.charCodeAt(i) == 37) { string.push(template.substring(j, i), (f = d3_time_formats[c = template.charAt(++i)]) ? f(date) : c); j = i + 1; } } string.push(template.substring(j, i)); return string.join(""); } var n = template.length; format.parse = function(string) { var d = { y: 1900, m: 0, d: 1, H: 0, M: 0, S: 0, L: 0 }, i = d3_time_parse(d, template, string, 0); if (i != string.length) return null; if ("p" in d) d.H = d.H % 12 + d.p * 12; var date = new d3_time; date.setFullYear(d.y, d.m, d.d); date.setHours(d.H, d.M, d.S, d.L); return date; }; format.toString = function() { return template; }; return format; }; var d3_time_zfill2 = d3.format("02d"), d3_time_zfill3 = d3.format("03d"), d3_time_zfill4 = d3.format("04d"), d3_time_sfill2 = d3.format("2d"); var d3_time_dayRe = d3_time_formatRe(d3_time_days), d3_time_dayAbbrevRe = d3_time_formatRe(d3_time_dayAbbreviations), d3_time_monthRe = d3_time_formatRe(d3_time_months), d3_time_monthLookup = d3_time_formatLookup(d3_time_months), d3_time_monthAbbrevRe = d3_time_formatRe(d3_time_monthAbbreviations), d3_time_monthAbbrevLookup = d3_time_formatLookup(d3_time_monthAbbreviations); var d3_time_formats = { a: function(d) { return d3_time_dayAbbreviations[d.getDay()]; }, A: function(d) { return d3_time_days[d.getDay()]; }, b: function(d) { return d3_time_monthAbbreviations[d.getMonth()]; }, B: function(d) { return d3_time_months[d.getMonth()]; }, c: d3.time.format(d3_time_formatDateTime), d: function(d) { return d3_time_zfill2(d.getDate()); }, e: function(d) { return d3_time_sfill2(d.getDate()); }, H: function(d) { return d3_time_zfill2(d.getHours()); }, I: function(d) { return d3_time_zfill2(d.getHours() % 12 || 12); }, j: function(d) { return d3_time_zfill3(1 + d3.time.dayOfYear(d)); }, L: function(d) { return d3_time_zfill3(d.getMilliseconds()); }, m: function(d) { return d3_time_zfill2(d.getMonth() + 1); }, M: function(d) { return d3_time_zfill2(d.getMinutes()); }, p: function(d) { return d.getHours() >= 12 ? "PM" : "AM"; }, S: function(d) { return d3_time_zfill2(d.getSeconds()); }, U: function(d) { return d3_time_zfill2(d3.time.sundayOfYear(d)); }, w: function(d) { return d.getDay(); }, W: function(d) { return d3_time_zfill2(d3.time.mondayOfYear(d)); }, x: d3.time.format(d3_time_formatDate), X: d3.time.format(d3_time_formatTime), y: function(d) { return d3_time_zfill2(d.getFullYear() % 100); }, Y: function(d) { return d3_time_zfill4(d.getFullYear() % 1e4); }, Z: d3_time_zone, "%": function(d) { return "%"; } }; var d3_time_parsers = { a: d3_time_parseWeekdayAbbrev, A: d3_time_parseWeekday, b: d3_time_parseMonthAbbrev, B: d3_time_parseMonth, c: d3_time_parseLocaleFull, d: d3_time_parseDay, e: d3_time_parseDay, H: d3_time_parseHour24, I: d3_time_parseHour24, L: d3_time_parseMilliseconds, m: d3_time_parseMonthNumber, M: d3_time_parseMinutes, p: d3_time_parseAmPm, S: d3_time_parseSeconds, x: d3_time_parseLocaleDate, X: d3_time_parseLocaleTime, y: d3_time_parseYear, Y: d3_time_parseFullYear }; var d3_time_numberRe = /^\s*\d+/; var d3_time_amPmLookup = d3.map({ am: 0, pm: 1 }); d3.time.format.utc = function(template) { function format(date) { try { d3_time = d3_time_utc; var utc = new d3_time; utc._ = date; return local(utc); } finally { d3_time = Date; } } var local = d3.time.format(template); format.parse = function(string) { try { d3_time = d3_time_utc; var date = local.parse(string); return date && date._; } finally { d3_time = Date; } }; format.toString = local.toString; return format; }; var d3_time_formatIso = d3.time.format.utc("%Y-%m-%dT%H:%M:%S.%LZ"); d3.time.format.iso = Date.prototype.toISOString ? d3_time_formatIsoNative : d3_time_formatIso; d3_time_formatIsoNative.parse = function(string) { var date = new Date(string); return isNaN(date) ? null : date; }; d3_time_formatIsoNative.toString = d3_time_formatIso.toString; d3.time.second = d3_time_interval(function(date) { return new d3_time(Math.floor(date / 1e3) * 1e3); }, function(date, offset) { date.setTime(date.getTime() + Math.floor(offset) * 1e3); }, function(date) { return date.getSeconds(); }); d3.time.seconds = d3.time.second.range; d3.time.seconds.utc = d3.time.second.utc.range; d3.time.minute = d3_time_interval(function(date) { return new d3_time(Math.floor(date / 6e4) * 6e4); }, function(date, offset) { date.setTime(date.getTime() + Math.floor(offset) * 6e4); }, function(date) { return date.getMinutes(); }); d3.time.minutes = d3.time.minute.range; d3.time.minutes.utc = d3.time.minute.utc.range; d3.time.hour = d3_time_interval(function(date) { var timezone = date.getTimezoneOffset() / 60; return new d3_time((Math.floor(date / 36e5 - timezone) + timezone) * 36e5); }, function(date, offset) { date.setTime(date.getTime() + Math.floor(offset) * 36e5); }, function(date) { return date.getHours(); }); d3.time.hours = d3.time.hour.range; d3.time.hours.utc = d3.time.hour.utc.range; d3.time.day = d3_time_interval(function(date) { var day = new d3_time(1970, 0); day.setFullYear(date.getFullYear(), date.getMonth(), date.getDate()); return day; }, function(date, offset) { date.setDate(date.getDate() + offset); }, function(date) { return date.getDate() - 1; }); d3.time.days = d3.time.day.range; d3.time.days.utc = d3.time.day.utc.range; d3.time.dayOfYear = function(date) { var year = d3.time.year(date); return Math.floor((date - year - (date.getTimezoneOffset() - year.getTimezoneOffset()) * 6e4) / 864e5); }; d3_time_daySymbols.forEach(function(day, i) { day = day.toLowerCase(); i = 7 - i; var interval = d3.time[day] = d3_time_interval(function(date) { (date = d3.time.day(date)).setDate(date.getDate() - (date.getDay() + i) % 7); return date; }, function(date, offset) { date.setDate(date.getDate() + Math.floor(offset) * 7); }, function(date) { var day = d3.time.year(date).getDay(); return Math.floor((d3.time.dayOfYear(date) + (day + i) % 7) / 7) - (day !== i); }); d3.time[day + "s"] = interval.range; d3.time[day + "s"].utc = interval.utc.range; d3.time[day + "OfYear"] = function(date) { var day = d3.time.year(date).getDay(); return Math.floor((d3.time.dayOfYear(date) + (day + i) % 7) / 7); }; }); d3.time.week = d3.time.sunday; d3.time.weeks = d3.time.sunday.range; d3.time.weeks.utc = d3.time.sunday.utc.range; d3.time.weekOfYear = d3.time.sundayOfYear; d3.time.month = d3_time_interval(function(date) { date = d3.time.day(date); date.setDate(1); return date; }, function(date, offset) { date.setMonth(date.getMonth() + offset); }, function(date) { return date.getMonth(); }); d3.time.months = d3.time.month.range; d3.time.months.utc = d3.time.month.utc.range; d3.time.year = d3_time_interval(function(date) { date = d3.time.day(date); date.setMonth(0, 1); return date; }, function(date, offset) { date.setFullYear(date.getFullYear() + offset); }, function(date) { return date.getFullYear(); }); d3.time.years = d3.time.year.range; d3.time.years.utc = d3.time.year.utc.range; var d3_time_scaleSteps = [ 1e3, 5e3, 15e3, 3e4, 6e4, 3e5, 9e5, 18e5, 36e5, 108e5, 216e5, 432e5, 864e5, 1728e5, 6048e5, 2592e6, 7776e6, 31536e6 ]; var d3_time_scaleLocalMethods = [ [ d3.time.second, 1 ], [ d3.time.second, 5 ], [ d3.time.second, 15 ], [ d3.time.second, 30 ], [ d3.time.minute, 1 ], [ d3.time.minute, 5 ], [ d3.time.minute, 15 ], [ d3.time.minute, 30 ], [ d3.time.hour, 1 ], [ d3.time.hour, 3 ], [ d3.time.hour, 6 ], [ d3.time.hour, 12 ], [ d3.time.day, 1 ], [ d3.time.day, 2 ], [ d3.time.week, 1 ], [ d3.time.month, 1 ], [ d3.time.month, 3 ], [ d3.time.year, 1 ] ]; var d3_time_scaleLocalFormats = [ [ d3.time.format("%Y"), function(d) { return true; } ], [ d3.time.format("%B"), function(d) { return d.getMonth(); } ], [ d3.time.format("%b %d"), function(d) { return d.getDate() != 1; } ], [ d3.time.format("%a %d"), function(d) { return d.getDay() && d.getDate() != 1; } ], [ d3.time.format("%I %p"), function(d) { return d.getHours(); } ], [ d3.time.format("%I:%M"), function(d) { return d.getMinutes(); } ], [ d3.time.format(":%S"), function(d) { return d.getSeconds(); } ], [ d3.time.format(".%L"), function(d) { return d.getMilliseconds(); } ] ]; var d3_time_scaleLinear = d3.scale.linear(), d3_time_scaleLocalFormat = d3_time_scaleFormat(d3_time_scaleLocalFormats); d3_time_scaleLocalMethods.year = function(extent, m) { return d3_time_scaleLinear.domain(extent.map(d3_time_scaleGetYear)).ticks(m).map(d3_time_scaleSetYear); }; d3.time.scale = function() { return d3_time_scale(d3.scale.linear(), d3_time_scaleLocalMethods, d3_time_scaleLocalFormat); }; var d3_time_scaleUTCMethods = d3_time_scaleLocalMethods.map(function(m) { return [ m[0].utc, m[1] ]; }); var d3_time_scaleUTCFormats = [ [ d3.time.format.utc("%Y"), function(d) { return true; } ], [ d3.time.format.utc("%B"), function(d) { return d.getUTCMonth(); } ], [ d3.time.format.utc("%b %d"), function(d) { return d.getUTCDate() != 1; } ], [ d3.time.format.utc("%a %d"), function(d) { return d.getUTCDay() && d.getUTCDate() != 1; } ], [ d3.time.format.utc("%I %p"), function(d) { return d.getUTCHours(); } ], [ d3.time.format.utc("%I:%M"), function(d) { return d.getUTCMinutes(); } ], [ d3.time.format.utc(":%S"), function(d) { return d.getUTCSeconds(); } ], [ d3.time.format.utc(".%L"), function(d) { return d.getUTCMilliseconds(); } ] ]; var d3_time_scaleUTCFormat = d3_time_scaleFormat(d3_time_scaleUTCFormats); d3_time_scaleUTCMethods.year = function(extent, m) { return d3_time_scaleLinear.domain(extent.map(d3_time_scaleUTCGetYear)).ticks(m).map(d3_time_scaleUTCSetYear); }; d3.time.scale.utc = function() { return d3_time_scale(d3.scale.linear(), d3_time_scaleUTCMethods, d3_time_scaleUTCFormat); }; })();apache-couchdb-1.5.0/src/fauxton/assets/js/libs/nv.d3.js0000755000175000001440000143420312230722213017674 00000000000000(function(){ var nv = window.nv || {}; nv.version = '0.0.1a'; nv.dev = true //set false when in production window.nv = nv; nv.tooltip = {}; // For the tooltip system nv.utils = {}; // Utility subsystem nv.models = {}; //stores all the possible models/components nv.charts = {}; //stores all the ready to use charts nv.graphs = []; //stores all the graphs currently on the page nv.logs = {}; //stores some statistics and potential error messages nv.dispatch = d3.dispatch('render_start', 'render_end'); // ************************************************************************* // Development render timers - disabled if dev = false if (nv.dev) { nv.dispatch.on('render_start', function(e) { nv.logs.startTime = +new Date(); }); nv.dispatch.on('render_end', function(e) { nv.logs.endTime = +new Date(); nv.logs.totalTime = nv.logs.endTime - nv.logs.startTime; nv.log('total', nv.logs.totalTime); // used for development, to keep track of graph generation times }); } // ******************************************** // Public Core NV functions // Logs all arguments, and returns the last so you can test things in place nv.log = function() { if (nv.dev && console.log && console.log.apply) console.log.apply(console, arguments) else if (nv.dev && console.log && Function.prototype.bind) { var log = Function.prototype.bind.call(console.log, console); log.apply(console, arguments); } return arguments[arguments.length - 1]; }; nv.render = function render(step) { step = step || 1; // number of graphs to generate in each timeout loop nv.render.active = true; nv.dispatch.render_start(); setTimeout(function() { var chart, graph; for (var i = 0; i < step && (graph = nv.render.queue[i]); i++) { chart = graph.generate(); if (typeof graph.callback == typeof(Function)) graph.callback(chart); nv.graphs.push(chart); } nv.render.queue.splice(0, i); if (nv.render.queue.length) setTimeout(arguments.callee, 0); else { nv.render.active = false; nv.dispatch.render_end(); } }, 0); }; nv.render.active = false; nv.render.queue = []; nv.addGraph = function(obj) { if (typeof arguments[0] === typeof(Function)) obj = {generate: arguments[0], callback: arguments[1]}; nv.render.queue.push(obj); if (!nv.render.active) nv.render(); }; nv.identity = function(d) { return d; }; nv.strip = function(s) { return s.replace(/(\s|&)/g,''); }; function daysInMonth(month,year) { return (new Date(year, month+1, 0)).getDate(); } function d3_time_range(floor, step, number) { return function(t0, t1, dt) { var time = floor(t0), times = []; if (time < t0) step(time); if (dt > 1) { while (time < t1) { var date = new Date(+time); if ((number(date) % dt === 0)) times.push(date); step(time); } } else { while (time < t1) { times.push(new Date(+time)); step(time); } } return times; }; } d3.time.monthEnd = function(date) { return new Date(date.getFullYear(), date.getMonth(), 0); }; d3.time.monthEnds = d3_time_range(d3.time.monthEnd, function(date) { date.setUTCDate(date.getUTCDate() + 1); date.setDate(daysInMonth(date.getMonth() + 1, date.getFullYear())); }, function(date) { return date.getMonth(); } ); /***** * A no-frills tooltip implementation. *****/ (function() { var nvtooltip = window.nv.tooltip = {}; nvtooltip.show = function(pos, content, gravity, dist, parentContainer, classes) { var container = document.createElement('div'); container.className = 'nvtooltip ' + (classes ? classes : 'xy-tooltip'); gravity = gravity || 's'; dist = dist || 20; var body = parentContainer; if ( !parentContainer || parentContainer.tagName.match(/g|svg/i)) { //If the parent element is an SVG element, place tooltip in the element. body = document.getElementsByTagName('body')[0]; } container.innerHTML = content; container.style.left = 0; container.style.top = 0; container.style.opacity = 0; body.appendChild(container); var height = parseInt(container.offsetHeight), width = parseInt(container.offsetWidth), windowWidth = nv.utils.windowSize().width, windowHeight = nv.utils.windowSize().height, scrollTop = window.scrollY, scrollLeft = window.scrollX, left, top; windowHeight = window.innerWidth >= document.body.scrollWidth ? windowHeight : windowHeight - 16; windowWidth = window.innerHeight >= document.body.scrollHeight ? windowWidth : windowWidth - 16; var tooltipTop = function ( Elem ) { var offsetTop = top; do { if( !isNaN( Elem.offsetTop ) ) { offsetTop += (Elem.offsetTop); } } while( Elem = Elem.offsetParent ); return offsetTop; } var tooltipLeft = function ( Elem ) { var offsetLeft = left; do { if( !isNaN( Elem.offsetLeft ) ) { offsetLeft += (Elem.offsetLeft); } } while( Elem = Elem.offsetParent ); return offsetLeft; } switch (gravity) { case 'e': left = pos[0] - width - dist; top = pos[1] - (height / 2); var tLeft = tooltipLeft(container); var tTop = tooltipTop(container); if (tLeft < scrollLeft) left = pos[0] + dist > scrollLeft ? pos[0] + dist : scrollLeft - tLeft + left; if (tTop < scrollTop) top = scrollTop - tTop + top; if (tTop + height > scrollTop + windowHeight) top = scrollTop + windowHeight - tTop + top - height; break; case 'w': left = pos[0] + dist; top = pos[1] - (height / 2); if (tLeft + width > windowWidth) left = pos[0] - width - dist; if (tTop < scrollTop) top = scrollTop + 5; if (tTop + height > scrollTop + windowHeight) top = scrollTop - height - 5; break; case 'n': left = pos[0] - (width / 2) - 5; top = pos[1] + dist; var tLeft = tooltipLeft(container); var tTop = tooltipTop(container); if (tLeft < scrollLeft) left = scrollLeft + 5; if (tLeft + width > windowWidth) left = left - width/2 + 5; if (tTop + height > scrollTop + windowHeight) top = scrollTop + windowHeight - tTop + top - height; break; case 's': left = pos[0] - (width / 2); top = pos[1] - height - dist; var tLeft = tooltipLeft(container); var tTop = tooltipTop(container); if (tLeft < scrollLeft) left = scrollLeft + 5; if (tLeft + width > windowWidth) left = left - width/2 + 5; if (scrollTop > tTop) top = scrollTop; break; } container.style.left = left+'px'; container.style.top = top+'px'; container.style.opacity = 1; container.style.position = 'absolute'; //fix scroll bar issue container.style.pointerEvents = 'none'; //fix scroll bar issue return container; }; nvtooltip.cleanup = function() { // Find the tooltips, mark them for removal by this class (so others cleanups won't find it) var tooltips = document.getElementsByClassName('nvtooltip'); var purging = []; while(tooltips.length) { purging.push(tooltips[0]); tooltips[0].style.transitionDelay = '0 !important'; tooltips[0].style.opacity = 0; tooltips[0].className = 'nvtooltip-pending-removal'; } setTimeout(function() { while (purging.length) { var removeMe = purging.pop(); removeMe.parentNode.removeChild(removeMe); } }, 500); }; })(); nv.utils.windowSize = function() { // Sane defaults var size = {width: 640, height: 480}; // Earlier IE uses Doc.body if (document.body && document.body.offsetWidth) { size.width = document.body.offsetWidth; size.height = document.body.offsetHeight; } // IE can use depending on mode it is in if (document.compatMode=='CSS1Compat' && document.documentElement && document.documentElement.offsetWidth ) { size.width = document.documentElement.offsetWidth; size.height = document.documentElement.offsetHeight; } // Most recent browsers use if (window.innerWidth && window.innerHeight) { size.width = window.innerWidth; size.height = window.innerHeight; } return (size); }; // Easy way to bind multiple functions to window.onresize // TODO: give a way to remove a function after its bound, other than removing all of them nv.utils.windowResize = function(fun){ var oldresize = window.onresize; window.onresize = function(e) { if (typeof oldresize == 'function') oldresize(e); fun(e); } } // Backwards compatible way to implement more d3-like coloring of graphs. // If passed an array, wrap it in a function which implements the old default // behavior nv.utils.getColor = function(color) { if (!arguments.length) return nv.utils.defaultColor(); //if you pass in nothing, get default colors back if( Object.prototype.toString.call( color ) === '[object Array]' ) return function(d, i) { return d.color || color[i % color.length]; }; else return color; //can't really help it if someone passes rubbish as color } // Default color chooser uses the index of an object as before. nv.utils.defaultColor = function() { var colors = d3.scale.category20().range(); return function(d, i) { return d.color || colors[i % colors.length] }; } // Returns a color function that takes the result of 'getKey' for each series and // looks for a corresponding color from the dictionary, nv.utils.customTheme = function(dictionary, getKey, defaultColors) { getKey = getKey || function(series) { return series.key }; // use default series.key if getKey is undefined defaultColors = defaultColors || d3.scale.category20().range(); //default color function var defIndex = defaultColors.length; //current default color (going in reverse) return function(series, index) { var key = getKey(series); if (!defIndex) defIndex = defaultColors.length; //used all the default colors, start over if (typeof dictionary[key] !== "undefined") return (typeof dictionary[key] === "function") ? dictionary[key]() : dictionary[key]; else return defaultColors[--defIndex]; // no match in dictionary, use default color } } // From the PJAX example on d3js.org, while this is not really directly needed // it's a very cool method for doing pjax, I may expand upon it a little bit, // open to suggestions on anything that may be useful nv.utils.pjax = function(links, content) { d3.selectAll(links).on("click", function() { history.pushState(this.href, this.textContent, this.href); load(this.href); d3.event.preventDefault(); }); function load(href) { d3.html(href, function(fragment) { var target = d3.select(content).node(); target.parentNode.replaceChild(d3.select(fragment).select(content).node(), target); nv.utils.pjax(links, content); }); } d3.select(window).on("popstate", function() { if (d3.event.state) load(d3.event.state); }); } /* For situations where we want to approximate the width in pixels for an SVG:text element. Most common instance is when the element is in a display:none; container. Forumla is : text.length * font-size * constant_factor */ nv.utils.calcApproxTextWidth = function (svgTextElem) { if (svgTextElem instanceof d3.selection) { var fontSize = parseInt(svgTextElem.style("font-size").replace("px","")); var textLength = svgTextElem.text().length; return textLength * fontSize * 0.5; } return 0; }; nv.models.axis = function() { //============================================================ // Public Variables with Default Settings //------------------------------------------------------------ var axis = d3.svg.axis() ; var margin = {top: 0, right: 0, bottom: 0, left: 0} , width = 75 //only used for tickLabel currently , height = 60 //only used for tickLabel currently , scale = d3.scale.linear() , axisLabelText = null , showMaxMin = true //TODO: showMaxMin should be disabled on all ordinal scaled axes , highlightZero = true , rotateLabels = 0 , rotateYLabel = true , staggerLabels = false , isOrdinal = false , ticks = null ; axis .scale(scale) .orient('bottom') .tickFormat(function(d) { return d }) ; //============================================================ //============================================================ // Private Variables //------------------------------------------------------------ var scale0; //============================================================ function chart(selection) { selection.each(function(data) { var container = d3.select(this); //------------------------------------------------------------ // Setup containers and skeleton of chart var wrap = container.selectAll('g.nv-wrap.nv-axis').data([data]); var wrapEnter = wrap.enter().append('g').attr('class', 'nvd3 nv-wrap nv-axis'); var gEnter = wrapEnter.append('g'); var g = wrap.select('g') //------------------------------------------------------------ if (ticks !== null) axis.ticks(ticks); else if (axis.orient() == 'top' || axis.orient() == 'bottom') axis.ticks(Math.abs(scale.range()[1] - scale.range()[0]) / 100); //TODO: consider calculating width/height based on whether or not label is added, for reference in charts using this component d3.transition(g) .call(axis); scale0 = scale0 || axis.scale(); var fmt = axis.tickFormat(); if (fmt == null) { fmt = scale0.tickFormat(); } var axisLabel = g.selectAll('text.nv-axislabel') .data([axisLabelText || null]); axisLabel.exit().remove(); switch (axis.orient()) { case 'top': axisLabel.enter().append('text').attr('class', 'nv-axislabel'); var w = (scale.range().length==2) ? scale.range()[1] : (scale.range()[scale.range().length-1]+(scale.range()[1]-scale.range()[0])); axisLabel .attr('text-anchor', 'middle') .attr('y', 0) .attr('x', w/2); if (showMaxMin) { var axisMaxMin = wrap.selectAll('g.nv-axisMaxMin') .data(scale.domain()); axisMaxMin.enter().append('g').attr('class', 'nv-axisMaxMin').append('text'); axisMaxMin.exit().remove(); axisMaxMin .attr('transform', function(d,i) { return 'translate(' + scale(d) + ',0)' }) .select('text') .attr('dy', '0em') .attr('y', -axis.tickPadding()) .attr('text-anchor', 'middle') .text(function(d,i) { var v = fmt(d); return ('' + v).match('NaN') ? '' : v; }); d3.transition(axisMaxMin) .attr('transform', function(d,i) { return 'translate(' + scale.range()[i] + ',0)' }); } break; case 'bottom': var xLabelMargin = 36; var maxTextWidth = 30; var xTicks = g.selectAll('g').select("text"); if (rotateLabels%360) { //Calculate the longest xTick width xTicks.each(function(d,i){ var width = this.getBBox().width; if(width > maxTextWidth) maxTextWidth = width; }); //Convert to radians before calculating sin. Add 30 to margin for healthy padding. var sin = Math.abs(Math.sin(rotateLabels*Math.PI/180)); var xLabelMargin = (sin ? sin*maxTextWidth : maxTextWidth)+30; //Rotate all xTicks xTicks .attr('transform', function(d,i,j) { return 'rotate(' + rotateLabels + ' 0,0)' }) .attr('text-anchor', rotateLabels%360 > 0 ? 'start' : 'end'); } axisLabel.enter().append('text').attr('class', 'nv-axislabel'); var w = (scale.range().length==2) ? scale.range()[1] : (scale.range()[scale.range().length-1]+(scale.range()[1]-scale.range()[0])); axisLabel .attr('text-anchor', 'middle') .attr('y', xLabelMargin) .attr('x', w/2); if (showMaxMin) { //if (showMaxMin && !isOrdinal) { var axisMaxMin = wrap.selectAll('g.nv-axisMaxMin') //.data(scale.domain()) .data([scale.domain()[0], scale.domain()[scale.domain().length - 1]]); axisMaxMin.enter().append('g').attr('class', 'nv-axisMaxMin').append('text'); axisMaxMin.exit().remove(); axisMaxMin .attr('transform', function(d,i) { return 'translate(' + (scale(d) + (isOrdinal ? scale.rangeBand() / 2 : 0)) + ',0)' }) .select('text') .attr('dy', '.71em') .attr('y', axis.tickPadding()) .attr('transform', function(d,i,j) { return 'rotate(' + rotateLabels + ' 0,0)' }) .attr('text-anchor', rotateLabels ? (rotateLabels%360 > 0 ? 'start' : 'end') : 'middle') .text(function(d,i) { var v = fmt(d); return ('' + v).match('NaN') ? '' : v; }); d3.transition(axisMaxMin) .attr('transform', function(d,i) { //return 'translate(' + scale.range()[i] + ',0)' //return 'translate(' + scale(d) + ',0)' return 'translate(' + (scale(d) + (isOrdinal ? scale.rangeBand() / 2 : 0)) + ',0)' }); } if (staggerLabels) xTicks .attr('transform', function(d,i) { return 'translate(0,' + (i % 2 == 0 ? '0' : '12') + ')' }); break; case 'right': axisLabel.enter().append('text').attr('class', 'nv-axislabel'); axisLabel .attr('text-anchor', rotateYLabel ? 'middle' : 'begin') .attr('transform', rotateYLabel ? 'rotate(90)' : '') .attr('y', rotateYLabel ? (-Math.max(margin.right,width) + 12) : -10) //TODO: consider calculating this based on largest tick width... OR at least expose this on chart .attr('x', rotateYLabel ? (scale.range()[0] / 2) : axis.tickPadding()); if (showMaxMin) { var axisMaxMin = wrap.selectAll('g.nv-axisMaxMin') .data(scale.domain()); axisMaxMin.enter().append('g').attr('class', 'nv-axisMaxMin').append('text') .style('opacity', 0); axisMaxMin.exit().remove(); axisMaxMin .attr('transform', function(d,i) { return 'translate(0,' + scale(d) + ')' }) .select('text') .attr('dy', '.32em') .attr('y', 0) .attr('x', axis.tickPadding()) .attr('text-anchor', 'start') .text(function(d,i) { var v = fmt(d); return ('' + v).match('NaN') ? '' : v; }); d3.transition(axisMaxMin) .attr('transform', function(d,i) { return 'translate(0,' + scale.range()[i] + ')' }) .select('text') .style('opacity', 1); } break; case 'left': /* //For dynamically placing the label. Can be used with dynamically-sized chart axis margins var yTicks = g.selectAll('g').select("text"); yTicks.each(function(d,i){ var labelPadding = this.getBBox().width + axis.tickPadding() + 16; if(labelPadding > width) width = labelPadding; }); */ axisLabel.enter().append('text').attr('class', 'nv-axislabel'); axisLabel .attr('text-anchor', rotateYLabel ? 'middle' : 'end') .attr('transform', rotateYLabel ? 'rotate(-90)' : '') .attr('y', rotateYLabel ? (-Math.max(margin.left,width) + 12) : -10) //TODO: consider calculating this based on largest tick width... OR at least expose this on chart .attr('x', rotateYLabel ? (-scale.range()[0] / 2) : -axis.tickPadding()); if (showMaxMin) { var axisMaxMin = wrap.selectAll('g.nv-axisMaxMin') .data(scale.domain()); axisMaxMin.enter().append('g').attr('class', 'nv-axisMaxMin').append('text') .style('opacity', 0); axisMaxMin.exit().remove(); axisMaxMin .attr('transform', function(d,i) { return 'translate(0,' + scale0(d) + ')' }) .select('text') .attr('dy', '.32em') .attr('y', 0) .attr('x', -axis.tickPadding()) .attr('text-anchor', 'end') .text(function(d,i) { var v = fmt(d); return ('' + v).match('NaN') ? '' : v; }); d3.transition(axisMaxMin) .attr('transform', function(d,i) { return 'translate(0,' + scale.range()[i] + ')' }) .select('text') .style('opacity', 1); } break; } axisLabel .text(function(d) { return d }); if (showMaxMin && (axis.orient() === 'left' || axis.orient() === 'right')) { //check if max and min overlap other values, if so, hide the values that overlap g.selectAll('g') // the g's wrapping each tick .each(function(d,i) { d3.select(this).select('text').attr('opacity', 1); if (scale(d) < scale.range()[1] + 10 || scale(d) > scale.range()[0] - 10) { // 10 is assuming text height is 16... if d is 0, leave it! if (d > 1e-10 || d < -1e-10) // accounts for minor floating point errors... though could be problematic if the scale is EXTREMELY SMALL d3.select(this).attr('opacity', 0); d3.select(this).select('text').attr('opacity', 0); // Don't remove the ZERO line!! } }); //if Max and Min = 0 only show min, Issue #281 if (scale.domain()[0] == scale.domain()[1] && scale.domain()[0] == 0) wrap.selectAll('g.nv-axisMaxMin') .style('opacity', function(d,i) { return !i ? 1 : 0 }); } if (showMaxMin && (axis.orient() === 'top' || axis.orient() === 'bottom')) { var maxMinRange = []; wrap.selectAll('g.nv-axisMaxMin') .each(function(d,i) { try { if (i) // i== 1, max position maxMinRange.push(scale(d) - this.getBBox().width - 4) //assuming the max and min labels are as wide as the next tick (with an extra 4 pixels just in case) else // i==0, min position maxMinRange.push(scale(d) + this.getBBox().width + 4) }catch (err) { if (i) // i== 1, max position maxMinRange.push(scale(d) - 4) //assuming the max and min labels are as wide as the next tick (with an extra 4 pixels just in case) else // i==0, min position maxMinRange.push(scale(d) + 4) } }); g.selectAll('g') // the g's wrapping each tick .each(function(d,i) { if (scale(d) < maxMinRange[0] || scale(d) > maxMinRange[1]) { if (d > 1e-10 || d < -1e-10) // accounts for minor floating point errors... though could be problematic if the scale is EXTREMELY SMALL d3.select(this).remove(); else d3.select(this).select('text').remove(); // Don't remove the ZERO line!! } }); } //highlight zero line ... Maybe should not be an option and should just be in CSS? if (highlightZero) g.selectAll('.tick') .filter(function(d) { return !parseFloat(Math.round(d.__data__*100000)/1000000) && (d.__data__ !== undefined) }) //this is because sometimes the 0 tick is a very small fraction, TODO: think of cleaner technique .classed('zero', true); //store old scales for use in transitions on update scale0 = scale.copy(); }); return chart; } //============================================================ // Expose Public Variables //------------------------------------------------------------ // expose chart's sub-components chart.axis = axis; d3.rebind(chart, axis, 'orient', 'tickValues', 'tickSubdivide', 'tickSize', 'tickPadding', 'tickFormat'); d3.rebind(chart, scale, 'domain', 'range', 'rangeBand', 'rangeBands'); //these are also accessible by chart.scale(), but added common ones directly for ease of use chart.margin = function(_) { if(!arguments.length) return margin; margin.top = typeof _.top != 'undefined' ? _.top : margin.top; margin.right = typeof _.right != 'undefined' ? _.right : margin.right; margin.bottom = typeof _.bottom != 'undefined' ? _.bottom : margin.bottom; margin.left = typeof _.left != 'undefined' ? _.left : margin.left; return chart; } chart.width = function(_) { if (!arguments.length) return width; width = _; return chart; }; chart.ticks = function(_) { if (!arguments.length) return ticks; ticks = _; return chart; }; chart.height = function(_) { if (!arguments.length) return height; height = _; return chart; }; chart.axisLabel = function(_) { if (!arguments.length) return axisLabelText; axisLabelText = _; return chart; } chart.showMaxMin = function(_) { if (!arguments.length) return showMaxMin; showMaxMin = _; return chart; } chart.highlightZero = function(_) { if (!arguments.length) return highlightZero; highlightZero = _; return chart; } chart.scale = function(_) { if (!arguments.length) return scale; scale = _; axis.scale(scale); isOrdinal = typeof scale.rangeBands === 'function'; d3.rebind(chart, scale, 'domain', 'range', 'rangeBand', 'rangeBands'); return chart; } chart.rotateYLabel = function(_) { if(!arguments.length) return rotateYLabel; rotateYLabel = _; return chart; } chart.rotateLabels = function(_) { if(!arguments.length) return rotateLabels; rotateLabels = _; return chart; } chart.staggerLabels = function(_) { if (!arguments.length) return staggerLabels; staggerLabels = _; return chart; }; //============================================================ return chart; } // Chart design based on the recommendations of Stephen Few. Implementation // based on the work of Clint Ivy, Jamie Love, and Jason Davies. // http://projects.instantcognition.com/protovis/bulletchart/ nv.models.bullet = function() { //============================================================ // Public Variables with Default Settings //------------------------------------------------------------ var margin = {top: 0, right: 0, bottom: 0, left: 0} , orient = 'left' // TODO top & bottom , reverse = false , ranges = function(d) { return d.ranges } , markers = function(d) { return d.markers } , measures = function(d) { return d.measures } , forceX = [0] // List of numbers to Force into the X scale (ie. 0, or a max / min, etc.) , width = 380 , height = 30 , tickFormat = null , color = nv.utils.getColor(['#1f77b4']) , dispatch = d3.dispatch('elementMouseover', 'elementMouseout') ; //============================================================ function chart(selection) { selection.each(function(d, i) { var availableWidth = width - margin.left - margin.right, availableHeight = height - margin.top - margin.bottom, container = d3.select(this); var rangez = ranges.call(this, d, i).slice().sort(d3.descending), markerz = markers.call(this, d, i).slice().sort(d3.descending), measurez = measures.call(this, d, i).slice().sort(d3.descending); //------------------------------------------------------------ // Setup Scales // Compute the new x-scale. var x1 = d3.scale.linear() .domain( d3.extent(d3.merge([forceX, rangez])) ) .range(reverse ? [availableWidth, 0] : [0, availableWidth]); // Retrieve the old x-scale, if this is an update. var x0 = this.__chart__ || d3.scale.linear() .domain([0, Infinity]) .range(x1.range()); // Stash the new scale. this.__chart__ = x1; var rangeMin = d3.min(rangez), //rangez[2] rangeMax = d3.max(rangez), //rangez[0] rangeAvg = rangez[1]; //------------------------------------------------------------ //------------------------------------------------------------ // Setup containers and skeleton of chart var wrap = container.selectAll('g.nv-wrap.nv-bullet').data([d]); var wrapEnter = wrap.enter().append('g').attr('class', 'nvd3 nv-wrap nv-bullet'); var gEnter = wrapEnter.append('g'); var g = wrap.select('g'); gEnter.append('rect').attr('class', 'nv-range nv-rangeMax'); gEnter.append('rect').attr('class', 'nv-range nv-rangeAvg'); gEnter.append('rect').attr('class', 'nv-range nv-rangeMin'); gEnter.append('rect').attr('class', 'nv-measure'); gEnter.append('path').attr('class', 'nv-markerTriangle'); wrap.attr('transform', 'translate(' + margin.left + ',' + margin.top + ')'); //------------------------------------------------------------ var w0 = function(d) { return Math.abs(x0(d) - x0(0)) }, // TODO: could optimize by precalculating x0(0) and x1(0) w1 = function(d) { return Math.abs(x1(d) - x1(0)) }; var xp0 = function(d) { return d < 0 ? x0(d) : x0(0) }, xp1 = function(d) { return d < 0 ? x1(d) : x1(0) }; g.select('rect.nv-rangeMax') .attr('height', availableHeight) .attr('width', w1(rangeMax > 0 ? rangeMax : rangeMin)) .attr('x', xp1(rangeMax > 0 ? rangeMax : rangeMin)) .datum(rangeMax > 0 ? rangeMax : rangeMin) /* .attr('x', rangeMin < 0 ? rangeMax > 0 ? x1(rangeMin) : x1(rangeMax) : x1(0)) */ g.select('rect.nv-rangeAvg') .attr('height', availableHeight) .attr('width', w1(rangeAvg)) .attr('x', xp1(rangeAvg)) .datum(rangeAvg) /* .attr('width', rangeMax <= 0 ? x1(rangeMax) - x1(rangeAvg) : x1(rangeAvg) - x1(rangeMin)) .attr('x', rangeMax <= 0 ? x1(rangeAvg) : x1(rangeMin)) */ g.select('rect.nv-rangeMin') .attr('height', availableHeight) .attr('width', w1(rangeMax)) .attr('x', xp1(rangeMax)) .attr('width', w1(rangeMax > 0 ? rangeMin : rangeMax)) .attr('x', xp1(rangeMax > 0 ? rangeMin : rangeMax)) .datum(rangeMax > 0 ? rangeMin : rangeMax) /* .attr('width', rangeMax <= 0 ? x1(rangeAvg) - x1(rangeMin) : x1(rangeMax) - x1(rangeAvg)) .attr('x', rangeMax <= 0 ? x1(rangeMin) : x1(rangeAvg)) */ g.select('rect.nv-measure') .style('fill', color) .attr('height', availableHeight / 3) .attr('y', availableHeight / 3) .attr('width', measurez < 0 ? x1(0) - x1(measurez[0]) : x1(measurez[0]) - x1(0)) .attr('x', xp1(measurez)) .on('mouseover', function() { dispatch.elementMouseover({ value: measurez[0], label: 'Current', pos: [x1(measurez[0]), availableHeight/2] }) }) .on('mouseout', function() { dispatch.elementMouseout({ value: measurez[0], label: 'Current' }) }) var h3 = availableHeight / 6; if (markerz[0]) { g.selectAll('path.nv-markerTriangle') .attr('transform', function(d) { return 'translate(' + x1(markerz[0]) + ',' + (availableHeight / 2) + ')' }) .attr('d', 'M0,' + h3 + 'L' + h3 + ',' + (-h3) + ' ' + (-h3) + ',' + (-h3) + 'Z') .on('mouseover', function() { dispatch.elementMouseover({ value: markerz[0], label: 'Previous', pos: [x1(markerz[0]), availableHeight/2] }) }) .on('mouseout', function() { dispatch.elementMouseout({ value: markerz[0], label: 'Previous' }) }); } else { g.selectAll('path.nv-markerTriangle').remove(); } wrap.selectAll('.nv-range') .on('mouseover', function(d,i) { var label = !i ? "Maximum" : i == 1 ? "Mean" : "Minimum"; dispatch.elementMouseover({ value: d, label: label, pos: [x1(d), availableHeight/2] }) }) .on('mouseout', function(d,i) { var label = !i ? "Maximum" : i == 1 ? "Mean" : "Minimum"; dispatch.elementMouseout({ value: d, label: label }) }) /* // THIS IS THE PREVIOUS BULLET IMPLEMENTATION, WILL REMOVE SHORTLY // Update the range rects. var range = g.selectAll('rect.nv-range') .data(rangez); range.enter().append('rect') .attr('class', function(d, i) { return 'nv-range nv-s' + i; }) .attr('width', w0) .attr('height', availableHeight) .attr('x', reverse ? x0 : 0) .on('mouseover', function(d,i) { dispatch.elementMouseover({ value: d, label: (i <= 0) ? 'Maximum' : (i > 1) ? 'Minimum' : 'Mean', //TODO: make these labels a variable pos: [x1(d), availableHeight/2] }) }) .on('mouseout', function(d,i) { dispatch.elementMouseout({ value: d, label: (i <= 0) ? 'Minimum' : (i >=1) ? 'Maximum' : 'Mean' //TODO: make these labels a variable }) }) d3.transition(range) .attr('x', reverse ? x1 : 0) .attr('width', w1) .attr('height', availableHeight); // Update the measure rects. var measure = g.selectAll('rect.nv-measure') .data(measurez); measure.enter().append('rect') .attr('class', function(d, i) { return 'nv-measure nv-s' + i; }) .style('fill', function(d,i) { return color(d,i ) }) .attr('width', w0) .attr('height', availableHeight / 3) .attr('x', reverse ? x0 : 0) .attr('y', availableHeight / 3) .on('mouseover', function(d) { dispatch.elementMouseover({ value: d, label: 'Current', //TODO: make these labels a variable pos: [x1(d), availableHeight/2] }) }) .on('mouseout', function(d) { dispatch.elementMouseout({ value: d, label: 'Current' //TODO: make these labels a variable }) }) d3.transition(measure) .attr('width', w1) .attr('height', availableHeight / 3) .attr('x', reverse ? x1 : 0) .attr('y', availableHeight / 3); // Update the marker lines. var marker = g.selectAll('path.nv-markerTriangle') .data(markerz); var h3 = availableHeight / 6; marker.enter().append('path') .attr('class', 'nv-markerTriangle') .attr('transform', function(d) { return 'translate(' + x0(d) + ',' + (availableHeight / 2) + ')' }) .attr('d', 'M0,' + h3 + 'L' + h3 + ',' + (-h3) + ' ' + (-h3) + ',' + (-h3) + 'Z') .on('mouseover', function(d,i) { dispatch.elementMouseover({ value: d, label: 'Previous', pos: [x1(d), availableHeight/2] }) }) .on('mouseout', function(d,i) { dispatch.elementMouseout({ value: d, label: 'Previous' }) }); d3.transition(marker) .attr('transform', function(d) { return 'translate(' + (x1(d) - x1(0)) + ',' + (availableHeight / 2) + ')' }); marker.exit().remove(); */ }); // d3.timer.flush(); // Not needed? return chart; } //============================================================ // Expose Public Variables //------------------------------------------------------------ chart.dispatch = dispatch; // left, right, top, bottom chart.orient = function(_) { if (!arguments.length) return orient; orient = _; reverse = orient == 'right' || orient == 'bottom'; return chart; }; // ranges (bad, satisfactory, good) chart.ranges = function(_) { if (!arguments.length) return ranges; ranges = _; return chart; }; // markers (previous, goal) chart.markers = function(_) { if (!arguments.length) return markers; markers = _; return chart; }; // measures (actual, forecast) chart.measures = function(_) { if (!arguments.length) return measures; measures = _; return chart; }; chart.forceX = function(_) { if (!arguments.length) return forceX; forceX = _; return chart; }; chart.width = function(_) { if (!arguments.length) return width; width = _; return chart; }; chart.height = function(_) { if (!arguments.length) return height; height = _; return chart; }; chart.margin = function(_) { if (!arguments.length) return margin; margin.top = typeof _.top != 'undefined' ? _.top : margin.top; margin.right = typeof _.right != 'undefined' ? _.right : margin.right; margin.bottom = typeof _.bottom != 'undefined' ? _.bottom : margin.bottom; margin.left = typeof _.left != 'undefined' ? _.left : margin.left; return chart; }; chart.tickFormat = function(_) { if (!arguments.length) return tickFormat; tickFormat = _; return chart; }; chart.color = function(_) { if (!arguments.length) return color; color = nv.utils.getColor(_); return chart; }; //============================================================ return chart; }; // Chart design based on the recommendations of Stephen Few. Implementation // based on the work of Clint Ivy, Jamie Love, and Jason Davies. // http://projects.instantcognition.com/protovis/bulletchart/ nv.models.bulletChart = function() { //============================================================ // Public Variables with Default Settings //------------------------------------------------------------ var bullet = nv.models.bullet() ; var orient = 'left' // TODO top & bottom , reverse = false , margin = {top: 5, right: 40, bottom: 20, left: 120} , ranges = function(d) { return d.ranges } , markers = function(d) { return d.markers } , measures = function(d) { return d.measures } , width = null , height = 55 , tickFormat = null , tooltips = true , tooltip = function(key, x, y, e, graph) { return '

    ' + x + '

    ' + '

    ' + y + '

    ' } , noData = 'No Data Available.' , dispatch = d3.dispatch('tooltipShow', 'tooltipHide') ; //============================================================ //============================================================ // Private Variables //------------------------------------------------------------ var showTooltip = function(e, offsetElement) { var left = e.pos[0] + ( offsetElement.offsetLeft || 0 ) + margin.left, top = e.pos[1] + ( offsetElement.offsetTop || 0) + margin.top, content = tooltip(e.key, e.label, e.value, e, chart); nv.tooltip.show([left, top], content, e.value < 0 ? 'e' : 'w', null, offsetElement); }; //============================================================ function chart(selection) { selection.each(function(d, i) { var container = d3.select(this); var availableWidth = (width || parseInt(container.style('width')) || 960) - margin.left - margin.right, availableHeight = height - margin.top - margin.bottom, that = this; chart.update = function() { chart(selection) }; chart.container = this; //------------------------------------------------------------ // Display No Data message if there's nothing to show. if (!d || !ranges.call(this, d, i)) { var noDataText = container.selectAll('.nv-noData').data([noData]); noDataText.enter().append('text') .attr('class', 'nvd3 nv-noData') .attr('dy', '-.7em') .style('text-anchor', 'middle'); noDataText .attr('x', margin.left + availableWidth / 2) .attr('y', 18 + margin.top + availableHeight / 2) .text(function(d) { return d }); return chart; } else { container.selectAll('.nv-noData').remove(); } //------------------------------------------------------------ var rangez = ranges.call(this, d, i).slice().sort(d3.descending), markerz = markers.call(this, d, i).slice().sort(d3.descending), measurez = measures.call(this, d, i).slice().sort(d3.descending); //------------------------------------------------------------ // Setup containers and skeleton of chart var wrap = container.selectAll('g.nv-wrap.nv-bulletChart').data([d]); var wrapEnter = wrap.enter().append('g').attr('class', 'nvd3 nv-wrap nv-bulletChart'); var gEnter = wrapEnter.append('g'); var g = wrap.select('g'); gEnter.append('g').attr('class', 'nv-bulletWrap'); gEnter.append('g').attr('class', 'nv-titles'); wrap.attr('transform', 'translate(' + margin.left + ',' + margin.top + ')'); //------------------------------------------------------------ // Compute the new x-scale. var x1 = d3.scale.linear() .domain([0, Math.max(rangez[0], markerz[0], measurez[0])]) // TODO: need to allow forceX and forceY, and xDomain, yDomain .range(reverse ? [availableWidth, 0] : [0, availableWidth]); // Retrieve the old x-scale, if this is an update. var x0 = this.__chart__ || d3.scale.linear() .domain([0, Infinity]) .range(x1.range()); // Stash the new scale. this.__chart__ = x1; /* // Derive width-scales from the x-scales. var w0 = bulletWidth(x0), w1 = bulletWidth(x1); function bulletWidth(x) { var x0 = x(0); return function(d) { return Math.abs(x(d) - x(0)); }; } function bulletTranslate(x) { return function(d) { return 'translate(' + x(d) + ',0)'; }; } */ var w0 = function(d) { return Math.abs(x0(d) - x0(0)) }, // TODO: could optimize by precalculating x0(0) and x1(0) w1 = function(d) { return Math.abs(x1(d) - x1(0)) }; var title = gEnter.select('.nv-titles').append('g') .attr('text-anchor', 'end') .attr('transform', 'translate(-6,' + (height - margin.top - margin.bottom) / 2 + ')'); title.append('text') .attr('class', 'nv-title') .text(function(d) { return d.title; }); title.append('text') .attr('class', 'nv-subtitle') .attr('dy', '1em') .text(function(d) { return d.subtitle; }); bullet .width(availableWidth) .height(availableHeight) var bulletWrap = g.select('.nv-bulletWrap'); d3.transition(bulletWrap).call(bullet); // Compute the tick format. var format = tickFormat || x1.tickFormat( availableWidth / 100 ); // Update the tick groups. var tick = g.selectAll('g.nv-tick') .data(x1.ticks( availableWidth / 50 ), function(d) { return this.textContent || format(d); }); // Initialize the ticks with the old scale, x0. var tickEnter = tick.enter().append('g') .attr('class', 'nv-tick') .attr('transform', function(d) { return 'translate(' + x0(d) + ',0)' }) .style('opacity', 1e-6); tickEnter.append('line') .attr('y1', availableHeight) .attr('y2', availableHeight * 7 / 6); tickEnter.append('text') .attr('text-anchor', 'middle') .attr('dy', '1em') .attr('y', availableHeight * 7 / 6) .text(format); // Transition the updating ticks to the new scale, x1. var tickUpdate = d3.transition(tick) .attr('transform', function(d) { return 'translate(' + x1(d) + ',0)' }) .style('opacity', 1); tickUpdate.select('line') .attr('y1', availableHeight) .attr('y2', availableHeight * 7 / 6); tickUpdate.select('text') .attr('y', availableHeight * 7 / 6); // Transition the exiting ticks to the new scale, x1. d3.transition(tick.exit()) .attr('transform', function(d) { return 'translate(' + x1(d) + ',0)' }) .style('opacity', 1e-6) .remove(); //============================================================ // Event Handling/Dispatching (in chart's scope) //------------------------------------------------------------ dispatch.on('tooltipShow', function(e) { e.key = d.title; if (tooltips) showTooltip(e, that.parentNode); }); //============================================================ }); d3.timer.flush(); return chart; } //============================================================ // Event Handling/Dispatching (out of chart's scope) //------------------------------------------------------------ bullet.dispatch.on('elementMouseover.tooltip', function(e) { dispatch.tooltipShow(e); }); bullet.dispatch.on('elementMouseout.tooltip', function(e) { dispatch.tooltipHide(e); }); dispatch.on('tooltipHide', function() { if (tooltips) nv.tooltip.cleanup(); }); //============================================================ //============================================================ // Expose Public Variables //------------------------------------------------------------ chart.dispatch = dispatch; chart.bullet = bullet; d3.rebind(chart, bullet, 'color'); // left, right, top, bottom chart.orient = function(x) { if (!arguments.length) return orient; orient = x; reverse = orient == 'right' || orient == 'bottom'; return chart; }; // ranges (bad, satisfactory, good) chart.ranges = function(x) { if (!arguments.length) return ranges; ranges = x; return chart; }; // markers (previous, goal) chart.markers = function(x) { if (!arguments.length) return markers; markers = x; return chart; }; // measures (actual, forecast) chart.measures = function(x) { if (!arguments.length) return measures; measures = x; return chart; }; chart.width = function(x) { if (!arguments.length) return width; width = x; return chart; }; chart.height = function(x) { if (!arguments.length) return height; height = x; return chart; }; chart.margin = function(_) { if (!arguments.length) return margin; margin.top = typeof _.top != 'undefined' ? _.top : margin.top; margin.right = typeof _.right != 'undefined' ? _.right : margin.right; margin.bottom = typeof _.bottom != 'undefined' ? _.bottom : margin.bottom; margin.left = typeof _.left != 'undefined' ? _.left : margin.left; return chart; }; chart.tickFormat = function(x) { if (!arguments.length) return tickFormat; tickFormat = x; return chart; }; chart.tooltips = function(_) { if (!arguments.length) return tooltips; tooltips = _; return chart; }; chart.tooltipContent = function(_) { if (!arguments.length) return tooltip; tooltip = _; return chart; }; chart.noData = function(_) { if (!arguments.length) return noData; noData = _; return chart; }; //============================================================ return chart; }; nv.models.cumulativeLineChart = function() { //============================================================ // Public Variables with Default Settings //------------------------------------------------------------ var lines = nv.models.line() , xAxis = nv.models.axis() , yAxis = nv.models.axis() , legend = nv.models.legend() , controls = nv.models.legend() ; var margin = {top: 30, right: 30, bottom: 50, left: 60} , color = nv.utils.defaultColor() , width = null , height = null , showLegend = true , tooltips = true , showControls = true , rescaleY = true , tooltip = function(key, x, y, e, graph) { return '

    ' + key + '

    ' + '

    ' + y + ' at ' + x + '

    ' } , x //can be accessed via chart.xScale() , y //can be accessed via chart.yScale() , id = lines.id() , state = { index: 0, rescaleY: rescaleY } , defaultState = null , noData = 'No Data Available.' , average = function(d) { return d.average } , dispatch = d3.dispatch('tooltipShow', 'tooltipHide', 'stateChange', 'changeState') ; xAxis .orient('bottom') .tickPadding(7) ; yAxis .orient('left') ; //============================================================ //============================================================ // Private Variables //------------------------------------------------------------ var dx = d3.scale.linear() , index = {i: 0, x: 0} ; var showTooltip = function(e, offsetElement) { var left = e.pos[0] + ( offsetElement.offsetLeft || 0 ), top = e.pos[1] + ( offsetElement.offsetTop || 0), x = xAxis.tickFormat()(lines.x()(e.point, e.pointIndex)), y = yAxis.tickFormat()(lines.y()(e.point, e.pointIndex)), content = tooltip(e.series.key, x, y, e, chart); nv.tooltip.show([left, top], content, null, null, offsetElement); }; /* //Moved to see if we can get better behavior to fix issue #315 var indexDrag = d3.behavior.drag() .on('dragstart', dragStart) .on('drag', dragMove) .on('dragend', dragEnd); function dragStart(d,i) { d3.select(chart.container) .style('cursor', 'ew-resize'); } function dragMove(d,i) { d.x += d3.event.dx; d.i = Math.round(dx.invert(d.x)); d3.select(this).attr('transform', 'translate(' + dx(d.i) + ',0)'); chart.update(); } function dragEnd(d,i) { d3.select(chart.container) .style('cursor', 'auto'); chart.update(); } */ //============================================================ function chart(selection) { selection.each(function(data) { var container = d3.select(this).classed('nv-chart-' + id, true), that = this; var availableWidth = (width || parseInt(container.style('width')) || 960) - margin.left - margin.right, availableHeight = (height || parseInt(container.style('height')) || 400) - margin.top - margin.bottom; chart.update = function() { container.transition().call(chart) }; chart.container = this; //set state.disabled state.disabled = data.map(function(d) { return !!d.disabled }); if (!defaultState) { var key; defaultState = {}; for (key in state) { if (state[key] instanceof Array) defaultState[key] = state[key].slice(0); else defaultState[key] = state[key]; } } var indexDrag = d3.behavior.drag() .on('dragstart', dragStart) .on('drag', dragMove) .on('dragend', dragEnd); function dragStart(d,i) { d3.select(chart.container) .style('cursor', 'ew-resize'); } function dragMove(d,i) { index.x = d3.event.x; index.i = Math.round(dx.invert(index.x)); updateZero(); } function dragEnd(d,i) { d3.select(chart.container) .style('cursor', 'auto'); // update state and send stateChange with new index state.index = index.i; dispatch.stateChange(state); } //------------------------------------------------------------ // Display No Data message if there's nothing to show. if (!data || !data.length || !data.filter(function(d) { return d.values.length }).length) { var noDataText = container.selectAll('.nv-noData').data([noData]); noDataText.enter().append('text') .attr('class', 'nvd3 nv-noData') .attr('dy', '-.7em') .style('text-anchor', 'middle'); noDataText .attr('x', margin.left + availableWidth / 2) .attr('y', margin.top + availableHeight / 2) .text(function(d) { return d }); return chart; } else { container.selectAll('.nv-noData').remove(); } //------------------------------------------------------------ //------------------------------------------------------------ // Setup Scales x = lines.xScale(); y = lines.yScale(); if (!rescaleY) { var seriesDomains = data .filter(function(series) { return !series.disabled }) .map(function(series,i) { var initialDomain = d3.extent(series.values, lines.y()); //account for series being disabled when losing 95% or more if (initialDomain[0] < -.95) initialDomain[0] = -.95; return [ (initialDomain[0] - initialDomain[1]) / (1 + initialDomain[1]), (initialDomain[1] - initialDomain[0]) / (1 + initialDomain[0]) ]; }); var completeDomain = [ d3.min(seriesDomains, function(d) { return d[0] }), d3.max(seriesDomains, function(d) { return d[1] }) ] lines.yDomain(completeDomain); } else { lines.yDomain(null); } dx .domain([0, data[0].values.length - 1]) //Assumes all series have same length .range([0, availableWidth]) .clamp(true); //------------------------------------------------------------ var data = indexify(index.i, data); //------------------------------------------------------------ // Setup containers and skeleton of chart var wrap = container.selectAll('g.nv-wrap.nv-cumulativeLine').data([data]); var gEnter = wrap.enter().append('g').attr('class', 'nvd3 nv-wrap nv-cumulativeLine').append('g'); var g = wrap.select('g'); gEnter.append('g').attr('class', 'nv-x nv-axis'); gEnter.append('g').attr('class', 'nv-y nv-axis'); gEnter.append('g').attr('class', 'nv-background'); gEnter.append('g').attr('class', 'nv-linesWrap'); gEnter.append('g').attr('class', 'nv-avgLinesWrap'); gEnter.append('g').attr('class', 'nv-legendWrap'); gEnter.append('g').attr('class', 'nv-controlsWrap'); //------------------------------------------------------------ //------------------------------------------------------------ // Legend if (showLegend) { legend.width(availableWidth); g.select('.nv-legendWrap') .datum(data) .call(legend); if ( margin.top != legend.height()) { margin.top = legend.height() + legend.legendBelowPadding();// added legend.legendBelowPadding to allow for more spacing availableHeight = (height || parseInt(container.style('height')) || 400) - margin.top - margin.bottom; } g.select('.nv-legendWrap') .attr('transform', 'translate(0,' + (-margin.top) +')') } //------------------------------------------------------------ //------------------------------------------------------------ // Controls if (showControls) { var controlsData = [ { key: 'Re-scale y-axis', disabled: !rescaleY } ]; controls.width(140).color(['#444', '#444', '#444']); g.select('.nv-controlsWrap') .datum(controlsData) .attr('transform', 'translate(0,' + (-margin.top) +')') .call(controls); } //------------------------------------------------------------ wrap.attr('transform', 'translate(' + margin.left + ',' + margin.top + ')'); // Show error if series goes below 100% var tempDisabled = data.filter(function(d) { return d.tempDisabled }); wrap.select('.tempDisabled').remove(); //clean-up and prevent duplicates if (tempDisabled.length) { wrap.append('text').attr('class', 'tempDisabled') .attr('x', availableWidth / 2) .attr('y', '-.71em') .style('text-anchor', 'end') .text(tempDisabled.map(function(d) { return d.key }).join(', ') + ' values cannot be calculated for this time period.'); } //------------------------------------------------------------ // Main Chart Component(s) gEnter.select('.nv-background') .append('rect'); g.select('.nv-background rect') .attr('width', availableWidth) .attr('height', availableHeight); lines //.x(function(d) { return d.x }) .y(function(d) { return d.display.y }) .width(availableWidth) .height(availableHeight) .color(data.map(function(d,i) { return d.color || color(d, i); }).filter(function(d,i) { return !data[i].disabled && !data[i].tempDisabled; })); var linesWrap = g.select('.nv-linesWrap') .datum(data.filter(function(d) { return !d.disabled && !d.tempDisabled })); //d3.transition(linesWrap).call(lines); linesWrap.call(lines); /*Handle average lines [AN-612] ----------------------------*/ //Store a series index number in the data array. data.forEach(function(d,i) { d.seriesIndex = i; }); var avgLineData = data.filter(function(d) { return !d.disabled && !!average(d); }); var avgLines = g.select(".nv-avgLinesWrap").selectAll("line") .data(avgLineData, function(d) { return d.key; }); avgLines.enter() .append('line') .style('stroke-width',2) .style('stroke-dasharray','10,10') .style('stroke',function (d,i) { return lines.color()(d,d.seriesIndex); }) .attr('x1',0) .attr('x2',availableWidth) .attr('y1', function(d) { return y(average(d)); }) .attr('y2', function(d) { return y(average(d)); }); avgLines .attr('x1',0) .attr('x2',availableWidth) .attr('y1', function(d) { return y(average(d)); }) .attr('y2', function(d) { return y(average(d)); }); avgLines.exit().remove(); //Create index line ----------------------------------------- var indexLine = linesWrap.selectAll('.nv-indexLine') .data([index]); indexLine.enter().append('rect').attr('class', 'nv-indexLine') .attr('width', 3) .attr('x', -2) .attr('fill', 'red') .attr('fill-opacity', .5) .call(indexDrag) indexLine .attr('transform', function(d) { return 'translate(' + dx(d.i) + ',0)' }) .attr('height', availableHeight) //------------------------------------------------------------ //------------------------------------------------------------ // Setup Axes xAxis .scale(x) //Suggest how many ticks based on the chart width and D3 should listen (70 is the optimal number for MM/DD/YY dates) .ticks( Math.min(data[0].values.length,availableWidth/70) ) .tickSize(-availableHeight, 0); g.select('.nv-x.nv-axis') .attr('transform', 'translate(0,' + y.range()[0] + ')'); d3.transition(g.select('.nv-x.nv-axis')) .call(xAxis); yAxis .scale(y) .ticks( availableHeight / 36 ) .tickSize( -availableWidth, 0); d3.transition(g.select('.nv-y.nv-axis')) .call(yAxis); //------------------------------------------------------------ //============================================================ // Event Handling/Dispatching (in chart's scope) //------------------------------------------------------------ function updateZero() { indexLine .data([index]); container.call(chart); } g.select('.nv-background rect') .on('click', function() { index.x = d3.mouse(this)[0]; index.i = Math.round(dx.invert(index.x)); // update state and send stateChange with new index state.index = index.i; dispatch.stateChange(state); updateZero(); }); lines.dispatch.on('elementClick', function(e) { index.i = e.pointIndex; index.x = dx(index.i); // update state and send stateChange with new index state.index = index.i; dispatch.stateChange(state); updateZero(); }); controls.dispatch.on('legendClick', function(d,i) { d.disabled = !d.disabled; rescaleY = !d.disabled; state.rescaleY = rescaleY; dispatch.stateChange(state); //selection.transition().call(chart); chart.update(); }); legend.dispatch.on('legendClick', function(d,i) { d.disabled = !d.disabled; if (!data.filter(function(d) { return !d.disabled }).length) { data.map(function(d) { d.disabled = false; wrap.selectAll('.nv-series').classed('disabled', false); return d; }); } state.disabled = data.map(function(d) { return !!d.disabled }); dispatch.stateChange(state); //selection.transition().call(chart); chart.update(); }); legend.dispatch.on('legendDblclick', function(d) { //Double clicking should always enable current series, and disabled all others. data.forEach(function(d) { d.disabled = true; }); d.disabled = false; state.disabled = data.map(function(d) { return !!d.disabled }); dispatch.stateChange(state); chart.update(); }); /* // legend.dispatch.on('legendMouseover', function(d, i) { d.hover = true; selection.transition().call(chart) }); legend.dispatch.on('legendMouseout', function(d, i) { d.hover = false; selection.transition().call(chart) }); */ dispatch.on('tooltipShow', function(e) { if (tooltips) showTooltip(e, that.parentNode); }); // Update chart from a state object passed to event handler dispatch.on('changeState', function(e) { if (typeof e.disabled !== 'undefined') { data.forEach(function(series,i) { series.disabled = e.disabled[i]; }); state.disabled = e.disabled; } if (typeof e.index !== 'undefined') { index.i = e.index; index.x = dx(index.i); state.index = e.index; indexLine .data([index]); } if (typeof e.rescaleY !== 'undefined') { rescaleY = e.rescaleY; } chart.update(); }); //============================================================ }); return chart; } //============================================================ // Event Handling/Dispatching (out of chart's scope) //------------------------------------------------------------ lines.dispatch.on('elementMouseover.tooltip', function(e) { e.pos = [e.pos[0] + margin.left, e.pos[1] + margin.top]; dispatch.tooltipShow(e); }); lines.dispatch.on('elementMouseout.tooltip', function(e) { dispatch.tooltipHide(e); }); dispatch.on('tooltipHide', function() { if (tooltips) nv.tooltip.cleanup(); }); //============================================================ //============================================================ // Expose Public Variables //------------------------------------------------------------ // expose chart's sub-components chart.dispatch = dispatch; chart.lines = lines; chart.legend = legend; chart.xAxis = xAxis; chart.yAxis = yAxis; d3.rebind(chart, lines, 'defined', 'isArea', 'x', 'y', 'size', 'xDomain', 'yDomain', 'forceX', 'forceY', 'interactive', 'clipEdge', 'clipVoronoi', 'id'); chart.margin = function(_) { if (!arguments.length) return margin; margin.top = typeof _.top != 'undefined' ? _.top : margin.top; margin.right = typeof _.right != 'undefined' ? _.right : margin.right; margin.bottom = typeof _.bottom != 'undefined' ? _.bottom : margin.bottom; margin.left = typeof _.left != 'undefined' ? _.left : margin.left; return chart; }; chart.width = function(_) { if (!arguments.length) return width; width = _; return chart; }; chart.height = function(_) { if (!arguments.length) return height; height = _; return chart; }; chart.color = function(_) { if (!arguments.length) return color; color = nv.utils.getColor(_); legend.color(color); return chart; }; chart.rescaleY = function(_) { if (!arguments.length) return rescaleY; rescaleY = _ return rescaleY; }; chart.showControls = function(_) { if (!arguments.length) return showControls; showControls = _; return chart; }; chart.showLegend = function(_) { if (!arguments.length) return showLegend; showLegend = _; return chart; }; chart.tooltips = function(_) { if (!arguments.length) return tooltips; tooltips = _; return chart; }; chart.tooltipContent = function(_) { if (!arguments.length) return tooltip; tooltip = _; return chart; }; chart.state = function(_) { if (!arguments.length) return state; state = _; return chart; }; chart.defaultState = function(_) { if (!arguments.length) return defaultState; defaultState = _; return chart; }; chart.noData = function(_) { if (!arguments.length) return noData; noData = _; return chart; }; chart.average = function(_) { if(!arguments.length) return average; average = _; return chart; }; //============================================================ //============================================================ // Functions //------------------------------------------------------------ /* Normalize the data according to an index point. */ function indexify(idx, data) { return data.map(function(line, i) { if (!line.values) { return line; } var v = lines.y()(line.values[idx], idx); //TODO: implement check below, and disable series if series loses 100% or more cause divide by 0 issue if (v < -.95) { //if a series loses more than 100%, calculations fail.. anything close can cause major distortion (but is mathematically correct till it hits 100) line.tempDisabled = true; return line; } line.tempDisabled = false; line.values = line.values.map(function(point, pointIndex) { point.display = {'y': (lines.y()(point, pointIndex) - v) / (1 + v) }; return point; }) return line; }) } //============================================================ return chart; } //TODO: consider deprecating by adding necessary features to multiBar model nv.models.discreteBar = function() { //============================================================ // Public Variables with Default Settings //------------------------------------------------------------ var margin = {top: 0, right: 0, bottom: 0, left: 0} , width = 960 , height = 500 , id = Math.floor(Math.random() * 10000) //Create semi-unique ID in case user doesn't select one , x = d3.scale.ordinal() , y = d3.scale.linear() , getX = function(d) { return d.x } , getY = function(d) { return d.y } , forceY = [0] // 0 is forced by default.. this makes sense for the majority of bar graphs... user can always do chart.forceY([]) to remove , color = nv.utils.defaultColor() , showValues = false , valueFormat = d3.format(',.2f') , xDomain , yDomain , dispatch = d3.dispatch('chartClick', 'elementClick', 'elementDblClick', 'elementMouseover', 'elementMouseout') , rectClass = 'discreteBar' ; //============================================================ //============================================================ // Private Variables //------------------------------------------------------------ var x0, y0; //============================================================ function chart(selection) { selection.each(function(data) { var availableWidth = width - margin.left - margin.right, availableHeight = height - margin.top - margin.bottom, container = d3.select(this); //add series index to each data point for reference data = data.map(function(series, i) { series.values = series.values.map(function(point) { point.series = i; return point; }); return series; }); //------------------------------------------------------------ // Setup Scales // remap and flatten the data for use in calculating the scales' domains var seriesData = (xDomain && yDomain) ? [] : // if we know xDomain and yDomain, no need to calculate data.map(function(d) { return d.values.map(function(d,i) { return { x: getX(d,i), y: getY(d,i), y0: d.y0 } }) }); x .domain(xDomain || d3.merge(seriesData).map(function(d) { return d.x })) .rangeBands([0, availableWidth], .1); y .domain(yDomain || d3.extent(d3.merge(seriesData).map(function(d) { return d.y }).concat(forceY))); // If showValues, pad the Y axis range to account for label height if (showValues) y.range([availableHeight - (y.domain()[0] < 0 ? 12 : 0), y.domain()[1] > 0 ? 12 : 0]); else y.range([availableHeight, 0]); //store old scales if they exist x0 = x0 || x; y0 = y0 || y.copy().range([y(0),y(0)]); //------------------------------------------------------------ //------------------------------------------------------------ // Setup containers and skeleton of chart var wrap = container.selectAll('g.nv-wrap.nv-discretebar').data([data]); var wrapEnter = wrap.enter().append('g').attr('class', 'nvd3 nv-wrap nv-discretebar'); var gEnter = wrapEnter.append('g'); var g = wrap.select('g'); gEnter.append('g').attr('class', 'nv-groups'); wrap.attr('transform', 'translate(' + margin.left + ',' + margin.top + ')'); //------------------------------------------------------------ //TODO: by definition, the discrete bar should not have multiple groups, will modify/remove later var groups = wrap.select('.nv-groups').selectAll('.nv-group') .data(function(d) { return d }, function(d) { return d.key }); groups.enter().append('g') .style('stroke-opacity', 1e-6) .style('fill-opacity', 1e-6); d3.transition(groups.exit()) .style('stroke-opacity', 1e-6) .style('fill-opacity', 1e-6) .remove(); groups .attr('class', function(d,i) { return 'nv-group nv-series-' + i }) .classed('hover', function(d) { return d.hover }); d3.transition(groups) .style('stroke-opacity', 1) .style('fill-opacity', .75); var bars = groups.selectAll('g.nv-bar') .data(function(d) { return d.values }); bars.exit().remove(); var barsEnter = bars.enter().append('g') .attr('transform', function(d,i,j) { return 'translate(' + (x(getX(d,i)) + x.rangeBand() * .05 ) + ', ' + y(0) + ')' }) .on('mouseover', function(d,i) { //TODO: figure out why j works above, but not here d3.select(this).classed('hover', true); dispatch.elementMouseover({ value: getY(d,i), point: d, series: data[d.series], pos: [x(getX(d,i)) + (x.rangeBand() * (d.series + .5) / data.length), y(getY(d,i))], // TODO: Figure out why the value appears to be shifted pointIndex: i, seriesIndex: d.series, e: d3.event }); }) .on('mouseout', function(d,i) { d3.select(this).classed('hover', false); dispatch.elementMouseout({ value: getY(d,i), point: d, series: data[d.series], pointIndex: i, seriesIndex: d.series, e: d3.event }); }) .on('click', function(d,i) { dispatch.elementClick({ value: getY(d,i), point: d, series: data[d.series], pos: [x(getX(d,i)) + (x.rangeBand() * (d.series + .5) / data.length), y(getY(d,i))], // TODO: Figure out why the value appears to be shifted pointIndex: i, seriesIndex: d.series, e: d3.event }); d3.event.stopPropagation(); }) .on('dblclick', function(d,i) { dispatch.elementDblClick({ value: getY(d,i), point: d, series: data[d.series], pos: [x(getX(d,i)) + (x.rangeBand() * (d.series + .5) / data.length), y(getY(d,i))], // TODO: Figure out why the value appears to be shifted pointIndex: i, seriesIndex: d.series, e: d3.event }); d3.event.stopPropagation(); }); barsEnter.append('rect') .attr('height', 0) .attr('width', x.rangeBand() * .9 / data.length ) if (showValues) { barsEnter.append('text') .attr('text-anchor', 'middle') bars.select('text') .attr('x', x.rangeBand() * .9 / 2) .attr('y', function(d,i) { return getY(d,i) < 0 ? y(getY(d,i)) - y(0) + 12 : -4 }) .text(function(d,i) { return valueFormat(getY(d,i)) }); } else { bars.selectAll('text').remove(); } bars .attr('class', function(d,i) { return getY(d,i) < 0 ? 'nv-bar negative' : 'nv-bar positive' }) .style('fill', function(d,i) { return d.color || color(d,i) }) .style('stroke', function(d,i) { return d.color || color(d,i) }) .select('rect') .attr('class', rectClass) .attr('width', x.rangeBand() * .9 / data.length); d3.transition(bars) //.delay(function(d,i) { return i * 1200 / data[0].values.length }) .attr('transform', function(d,i) { var left = x(getX(d,i)) + x.rangeBand() * .05, top = getY(d,i) < 0 ? y(0) : y(0) - y(getY(d,i)) < 1 ? y(0) - 1 : //make 1 px positive bars show up above y=0 y(getY(d,i)); return 'translate(' + left + ', ' + top + ')' }) .select('rect') .attr('height', function(d,i) { return Math.max(Math.abs(y(getY(d,i)) - y(0)) || 1) }); //store old scales for use in transitions on update x0 = x.copy(); y0 = y.copy(); }); return chart; } //============================================================ // Expose Public Variables //------------------------------------------------------------ chart.dispatch = dispatch; chart.x = function(_) { if (!arguments.length) return getX; getX = _; return chart; }; chart.y = function(_) { if (!arguments.length) return getY; getY = _; return chart; }; chart.margin = function(_) { if (!arguments.length) return margin; margin.top = typeof _.top != 'undefined' ? _.top : margin.top; margin.right = typeof _.right != 'undefined' ? _.right : margin.right; margin.bottom = typeof _.bottom != 'undefined' ? _.bottom : margin.bottom; margin.left = typeof _.left != 'undefined' ? _.left : margin.left; return chart; }; chart.width = function(_) { if (!arguments.length) return width; width = _; return chart; }; chart.height = function(_) { if (!arguments.length) return height; height = _; return chart; }; chart.xScale = function(_) { if (!arguments.length) return x; x = _; return chart; }; chart.yScale = function(_) { if (!arguments.length) return y; y = _; return chart; }; chart.xDomain = function(_) { if (!arguments.length) return xDomain; xDomain = _; return chart; }; chart.yDomain = function(_) { if (!arguments.length) return yDomain; yDomain = _; return chart; }; chart.forceY = function(_) { if (!arguments.length) return forceY; forceY = _; return chart; }; chart.color = function(_) { if (!arguments.length) return color; color = nv.utils.getColor(_); return chart; }; chart.id = function(_) { if (!arguments.length) return id; id = _; return chart; }; chart.showValues = function(_) { if (!arguments.length) return showValues; showValues = _; return chart; }; chart.valueFormat= function(_) { if (!arguments.length) return valueFormat; valueFormat = _; return chart; }; chart.rectClass= function(_) { if (!arguments.length) return rectClass; rectClass = _; return chart; } //============================================================ return chart; } nv.models.discreteBarChart = function() { //============================================================ // Public Variables with Default Settings //------------------------------------------------------------ var discretebar = nv.models.discreteBar() , xAxis = nv.models.axis() , yAxis = nv.models.axis() ; var margin = {top: 15, right: 10, bottom: 50, left: 60} , width = null , height = null , color = nv.utils.getColor() , staggerLabels = false , tooltips = true , tooltip = function(key, x, y, e, graph) { return '

    ' + x + '

    ' + '

    ' + y + '

    ' } , x , y , noData = "No Data Available." , dispatch = d3.dispatch('tooltipShow', 'tooltipHide', 'beforeUpdate') ; xAxis .orient('bottom') .highlightZero(false) .showMaxMin(false) .tickFormat(function(d) { return d }) ; yAxis .orient('left') .tickFormat(d3.format(',.1f')) ; //============================================================ //============================================================ // Private Variables //------------------------------------------------------------ var showTooltip = function(e, offsetElement) { var left = e.pos[0] + ( offsetElement.offsetLeft || 0 ), top = e.pos[1] + ( offsetElement.offsetTop || 0), x = xAxis.tickFormat()(discretebar.x()(e.point, e.pointIndex)), y = yAxis.tickFormat()(discretebar.y()(e.point, e.pointIndex)), content = tooltip(e.series.key, x, y, e, chart); nv.tooltip.show([left, top], content, e.value < 0 ? 'n' : 's', null, offsetElement); }; //============================================================ function chart(selection) { selection.each(function(data) { var container = d3.select(this), that = this; var availableWidth = (width || parseInt(container.style('width')) || 960) - margin.left - margin.right, availableHeight = (height || parseInt(container.style('height')) || 400) - margin.top - margin.bottom; chart.update = function() { dispatch.beforeUpdate(); container.transition().call(chart); }; chart.container = this; //------------------------------------------------------------ // Display No Data message if there's nothing to show. if (!data || !data.length || !data.filter(function(d) { return d.values.length }).length) { var noDataText = container.selectAll('.nv-noData').data([noData]); noDataText.enter().append('text') .attr('class', 'nvd3 nv-noData') .attr('dy', '-.7em') .style('text-anchor', 'middle'); noDataText .attr('x', margin.left + availableWidth / 2) .attr('y', margin.top + availableHeight / 2) .text(function(d) { return d }); return chart; } else { container.selectAll('.nv-noData').remove(); } //------------------------------------------------------------ //------------------------------------------------------------ // Setup Scales x = discretebar.xScale(); y = discretebar.yScale(); //------------------------------------------------------------ //------------------------------------------------------------ // Setup containers and skeleton of chart var wrap = container.selectAll('g.nv-wrap.nv-discreteBarWithAxes').data([data]); var gEnter = wrap.enter().append('g').attr('class', 'nvd3 nv-wrap nv-discreteBarWithAxes').append('g'); var defsEnter = gEnter.append('defs'); var g = wrap.select('g'); gEnter.append('g').attr('class', 'nv-x nv-axis'); gEnter.append('g').attr('class', 'nv-y nv-axis'); gEnter.append('g').attr('class', 'nv-barsWrap'); g.attr('transform', 'translate(' + margin.left + ',' + margin.top + ')'); //------------------------------------------------------------ //------------------------------------------------------------ // Main Chart Component(s) discretebar .width(availableWidth) .height(availableHeight); var barsWrap = g.select('.nv-barsWrap') .datum(data.filter(function(d) { return !d.disabled })) d3.transition(barsWrap).call(discretebar); //------------------------------------------------------------ defsEnter.append('clipPath') .attr('id', 'nv-x-label-clip-' + discretebar.id()) .append('rect'); g.select('#nv-x-label-clip-' + discretebar.id() + ' rect') .attr('width', x.rangeBand() * (staggerLabels ? 2 : 1)) .attr('height', 16) .attr('x', -x.rangeBand() / (staggerLabels ? 1 : 2 )); //------------------------------------------------------------ // Setup Axes xAxis .scale(x) .ticks( availableWidth / 100 ) .tickSize(-availableHeight, 0); g.select('.nv-x.nv-axis') .attr('transform', 'translate(0,' + (y.range()[0] + ((discretebar.showValues() && y.domain()[0] < 0) ? 16 : 0)) + ')'); //d3.transition(g.select('.nv-x.nv-axis')) g.select('.nv-x.nv-axis').transition().duration(0) .call(xAxis); var xTicks = g.select('.nv-x.nv-axis').selectAll('g'); if (staggerLabels) { xTicks .selectAll('text') .attr('transform', function(d,i,j) { return 'translate(0,' + (j % 2 == 0 ? '5' : '17') + ')' }) } yAxis .scale(y) .ticks( availableHeight / 36 ) .tickSize( -availableWidth, 0); d3.transition(g.select('.nv-y.nv-axis')) .call(yAxis); //------------------------------------------------------------ //============================================================ // Event Handling/Dispatching (in chart's scope) //------------------------------------------------------------ dispatch.on('tooltipShow', function(e) { if (tooltips) showTooltip(e, that.parentNode); }); //============================================================ }); return chart; } //============================================================ // Event Handling/Dispatching (out of chart's scope) //------------------------------------------------------------ discretebar.dispatch.on('elementMouseover.tooltip', function(e) { e.pos = [e.pos[0] + margin.left, e.pos[1] + margin.top]; dispatch.tooltipShow(e); }); discretebar.dispatch.on('elementMouseout.tooltip', function(e) { dispatch.tooltipHide(e); }); dispatch.on('tooltipHide', function() { if (tooltips) nv.tooltip.cleanup(); }); //============================================================ //============================================================ // Expose Public Variables //------------------------------------------------------------ // expose chart's sub-components chart.dispatch = dispatch; chart.discretebar = discretebar; chart.xAxis = xAxis; chart.yAxis = yAxis; d3.rebind(chart, discretebar, 'x', 'y', 'xDomain', 'yDomain', 'forceX', 'forceY', 'id', 'showValues', 'valueFormat'); chart.margin = function(_) { if (!arguments.length) return margin; margin.top = typeof _.top != 'undefined' ? _.top : margin.top; margin.right = typeof _.right != 'undefined' ? _.right : margin.right; margin.bottom = typeof _.bottom != 'undefined' ? _.bottom : margin.bottom; margin.left = typeof _.left != 'undefined' ? _.left : margin.left; return chart; }; chart.width = function(_) { if (!arguments.length) return width; width = _; return chart; }; chart.height = function(_) { if (!arguments.length) return height; height = _; return chart; }; chart.color = function(_) { if (!arguments.length) return color; color = nv.utils.getColor(_); discretebar.color(color); return chart; }; chart.staggerLabels = function(_) { if (!arguments.length) return staggerLabels; staggerLabels = _; return chart; }; chart.tooltips = function(_) { if (!arguments.length) return tooltips; tooltips = _; return chart; }; chart.tooltipContent = function(_) { if (!arguments.length) return tooltip; tooltip = _; return chart; }; chart.noData = function(_) { if (!arguments.length) return noData; noData = _; return chart; }; //============================================================ return chart; } nv.models.distribution = function() { //============================================================ // Public Variables with Default Settings //------------------------------------------------------------ var margin = {top: 0, right: 0, bottom: 0, left: 0} , width = 400 //technically width or height depending on x or y.... , size = 8 , axis = 'x' // 'x' or 'y'... horizontal or vertical , getData = function(d) { return d[axis] } // defaults d.x or d.y , color = nv.utils.defaultColor() , scale = d3.scale.linear() , domain ; //============================================================ //============================================================ // Private Variables //------------------------------------------------------------ var scale0; //============================================================ function chart(selection) { selection.each(function(data) { var availableLength = width - (axis === 'x' ? margin.left + margin.right : margin.top + margin.bottom), naxis = axis == 'x' ? 'y' : 'x', container = d3.select(this); //------------------------------------------------------------ // Setup Scales scale0 = scale0 || scale; //------------------------------------------------------------ //------------------------------------------------------------ // Setup containers and skeleton of chart var wrap = container.selectAll('g.nv-distribution').data([data]); var wrapEnter = wrap.enter().append('g').attr('class', 'nvd3 nv-distribution'); var gEnter = wrapEnter.append('g'); var g = wrap.select('g'); wrap.attr('transform', 'translate(' + margin.left + ',' + margin.top + ')') //------------------------------------------------------------ var distWrap = g.selectAll('g.nv-dist') .data(function(d) { return d }, function(d) { return d.key }); distWrap.enter().append('g'); distWrap .attr('class', function(d,i) { return 'nv-dist nv-series-' + i }) .style('stroke', function(d,i) { return color(d, i) }); var dist = distWrap.selectAll('line.nv-dist' + axis) .data(function(d) { return d.values }) dist.enter().append('line') .attr(axis + '1', function(d,i) { return scale0(getData(d,i)) }) .attr(axis + '2', function(d,i) { return scale0(getData(d,i)) }) d3.transition(distWrap.exit().selectAll('line.nv-dist' + axis)) .attr(axis + '1', function(d,i) { return scale(getData(d,i)) }) .attr(axis + '2', function(d,i) { return scale(getData(d,i)) }) .style('stroke-opacity', 0) .remove(); dist .attr('class', function(d,i) { return 'nv-dist' + axis + ' nv-dist' + axis + '-' + i }) .attr(naxis + '1', 0) .attr(naxis + '2', size); d3.transition(dist) .attr(axis + '1', function(d,i) { return scale(getData(d,i)) }) .attr(axis + '2', function(d,i) { return scale(getData(d,i)) }) scale0 = scale.copy(); }); return chart; } //============================================================ // Expose Public Variables //------------------------------------------------------------ chart.margin = function(_) { if (!arguments.length) return margin; margin.top = typeof _.top != 'undefined' ? _.top : margin.top; margin.right = typeof _.right != 'undefined' ? _.right : margin.right; margin.bottom = typeof _.bottom != 'undefined' ? _.bottom : margin.bottom; margin.left = typeof _.left != 'undefined' ? _.left : margin.left; return chart; }; chart.width = function(_) { if (!arguments.length) return width; width = _; return chart; }; chart.axis = function(_) { if (!arguments.length) return axis; axis = _; return chart; }; chart.size = function(_) { if (!arguments.length) return size; size = _; return chart; }; chart.getData = function(_) { if (!arguments.length) return getData; getData = d3.functor(_); return chart; }; chart.scale = function(_) { if (!arguments.length) return scale; scale = _; return chart; }; chart.color = function(_) { if (!arguments.length) return color; color = nv.utils.getColor(_); return chart; }; //============================================================ return chart; } //TODO: consider deprecating and using multibar with single series for this nv.models.historicalBar = function() { //============================================================ // Public Variables with Default Settings //------------------------------------------------------------ var margin = {top: 0, right: 0, bottom: 0, left: 0} , width = 960 , height = 500 , id = Math.floor(Math.random() * 10000) //Create semi-unique ID in case user doesn't select one , x = d3.scale.linear() , y = d3.scale.linear() , getX = function(d) { return d.x } , getY = function(d) { return d.y } , forceX = [] , forceY = [0] , padData = false , clipEdge = true , color = nv.utils.defaultColor() , xDomain , yDomain , dispatch = d3.dispatch('chartClick', 'elementClick', 'elementDblClick', 'elementMouseover', 'elementMouseout') ; //============================================================ function chart(selection) { selection.each(function(data) { var availableWidth = width - margin.left - margin.right, availableHeight = height - margin.top - margin.bottom, container = d3.select(this); //------------------------------------------------------------ // Setup Scales x .domain(xDomain || d3.extent(data[0].values.map(getX).concat(forceX) )) if (padData) x.range([availableWidth * .5 / data[0].values.length, availableWidth * (data[0].values.length - .5) / data[0].values.length ]); else x.range([0, availableWidth]); y .domain(yDomain || d3.extent(data[0].values.map(getY).concat(forceY) )) .range([availableHeight, 0]); // If scale's domain don't have a range, slightly adjust to make one... so a chart can show a single data point if (x.domain()[0] === x.domain()[1] || y.domain()[0] === y.domain()[1]) singlePoint = true; if (x.domain()[0] === x.domain()[1]) x.domain()[0] ? x.domain([x.domain()[0] - x.domain()[0] * 0.01, x.domain()[1] + x.domain()[1] * 0.01]) : x.domain([-1,1]); if (y.domain()[0] === y.domain()[1]) y.domain()[0] ? y.domain([y.domain()[0] + y.domain()[0] * 0.01, y.domain()[1] - y.domain()[1] * 0.01]) : y.domain([-1,1]); //------------------------------------------------------------ //------------------------------------------------------------ // Setup containers and skeleton of chart var wrap = container.selectAll('g.nv-wrap.nv-bar').data([data[0].values]); var wrapEnter = wrap.enter().append('g').attr('class', 'nvd3 nv-wrap nv-bar'); var defsEnter = wrapEnter.append('defs'); var gEnter = wrapEnter.append('g'); var g = wrap.select('g'); gEnter.append('g').attr('class', 'nv-bars'); wrap.attr('transform', 'translate(' + margin.left + ',' + margin.top + ')'); //------------------------------------------------------------ container .on('click', function(d,i) { dispatch.chartClick({ data: d, index: i, pos: d3.event, id: id }); }); defsEnter.append('clipPath') .attr('id', 'nv-chart-clip-path-' + id) .append('rect'); wrap.select('#nv-chart-clip-path-' + id + ' rect') .attr('width', availableWidth) .attr('height', availableHeight); g .attr('clip-path', clipEdge ? 'url(#nv-chart-clip-path-' + id + ')' : ''); var bars = wrap.select('.nv-bars').selectAll('.nv-bar') .data(function(d) { return d }); bars.exit().remove(); var barsEnter = bars.enter().append('rect') //.attr('class', function(d,i,j) { return (getY(d,i) < 0 ? 'nv-bar negative' : 'nv-bar positive') + ' nv-bar-' + j + '-' + i }) .attr('x', 0 ) .attr('y', function(d,i) { return y(Math.max(0, getY(d,i))) }) .attr('height', function(d,i) { return Math.abs(y(getY(d,i)) - y(0)) }) .on('mouseover', function(d,i) { d3.select(this).classed('hover', true); dispatch.elementMouseover({ point: d, series: data[0], pos: [x(getX(d,i)), y(getY(d,i))], // TODO: Figure out why the value appears to be shifted pointIndex: i, seriesIndex: 0, e: d3.event }); }) .on('mouseout', function(d,i) { d3.select(this).classed('hover', false); dispatch.elementMouseout({ point: d, series: data[0], pointIndex: i, seriesIndex: 0, e: d3.event }); }) .on('click', function(d,i) { dispatch.elementClick({ //label: d[label], value: getY(d,i), data: d, index: i, pos: [x(getX(d,i)), y(getY(d,i))], e: d3.event, id: id }); d3.event.stopPropagation(); }) .on('dblclick', function(d,i) { dispatch.elementDblClick({ //label: d[label], value: getY(d,i), data: d, index: i, pos: [x(getX(d,i)), y(getY(d,i))], e: d3.event, id: id }); d3.event.stopPropagation(); }); bars .attr('fill', function(d,i) { return color(d, i); }) .attr('class', function(d,i,j) { return (getY(d,i) < 0 ? 'nv-bar negative' : 'nv-bar positive') + ' nv-bar-' + j + '-' + i }) .attr('transform', function(d,i) { return 'translate(' + (x(getX(d,i)) - availableWidth / data[0].values.length * .45) + ',0)'; }) //TODO: better width calculations that don't assume always uniform data spacing;w .attr('width', (availableWidth / data[0].values.length) * .9 ) d3.transition(bars) //.attr('y', function(d,i) { return y(Math.max(0, getY(d,i))) }) .attr('y', function(d,i) { return getY(d,i) < 0 ? y(0) : y(0) - y(getY(d,i)) < 1 ? y(0) - 1 : y(getY(d,i)) }) .attr('height', function(d,i) { return Math.max(Math.abs(y(getY(d,i)) - y(0)),1) }); //.order(); // not sure if this makes any sense for this model }); return chart; } //============================================================ // Expose Public Variables //------------------------------------------------------------ chart.dispatch = dispatch; chart.x = function(_) { if (!arguments.length) return getX; getX = _; return chart; }; chart.y = function(_) { if (!arguments.length) return getY; getY = _; return chart; }; chart.margin = function(_) { if (!arguments.length) return margin; margin.top = typeof _.top != 'undefined' ? _.top : margin.top; margin.right = typeof _.right != 'undefined' ? _.right : margin.right; margin.bottom = typeof _.bottom != 'undefined' ? _.bottom : margin.bottom; margin.left = typeof _.left != 'undefined' ? _.left : margin.left; return chart; }; chart.width = function(_) { if (!arguments.length) return width; width = _; return chart; }; chart.height = function(_) { if (!arguments.length) return height; height = _; return chart; }; chart.xScale = function(_) { if (!arguments.length) return x; x = _; return chart; }; chart.yScale = function(_) { if (!arguments.length) return y; y = _; return chart; }; chart.xDomain = function(_) { if (!arguments.length) return xDomain; xDomain = _; return chart; }; chart.yDomain = function(_) { if (!arguments.length) return yDomain; yDomain = _; return chart; }; chart.forceX = function(_) { if (!arguments.length) return forceX; forceX = _; return chart; }; chart.forceY = function(_) { if (!arguments.length) return forceY; forceY = _; return chart; }; chart.padData = function(_) { if (!arguments.length) return padData; padData = _; return chart; }; chart.clipEdge = function(_) { if (!arguments.length) return clipEdge; clipEdge = _; return chart; }; chart.color = function(_) { if (!arguments.length) return color; color = nv.utils.getColor(_); return chart; }; chart.id = function(_) { if (!arguments.length) return id; id = _; return chart; }; //============================================================ return chart; } nv.models.historicalBarChart = function() { //============================================================ // Public Variables with Default Settings //------------------------------------------------------------ var bars = nv.models.historicalBar() , xAxis = nv.models.axis() , yAxis = nv.models.axis() , legend = nv.models.legend() ; var margin = {top: 30, right: 90, bottom: 50, left: 90} , color = nv.utils.defaultColor() , width = null , height = null , showLegend = false , showXAxis = true , showYAxis = true , rightAlignYAxis = false , tooltips = true , tooltip = function(key, x, y, e, graph) { return '

    ' + key + '

    ' + '

    ' + y + ' at ' + x + '

    ' } , x , y , state = {} , defaultState = null , noData = 'No Data Available.' , dispatch = d3.dispatch('tooltipShow', 'tooltipHide', 'stateChange', 'changeState') ; xAxis .orient('bottom') .tickPadding(7) ; yAxis .orient( (rightAlignYAxis) ? 'right' : 'left') ; //============================================================ //============================================================ // Private Variables //------------------------------------------------------------ var showTooltip = function(e, offsetElement) { // New addition to calculate position if SVG is scaled with viewBox, may move TODO: consider implementing everywhere else if (offsetElement) { var svg = d3.select(offsetElement).select('svg'); var viewBox = (svg.node()) ? svg.attr('viewBox') : null; if (viewBox) { viewBox = viewBox.split(' '); var ratio = parseInt(svg.style('width')) / viewBox[2]; e.pos[0] = e.pos[0] * ratio; e.pos[1] = e.pos[1] * ratio; } } var left = e.pos[0] + ( offsetElement.offsetLeft || 0 ), top = e.pos[1] + ( offsetElement.offsetTop || 0), x = xAxis.tickFormat()(bars.x()(e.point, e.pointIndex)), y = yAxis.tickFormat()(bars.y()(e.point, e.pointIndex)), content = tooltip(e.series.key, x, y, e, chart); nv.tooltip.show([left, top], content, null, null, offsetElement); }; //============================================================ function chart(selection) { selection.each(function(data) { var container = d3.select(this), that = this; var availableWidth = (width || parseInt(container.style('width')) || 960) - margin.left - margin.right, availableHeight = (height || parseInt(container.style('height')) || 400) - margin.top - margin.bottom; chart.update = function() { chart(selection) }; chart.container = this; //set state.disabled state.disabled = data.map(function(d) { return !!d.disabled }); if (!defaultState) { var key; defaultState = {}; for (key in state) { if (state[key] instanceof Array) defaultState[key] = state[key].slice(0); else defaultState[key] = state[key]; } } //------------------------------------------------------------ // Display noData message if there's nothing to show. if (!data || !data.length || !data.filter(function(d) { return d.values.length }).length) { var noDataText = container.selectAll('.nv-noData').data([noData]); noDataText.enter().append('text') .attr('class', 'nvd3 nv-noData') .attr('dy', '-.7em') .style('text-anchor', 'middle'); noDataText .attr('x', margin.left + availableWidth / 2) .attr('y', margin.top + availableHeight / 2) .text(function(d) { return d }); return chart; } else { container.selectAll('.nv-noData').remove(); } //------------------------------------------------------------ //------------------------------------------------------------ // Setup Scales x = bars.xScale(); y = bars.yScale(); //------------------------------------------------------------ //------------------------------------------------------------ // Setup containers and skeleton of chart var wrap = container.selectAll('g.nv-wrap.nv-lineChart').data([data]); var gEnter = wrap.enter().append('g').attr('class', 'nvd3 nv-wrap nv-lineChart').append('g'); var g = wrap.select('g'); gEnter.append('g').attr('class', 'nv-x nv-axis'); gEnter.append('g').attr('class', 'nv-y nv-axis'); gEnter.append('g').attr('class', 'nv-barsWrap'); gEnter.append('g').attr('class', 'nv-legendWrap'); //------------------------------------------------------------ //------------------------------------------------------------ // Legend if (showLegend) { legend.width(availableWidth); g.select('.nv-legendWrap') .datum(data) .call(legend); if ( margin.top != legend.height()) { margin.top = legend.height() + legend.legendBelowPadding();// added legend.legendBelowPadding to allow for more spacing availableHeight = (height || parseInt(container.style('height')) || 400) - margin.top - margin.bottom; } wrap.select('.nv-legendWrap') .attr('transform', 'translate(0,' + (-margin.top) +')') } //------------------------------------------------------------ wrap.attr('transform', 'translate(' + margin.left + ',' + margin.top + ')'); if (rightAlignYAxis) { g.select(".nv-y.nv-axis") .attr("transform", "translate(" + availableWidth + ",0)"); } //------------------------------------------------------------ // Main Chart Component(s) bars .width(availableWidth) .height(availableHeight) .color(data.map(function(d,i) { return d.color || color(d, i); }).filter(function(d,i) { return !data[i].disabled })); var barsWrap = g.select('.nv-barsWrap') .datum(data.filter(function(d) { return !d.disabled })) d3.transition(barsWrap).call(bars); //------------------------------------------------------------ //------------------------------------------------------------ // Setup Axes if (showXAxis) { xAxis .scale(x) .tickSize(-availableHeight, 0); g.select('.nv-x.nv-axis') .attr('transform', 'translate(0,' + y.range()[0] + ')'); g.select('.nv-x.nv-axis') .transition() .call(xAxis); } if (showYAxis) { yAxis .scale(y) .ticks( availableHeight / 36 ) .tickSize( -availableWidth, 0); g.select('.nv-y.nv-axis') .transition().duration(0) .call(yAxis); } //------------------------------------------------------------ //============================================================ // Event Handling/Dispatching (in chart's scope) //------------------------------------------------------------ legend.dispatch.on('legendClick', function(d,i) { d.disabled = !d.disabled; if (!data.filter(function(d) { return !d.disabled }).length) { data.map(function(d) { d.disabled = false; wrap.selectAll('.nv-series').classed('disabled', false); return d; }); } state.disabled = data.map(function(d) { return !!d.disabled }); dispatch.stateChange(state); selection.transition().call(chart); }); legend.dispatch.on('legendDblclick', function(d) { //Double clicking should always enable current series, and disabled all others. data.forEach(function(d) { d.disabled = true; }); d.disabled = false; state.disabled = data.map(function(d) { return !!d.disabled }); dispatch.stateChange(state); chart.update(); }); /* legend.dispatch.on('legendMouseover', function(d, i) { d.hover = true; selection.transition().call(chart) }); legend.dispatch.on('legendMouseout', function(d, i) { d.hover = false; selection.transition().call(chart) }); */ dispatch.on('tooltipShow', function(e) { if (tooltips) showTooltip(e, that.parentNode); }); dispatch.on('changeState', function(e) { if (typeof e.disabled !== 'undefined') { data.forEach(function(series,i) { series.disabled = e.disabled[i]; }); state.disabled = e.disabled; } selection.call(chart); }); //============================================================ }); return chart; } //============================================================ // Event Handling/Dispatching (out of chart's scope) //------------------------------------------------------------ bars.dispatch.on('elementMouseover.tooltip', function(e) { e.pos = [e.pos[0] + margin.left, e.pos[1] + margin.top]; dispatch.tooltipShow(e); }); bars.dispatch.on('elementMouseout.tooltip', function(e) { dispatch.tooltipHide(e); }); dispatch.on('tooltipHide', function() { if (tooltips) nv.tooltip.cleanup(); }); //============================================================ //============================================================ // Expose Public Variables //------------------------------------------------------------ // expose chart's sub-components chart.dispatch = dispatch; chart.bars = bars; chart.legend = legend; chart.xAxis = xAxis; chart.yAxis = yAxis; d3.rebind(chart, bars, 'defined', 'isArea', 'x', 'y', 'size', 'xScale', 'yScale', 'xDomain', 'yDomain', 'forceX', 'forceY', 'interactive', 'clipEdge', 'clipVoronoi', 'id', 'interpolate'); chart.margin = function(_) { if (!arguments.length) return margin; margin.top = typeof _.top != 'undefined' ? _.top : margin.top; margin.right = typeof _.right != 'undefined' ? _.right : margin.right; margin.bottom = typeof _.bottom != 'undefined' ? _.bottom : margin.bottom; margin.left = typeof _.left != 'undefined' ? _.left : margin.left; return chart; }; chart.width = function(_) { if (!arguments.length) return width; width = _; return chart; }; chart.height = function(_) { if (!arguments.length) return height; height = _; return chart; }; chart.color = function(_) { if (!arguments.length) return color; color = nv.utils.getColor(_); legend.color(color); return chart; }; chart.showLegend = function(_) { if (!arguments.length) return showLegend; showLegend = _; return chart; }; chart.showXAxis = function(_) { if (!arguments.length) return showXAxis; showXAxis = _; return chart; }; chart.showYAxis = function(_) { if (!arguments.length) return showYAxis; showYAxis = _; return chart; }; chart.rightAlignYAxis = function(_) { if(!arguments.length) return rightAlignYAxis; rightAlignYAxis = _; yAxis.orient( (_) ? 'right' : 'left'); return chart; }; chart.tooltips = function(_) { if (!arguments.length) return tooltips; tooltips = _; return chart; }; chart.tooltipContent = function(_) { if (!arguments.length) return tooltip; tooltip = _; return chart; }; chart.state = function(_) { if (!arguments.length) return state; state = _; return chart; }; chart.defaultState = function(_) { if (!arguments.length) return defaultState; defaultState = _; return chart; }; chart.noData = function(_) { if (!arguments.length) return noData; noData = _; return chart; }; //============================================================ return chart; } nv.models.indentedTree = function() { //============================================================ // Public Variables with Default Settings //------------------------------------------------------------ var margin = {top: 0, right: 0, bottom: 0, left: 0} //TODO: implement, maybe as margin on the containing div , width = 960 , height = 500 , color = nv.utils.defaultColor() , id = Math.floor(Math.random() * 10000) , header = true , filterZero = false , noData = "No Data Available." , childIndent = 20 , columns = [{key:'key', label: 'Name', type:'text'}] //TODO: consider functions like chart.addColumn, chart.removeColumn, instead of a block like this , tableClass = null , iconOpen = 'images/grey-plus.png' //TODO: consider removing this and replacing with a '+' or '-' unless user defines images , iconClose = 'images/grey-minus.png' , dispatch = d3.dispatch('elementClick', 'elementDblclick', 'elementMouseover', 'elementMouseout') ; //============================================================ var idx = 0; function chart(selection) { selection.each(function(data) { var depth = 1, container = d3.select(this); var tree = d3.layout.tree() .children(function(d) { return d.values }) .size([height, childIndent]); //Not sure if this is needed now that the result is HTML chart.update = function() { container.transition().duration(600).call(chart) }; //------------------------------------------------------------ // Display No Data message if there's nothing to show. if (!data[0]) data[0] = {key: noData}; //------------------------------------------------------------ var nodes = tree.nodes(data[0]); // nodes.map(function(d) { // d.id = i++; // }) //------------------------------------------------------------ // Setup containers and skeleton of chart var wrap = d3.select(this).selectAll('div').data([[nodes]]); var wrapEnter = wrap.enter().append('div').attr('class', 'nvd3 nv-wrap nv-indentedtree'); var tableEnter = wrapEnter.append('table'); var table = wrap.select('table').attr('width', '100%').attr('class', tableClass); //------------------------------------------------------------ if (header) { var thead = tableEnter.append('thead'); var theadRow1 = thead.append('tr'); columns.forEach(function(column) { theadRow1 .append('th') .attr('width', column.width ? column.width : '10%') .style('text-align', column.type == 'numeric' ? 'right' : 'left') .append('span') .text(column.label); }); } var tbody = table.selectAll('tbody') .data(function(d) { return d }); tbody.enter().append('tbody'); //compute max generations depth = d3.max(nodes, function(node) { return node.depth }); tree.size([height, depth * childIndent]); //TODO: see if this is necessary at all // Update the nodes… var node = tbody.selectAll('tr') // .data(function(d) { return d; }, function(d) { return d.id || (d.id == ++i)}); .data(function(d) { return d.filter(function(d) { return (filterZero && !d.children) ? filterZero(d) : true; } )}, function(d,i) { return d.id || (d.id || ++idx)}); //.style('display', 'table-row'); //TODO: see if this does anything node.exit().remove(); node.select('img.nv-treeicon') .attr('src', icon) .classed('folded', folded); var nodeEnter = node.enter().append('tr'); columns.forEach(function(column, index) { var nodeName = nodeEnter.append('td') .style('padding-left', function(d) { return (index ? 0 : d.depth * childIndent + 12 + (icon(d) ? 0 : 16)) + 'px' }, 'important') //TODO: check why I did the ternary here .style('text-align', column.type == 'numeric' ? 'right' : 'left'); if (index == 0) { nodeName.append('img') .classed('nv-treeicon', true) .classed('nv-folded', folded) .attr('src', icon) .style('width', '14px') .style('height', '14px') .style('padding', '0 1px') .style('display', function(d) { return icon(d) ? 'inline-block' : 'none'; }) .on('click', click); } nodeName.append('span') .attr('class', d3.functor(column.classes) ) .text(function(d) { return column.format ? column.format(d) : (d[column.key] || '-') }); if (column.showCount) { nodeName.append('span') .attr('class', 'nv-childrenCount'); node.selectAll('span.nv-childrenCount').text(function(d) { return ((d.values && d.values.length) || (d._values && d._values.length)) ? //If this is a parent '(' + ((d.values && (d.values.filter(function(d) { return filterZero ? filterZero(d) : true; }).length)) //If children are in values check its children and filter || (d._values && d._values.filter(function(d) { return filterZero ? filterZero(d) : true; }).length) //Otherwise, do the same, but with the other name, _values... || 0) + ')' //This is the catch-all in case there are no children after a filter : '' //If this is not a parent, just give an empty string }); } if (column.click) nodeName.select('span').on('click', column.click); }); node .order() .on('click', function(d) { dispatch.elementClick({ row: this, //TODO: decide whether or not this should be consistent with scatter/line events or should be an html link (a href) data: d, pos: [d.x, d.y] }); }) .on('dblclick', function(d) { dispatch.elementDblclick({ row: this, data: d, pos: [d.x, d.y] }); }) .on('mouseover', function(d) { dispatch.elementMouseover({ row: this, data: d, pos: [d.x, d.y] }); }) .on('mouseout', function(d) { dispatch.elementMouseout({ row: this, data: d, pos: [d.x, d.y] }); }); // Toggle children on click. function click(d, _, unshift) { d3.event.stopPropagation(); if(d3.event.shiftKey && !unshift) { //If you shift-click, it'll toggle fold all the children, instead of itself d3.event.shiftKey = false; d.values && d.values.forEach(function(node){ if (node.values || node._values) { click(node, 0, true); } }); return true; } if(!hasChildren(d)) { //download file //window.location.href = d.url; return true; } if (d.values) { d._values = d.values; d.values = null; } else { d.values = d._values; d._values = null; } chart.update(); } function icon(d) { return (d._values && d._values.length) ? iconOpen : (d.values && d.values.length) ? iconClose : ''; } function folded(d) { return (d._values && d._values.length); } function hasChildren(d) { var values = d.values || d._values; return (values && values.length); } }); return chart; } //============================================================ // Expose Public Variables //------------------------------------------------------------ chart.margin = function(_) { if (!arguments.length) return margin; margin.top = typeof _.top != 'undefined' ? _.top : margin.top; margin.right = typeof _.right != 'undefined' ? _.right : margin.right; margin.bottom = typeof _.bottom != 'undefined' ? _.bottom : margin.bottom; margin.left = typeof _.left != 'undefined' ? _.left : margin.left; return chart; }; chart.width = function(_) { if (!arguments.length) return width; width = _; return chart; }; chart.height = function(_) { if (!arguments.length) return height; height = _; return chart; }; chart.color = function(_) { if (!arguments.length) return color; color = nv.utils.getColor(_); scatter.color(color); return chart; }; chart.id = function(_) { if (!arguments.length) return id; id = _; return chart; }; chart.header = function(_) { if (!arguments.length) return header; header = _; return chart; }; chart.noData = function(_) { if (!arguments.length) return noData; noData = _; return chart; }; chart.filterZero = function(_) { if (!arguments.length) return filterZero; filterZero = _; return chart; }; chart.columns = function(_) { if (!arguments.length) return columns; columns = _; return chart; }; chart.tableClass = function(_) { if (!arguments.length) return tableClass; tableClass = _; return chart; }; chart.iconOpen = function(_){ if (!arguments.length) return iconOpen; iconOpen = _; return chart; } chart.iconClose = function(_){ if (!arguments.length) return iconClose; iconClose = _; return chart; } //============================================================ return chart; };nv.models.legend = function() { //============================================================ // Public Variables with Default Settings //------------------------------------------------------------ var margin = {top: 5, right: 0, bottom: 5, left: 0} , width = 400 , height = 20 , getKey = function(d) { return d.key } , color = nv.utils.defaultColor() , align = true , dispatch = d3.dispatch('legendClick', 'legendDblclick', 'legendMouseover', 'legendMouseout') , svgComputedTextPadding = 28 , roundedRecRadius = 0 , legendBelowPadding = 20 ; //============================================================ /* Rounded Rec Path: x: x-coordinate y: y-coordinate w: width h: height r: corner radius tl: top_left rounded? tr: top_right rounded? bl: bottom_left rounded? br: bottom_right rounded? */ function rounded_rect(x, y, w, h, r, tl, tr, bl, br) { var retval; retval = "M" + (x + r) + "," + y; retval += "h" + (w - 2*r); if (tr) { retval += "a" + r + "," + r + " 0 0 1 " + r + "," + r; } else { retval += "h" + r; retval += "v" + r; } retval += "v" + (h - 2*r); if (br) { retval += "a" + r + "," + r + " 0 0 1 " + -r + "," + r; } else { retval += "v" + r; retval += "h" + -r; } retval += "h" + (2*r - w); if (bl) { retval += "a" + r + "," + r + " 0 0 1 " + -r + "," + -r; } else { retval += "h" + -r; retval += "v" + -r; } retval += "v" + (2*r - h); if (tl) { retval += "a" + r + "," + r + " 0 0 1 " + r + "," + -r; } else { retval += "v" + -r; retval += "h" + r; } retval += "z"; return retval; } function chart(selection) { selection.each(function(data) { var availableWidth = width - margin.left - margin.right, container = d3.select(this); //------------------------------------------------------------ // Setup containers and skeleton of chart var wrap = container.selectAll('g.nv-legend').data([data]); var gEnter = wrap.enter().append('g').attr('class', 'nvd3 nv-legend').append('g'); var g = wrap.select('g'); wrap.attr('transform', 'translate(' + margin.left + ',' + margin.top + ')'); //------------------------------------------------------------ var series = g.selectAll('.nv-series') .data(function(d) { return d }); var seriesEnter = series.enter().append('g').attr('class', 'nv-series') .on('mouseover', function(d,i) { dispatch.legendMouseover(d,i); //TODO: Make consistent with other event objects }) .on('mouseout', function(d,i) { dispatch.legendMouseout(d,i); }) .on('click', function(d,i) { dispatch.legendClick(d,i); }) .on('dblclick', function(d,i) { dispatch.legendDblclick(d,i); }); seriesEnter.append('path'); seriesEnter.append('circle') .style('stroke-width', 2) .attr('r', 5); seriesEnter.append('text') .attr('text-anchor', 'start') .attr('dy', '.33em') .attr('dx', '12'); series.classed('disabled', function(d) { return d.disabled }); series.exit().remove(); series.select('circle') .style('fill', function(d,i) { return d.color || color(d,i)}) .style('stroke', function(d,i) { return d.color || color(d, i) }); series.select('text').text(getKey); //TODO: implement fixed-width and max-width options (max-width is especially useful with the align option) // NEW ALIGNING CODE, TODO: clean up if (align) { var seriesWidths = []; series.each(function(d,i) { var legendText = d3.select(this).select('text'); var svgComputedTextLength = legendText.node().getComputedTextLength() || nv.utils.calcApproxTextWidth(legendText); seriesWidths.push(svgComputedTextLength + svgComputedTextPadding); //40 is for adding additional padding, TODO make value a property }); //nv.log('Series Widths: ', JSON.stringify(seriesWidths)); var seriesPerRow = 0; var legendWidth = 0; var columnWidths = []; while ( legendWidth < availableWidth && seriesPerRow < seriesWidths.length) { columnWidths[seriesPerRow] = seriesWidths[seriesPerRow]; legendWidth += seriesWidths[seriesPerRow++]; } while ( legendWidth > availableWidth && seriesPerRow > 1 ) { columnWidths = []; seriesPerRow--; for (k = 0; k < seriesWidths.length; k++) { if (seriesWidths[k] > (columnWidths[k % seriesPerRow] || 0) ) columnWidths[k % seriesPerRow] = seriesWidths[k]; } legendWidth = columnWidths.reduce(function(prev, cur, index, array) { return prev + cur; }); } //console.log(columnWidths, legendWidth, seriesPerRow); var xPositions = []; for (var i = 0, curX = 0; i < seriesPerRow; i++) { xPositions[i] = curX; curX += columnWidths[i]; } series .attr('transform', function(d, i) { return 'translate(' + xPositions[i % seriesPerRow] + ',' + (5 + Math.floor(i / seriesPerRow) * 20) + ')'; }).select("path") .attr("d", function(d, i) { var addLeftCap = false; var addRightCap = false; if(i == 0){ addLeftCap = true; }else if (i == seriesWidths.length-1){ addRightCap = true; } return rounded_rect(-14, -14, seriesWidths[i] , 28, roundedRecRadius, addLeftCap, addRightCap, addLeftCap, addRightCap); }); //position legend as far right as possible within the total width g.attr('transform', 'translate(' + (width - margin.right - legendWidth) + ',' + margin.top + ')'); height = margin.top + margin.bottom + (Math.ceil(seriesWidths.length / seriesPerRow) * 20); } else { var ypos = 5, newxpos = 5, maxwidth = 0, xpos; series .attr('transform', function(d, i) { var length = d3.select(this).select('text').node().getComputedTextLength() + 28; xpos = newxpos; if (width < margin.left + margin.right + xpos + length) { newxpos = xpos = 5; ypos += 20; } newxpos += length; if (newxpos > maxwidth) maxwidth = newxpos; return 'translate(' + xpos + ',' + ypos + ')'; }); //position legend as far right as possible within the total width g.attr('transform', 'translate(' + (width - margin.right - maxwidth) + ',' + margin.top + ')'); height = margin.top + margin.bottom + ypos + 15; } }); return chart; } //============================================================ // Expose Public Variables //------------------------------------------------------------ chart.dispatch = dispatch; chart.svgComputedTextPadding = function(_) { if (!arguments.length) return svgComputedTextPadding; svgComputedTextPadding = _; return chart; }; chart.roundedRecRadius = function(_) { if (!arguments.length) return roundedRecRadius; roundedRecRadius = _; return chart; }; chart.legendBelowPadding = function(_) { if (!arguments.length) return legendBelowPadding; legendBelowPadding = _; return chart; }; chart.margin = function(_) { if (!arguments.length) return margin; margin.top = typeof _.top != 'undefined' ? _.top : margin.top; margin.right = typeof _.right != 'undefined' ? _.right : margin.right; margin.bottom = typeof _.bottom != 'undefined' ? _.bottom : margin.bottom; margin.left = typeof _.left != 'undefined' ? _.left : margin.left; return chart; }; chart.width = function(_) { if (!arguments.length) return width; width = _; return chart; }; chart.height = function(_) { if (!arguments.length) return height; height = _; return chart; }; chart.key = function(_) { if (!arguments.length) return getKey; getKey = _; return chart; }; chart.color = function(_) { if (!arguments.length) return color; color = nv.utils.getColor(_); return chart; }; chart.align = function(_) { if (!arguments.length) return align; align = _; return chart; }; //============================================================ return chart; } nv.models.line = function() { //============================================================ // Public Variables with Default Settings //------------------------------------------------------------ var scatter = nv.models.scatter() ; var margin = {top: 0, right: 0, bottom: 0, left: 0} , width = 960 , height = 500 , color = nv.utils.defaultColor() // a function that returns a color , getX = function(d) { return d.x } // accessor to get the x value from a data point , getY = function(d) { return d.y } // accessor to get the y value from a data point , defined = function(d,i) { return !isNaN(getY(d,i)) && getY(d,i) !== null } // allows a line to be not continuous when it is not defined , isArea = function(d) { return d.area } // decides if a line is an area or just a line , clipEdge = false // if true, masks lines within x and y scale , x //can be accessed via chart.xScale() , y //can be accessed via chart.yScale() , interpolate = "linear" // controls the line interpolation ; scatter .size(16) // default size .sizeDomain([16,256]) //set to speed up calculation, needs to be unset if there is a custom size accessor ; //============================================================ //============================================================ // Private Variables //------------------------------------------------------------ var x0, y0 //used to store previous scales ; //============================================================ function chart(selection) { selection.each(function(data) { var availableWidth = width - margin.left - margin.right, availableHeight = height - margin.top - margin.bottom, container = d3.select(this); //------------------------------------------------------------ // Setup Scales x = scatter.xScale(); y = scatter.yScale(); x0 = x0 || x; y0 = y0 || y; //------------------------------------------------------------ //------------------------------------------------------------ // Setup containers and skeleton of chart var wrap = container.selectAll('g.nv-wrap.nv-line').data([data]); var wrapEnter = wrap.enter().append('g').attr('class', 'nvd3 nv-wrap nv-line'); var defsEnter = wrapEnter.append('defs'); var gEnter = wrapEnter.append('g'); var g = wrap.select('g') gEnter.append('g').attr('class', 'nv-groups'); gEnter.append('g').attr('class', 'nv-scatterWrap'); wrap.attr('transform', 'translate(' + margin.left + ',' + margin.top + ')'); //------------------------------------------------------------ scatter .width(availableWidth) .height(availableHeight) var scatterWrap = wrap.select('.nv-scatterWrap'); //.datum(data); // Data automatically trickles down from the wrap d3.transition(scatterWrap).call(scatter); defsEnter.append('clipPath') .attr('id', 'nv-edge-clip-' + scatter.id()) .append('rect'); wrap.select('#nv-edge-clip-' + scatter.id() + ' rect') .attr('width', availableWidth) .attr('height', availableHeight); g .attr('clip-path', clipEdge ? 'url(#nv-edge-clip-' + scatter.id() + ')' : ''); scatterWrap .attr('clip-path', clipEdge ? 'url(#nv-edge-clip-' + scatter.id() + ')' : ''); var groups = wrap.select('.nv-groups').selectAll('.nv-group') .data(function(d) { return d }, function(d) { return d.key }); groups.enter().append('g') .style('stroke-opacity', 1e-6) .style('fill-opacity', 1e-6); d3.transition(groups.exit()) .style('stroke-opacity', 1e-6) .style('fill-opacity', 1e-6) .remove(); groups .attr('class', function(d,i) { return 'nv-group nv-series-' + i }) .classed('hover', function(d) { return d.hover }) .style('fill', function(d,i){ return color(d, i) }) .style('stroke', function(d,i){ return color(d, i)}); d3.transition(groups) .style('stroke-opacity', 1) .style('fill-opacity', .5); var areaPaths = groups.selectAll('path.nv-area') .data(function(d) { return isArea(d) ? [d] : [] }); // this is done differently than lines because I need to check if series is an area areaPaths.enter().append('path') .attr('class', 'nv-area') .attr('d', function(d) { return d3.svg.area() .interpolate(interpolate) .defined(defined) .x(function(d,i) { return x0(getX(d,i)) }) .y0(function(d,i) { return y0(getY(d,i)) }) .y1(function(d,i) { return y0( y.domain()[0] <= 0 ? y.domain()[1] >= 0 ? 0 : y.domain()[1] : y.domain()[0] ) }) //.y1(function(d,i) { return y0(0) }) //assuming 0 is within y domain.. may need to tweak this .apply(this, [d.values]) }); d3.transition(groups.exit().selectAll('path.nv-area')) .attr('d', function(d) { return d3.svg.area() .interpolate(interpolate) .defined(defined) .x(function(d,i) { return x(getX(d,i)) }) .y0(function(d,i) { return y(getY(d,i)) }) .y1(function(d,i) { return y( y.domain()[0] <= 0 ? y.domain()[1] >= 0 ? 0 : y.domain()[1] : y.domain()[0] ) }) //.y1(function(d,i) { return y0(0) }) //assuming 0 is within y domain.. may need to tweak this .apply(this, [d.values]) }); d3.transition(areaPaths) .attr('d', function(d) { return d3.svg.area() .interpolate(interpolate) .defined(defined) .x(function(d,i) { return x(getX(d,i)) }) .y0(function(d,i) { return y(getY(d,i)) }) .y1(function(d,i) { return y( y.domain()[0] <= 0 ? y.domain()[1] >= 0 ? 0 : y.domain()[1] : y.domain()[0] ) }) //.y1(function(d,i) { return y0(0) }) //assuming 0 is within y domain.. may need to tweak this .apply(this, [d.values]) }); var linePaths = groups.selectAll('path.nv-line') .data(function(d) { return [d.values] }); linePaths.enter().append('path') .attr('class', 'nv-line') .attr('d', d3.svg.line() .interpolate(interpolate) .defined(defined) .x(function(d,i) { return x0(getX(d,i)) }) .y(function(d,i) { return y0(getY(d,i)) }) ); d3.transition(groups.exit().selectAll('path.nv-line')) .attr('d', d3.svg.line() .interpolate(interpolate) .defined(defined) .x(function(d,i) { return x(getX(d,i)) }) .y(function(d,i) { return y(getY(d,i)) }) ); d3.transition(linePaths) .attr('d', d3.svg.line() .interpolate(interpolate) .defined(defined) .x(function(d,i) { return x(getX(d,i)) }) .y(function(d,i) { return y(getY(d,i)) }) ); //store old scales for use in transitions on update x0 = x.copy(); y0 = y.copy(); }); return chart; } //============================================================ // Expose Public Variables //------------------------------------------------------------ chart.dispatch = scatter.dispatch; chart.scatter = scatter; d3.rebind(chart, scatter, 'id', 'interactive', 'size', 'xScale', 'yScale', 'zScale', 'xDomain', 'yDomain', 'sizeDomain', 'forceX', 'forceY', 'forceSize', 'clipVoronoi', 'clipRadius', 'padData'); chart.margin = function(_) { if (!arguments.length) return margin; margin.top = typeof _.top != 'undefined' ? _.top : margin.top; margin.right = typeof _.right != 'undefined' ? _.right : margin.right; margin.bottom = typeof _.bottom != 'undefined' ? _.bottom : margin.bottom; margin.left = typeof _.left != 'undefined' ? _.left : margin.left; return chart; }; chart.width = function(_) { if (!arguments.length) return width; width = _; return chart; }; chart.height = function(_) { if (!arguments.length) return height; height = _; return chart; }; chart.x = function(_) { if (!arguments.length) return getX; getX = _; scatter.x(_); return chart; }; chart.y = function(_) { if (!arguments.length) return getY; getY = _; scatter.y(_); return chart; }; chart.clipEdge = function(_) { if (!arguments.length) return clipEdge; clipEdge = _; return chart; }; chart.color = function(_) { if (!arguments.length) return color; color = nv.utils.getColor(_); scatter.color(color); return chart; }; chart.interpolate = function(_) { if (!arguments.length) return interpolate; interpolate = _; return chart; }; chart.defined = function(_) { if (!arguments.length) return defined; defined = _; return chart; }; chart.isArea = function(_) { if (!arguments.length) return isArea; isArea = d3.functor(_); return chart; }; //============================================================ return chart; } nv.models.lineChart = function() { //============================================================ // Public Variables with Default Settings //------------------------------------------------------------ var lines = nv.models.line() , xAxis = nv.models.axis() , yAxis = nv.models.axis() , legend = nv.models.legend() ; //set margin.right to 23 to fit dates on the x-axis within the chart var margin = {top: 30, right: 20, bottom: 50, left: 60} , color = nv.utils.defaultColor() , width = null , height = null , showLegend = true , showXAxis = true , showYAxis = true , rightAlignYAxis = false , tooltips = true , tooltip = function(key, x, y, e, graph) { return '

    ' + key + '

    ' + '

    ' + y + ' at ' + x + '

    ' } , x , y , state = {} , defaultState = null , noData = 'No Data Available.' , dispatch = d3.dispatch('tooltipShow', 'tooltipHide', 'stateChange', 'changeState') ; xAxis .orient('bottom') .tickPadding(7) ; yAxis .orient((rightAlignYAxis) ? 'right' : 'left') ; //============================================================ //============================================================ // Private Variables //------------------------------------------------------------ var showTooltip = function(e, offsetElement) { // New addition to calculate position if SVG is scaled with viewBox, may move TODO: consider implementing everywhere else if (offsetElement) { var svg = d3.select(offsetElement).select('svg'); var viewBox = (svg.node()) ? svg.attr('viewBox') : null; if (viewBox) { viewBox = viewBox.split(' '); var ratio = parseInt(svg.style('width')) / viewBox[2]; e.pos[0] = e.pos[0] * ratio; e.pos[1] = e.pos[1] * ratio; } } var left = e.pos[0] + ( offsetElement.offsetLeft || 0 ), top = e.pos[1] + ( offsetElement.offsetTop || 0), x = xAxis.tickFormat()(lines.x()(e.point, e.pointIndex)), y = yAxis.tickFormat()(lines.y()(e.point, e.pointIndex)), content = tooltip(e.series.key, x, y, e, chart); nv.tooltip.show([left, top], content, null, null, offsetElement); }; //============================================================ function chart(selection) { selection.each(function(data) { var container = d3.select(this), that = this; var availableWidth = (width || parseInt(container.style('width')) || 960) - margin.left - margin.right, availableHeight = (height || parseInt(container.style('height')) || 400) - margin.top - margin.bottom; chart.update = function() { container.transition().call(chart) }; chart.container = this; //set state.disabled state.disabled = data.map(function(d) { return !!d.disabled }); if (!defaultState) { var key; defaultState = {}; for (key in state) { if (state[key] instanceof Array) defaultState[key] = state[key].slice(0); else defaultState[key] = state[key]; } } //------------------------------------------------------------ // Display noData message if there's nothing to show. if (!data || !data.length || !data.filter(function(d) { return d.values.length }).length) { var noDataText = container.selectAll('.nv-noData').data([noData]); noDataText.enter().append('text') .attr('class', 'nvd3 nv-noData') .attr('dy', '-.7em') .style('text-anchor', 'middle'); noDataText .attr('x', margin.left + availableWidth / 2) .attr('y', margin.top + availableHeight / 2) .text(function(d) { return d }); return chart; } else { container.selectAll('.nv-noData').remove(); } //------------------------------------------------------------ //------------------------------------------------------------ // Setup Scales x = lines.xScale(); y = lines.yScale(); //------------------------------------------------------------ //------------------------------------------------------------ // Setup containers and skeleton of chart var wrap = container.selectAll('g.nv-wrap.nv-lineChart').data([data]); var gEnter = wrap.enter().append('g').attr('class', 'nvd3 nv-wrap nv-lineChart').append('g'); var g = wrap.select('g'); gEnter.append('g').attr('class', 'nv-x nv-axis'); gEnter.append('g').attr('class', 'nv-y nv-axis'); gEnter.append('g').attr('class', 'nv-linesWrap'); gEnter.append('g').attr('class', 'nv-legendWrap'); //------------------------------------------------------------ //------------------------------------------------------------ // Legend if (showLegend) { legend.width(availableWidth); g.select('.nv-legendWrap') .datum(data) .call(legend); if ( margin.top != legend.height()) { margin.top = legend.height() + legend.legendBelowPadding();// added legend.legendBelowPadding to allow for more spacing availableHeight = (height || parseInt(container.style('height')) || 400) - margin.top - margin.bottom; } wrap.select('.nv-legendWrap') .attr('transform', 'translate(0,' + (-margin.top) +')') } //------------------------------------------------------------ wrap.attr('transform', 'translate(' + margin.left + ',' + margin.top + ')'); if (rightAlignYAxis) { g.select(".nv-y.nv-axis") .attr("transform", "translate(" + availableWidth + ",0)"); } //------------------------------------------------------------ // Main Chart Component(s) lines .width(availableWidth) .height(availableHeight) .color(data.map(function(d,i) { return d.color || color(d, i); }).filter(function(d,i) { return !data[i].disabled })); var linesWrap = g.select('.nv-linesWrap') .datum(data.filter(function(d) { return !d.disabled })) d3.transition(linesWrap).call(lines); //------------------------------------------------------------ //------------------------------------------------------------ // Setup Axes if (showXAxis) { xAxis .scale(x) .ticks( availableWidth / 100 ) .tickSize(-availableHeight, 0); g.select('.nv-x.nv-axis') .attr('transform', 'translate(0,' + y.range()[0] + ')'); d3.transition(g.select('.nv-x.nv-axis')) .call(xAxis); } if (showYAxis) { yAxis .scale(y) .ticks( availableHeight / 36 ) .tickSize( -availableWidth, 0); d3.transition(g.select('.nv-y.nv-axis')) .call(yAxis); } //------------------------------------------------------------ //============================================================ // Event Handling/Dispatching (in chart's scope) //------------------------------------------------------------ legend.dispatch.on('legendClick', function(d,i) { d.disabled = !d.disabled; if (!data.filter(function(d) { return !d.disabled }).length) { data.map(function(d) { d.disabled = false; wrap.selectAll('.nv-series').classed('disabled', false); return d; }); } state.disabled = data.map(function(d) { return !!d.disabled }); dispatch.stateChange(state); // container.transition().call(chart); chart.update(); }); legend.dispatch.on('legendDblclick', function(d) { //Double clicking should always enable current series, and disabled all others. data.forEach(function(d) { d.disabled = true; }); d.disabled = false; state.disabled = data.map(function(d) { return !!d.disabled }); dispatch.stateChange(state); chart.update(); }); /* legend.dispatch.on('legendMouseover', function(d, i) { d.hover = true; selection.transition().call(chart) }); legend.dispatch.on('legendMouseout', function(d, i) { d.hover = false; selection.transition().call(chart) }); */ dispatch.on('tooltipShow', function(e) { if (tooltips) showTooltip(e, that.parentNode); }); dispatch.on('changeState', function(e) { if (typeof e.disabled !== 'undefined') { data.forEach(function(series,i) { series.disabled = e.disabled[i]; }); state.disabled = e.disabled; } chart.update(); }); //============================================================ }); return chart; } //============================================================ // Event Handling/Dispatching (out of chart's scope) //------------------------------------------------------------ lines.dispatch.on('elementMouseover.tooltip', function(e) { e.pos = [e.pos[0] + margin.left, e.pos[1] + margin.top]; dispatch.tooltipShow(e); }); lines.dispatch.on('elementMouseout.tooltip', function(e) { dispatch.tooltipHide(e); }); dispatch.on('tooltipHide', function() { if (tooltips) nv.tooltip.cleanup(); }); //============================================================ //============================================================ // Expose Public Variables //------------------------------------------------------------ // expose chart's sub-components chart.dispatch = dispatch; chart.lines = lines; chart.legend = legend; chart.xAxis = xAxis; chart.yAxis = yAxis; d3.rebind(chart, lines, 'defined', 'isArea', 'x', 'y', 'size', 'xScale', 'yScale', 'xDomain', 'yDomain', 'forceX', 'forceY', 'interactive', 'clipEdge', 'clipVoronoi', 'id', 'interpolate'); chart.margin = function(_) { if (!arguments.length) return margin; margin.top = typeof _.top != 'undefined' ? _.top : margin.top; margin.right = typeof _.right != 'undefined' ? _.right : margin.right; margin.bottom = typeof _.bottom != 'undefined' ? _.bottom : margin.bottom; margin.left = typeof _.left != 'undefined' ? _.left : margin.left; return chart; }; chart.width = function(_) { if (!arguments.length) return width; width = _; return chart; }; chart.height = function(_) { if (!arguments.length) return height; height = _; return chart; }; chart.color = function(_) { if (!arguments.length) return color; color = nv.utils.getColor(_); legend.color(color); return chart; }; chart.showLegend = function(_) { if (!arguments.length) return showLegend; showLegend = _; return chart; }; chart.showXAxis = function(_) { if (!arguments.length) return showXAxis; showXAxis = _; return chart; }; chart.showYAxis = function(_) { if (!arguments.length) return showYAxis; showYAxis = _; return chart; }; chart.rightAlignYAxis = function(_) { if(!arguments.length) return rightAlignYAxis; rightAlignYAxis = _; yAxis.orient( (_) ? 'right' : 'left'); return chart; }; chart.tooltips = function(_) { if (!arguments.length) return tooltips; tooltips = _; return chart; }; chart.tooltipContent = function(_) { if (!arguments.length) return tooltip; tooltip = _; return chart; }; chart.state = function(_) { if (!arguments.length) return state; state = _; return chart; }; chart.defaultState = function(_) { if (!arguments.length) return defaultState; defaultState = _; return chart; }; chart.noData = function(_) { if (!arguments.length) return noData; noData = _; return chart; }; //============================================================ return chart; } nv.models.linePlusBarChart = function() { //============================================================ // Public Variables with Default Settings //------------------------------------------------------------ var lines = nv.models.line() , bars = nv.models.historicalBar() , xAxis = nv.models.axis() , y1Axis = nv.models.axis() , y2Axis = nv.models.axis() , legend = nv.models.legend() ; var margin = {top: 30, right: 60, bottom: 50, left: 60} , width = null , height = null , getX = function(d) { return d.x } , getY = function(d) { return d.y } , color = nv.utils.defaultColor() , showLegend = true , tooltips = true , tooltip = function(key, x, y, e, graph) { return '

    ' + key + '

    ' + '

    ' + y + ' at ' + x + '

    '; } , x , y1 , y2 , state = {} , defaultState = null , noData = "No Data Available." , dispatch = d3.dispatch('tooltipShow', 'tooltipHide', 'stateChange', 'changeState') ; bars .padData(true) ; lines .clipEdge(false) .padData(true) ; xAxis .orient('bottom') .tickPadding(7) .highlightZero(false) ; y1Axis .orient('left') ; y2Axis .orient('right') ; //============================================================ //============================================================ // Private Variables //------------------------------------------------------------ var showTooltip = function(e, offsetElement) { var left = e.pos[0] + ( offsetElement.offsetLeft || 0 ), top = e.pos[1] + ( offsetElement.offsetTop || 0), x = xAxis.tickFormat()(lines.x()(e.point, e.pointIndex)), y = (e.series.bar ? y1Axis : y2Axis).tickFormat()(lines.y()(e.point, e.pointIndex)), content = tooltip(e.series.key, x, y, e, chart); nv.tooltip.show([left, top], content, e.value < 0 ? 'n' : 's', null, offsetElement); } ; //------------------------------------------------------------ function chart(selection) { selection.each(function(data) { var container = d3.select(this), that = this; var availableWidth = (width || parseInt(container.style('width')) || 960) - margin.left - margin.right, availableHeight = (height || parseInt(container.style('height')) || 400) - margin.top - margin.bottom; chart.update = function() { container.transition().call(chart); }; // chart.container = this; //set state.disabled state.disabled = data.map(function(d) { return !!d.disabled }); if (!defaultState) { var key; defaultState = {}; for (key in state) { if (state[key] instanceof Array) defaultState[key] = state[key].slice(0); else defaultState[key] = state[key]; } } //------------------------------------------------------------ // Display No Data message if there's nothing to show. if (!data || !data.length || !data.filter(function(d) { return d.values.length }).length) { var noDataText = container.selectAll('.nv-noData').data([noData]); noDataText.enter().append('text') .attr('class', 'nvd3 nv-noData') .attr('dy', '-.7em') .style('text-anchor', 'middle'); noDataText .attr('x', margin.left + availableWidth / 2) .attr('y', margin.top + availableHeight / 2) .text(function(d) { return d }); return chart; } else { container.selectAll('.nv-noData').remove(); } //------------------------------------------------------------ //------------------------------------------------------------ // Setup Scales var dataBars = data.filter(function(d) { return !d.disabled && d.bar }); var dataLines = data.filter(function(d) { return !d.bar }); // removed the !d.disabled clause here to fix Issue #240 //x = xAxis.scale(); x = dataLines.filter(function(d) { return !d.disabled; }).length && dataLines.filter(function(d) { return !d.disabled; })[0].values.length ? lines.xScale() : bars.xScale(); //x = dataLines.filter(function(d) { return !d.disabled; }).length ? lines.xScale() : bars.xScale(); //old code before change above y1 = bars.yScale(); y2 = lines.yScale(); //------------------------------------------------------------ //------------------------------------------------------------ // Setup containers and skeleton of chart var wrap = d3.select(this).selectAll('g.nv-wrap.nv-linePlusBar').data([data]); var gEnter = wrap.enter().append('g').attr('class', 'nvd3 nv-wrap nv-linePlusBar').append('g'); var g = wrap.select('g'); gEnter.append('g').attr('class', 'nv-x nv-axis'); gEnter.append('g').attr('class', 'nv-y1 nv-axis'); gEnter.append('g').attr('class', 'nv-y2 nv-axis'); gEnter.append('g').attr('class', 'nv-barsWrap'); gEnter.append('g').attr('class', 'nv-linesWrap'); gEnter.append('g').attr('class', 'nv-legendWrap'); //------------------------------------------------------------ //------------------------------------------------------------ // Legend if (showLegend) { legend.width( availableWidth / 2 ); g.select('.nv-legendWrap') .datum(data.map(function(series) { series.originalKey = series.originalKey === undefined ? series.key : series.originalKey; series.key = series.originalKey + (series.bar ? ' (left axis)' : ' (right axis)'); return series; })) .call(legend); if ( margin.top != legend.height()) { margin.top = legend.height() + legend.legendBelowPadding();// added legend.legendBelowPadding to allow for more spacing availableHeight = (height || parseInt(container.style('height')) || 400) - margin.top - margin.bottom; } g.select('.nv-legendWrap') .attr('transform', 'translate(' + ( availableWidth / 2 ) + ',' + (-margin.top) +')'); } //------------------------------------------------------------ wrap.attr('transform', 'translate(' + margin.left + ',' + margin.top + ')'); //------------------------------------------------------------ // Main Chart Component(s) lines .width(availableWidth) .height(availableHeight) .color(data.map(function(d,i) { return d.color || color(d, i); }).filter(function(d,i) { return !data[i].disabled && !data[i].bar })) bars .width(availableWidth) .height(availableHeight) .color(data.map(function(d,i) { return d.color || color(d, i); }).filter(function(d,i) { return !data[i].disabled && data[i].bar })) var barsWrap = g.select('.nv-barsWrap') .datum(dataBars.length ? dataBars : [{values:[]}]) var linesWrap = g.select('.nv-linesWrap') .datum(dataLines[0] && !dataLines[0].disabled ? dataLines : [{values:[]}] ); //.datum(!dataLines[0].disabled ? dataLines : [{values:dataLines[0].values.map(function(d) { return [d[0], null] }) }] ); d3.transition(barsWrap).call(bars); d3.transition(linesWrap).call(lines); //------------------------------------------------------------ //------------------------------------------------------------ // Setup Axes xAxis .scale(x) .ticks( availableWidth / 100 ) .tickSize(-availableHeight, 0); g.select('.nv-x.nv-axis') .attr('transform', 'translate(0,' + y1.range()[0] + ')'); d3.transition(g.select('.nv-x.nv-axis')) .call(xAxis); y1Axis .scale(y1) .ticks( availableHeight / 36 ) .tickSize(-availableWidth, 0); d3.transition(g.select('.nv-y1.nv-axis')) .style('opacity', dataBars.length ? 1 : 0) .call(y1Axis); y2Axis .scale(y2) .ticks( availableHeight / 36 ) .tickSize(dataBars.length ? 0 : -availableWidth, 0); // Show the y2 rules only if y1 has none g.select('.nv-y2.nv-axis') .style('opacity', dataLines.length ? 1 : 0) .attr('transform', 'translate(' + availableWidth + ',0)'); //.attr('transform', 'translate(' + x.range()[1] + ',0)'); d3.transition(g.select('.nv-y2.nv-axis')) .call(y2Axis); //------------------------------------------------------------ //============================================================ // Event Handling/Dispatching (in chart's scope) //------------------------------------------------------------ legend.dispatch.on('legendClick', function(d,i) { d.disabled = !d.disabled; if (!data.filter(function(d) { return !d.disabled }).length) { data.map(function(d) { d.disabled = false; wrap.selectAll('.nv-series').classed('disabled', false); return d; }); } state.disabled = data.map(function(d) { return !!d.disabled }); dispatch.stateChange(state); chart.update(); }); legend.dispatch.on('legendDblclick', function(d) { //Double clicking should always enable current series, and disabled all others. data.forEach(function(d) { d.disabled = true; }); d.disabled = false; state.disabled = data.map(function(d) { return !!d.disabled }); dispatch.stateChange(state); chart.update(); }); dispatch.on('tooltipShow', function(e) { if (tooltips) showTooltip(e, that.parentNode); }); // Update chart from a state object passed to event handler dispatch.on('changeState', function(e) { if (typeof e.disabled !== 'undefined') { data.forEach(function(series,i) { series.disabled = e.disabled[i]; }); state.disabled = e.disabled; } chart.update(); }); //============================================================ }); return chart; } //============================================================ // Event Handling/Dispatching (out of chart's scope) //------------------------------------------------------------ lines.dispatch.on('elementMouseover.tooltip', function(e) { e.pos = [e.pos[0] + margin.left, e.pos[1] + margin.top]; dispatch.tooltipShow(e); }); lines.dispatch.on('elementMouseout.tooltip', function(e) { dispatch.tooltipHide(e); }); bars.dispatch.on('elementMouseover.tooltip', function(e) { e.pos = [e.pos[0] + margin.left, e.pos[1] + margin.top]; dispatch.tooltipShow(e); }); bars.dispatch.on('elementMouseout.tooltip', function(e) { dispatch.tooltipHide(e); }); dispatch.on('tooltipHide', function() { if (tooltips) nv.tooltip.cleanup(); }); //============================================================ //============================================================ // Expose Public Variables //------------------------------------------------------------ // expose chart's sub-components chart.dispatch = dispatch; chart.legend = legend; chart.lines = lines; chart.bars = bars; chart.xAxis = xAxis; chart.y1Axis = y1Axis; chart.y2Axis = y2Axis; d3.rebind(chart, lines, 'defined', 'size', 'clipVoronoi', 'interpolate'); //TODO: consider rebinding x, y and some other stuff, and simply do soemthign lile bars.x(lines.x()), etc. //d3.rebind(chart, lines, 'x', 'y', 'size', 'xDomain', 'yDomain', 'forceX', 'forceY', 'interactive', 'clipEdge', 'clipVoronoi', 'id'); chart.x = function(_) { if (!arguments.length) return getX; getX = _; lines.x(_); bars.x(_); return chart; }; chart.y = function(_) { if (!arguments.length) return getY; getY = _; lines.y(_); bars.y(_); return chart; }; chart.margin = function(_) { if (!arguments.length) return margin; margin.top = typeof _.top != 'undefined' ? _.top : margin.top; margin.right = typeof _.right != 'undefined' ? _.right : margin.right; margin.bottom = typeof _.bottom != 'undefined' ? _.bottom : margin.bottom; margin.left = typeof _.left != 'undefined' ? _.left : margin.left; return chart; }; chart.width = function(_) { if (!arguments.length) return width; width = _; return chart; }; chart.height = function(_) { if (!arguments.length) return height; height = _; return chart; }; chart.color = function(_) { if (!arguments.length) return color; color = nv.utils.getColor(_); legend.color(color); return chart; }; chart.showLegend = function(_) { if (!arguments.length) return showLegend; showLegend = _; return chart; }; chart.tooltips = function(_) { if (!arguments.length) return tooltips; tooltips = _; return chart; }; chart.tooltipContent = function(_) { if (!arguments.length) return tooltip; tooltip = _; return chart; }; chart.state = function(_) { if (!arguments.length) return state; state = _; return chart; }; chart.defaultState = function(_) { if (!arguments.length) return defaultState; defaultState = _; return chart; }; chart.noData = function(_) { if (!arguments.length) return noData; noData = _; return chart; }; //============================================================ return chart; } nv.models.lineWithFocusChart = function() { //============================================================ // Public Variables with Default Settings //------------------------------------------------------------ var lines = nv.models.line() , lines2 = nv.models.line() , xAxis = nv.models.axis() , yAxis = nv.models.axis() , x2Axis = nv.models.axis() , y2Axis = nv.models.axis() , legend = nv.models.legend() , brush = d3.svg.brush() ; var margin = {top: 30, right: 30, bottom: 30, left: 60} , margin2 = {top: 0, right: 30, bottom: 20, left: 60} , color = nv.utils.defaultColor() , width = null , height = null , height2 = 100 , x , y , x2 , y2 , showLegend = true , brushExtent = null , tooltips = true , tooltip = function(key, x, y, e, graph) { return '

    ' + key + '

    ' + '

    ' + y + ' at ' + x + '

    ' } , noData = "No Data Available." , dispatch = d3.dispatch('tooltipShow', 'tooltipHide', 'brush') ; lines .clipEdge(true) ; lines2 .interactive(false) ; xAxis .orient('bottom') .tickPadding(5) ; yAxis .orient('left') ; x2Axis .orient('bottom') .tickPadding(5) ; y2Axis .orient('left') ; //============================================================ //============================================================ // Private Variables //------------------------------------------------------------ var showTooltip = function(e, offsetElement) { var left = e.pos[0] + ( offsetElement.offsetLeft || 0 ), top = e.pos[1] + ( offsetElement.offsetTop || 0), x = xAxis.tickFormat()(lines.x()(e.point, e.pointIndex)), y = yAxis.tickFormat()(lines.y()(e.point, e.pointIndex)), content = tooltip(e.series.key, x, y, e, chart); nv.tooltip.show([left, top], content, null, null, offsetElement); }; //============================================================ function chart(selection) { selection.each(function(data) { var container = d3.select(this), that = this; var availableWidth = (width || parseInt(container.style('width')) || 960) - margin.left - margin.right, availableHeight1 = (height || parseInt(container.style('height')) || 400) - margin.top - margin.bottom - height2, availableHeight2 = height2 - margin2.top - margin2.bottom; chart.update = function() { container.transition().call(chart) }; chart.container = this; //------------------------------------------------------------ // Display No Data message if there's nothing to show. if (!data || !data.length || !data.filter(function(d) { return d.values.length }).length) { var noDataText = container.selectAll('.nv-noData').data([noData]); noDataText.enter().append('text') .attr('class', 'nvd3 nv-noData') .attr('dy', '-.7em') .style('text-anchor', 'middle'); noDataText .attr('x', margin.left + availableWidth / 2) .attr('y', margin.top + availableHeight1 / 2) .text(function(d) { return d }); return chart; } else { container.selectAll('.nv-noData').remove(); } //------------------------------------------------------------ //------------------------------------------------------------ // Setup Scales x = lines.xScale(); y = lines.yScale(); x2 = lines2.xScale(); y2 = lines2.yScale(); //------------------------------------------------------------ //------------------------------------------------------------ // Setup containers and skeleton of chart var wrap = container.selectAll('g.nv-wrap.nv-lineWithFocusChart').data([data]); var gEnter = wrap.enter().append('g').attr('class', 'nvd3 nv-wrap nv-lineWithFocusChart').append('g'); var g = wrap.select('g'); gEnter.append('g').attr('class', 'nv-legendWrap'); var focusEnter = gEnter.append('g').attr('class', 'nv-focus'); focusEnter.append('g').attr('class', 'nv-x nv-axis'); focusEnter.append('g').attr('class', 'nv-y nv-axis'); focusEnter.append('g').attr('class', 'nv-linesWrap'); var contextEnter = gEnter.append('g').attr('class', 'nv-context'); contextEnter.append('g').attr('class', 'nv-x nv-axis'); contextEnter.append('g').attr('class', 'nv-y nv-axis'); contextEnter.append('g').attr('class', 'nv-linesWrap'); contextEnter.append('g').attr('class', 'nv-brushBackground'); contextEnter.append('g').attr('class', 'nv-x nv-brush'); //------------------------------------------------------------ //------------------------------------------------------------ // Legend if (showLegend) { legend.width(availableWidth); g.select('.nv-legendWrap') .datum(data) .call(legend); if ( margin.top != legend.height()) { margin.top = legend.height() + legend.legendBelowPadding();// added legend.legendBelowPadding to allow for more spacing availableHeight1 = (height || parseInt(container.style('height')) || 400) - margin.top - margin.bottom - height2; } g.select('.nv-legendWrap') .attr('transform', 'translate(0,' + (-margin.top) +')') } //------------------------------------------------------------ wrap.attr('transform', 'translate(' + margin.left + ',' + margin.top + ')'); //------------------------------------------------------------ // Main Chart Component(s) lines .width(availableWidth) .height(availableHeight1) .color( data .map(function(d,i) { return d.color || color(d, i); }) .filter(function(d,i) { return !data[i].disabled; }) ); lines2 .defined(lines.defined()) .width(availableWidth) .height(availableHeight2) .color( data .map(function(d,i) { return d.color || color(d, i); }) .filter(function(d,i) { return !data[i].disabled; }) ); g.select('.nv-context') .attr('transform', 'translate(0,' + ( availableHeight1 + margin.bottom + margin2.top) + ')') var contextLinesWrap = g.select('.nv-context .nv-linesWrap') .datum(data.filter(function(d) { return !d.disabled })) d3.transition(contextLinesWrap).call(lines2); //------------------------------------------------------------ /* var focusLinesWrap = g.select('.nv-focus .nv-linesWrap') .datum(data.filter(function(d) { return !d.disabled })) d3.transition(focusLinesWrap).call(lines); */ //------------------------------------------------------------ // Setup Main (Focus) Axes xAxis .scale(x) .ticks( availableWidth / 100 ) .tickSize(-availableHeight1, 0); yAxis .scale(y) .ticks( availableHeight1 / 36 ) .tickSize( -availableWidth, 0); g.select('.nv-focus .nv-x.nv-axis') .attr('transform', 'translate(0,' + availableHeight1 + ')'); //------------------------------------------------------------ //------------------------------------------------------------ // Setup Brush brush .x(x2) .on('brush', onBrush); if (brushExtent) brush.extent(brushExtent); var brushBG = g.select('.nv-brushBackground').selectAll('g') .data([brushExtent || brush.extent()]) var brushBGenter = brushBG.enter() .append('g'); brushBGenter.append('rect') .attr('class', 'left') .attr('x', 0) .attr('y', 0) .attr('height', availableHeight2); brushBGenter.append('rect') .attr('class', 'right') .attr('x', 0) .attr('y', 0) .attr('height', availableHeight2); gBrush = g.select('.nv-x.nv-brush') .call(brush); gBrush.selectAll('rect') //.attr('y', -5) .attr('height', availableHeight2); gBrush.selectAll('.resize').append('path').attr('d', resizePath); onBrush(); //------------------------------------------------------------ //------------------------------------------------------------ // Setup Secondary (Context) Axes x2Axis .scale(x2) .ticks( availableWidth / 100 ) .tickSize(-availableHeight2, 0); g.select('.nv-context .nv-x.nv-axis') .attr('transform', 'translate(0,' + y2.range()[0] + ')'); d3.transition(g.select('.nv-context .nv-x.nv-axis')) .call(x2Axis); y2Axis .scale(y2) .ticks( availableHeight2 / 36 ) .tickSize( -availableWidth, 0); d3.transition(g.select('.nv-context .nv-y.nv-axis')) .call(y2Axis); g.select('.nv-context .nv-x.nv-axis') .attr('transform', 'translate(0,' + y2.range()[0] + ')'); //------------------------------------------------------------ //============================================================ // Event Handling/Dispatching (in chart's scope) //------------------------------------------------------------ legend.dispatch.on('legendClick', function(d,i) { d.disabled = !d.disabled; if (!data.filter(function(d) { return !d.disabled }).length) { data.map(function(d) { d.disabled = false; wrap.selectAll('.nv-series').classed('disabled', false); return d; }); } container.transition().call(chart); }); dispatch.on('tooltipShow', function(e) { if (tooltips) showTooltip(e, that.parentNode); }); //============================================================ //============================================================ // Functions //------------------------------------------------------------ // Taken from crossfilter (http://square.github.com/crossfilter/) function resizePath(d) { var e = +(d == 'e'), x = e ? 1 : -1, y = availableHeight2 / 3; return 'M' + (.5 * x) + ',' + y + 'A6,6 0 0 ' + e + ' ' + (6.5 * x) + ',' + (y + 6) + 'V' + (2 * y - 6) + 'A6,6 0 0 ' + e + ' ' + (.5 * x) + ',' + (2 * y) + 'Z' + 'M' + (2.5 * x) + ',' + (y + 8) + 'V' + (2 * y - 8) + 'M' + (4.5 * x) + ',' + (y + 8) + 'V' + (2 * y - 8); } function updateBrushBG() { if (!brush.empty()) brush.extent(brushExtent); brushBG .data([brush.empty() ? x2.domain() : brushExtent]) .each(function(d,i) { var leftWidth = x2(d[0]) - x.range()[0], rightWidth = x.range()[1] - x2(d[1]); d3.select(this).select('.left') .attr('width', leftWidth < 0 ? 0 : leftWidth); d3.select(this).select('.right') .attr('x', x2(d[1])) .attr('width', rightWidth < 0 ? 0 : rightWidth); }); } function onBrush() { brushExtent = brush.empty() ? null : brush.extent(); extent = brush.empty() ? x2.domain() : brush.extent(); dispatch.brush({extent: extent, brush: brush}); updateBrushBG(); // Update Main (Focus) var focusLinesWrap = g.select('.nv-focus .nv-linesWrap') .datum( data .filter(function(d) { return !d.disabled }) .map(function(d,i) { return { key: d.key, values: d.values.filter(function(d,i) { return lines.x()(d,i) >= extent[0] && lines.x()(d,i) <= extent[1]; }) } }) ); d3.transition(focusLinesWrap).call(lines); // Update Main (Focus) Axes d3.transition(g.select('.nv-focus .nv-x.nv-axis')) .call(xAxis); d3.transition(g.select('.nv-focus .nv-y.nv-axis')) .call(yAxis); } //============================================================ }); return chart; } //============================================================ // Event Handling/Dispatching (out of chart's scope) //------------------------------------------------------------ lines.dispatch.on('elementMouseover.tooltip', function(e) { e.pos = [e.pos[0] + margin.left, e.pos[1] + margin.top]; dispatch.tooltipShow(e); }); lines.dispatch.on('elementMouseout.tooltip', function(e) { dispatch.tooltipHide(e); }); dispatch.on('tooltipHide', function() { if (tooltips) nv.tooltip.cleanup(); }); //============================================================ //============================================================ // Expose Public Variables //------------------------------------------------------------ // expose chart's sub-components chart.dispatch = dispatch; chart.legend = legend; chart.lines = lines; chart.lines2 = lines2; chart.xAxis = xAxis; chart.yAxis = yAxis; chart.x2Axis = x2Axis; chart.y2Axis = y2Axis; d3.rebind(chart, lines, 'defined', 'isArea', 'size', 'xDomain', 'yDomain', 'forceX', 'forceY', 'interactive', 'clipEdge', 'clipVoronoi', 'id'); chart.x = function(_) { if (!arguments.length) return lines.x; lines.x(_); lines2.x(_); return chart; }; chart.y = function(_) { if (!arguments.length) return lines.y; lines.y(_); lines2.y(_); return chart; }; chart.margin = function(_) { if (!arguments.length) return margin; margin.top = typeof _.top != 'undefined' ? _.top : margin.top; margin.right = typeof _.right != 'undefined' ? _.right : margin.right; margin.bottom = typeof _.bottom != 'undefined' ? _.bottom : margin.bottom; margin.left = typeof _.left != 'undefined' ? _.left : margin.left; return chart; }; chart.margin2 = function(_) { if (!arguments.length) return margin2; margin2 = _; return chart; }; chart.width = function(_) { if (!arguments.length) return width; width = _; return chart; }; chart.height = function(_) { if (!arguments.length) return height; height = _; return chart; }; chart.height2 = function(_) { if (!arguments.length) return height2; height2 = _; return chart; }; chart.color = function(_) { if (!arguments.length) return color; color =nv.utils.getColor(_); legend.color(color); return chart; }; chart.showLegend = function(_) { if (!arguments.length) return showLegend; showLegend = _; return chart; }; chart.tooltips = function(_) { if (!arguments.length) return tooltips; tooltips = _; return chart; }; chart.tooltipContent = function(_) { if (!arguments.length) return tooltip; tooltip = _; return chart; }; chart.interpolate = function(_) { if (!arguments.length) return lines.interpolate(); lines.interpolate(_); lines2.interpolate(_); return chart; }; chart.noData = function(_) { if (!arguments.length) return noData; noData = _; return chart; }; // Chart has multiple similar Axes, to prevent code duplication, probably need to link all axis functions manually like below chart.xTickFormat = function(_) { if (!arguments.length) return xAxis.tickFormat(); xAxis.tickFormat(_); x2Axis.tickFormat(_); return chart; }; chart.yTickFormat = function(_) { if (!arguments.length) return yAxis.tickFormat(); yAxis.tickFormat(_); y2Axis.tickFormat(_); return chart; }; //============================================================ return chart; } nv.models.linePlusBarWithFocusChart = function() { //============================================================ // Public Variables with Default Settings //------------------------------------------------------------ var lines = nv.models.line() , lines2 = nv.models.line() , bars = nv.models.historicalBar() , bars2 = nv.models.historicalBar() , xAxis = nv.models.axis() , x2Axis = nv.models.axis() , y1Axis = nv.models.axis() , y2Axis = nv.models.axis() , y3Axis = nv.models.axis() , y4Axis = nv.models.axis() , legend = nv.models.legend() , brush = d3.svg.brush() ; var margin = {top: 30, right: 30, bottom: 30, left: 60} , margin2 = {top: 0, right: 30, bottom: 20, left: 60} , width = null , height = null , height2 = 100 , getX = function(d) { return d.x } , getY = function(d) { return d.y } , color = nv.utils.defaultColor() , showLegend = true , extent , brushExtent = null , tooltips = true , tooltip = function(key, x, y, e, graph) { return '

    ' + key + '

    ' + '

    ' + y + ' at ' + x + '

    '; } , x , x2 , y1 , y2 , y3 , y4 , noData = "No Data Available." , dispatch = d3.dispatch('tooltipShow', 'tooltipHide', 'brush') ; lines .clipEdge(true) ; lines2 .interactive(false) ; xAxis .orient('bottom') .tickPadding(5) ; y1Axis .orient('left') ; y2Axis .orient('right') ; x2Axis .orient('bottom') .tickPadding(5) ; y3Axis .orient('left') ; y4Axis .orient('right') ; //============================================================ //============================================================ // Private Variables //------------------------------------------------------------ var showTooltip = function(e, offsetElement) { if (extent) { e.pointIndex += Math.ceil(extent[0]); } var left = e.pos[0] + ( offsetElement.offsetLeft || 0 ), top = e.pos[1] + ( offsetElement.offsetTop || 0), x = xAxis.tickFormat()(lines.x()(e.point, e.pointIndex)), y = (e.series.bar ? y1Axis : y2Axis).tickFormat()(lines.y()(e.point, e.pointIndex)), content = tooltip(e.series.key, x, y, e, chart); nv.tooltip.show([left, top], content, e.value < 0 ? 'n' : 's', null, offsetElement); }; //------------------------------------------------------------ function chart(selection) { selection.each(function(data) { var container = d3.select(this), that = this; var availableWidth = (width || parseInt(container.style('width')) || 960) - margin.left - margin.right, availableHeight1 = (height || parseInt(container.style('height')) || 400) - margin.top - margin.bottom - height2, availableHeight2 = height2 - margin2.top - margin2.bottom; chart.update = function() { container.transition().call(chart); }; chart.container = this; //------------------------------------------------------------ // Display No Data message if there's nothing to show. if (!data || !data.length || !data.filter(function(d) { return d.values.length }).length) { var noDataText = container.selectAll('.nv-noData').data([noData]); noDataText.enter().append('text') .attr('class', 'nvd3 nv-noData') .attr('dy', '-.7em') .style('text-anchor', 'middle'); noDataText .attr('x', margin.left + availableWidth / 2) .attr('y', margin.top + availableHeight1 / 2) .text(function(d) { return d }); return chart; } else { container.selectAll('.nv-noData').remove(); } //------------------------------------------------------------ //------------------------------------------------------------ // Setup Scales var dataBars = data.filter(function(d) { return !d.disabled && d.bar }); var dataLines = data.filter(function(d) { return !d.bar }); // removed the !d.disabled clause here to fix Issue #240 x = bars.xScale(); x2 = x2Axis.scale(); y1 = bars.yScale(); y2 = lines.yScale(); y3 = bars2.yScale(); y4 = lines2.yScale(); var series1 = data .filter(function(d) { return !d.disabled && d.bar }) .map(function(d) { return d.values.map(function(d,i) { return { x: getX(d,i), y: getY(d,i) } }) }); var series2 = data .filter(function(d) { return !d.disabled && !d.bar }) .map(function(d) { return d.values.map(function(d,i) { return { x: getX(d,i), y: getY(d,i) } }) }); x .range([0, availableWidth]); x2 .domain(d3.extent(d3.merge(series1.concat(series2)), function(d) { return d.x } )) .range([0, availableWidth]); //------------------------------------------------------------ //------------------------------------------------------------ // Setup containers and skeleton of chart var wrap = container.selectAll('g.nv-wrap.nv-linePlusBar').data([data]); var gEnter = wrap.enter().append('g').attr('class', 'nvd3 nv-wrap nv-linePlusBar').append('g'); var g = wrap.select('g'); gEnter.append('g').attr('class', 'nv-legendWrap'); var focusEnter = gEnter.append('g').attr('class', 'nv-focus'); focusEnter.append('g').attr('class', 'nv-x nv-axis'); focusEnter.append('g').attr('class', 'nv-y1 nv-axis'); focusEnter.append('g').attr('class', 'nv-y2 nv-axis'); focusEnter.append('g').attr('class', 'nv-barsWrap'); focusEnter.append('g').attr('class', 'nv-linesWrap'); var contextEnter = gEnter.append('g').attr('class', 'nv-context'); contextEnter.append('g').attr('class', 'nv-x nv-axis'); contextEnter.append('g').attr('class', 'nv-y1 nv-axis'); contextEnter.append('g').attr('class', 'nv-y2 nv-axis'); contextEnter.append('g').attr('class', 'nv-barsWrap'); contextEnter.append('g').attr('class', 'nv-linesWrap'); contextEnter.append('g').attr('class', 'nv-brushBackground'); contextEnter.append('g').attr('class', 'nv-x nv-brush'); //------------------------------------------------------------ //------------------------------------------------------------ // Legend if (showLegend) { legend.width( availableWidth / 2 ); g.select('.nv-legendWrap') .datum(data.map(function(series) { series.originalKey = series.originalKey === undefined ? series.key : series.originalKey; series.key = series.originalKey + (series.bar ? ' (left axis)' : ' (right axis)'); return series; })) .call(legend); if ( margin.top != legend.height()) { margin.top = legend.height() + legend.legendBelowPadding();// added legend.legendBelowPadding to allow for more spacing availableHeight1 = (height || parseInt(container.style('height')) || 400) - margin.top - margin.bottom - height2; } g.select('.nv-legendWrap') .attr('transform', 'translate(' + ( availableWidth / 2 ) + ',' + (-margin.top) +')'); } //------------------------------------------------------------ wrap.attr('transform', 'translate(' + margin.left + ',' + margin.top + ')'); //------------------------------------------------------------ // Context Components bars2 .width(availableWidth) .height(availableHeight2) .color(data.map(function(d,i) { return d.color || color(d, i); }).filter(function(d,i) { return !data[i].disabled && data[i].bar })); lines2 .width(availableWidth) .height(availableHeight2) .color(data.map(function(d,i) { return d.color || color(d, i); }).filter(function(d,i) { return !data[i].disabled && !data[i].bar })); var bars2Wrap = g.select('.nv-context .nv-barsWrap') .datum(dataBars.length ? dataBars : [{values:[]}]); var lines2Wrap = g.select('.nv-context .nv-linesWrap') .datum(!dataLines[0].disabled ? dataLines : [{values:[]}]); g.select('.nv-context') .attr('transform', 'translate(0,' + ( availableHeight1 + margin.bottom + margin2.top) + ')') d3.transition(bars2Wrap).call(bars2); d3.transition(lines2Wrap).call(lines2); //------------------------------------------------------------ //------------------------------------------------------------ // Setup Brush brush .x(x2) .on('brush', onBrush); if (brushExtent) brush.extent(brushExtent); var brushBG = g.select('.nv-brushBackground').selectAll('g') .data([brushExtent || brush.extent()]) var brushBGenter = brushBG.enter() .append('g'); brushBGenter.append('rect') .attr('class', 'left') .attr('x', 0) .attr('y', 0) .attr('height', availableHeight2); brushBGenter.append('rect') .attr('class', 'right') .attr('x', 0) .attr('y', 0) .attr('height', availableHeight2); var gBrush = g.select('.nv-x.nv-brush') .call(brush); gBrush.selectAll('rect') //.attr('y', -5) .attr('height', availableHeight2); gBrush.selectAll('.resize').append('path').attr('d', resizePath); //------------------------------------------------------------ //------------------------------------------------------------ // Setup Secondary (Context) Axes x2Axis .ticks( availableWidth / 100 ) .tickSize(-availableHeight2, 0); g.select('.nv-context .nv-x.nv-axis') .attr('transform', 'translate(0,' + y3.range()[0] + ')'); d3.transition(g.select('.nv-context .nv-x.nv-axis')) .call(x2Axis); y3Axis .scale(y3) .ticks( availableHeight2 / 36 ) .tickSize( -availableWidth, 0); g.select('.nv-context .nv-y1.nv-axis') .style('opacity', dataBars.length ? 1 : 0) .attr('transform', 'translate(0,' + x2.range()[0] + ')'); d3.transition(g.select('.nv-context .nv-y1.nv-axis')) .call(y3Axis); y4Axis .scale(y4) .ticks( availableHeight2 / 36 ) .tickSize(dataBars.length ? 0 : -availableWidth, 0); // Show the y2 rules only if y1 has none g.select('.nv-context .nv-y2.nv-axis') .style('opacity', dataLines.length ? 1 : 0) .attr('transform', 'translate(' + x2.range()[1] + ',0)'); d3.transition(g.select('.nv-context .nv-y2.nv-axis')) .call(y4Axis); //------------------------------------------------------------ //============================================================ // Event Handling/Dispatching (in chart's scope) //------------------------------------------------------------ legend.dispatch.on('legendClick', function(d,i) { d.disabled = !d.disabled; if (!data.filter(function(d) { return !d.disabled }).length) { data.map(function(d) { d.disabled = false; wrap.selectAll('.nv-series').classed('disabled', false); return d; }); } chart.update(); }); dispatch.on('tooltipShow', function(e) { if (tooltips) showTooltip(e, that.parentNode); }); //============================================================ //============================================================ // Functions //------------------------------------------------------------ // Taken from crossfilter (http://square.github.com/crossfilter/) function resizePath(d) { var e = +(d == 'e'), x = e ? 1 : -1, y = availableHeight2 / 3; return 'M' + (.5 * x) + ',' + y + 'A6,6 0 0 ' + e + ' ' + (6.5 * x) + ',' + (y + 6) + 'V' + (2 * y - 6) + 'A6,6 0 0 ' + e + ' ' + (.5 * x) + ',' + (2 * y) + 'Z' + 'M' + (2.5 * x) + ',' + (y + 8) + 'V' + (2 * y - 8) + 'M' + (4.5 * x) + ',' + (y + 8) + 'V' + (2 * y - 8); } function updateBrushBG() { if (!brush.empty()) brush.extent(brushExtent); brushBG .data([brush.empty() ? x2.domain() : brushExtent]) .each(function(d,i) { var leftWidth = x2(d[0]) - x2.range()[0], rightWidth = x2.range()[1] - x2(d[1]); d3.select(this).select('.left') .attr('width', leftWidth < 0 ? 0 : leftWidth); d3.select(this).select('.right') .attr('x', x2(d[1])) .attr('width', rightWidth < 0 ? 0 : rightWidth); }); } function onBrush() { brushExtent = brush.empty() ? null : brush.extent(); extent = brush.empty() ? x2.domain() : brush.extent(); dispatch.brush({extent: extent, brush: brush}); updateBrushBG(); //------------------------------------------------------------ // Prepare Main (Focus) Bars and Lines bars .width(availableWidth) .height(availableHeight1) .color(data.map(function(d,i) { return d.color || color(d, i); }).filter(function(d,i) { return !data[i].disabled && data[i].bar })); lines .width(availableWidth) .height(availableHeight1) .color(data.map(function(d,i) { return d.color || color(d, i); }).filter(function(d,i) { return !data[i].disabled && !data[i].bar })); var focusBarsWrap = g.select('.nv-focus .nv-barsWrap') .datum(!dataBars.length ? [{values:[]}] : dataBars .map(function(d,i) { return { key: d.key, values: d.values.filter(function(d,i) { return bars.x()(d,i) >= extent[0] && bars.x()(d,i) <= extent[1]; }) } }) ); var focusLinesWrap = g.select('.nv-focus .nv-linesWrap') .datum(dataLines[0].disabled ? [{values:[]}] : dataLines .map(function(d,i) { return { key: d.key, values: d.values.filter(function(d,i) { return lines.x()(d,i) >= extent[0] && lines.x()(d,i) <= extent[1]; }) } }) ); //------------------------------------------------------------ //------------------------------------------------------------ // Update Main (Focus) X Axis if (dataBars.length) { x = bars.xScale(); } else { x = lines.xScale(); } xAxis .scale(x) .ticks( availableWidth / 100 ) .tickSize(-availableHeight1, 0); xAxis.domain([Math.ceil(extent[0]), Math.floor(extent[1])]); d3.transition(g.select('.nv-x.nv-axis')) .call(xAxis); //------------------------------------------------------------ //------------------------------------------------------------ // Update Main (Focus) Bars and Lines d3.transition(focusBarsWrap).call(bars); d3.transition(focusLinesWrap).call(lines); //------------------------------------------------------------ //------------------------------------------------------------ // Setup and Update Main (Focus) Y Axes g.select('.nv-focus .nv-x.nv-axis') .attr('transform', 'translate(0,' + y1.range()[0] + ')'); y1Axis .scale(y1) .ticks( availableHeight1 / 36 ) .tickSize(-availableWidth, 0); g.select('.nv-focus .nv-y1.nv-axis') .style('opacity', dataBars.length ? 1 : 0); y2Axis .scale(y2) .ticks( availableHeight1 / 36 ) .tickSize(dataBars.length ? 0 : -availableWidth, 0); // Show the y2 rules only if y1 has none g.select('.nv-focus .nv-y2.nv-axis') .style('opacity', dataLines.length ? 1 : 0) .attr('transform', 'translate(' + x.range()[1] + ',0)'); d3.transition(g.select('.nv-focus .nv-y1.nv-axis')) .call(y1Axis); d3.transition(g.select('.nv-focus .nv-y2.nv-axis')) .call(y2Axis); } //============================================================ onBrush(); }); return chart; } //============================================================ // Event Handling/Dispatching (out of chart's scope) //------------------------------------------------------------ lines.dispatch.on('elementMouseover.tooltip', function(e) { e.pos = [e.pos[0] + margin.left, e.pos[1] + margin.top]; dispatch.tooltipShow(e); }); lines.dispatch.on('elementMouseout.tooltip', function(e) { dispatch.tooltipHide(e); }); bars.dispatch.on('elementMouseover.tooltip', function(e) { e.pos = [e.pos[0] + margin.left, e.pos[1] + margin.top]; dispatch.tooltipShow(e); }); bars.dispatch.on('elementMouseout.tooltip', function(e) { dispatch.tooltipHide(e); }); dispatch.on('tooltipHide', function() { if (tooltips) nv.tooltip.cleanup(); }); //============================================================ //============================================================ // Expose Public Variables //------------------------------------------------------------ // expose chart's sub-components chart.dispatch = dispatch; chart.legend = legend; chart.lines = lines; chart.lines2 = lines2; chart.bars = bars; chart.bars2 = bars2; chart.xAxis = xAxis; chart.x2Axis = x2Axis; chart.y1Axis = y1Axis; chart.y2Axis = y2Axis; chart.y3Axis = y3Axis; chart.y4Axis = y4Axis; d3.rebind(chart, lines, 'defined', 'size', 'clipVoronoi', 'interpolate'); //TODO: consider rebinding x, y and some other stuff, and simply do soemthign lile bars.x(lines.x()), etc. //d3.rebind(chart, lines, 'x', 'y', 'size', 'xDomain', 'yDomain', 'forceX', 'forceY', 'interactive', 'clipEdge', 'clipVoronoi', 'id'); chart.x = function(_) { if (!arguments.length) return getX; getX = _; lines.x(_); bars.x(_); return chart; }; chart.y = function(_) { if (!arguments.length) return getY; getY = _; lines.y(_); bars.y(_); return chart; }; chart.margin = function(_) { if (!arguments.length) return margin; margin.top = typeof _.top != 'undefined' ? _.top : margin.top; margin.right = typeof _.right != 'undefined' ? _.right : margin.right; margin.bottom = typeof _.bottom != 'undefined' ? _.bottom : margin.bottom; margin.left = typeof _.left != 'undefined' ? _.left : margin.left; return chart; }; chart.width = function(_) { if (!arguments.length) return width; width = _; return chart; }; chart.height = function(_) { if (!arguments.length) return height; height = _; return chart; }; chart.color = function(_) { if (!arguments.length) return color; color = nv.utils.getColor(_); legend.color(color); return chart; }; chart.showLegend = function(_) { if (!arguments.length) return showLegend; showLegend = _; return chart; }; chart.tooltips = function(_) { if (!arguments.length) return tooltips; tooltips = _; return chart; }; chart.tooltipContent = function(_) { if (!arguments.length) return tooltip; tooltip = _; return chart; }; chart.noData = function(_) { if (!arguments.length) return noData; noData = _; return chart; }; chart.brushExtent = function(_) { if (!arguments.length) return brushExtent; brushExtent = _; return chart; }; //============================================================ return chart; } nv.models.multiBar = function() { //============================================================ // Public Variables with Default Settings //------------------------------------------------------------ var margin = {top: 0, right: 0, bottom: 0, left: 0} , width = 960 , height = 500 , x = d3.scale.ordinal() , y = d3.scale.linear() , id = Math.floor(Math.random() * 10000) //Create semi-unique ID in case user doesn't select one , getX = function(d) { return d.x } , getY = function(d) { return d.y } , forceY = [0] // 0 is forced by default.. this makes sense for the majority of bar graphs... user can always do chart.forceY([]) to remove , clipEdge = true , stacked = false , color = nv.utils.defaultColor() , hideable = false , barColor = null // adding the ability to set the color for each rather than the whole group , disabled // used in conjunction with barColor to communicate from multiBarHorizontalChart what series are disabled , delay = 1200 , drawTime = 500 , xDomain , yDomain , dispatch = d3.dispatch('chartClick', 'elementClick', 'elementDblClick', 'elementMouseover', 'elementMouseout') ; //============================================================ //============================================================ // Private Variables //------------------------------------------------------------ var x0, y0 //used to store previous scales ; //============================================================ function chart(selection) { selection.each(function(data) { var availableWidth = width - margin.left - margin.right, availableHeight = height - margin.top - margin.bottom, container = d3.select(this); if(hideable && data.length) hideable = [{ values: data[0].values.map(function(d) { return { x: d.x, y: 0, series: d.series, size: 0.01 };} )}]; if (stacked) data = d3.layout.stack() .offset('zero') .values(function(d){ return d.values }) .y(getY) (!data.length && hideable ? hideable : data); //add series index to each data point for reference data = data.map(function(series, i) { series.values = series.values.map(function(point) { point.series = i; return point; }); return series; }); //------------------------------------------------------------ // HACK for negative value stacking if (stacked) data[0].values.map(function(d,i) { var posBase = 0, negBase = 0; data.map(function(d) { var f = d.values[i] f.size = Math.abs(f.y); if (f.y<0) { f.y1 = negBase; negBase = negBase - f.size; } else { f.y1 = f.size + posBase; posBase = posBase + f.size; } }); }); //------------------------------------------------------------ // Setup Scales // remap and flatten the data for use in calculating the scales' domains var seriesData = (xDomain && yDomain) ? [] : // if we know xDomain and yDomain, no need to calculate data.map(function(d) { return d.values.map(function(d,i) { return { x: getX(d,i), y: getY(d,i), y0: d.y0, y1: d.y1 } }) }); x .domain(d3.merge(seriesData).map(function(d) { return d.x })) .rangeBands([0, availableWidth], .1); //y .domain(yDomain || d3.extent(d3.merge(seriesData).map(function(d) { return d.y + (stacked ? d.y1 : 0) }).concat(forceY))) y .domain(yDomain || d3.extent(d3.merge(seriesData).map(function(d) { return stacked ? (d.y > 0 ? d.y1 : d.y1 + d.y ) : d.y }).concat(forceY))) .range([availableHeight, 0]); // If scale's domain don't have a range, slightly adjust to make one... so a chart can show a single data point if (x.domain()[0] === x.domain()[1] || y.domain()[0] === y.domain()[1]) singlePoint = true; if (x.domain()[0] === x.domain()[1]) x.domain()[0] ? x.domain([x.domain()[0] - x.domain()[0] * 0.01, x.domain()[1] + x.domain()[1] * 0.01]) : x.domain([-1,1]); if (y.domain()[0] === y.domain()[1]) y.domain()[0] ? y.domain([y.domain()[0] + y.domain()[0] * 0.01, y.domain()[1] - y.domain()[1] * 0.01]) : y.domain([-1,1]); x0 = x0 || x; y0 = y0 || y; //------------------------------------------------------------ //------------------------------------------------------------ // Setup containers and skeleton of chart var wrap = container.selectAll('g.nv-wrap.nv-multibar').data([data]); var wrapEnter = wrap.enter().append('g').attr('class', 'nvd3 nv-wrap nv-multibar'); var defsEnter = wrapEnter.append('defs'); var gEnter = wrapEnter.append('g'); var g = wrap.select('g') gEnter.append('g').attr('class', 'nv-groups'); wrap.attr('transform', 'translate(' + margin.left + ',' + margin.top + ')'); //------------------------------------------------------------ defsEnter.append('clipPath') .attr('id', 'nv-edge-clip-' + id) .append('rect'); wrap.select('#nv-edge-clip-' + id + ' rect') .attr('width', availableWidth) .attr('height', availableHeight); g .attr('clip-path', clipEdge ? 'url(#nv-edge-clip-' + id + ')' : ''); var groups = wrap.select('.nv-groups').selectAll('.nv-group') .data(function(d) { return d }, function(d) { return d.key }); groups.enter().append('g') .style('stroke-opacity', 1e-6) .style('fill-opacity', 1e-6); groups.exit() .selectAll('rect.nv-bar') .transition() .delay(function(d,i) { return i * delay/ data[0].values.length }) .attr('y', function(d) { return stacked ? y0(d.y0) : y0(0) }) .attr('height', 0) .remove(); groups .attr('class', function(d,i) { return 'nv-group nv-series-' + i }) .classed('hover', function(d) { return d.hover }) .style('fill', function(d,i){ return color(d, i) }) .style('stroke', function(d,i){ return color(d, i) }); d3.transition(groups) .style('stroke-opacity', 1) .style('fill-opacity', .75); var bars = groups.selectAll('rect.nv-bar') .data(function(d) { return (hideable && !data.length) ? hideable.values : d.values }); bars.exit().remove(); var barsEnter = bars.enter().append('rect') .attr('class', function(d,i) { return getY(d,i) < 0 ? 'nv-bar negative' : 'nv-bar positive'}) .attr('x', function(d,i,j) { return stacked ? 0 : (j * x.rangeBand() / data.length ) }) .attr('y', function(d) { return y0(stacked ? d.y0 : 0) }) .attr('height', 0) .attr('width', x.rangeBand() / (stacked ? 1 : data.length) ); bars .style('fill', function(d,i,j){ return color(d, j, i); }) .style('stroke', function(d,i,j){ return color(d, j, i); }) .on('mouseover', function(d,i) { //TODO: figure out why j works above, but not here d3.select(this).classed('hover', true); dispatch.elementMouseover({ value: getY(d,i), point: d, series: data[d.series], pos: [x(getX(d,i)) + (x.rangeBand() * (stacked ? data.length / 2 : d.series + .5) / data.length), y(getY(d,i) + (stacked ? d.y0 : 0))], // TODO: Figure out why the value appears to be shifted pointIndex: i, seriesIndex: d.series, e: d3.event }); }) .on('mouseout', function(d,i) { d3.select(this).classed('hover', false); dispatch.elementMouseout({ value: getY(d,i), point: d, series: data[d.series], pointIndex: i, seriesIndex: d.series, e: d3.event }); }) .on('click', function(d,i) { dispatch.elementClick({ value: getY(d,i), point: d, series: data[d.series], pos: [x(getX(d,i)) + (x.rangeBand() * (stacked ? data.length / 2 : d.series + .5) / data.length), y(getY(d,i) + (stacked ? d.y0 : 0))], // TODO: Figure out why the value appears to be shifted pointIndex: i, seriesIndex: d.series, e: d3.event }); d3.event.stopPropagation(); }) .on('dblclick', function(d,i) { dispatch.elementDblClick({ value: getY(d,i), point: d, series: data[d.series], pos: [x(getX(d,i)) + (x.rangeBand() * (stacked ? data.length / 2 : d.series + .5) / data.length), y(getY(d,i) + (stacked ? d.y0 : 0))], // TODO: Figure out why the value appears to be shifted pointIndex: i, seriesIndex: d.series, e: d3.event }); d3.event.stopPropagation(); }); bars .attr('class', function(d,i) { return getY(d,i) < 0 ? 'nv-bar negative' : 'nv-bar positive'}) .attr('transform', function(d,i) { return 'translate(' + x(getX(d,i)) + ',0)'; }) if (barColor) { if (!disabled) disabled = data.map(function() { return true }); bars //.style('fill', barColor) //.style('stroke', barColor) //.style('fill', function(d,i,j) { return d3.rgb(barColor(d,i)).darker(j).toString(); }) //.style('stroke', function(d,i,j) { return d3.rgb(barColor(d,i)).darker(j).toString(); }) .style('fill', function(d,i,j) { return d3.rgb(barColor(d,i)).darker( disabled.map(function(d,i) { return i }).filter(function(d,i){ return !disabled[i] })[j] ).toString(); }) .style('stroke', function(d,i,j) { return d3.rgb(barColor(d,i)).darker( disabled.map(function(d,i) { return i }).filter(function(d,i){ return !disabled[i] })[j] ).toString(); }); } if (stacked) bars.transition() .delay(function(d,i) { return i * delay / data[0].values.length }) .attr('y', function(d,i) { return y((stacked ? d.y1 : 0)); }) .attr('height', function(d,i) { return Math.max(Math.abs(y(d.y + (stacked ? d.y0 : 0)) - y((stacked ? d.y0 : 0))),1); }) .each('end', function() { d3.select(this).transition().duration(drawTime) .attr('x', function(d,i) { return stacked ? 0 : (d.series * x.rangeBand() / data.length ) }) .attr('width', x.rangeBand() / (stacked ? 1 : data.length) ); }) else d3.transition(bars).duration(drawTime) .delay(function(d,i) { return i * delay/ data[0].values.length }) .attr('x', function(d,i) { return d.series * x.rangeBand() / data.length }) .attr('width', x.rangeBand() / data.length) .each('end', function() { d3.select(this).transition().duration(drawTime) .attr('y', function(d,i) { return getY(d,i) < 0 ? y(0) : y(0) - y(getY(d,i)) < 1 ? y(0) - 1 : y(getY(d,i)) || 0; }) .attr('height', function(d,i) { return Math.max(Math.abs(y(getY(d,i)) - y(0)),1) || 0; }); }) //store old scales for use in transitions on update x0 = x.copy(); y0 = y.copy(); }); return chart; } //============================================================ // Expose Public Variables //------------------------------------------------------------ chart.dispatch = dispatch; chart.x = function(_) { if (!arguments.length) return getX; getX = _; return chart; }; chart.y = function(_) { if (!arguments.length) return getY; getY = _; return chart; }; chart.margin = function(_) { if (!arguments.length) return margin; margin.top = typeof _.top != 'undefined' ? _.top : margin.top; margin.right = typeof _.right != 'undefined' ? _.right : margin.right; margin.bottom = typeof _.bottom != 'undefined' ? _.bottom : margin.bottom; margin.left = typeof _.left != 'undefined' ? _.left : margin.left; return chart; }; chart.width = function(_) { if (!arguments.length) return width; width = _; return chart; }; chart.height = function(_) { if (!arguments.length) return height; height = _; return chart; }; chart.xScale = function(_) { if (!arguments.length) return x; x = _; return chart; }; chart.yScale = function(_) { if (!arguments.length) return y; y = _; return chart; }; chart.xDomain = function(_) { if (!arguments.length) return xDomain; xDomain = _; return chart; }; chart.yDomain = function(_) { if (!arguments.length) return yDomain; yDomain = _; return chart; }; chart.forceY = function(_) { if (!arguments.length) return forceY; forceY = _; return chart; }; chart.stacked = function(_) { if (!arguments.length) return stacked; stacked = _; return chart; }; chart.clipEdge = function(_) { if (!arguments.length) return clipEdge; clipEdge = _; return chart; }; chart.color = function(_) { if (!arguments.length) return color; color = nv.utils.getColor(_); return chart; }; chart.barColor = function(_) { if (!arguments.length) return barColor; barColor = nv.utils.getColor(_); return chart; }; chart.disabled = function(_) { if (!arguments.length) return disabled; disabled = _; return chart; }; chart.id = function(_) { if (!arguments.length) return id; id = _; return chart; }; chart.hideable = function(_) { if (!arguments.length) return hideable; hideable = _; return chart; }; chart.delay = function(_) { if (!arguments.length) return delay; delay = _; return chart; }; chart.drawTime = function(_) { if (!arguments.length) return drawTime; drawTime = _; return chart; }; //============================================================ return chart; } nv.models.multiBarChart = function() { //============================================================ // Public Variables with Default Settings //------------------------------------------------------------ var multibar = nv.models.multiBar() , xAxis = nv.models.axis() , yAxis = nv.models.axis() , legend = nv.models.legend() , controls = nv.models.legend() ; var margin = {top: 30, right: 20, bottom: 50, left: 60} , width = null , height = null , color = nv.utils.defaultColor() , showControls = true , showLegend = true , reduceXTicks = true // if false a tick will show for every data point , staggerLabels = false , rotateLabels = 0 , tooltips = true , tooltip = function(key, x, y, e, graph) { return '

    ' + key + '

    ' + '

    ' + y + ' on ' + x + '

    ' } , x //can be accessed via chart.xScale() , y //can be accessed via chart.yScale() , state = { stacked: false } , defaultState = null , noData = "No Data Available." , dispatch = d3.dispatch('tooltipShow', 'tooltipHide', 'stateChange', 'changeState') , controlWidth = function() { return showControls ? 180 : 0 } ; multibar .stacked(false) ; xAxis .orient('bottom') .tickPadding(7) .highlightZero(true) .showMaxMin(false) .tickFormat(function(d) { return d }) ; yAxis .orient('left') .tickFormat(d3.format(',.1f')) ; //============================================================ //============================================================ // Private Variables //------------------------------------------------------------ var showTooltip = function(e, offsetElement) { var left = e.pos[0] + ( offsetElement.offsetLeft || 0 ), top = e.pos[1] + ( offsetElement.offsetTop || 0), x = xAxis.tickFormat()(multibar.x()(e.point, e.pointIndex)), y = yAxis.tickFormat()(multibar.y()(e.point, e.pointIndex)), content = tooltip(e.series.key, x, y, e, chart); nv.tooltip.show([left, top], content, e.value < 0 ? 'n' : 's', null, offsetElement); }; //============================================================ function chart(selection) { selection.each(function(data) { var container = d3.select(this), that = this; var availableWidth = (width || parseInt(container.style('width')) || 960) - margin.left - margin.right, availableHeight = (height || parseInt(container.style('height')) || 400) - margin.top - margin.bottom; chart.update = function() { container.transition().call(chart) }; chart.container = this; //set state.disabled state.disabled = data.map(function(d) { return !!d.disabled }); if (!defaultState) { var key; defaultState = {}; for (key in state) { if (state[key] instanceof Array) defaultState[key] = state[key].slice(0); else defaultState[key] = state[key]; } } //------------------------------------------------------------ // Display noData message if there's nothing to show. if (!data || !data.length || !data.filter(function(d) { return d.values.length }).length) { var noDataText = container.selectAll('.nv-noData').data([noData]); noDataText.enter().append('text') .attr('class', 'nvd3 nv-noData') .attr('dy', '-.7em') .style('text-anchor', 'middle'); noDataText .attr('x', margin.left + availableWidth / 2) .attr('y', margin.top + availableHeight / 2) .text(function(d) { return d }); return chart; } else { container.selectAll('.nv-noData').remove(); } //------------------------------------------------------------ //------------------------------------------------------------ // Setup Scales x = multibar.xScale(); y = multibar.yScale(); //------------------------------------------------------------ //------------------------------------------------------------ // Setup containers and skeleton of chart var wrap = container.selectAll('g.nv-wrap.nv-multiBarWithLegend').data([data]); var gEnter = wrap.enter().append('g').attr('class', 'nvd3 nv-wrap nv-multiBarWithLegend').append('g'); var g = wrap.select('g'); gEnter.append('g').attr('class', 'nv-x nv-axis'); gEnter.append('g').attr('class', 'nv-y nv-axis'); gEnter.append('g').attr('class', 'nv-barsWrap'); gEnter.append('g').attr('class', 'nv-legendWrap'); gEnter.append('g').attr('class', 'nv-controlsWrap'); //------------------------------------------------------------ //------------------------------------------------------------ // Legend if (showLegend) { legend.width(availableWidth - controlWidth()); if (multibar.barColor()) data.forEach(function(series,i) { series.color = d3.rgb('#ccc').darker(i * 1.5).toString(); }) g.select('.nv-legendWrap') .datum(data) .call(legend); if ( margin.top != legend.height()) { margin.top = legend.height() + legend.legendBelowPadding();// added legend.legendBelowPadding to allow for more spacing availableHeight = (height || parseInt(container.style('height')) || 400) - margin.top - margin.bottom; } g.select('.nv-legendWrap') .attr('transform', 'translate(' + controlWidth() + ',' + (-margin.top) +')'); } //------------------------------------------------------------ //------------------------------------------------------------ // Controls if (showControls) { var controlsData = [ { key: 'Grouped', disabled: multibar.stacked() }, { key: 'Stacked', disabled: !multibar.stacked() } ]; controls.width(controlWidth()).color(['#444', '#444', '#444']); g.select('.nv-controlsWrap') .datum(controlsData) .attr('transform', 'translate(0,' + (-margin.top) +')') .call(controls); } //------------------------------------------------------------ wrap.attr('transform', 'translate(' + margin.left + ',' + margin.top + ')'); //------------------------------------------------------------ // Main Chart Component(s) multibar .disabled(data.map(function(series) { return series.disabled })) .width(availableWidth) .height(availableHeight) .color(data.map(function(d,i) { return d.color || color(d, i); }).filter(function(d,i) { return !data[i].disabled })) var barsWrap = g.select('.nv-barsWrap') .datum(data.filter(function(d) { return !d.disabled })) d3.transition(barsWrap).call(multibar); //------------------------------------------------------------ //------------------------------------------------------------ // Setup Axes xAxis .scale(x) .ticks( availableWidth / 100 ) .tickSize(-availableHeight, 0); g.select('.nv-x.nv-axis') .attr('transform', 'translate(0,' + y.range()[0] + ')'); d3.transition(g.select('.nv-x.nv-axis')) .call(xAxis); var xTicks = g.select('.nv-x.nv-axis > g').selectAll('g'); xTicks .selectAll('line, text') .style('opacity', 1) if (staggerLabels) { var getTranslate = function(x,y) { return "translate(" + x + "," + y + ")"; }; var staggerUp = 5, staggerDown = 17; //pixels to stagger by // Issue #140 xTicks .selectAll("text") .attr('transform', function(d,i,j) { return getTranslate(0, (j % 2 == 0 ? staggerUp : staggerDown)); }); var totalInBetweenTicks = d3.selectAll(".nv-x.nv-axis .nv-wrap g g text")[0].length; g.selectAll(".nv-x.nv-axis .nv-axisMaxMin text") .attr("transform", function(d,i) { return getTranslate(0, (i === 0 || totalInBetweenTicks % 2 !== 0) ? staggerDown : staggerUp); }); } if (reduceXTicks) xTicks .filter(function(d,i) { return i % Math.ceil(data[0].values.length / (availableWidth / 100)) !== 0; }) .selectAll('text, line') .style('opacity', 0); if(rotateLabels) xTicks .selectAll('text') .attr('transform', 'rotate(' + rotateLabels + ' 0,0)') .attr('text-anchor', rotateLabels > 0 ? 'start' : 'end'); g.select('.nv-x.nv-axis').selectAll('g.nv-axisMaxMin text') .style('opacity', 1); yAxis .scale(y) .ticks( availableHeight / 36 ) .tickSize( -availableWidth, 0); d3.transition(g.select('.nv-y.nv-axis')) .call(yAxis); //------------------------------------------------------------ //============================================================ // Event Handling/Dispatching (in chart's scope) //------------------------------------------------------------ legend.dispatch.on('legendClick', function(d,i) { d.disabled = !d.disabled; if (!data.filter(function(d) { return !d.disabled }).length) { data.map(function(d) { d.disabled = false; wrap.selectAll('.nv-series').classed('disabled', false); return d; }); } state.disabled = data.map(function(d) { return !!d.disabled }); dispatch.stateChange(state); chart.update(); }); legend.dispatch.on('legendDblclick', function(d) { //Double clicking should always enable current series, and disabled all others. data.forEach(function(d) { d.disabled = true; }); d.disabled = false; state.disabled = data.map(function(d) { return !!d.disabled }); dispatch.stateChange(state); chart.update(); }); controls.dispatch.on('legendClick', function(d,i) { if (!d.disabled) return; controlsData = controlsData.map(function(s) { s.disabled = true; return s; }); d.disabled = false; switch (d.key) { case 'Grouped': multibar.stacked(false); break; case 'Stacked': multibar.stacked(true); break; } state.stacked = multibar.stacked(); dispatch.stateChange(state); chart.update(); }); dispatch.on('tooltipShow', function(e) { if (tooltips) showTooltip(e, that.parentNode) }); // Update chart from a state object passed to event handler dispatch.on('changeState', function(e) { if (typeof e.disabled !== 'undefined') { data.forEach(function(series,i) { series.disabled = e.disabled[i]; }); state.disabled = e.disabled; } if (typeof e.stacked !== 'undefined') { multibar.stacked(e.stacked); state.stacked = e.stacked; } chart.update(); }); //============================================================ }); return chart; } //============================================================ // Event Handling/Dispatching (out of chart's scope) //------------------------------------------------------------ multibar.dispatch.on('elementMouseover.tooltip', function(e) { e.pos = [e.pos[0] + margin.left, e.pos[1] + margin.top]; dispatch.tooltipShow(e); }); multibar.dispatch.on('elementMouseout.tooltip', function(e) { dispatch.tooltipHide(e); }); dispatch.on('tooltipHide', function() { if (tooltips) nv.tooltip.cleanup(); }); //============================================================ //============================================================ // Expose Public Variables //------------------------------------------------------------ // expose chart's sub-components chart.dispatch = dispatch; chart.multibar = multibar; chart.legend = legend; chart.xAxis = xAxis; chart.yAxis = yAxis; d3.rebind(chart, multibar, 'x', 'y', 'xDomain', 'yDomain', 'forceX', 'forceY', 'clipEdge', 'id', 'stacked', 'delay', 'barColor'); chart.margin = function(_) { if (!arguments.length) return margin; margin.top = typeof _.top != 'undefined' ? _.top : margin.top; margin.right = typeof _.right != 'undefined' ? _.right : margin.right; margin.bottom = typeof _.bottom != 'undefined' ? _.bottom : margin.bottom; margin.left = typeof _.left != 'undefined' ? _.left : margin.left; return chart; }; chart.width = function(_) { if (!arguments.length) return width; width = _; return chart; }; chart.height = function(_) { if (!arguments.length) return height; height = _; return chart; }; chart.color = function(_) { if (!arguments.length) return color; color = nv.utils.getColor(_); legend.color(color); return chart; }; chart.showControls = function(_) { if (!arguments.length) return showControls; showControls = _; return chart; }; chart.showLegend = function(_) { if (!arguments.length) return showLegend; showLegend = _; return chart; }; chart.reduceXTicks= function(_) { if (!arguments.length) return reduceXTicks; reduceXTicks = _; return chart; }; chart.rotateLabels = function(_) { if (!arguments.length) return rotateLabels; rotateLabels = _; return chart; } chart.staggerLabels = function(_) { if (!arguments.length) return staggerLabels; staggerLabels = _; return chart; }; chart.tooltip = function(_) { if (!arguments.length) return tooltip; tooltip = _; return chart; }; chart.tooltips = function(_) { if (!arguments.length) return tooltips; tooltips = _; return chart; }; chart.tooltipContent = function(_) { if (!arguments.length) return tooltip; tooltip = _; return chart; }; chart.state = function(_) { if (!arguments.length) return state; state = _; return chart; }; chart.defaultState = function(_) { if (!arguments.length) return defaultState; defaultState = _; return chart; }; chart.noData = function(_) { if (!arguments.length) return noData; noData = _; return chart; }; //============================================================ return chart; } nv.models.multiBarHorizontal = function() { //============================================================ // Public Variables with Default Settings //------------------------------------------------------------ var margin = {top: 0, right: 0, bottom: 0, left: 0} , width = 960 , height = 500 , id = Math.floor(Math.random() * 10000) //Create semi-unique ID in case user doesn't select one , x = d3.scale.ordinal() , y = d3.scale.linear() , getX = function(d) { return d.x } , getY = function(d) { return d.y } , forceY = [0] // 0 is forced by default.. this makes sense for the majority of bar graphs... user can always do chart.forceY([]) to remove , color = nv.utils.defaultColor() , barColor = null // adding the ability to set the color for each rather than the whole group , disabled // used in conjunction with barColor to communicate from multiBarHorizontalChart what series are disabled , stacked = false , showValues = false , valuePadding = 60 , valueFormat = d3.format(',.2f') , delay = 1200 , xDomain , yDomain , dispatch = d3.dispatch('chartClick', 'elementClick', 'elementDblClick', 'elementMouseover', 'elementMouseout') ; //============================================================ //============================================================ // Private Variables //------------------------------------------------------------ var x0, y0 //used to store previous scales ; //============================================================ function chart(selection) { selection.each(function(data) { var availableWidth = width - margin.left - margin.right, availableHeight = height - margin.top - margin.bottom, container = d3.select(this); if (stacked) data = d3.layout.stack() .offset('zero') .values(function(d){ return d.values }) .y(getY) (data); //add series index to each data point for reference data = data.map(function(series, i) { series.values = series.values.map(function(point) { point.series = i; return point; }); return series; }); //------------------------------------------------------------ // HACK for negative value stacking if (stacked) data[0].values.map(function(d,i) { var posBase = 0, negBase = 0; data.map(function(d) { var f = d.values[i] f.size = Math.abs(f.y); if (f.y<0) { f.y1 = negBase - f.size; negBase = negBase - f.size; } else { f.y1 = posBase; posBase = posBase + f.size; } }); }); //------------------------------------------------------------ // Setup Scales // remap and flatten the data for use in calculating the scales' domains var seriesData = (xDomain && yDomain) ? [] : // if we know xDomain and yDomain, no need to calculate data.map(function(d) { return d.values.map(function(d,i) { return { x: getX(d,i), y: getY(d,i), y0: d.y0, y1: d.y1 } }) }); x .domain(xDomain || d3.merge(seriesData).map(function(d) { return d.x })) .rangeBands([0, availableHeight], .1); //y .domain(yDomain || d3.extent(d3.merge(seriesData).map(function(d) { return d.y + (stacked ? d.y0 : 0) }).concat(forceY))) y .domain(yDomain || d3.extent(d3.merge(seriesData).map(function(d) { return stacked ? (d.y > 0 ? d.y1 + d.y : d.y1 ) : d.y }).concat(forceY))) if (showValues && !stacked) y.range([(y.domain()[0] < 0 ? valuePadding : 0), availableWidth - (y.domain()[1] > 0 ? valuePadding : 0) ]); else y.range([0, availableWidth]); x0 = x0 || x; y0 = y0 || d3.scale.linear().domain(y.domain()).range([y(0),y(0)]); //------------------------------------------------------------ //------------------------------------------------------------ // Setup containers and skeleton of chart var wrap = d3.select(this).selectAll('g.nv-wrap.nv-multibarHorizontal').data([data]); var wrapEnter = wrap.enter().append('g').attr('class', 'nvd3 nv-wrap nv-multibarHorizontal'); var defsEnter = wrapEnter.append('defs'); var gEnter = wrapEnter.append('g'); var g = wrap.select('g'); gEnter.append('g').attr('class', 'nv-groups'); wrap.attr('transform', 'translate(' + margin.left + ',' + margin.top + ')'); //------------------------------------------------------------ var groups = wrap.select('.nv-groups').selectAll('.nv-group') .data(function(d) { return d }, function(d) { return d.key }); groups.enter().append('g') .style('stroke-opacity', 1e-6) .style('fill-opacity', 1e-6); d3.transition(groups.exit()) .style('stroke-opacity', 1e-6) .style('fill-opacity', 1e-6) .remove(); groups .attr('class', function(d,i) { return 'nv-group nv-series-' + i }) .classed('hover', function(d) { return d.hover }) .style('fill', function(d,i){ return color(d, i) }) .style('stroke', function(d,i){ return color(d, i) }); d3.transition(groups) .style('stroke-opacity', 1) .style('fill-opacity', .75); var bars = groups.selectAll('g.nv-bar') .data(function(d) { return d.values }); bars.exit().remove(); var barsEnter = bars.enter().append('g') .attr('transform', function(d,i,j) { return 'translate(' + y0(stacked ? d.y0 : 0) + ',' + (stacked ? 0 : (j * x.rangeBand() / data.length ) + x(getX(d,i))) + ')' }); barsEnter.append('rect') .attr('width', 0) .attr('height', x.rangeBand() / (stacked ? 1 : data.length) ) bars .on('mouseover', function(d,i) { //TODO: figure out why j works above, but not here d3.select(this).classed('hover', true); dispatch.elementMouseover({ value: getY(d,i), point: d, series: data[d.series], pos: [ y(getY(d,i) + (stacked ? d.y0 : 0)), x(getX(d,i)) + (x.rangeBand() * (stacked ? data.length / 2 : d.series + .5) / data.length) ], pointIndex: i, seriesIndex: d.series, e: d3.event }); }) .on('mouseout', function(d,i) { d3.select(this).classed('hover', false); dispatch.elementMouseout({ value: getY(d,i), point: d, series: data[d.series], pointIndex: i, seriesIndex: d.series, e: d3.event }); }) .on('click', function(d,i) { dispatch.elementClick({ value: getY(d,i), point: d, series: data[d.series], pos: [x(getX(d,i)) + (x.rangeBand() * (stacked ? data.length / 2 : d.series + .5) / data.length), y(getY(d,i) + (stacked ? d.y0 : 0))], // TODO: Figure out why the value appears to be shifted pointIndex: i, seriesIndex: d.series, e: d3.event }); d3.event.stopPropagation(); }) .on('dblclick', function(d,i) { dispatch.elementDblClick({ value: getY(d,i), point: d, series: data[d.series], pos: [x(getX(d,i)) + (x.rangeBand() * (stacked ? data.length / 2 : d.series + .5) / data.length), y(getY(d,i) + (stacked ? d.y0 : 0))], // TODO: Figure out why the value appears to be shifted pointIndex: i, seriesIndex: d.series, e: d3.event }); d3.event.stopPropagation(); }); barsEnter.append('text'); if (showValues && !stacked) { bars.select('text') .attr('text-anchor', function(d,i) { return getY(d,i) < 0 ? 'end' : 'start' }) .attr('y', x.rangeBand() / (data.length * 2)) .attr('dy', '.32em') .text(function(d,i) { return valueFormat(getY(d,i)) }) d3.transition(bars) //.delay(function(d,i) { return i * delay / data[0].values.length }) .select('text') .attr('x', function(d,i) { return getY(d,i) < 0 ? -4 : y(getY(d,i)) - y(0) + 4 }) } else { //bars.selectAll('text').remove(); bars.selectAll('text').text(''); } bars .attr('class', function(d,i) { return getY(d,i) < 0 ? 'nv-bar negative' : 'nv-bar positive'}) if (barColor) { if (!disabled) disabled = data.map(function() { return true }); bars //.style('fill', barColor) //.style('stroke', barColor) //.style('fill', function(d,i,j) { return d3.rgb(barColor(d,i)).darker(j).toString(); }) //.style('stroke', function(d,i,j) { return d3.rgb(barColor(d,i)).darker(j).toString(); }) .style('fill', function(d,i,j) { return d3.rgb(barColor(d,i)).darker( disabled.map(function(d,i) { return i }).filter(function(d,i){ return !disabled[i] })[j] ).toString(); }) .style('stroke', function(d,i,j) { return d3.rgb(barColor(d,i)).darker( disabled.map(function(d,i) { return i }).filter(function(d,i){ return !disabled[i] })[j] ).toString(); }); } if (stacked) d3.transition(bars) //.delay(function(d,i) { return i * delay / data[0].values.length }) .attr('transform', function(d,i) { //return 'translate(' + y(d.y0) + ',0)' //return 'translate(' + y(d.y0) + ',' + x(getX(d,i)) + ')' return 'translate(' + y(d.y1) + ',' + x(getX(d,i)) + ')' }) .select('rect') .attr('width', function(d,i) { return Math.abs(y(getY(d,i) + d.y0) - y(d.y0)) }) .attr('height', x.rangeBand() ); else d3.transition(bars) //.delay(function(d,i) { return i * delay / data[0].values.length }) .attr('transform', function(d,i) { //TODO: stacked must be all positive or all negative, not both? return 'translate(' + (getY(d,i) < 0 ? y(getY(d,i)) : y(0)) + ',' + (d.series * x.rangeBand() / data.length + x(getX(d,i)) ) + ')' }) .select('rect') .attr('height', x.rangeBand() / data.length ) .attr('width', function(d,i) { return Math.max(Math.abs(y(getY(d,i)) - y(0)),1) }); //store old scales for use in transitions on update x0 = x.copy(); y0 = y.copy(); }); return chart; } //============================================================ // Expose Public Variables //------------------------------------------------------------ chart.dispatch = dispatch; chart.x = function(_) { if (!arguments.length) return getX; getX = _; return chart; }; chart.y = function(_) { if (!arguments.length) return getY; getY = _; return chart; }; chart.margin = function(_) { if (!arguments.length) return margin; margin.top = typeof _.top != 'undefined' ? _.top : margin.top; margin.right = typeof _.right != 'undefined' ? _.right : margin.right; margin.bottom = typeof _.bottom != 'undefined' ? _.bottom : margin.bottom; margin.left = typeof _.left != 'undefined' ? _.left : margin.left; return chart; }; chart.width = function(_) { if (!arguments.length) return width; width = _; return chart; }; chart.height = function(_) { if (!arguments.length) return height; height = _; return chart; }; chart.xScale = function(_) { if (!arguments.length) return x; x = _; return chart; }; chart.yScale = function(_) { if (!arguments.length) return y; y = _; return chart; }; chart.xDomain = function(_) { if (!arguments.length) return xDomain; xDomain = _; return chart; }; chart.yDomain = function(_) { if (!arguments.length) return yDomain; yDomain = _; return chart; }; chart.forceY = function(_) { if (!arguments.length) return forceY; forceY = _; return chart; }; chart.stacked = function(_) { if (!arguments.length) return stacked; stacked = _; return chart; }; chart.color = function(_) { if (!arguments.length) return color; color = nv.utils.getColor(_); return chart; }; chart.barColor = function(_) { if (!arguments.length) return barColor; barColor = nv.utils.getColor(_); return chart; }; chart.disabled = function(_) { if (!arguments.length) return disabled; disabled = _; return chart; }; chart.id = function(_) { if (!arguments.length) return id; id = _; return chart; }; chart.delay = function(_) { if (!arguments.length) return delay; delay = _; return chart; }; chart.showValues = function(_) { if (!arguments.length) return showValues; showValues = _; return chart; }; chart.valueFormat= function(_) { if (!arguments.length) return valueFormat; valueFormat = _; return chart; }; chart.valuePadding = function(_) { if (!arguments.length) return valuePadding; valuePadding = _; return chart; }; //============================================================ return chart; } nv.models.multiBarHorizontalChart = function() { //============================================================ // Public Variables with Default Settings //------------------------------------------------------------ var multibar = nv.models.multiBarHorizontal() , xAxis = nv.models.axis() , yAxis = nv.models.axis() , legend = nv.models.legend().height(30) , controls = nv.models.legend().height(30) ; var margin = {top: 30, right: 20, bottom: 50, left: 60} , width = null , height = null , color = nv.utils.defaultColor() , showControls = true , showLegend = true , stacked = false , tooltips = true , tooltip = function(key, x, y, e, graph) { return '

    ' + key + ' - ' + x + '

    ' + '

    ' + y + '

    ' } , x //can be accessed via chart.xScale() , y //can be accessed via chart.yScale() , state = { stacked: stacked } , defaultState = null , noData = 'No Data Available.' , dispatch = d3.dispatch('tooltipShow', 'tooltipHide', 'stateChange', 'changeState') , controlWidth = function() { return showControls ? 180 : 0 } ; multibar .stacked(stacked) ; xAxis .orient('left') .tickPadding(5) .highlightZero(false) .showMaxMin(false) .tickFormat(function(d) { return d }) ; yAxis .orient('bottom') .tickFormat(d3.format(',.1f')) ; //============================================================ //============================================================ // Private Variables //------------------------------------------------------------ var showTooltip = function(e, offsetElement) { var left = e.pos[0] + ( offsetElement.offsetLeft || 0 ), top = e.pos[1] + ( offsetElement.offsetTop || 0), x = xAxis.tickFormat()(multibar.x()(e.point, e.pointIndex)), y = yAxis.tickFormat()(multibar.y()(e.point, e.pointIndex)), content = tooltip(e.series.key, x, y, e, chart); nv.tooltip.show([left, top], content, e.value < 0 ? 'e' : 'w', null, offsetElement); }; //============================================================ function chart(selection) { selection.each(function(data) { var container = d3.select(this), that = this; var availableWidth = (width || parseInt(container.style('width')) || 960) - margin.left - margin.right, availableHeight = (height || parseInt(container.style('height')) || 400) - margin.top - margin.bottom; chart.update = function() { container.transition().call(chart) }; chart.container = this; //set state.disabled state.disabled = data.map(function(d) { return !!d.disabled }); if (!defaultState) { var key; defaultState = {}; for (key in state) { if (state[key] instanceof Array) defaultState[key] = state[key].slice(0); else defaultState[key] = state[key]; } } //------------------------------------------------------------ // Display No Data message if there's nothing to show. if (!data || !data.length || !data.filter(function(d) { return d.values.length }).length) { var noDataText = container.selectAll('.nv-noData').data([noData]); noDataText.enter().append('text') .attr('class', 'nvd3 nv-noData') .attr('dy', '-.7em') .style('text-anchor', 'middle'); noDataText .attr('x', margin.left + availableWidth / 2) .attr('y', margin.top + availableHeight / 2) .text(function(d) { return d }); return chart; } else { container.selectAll('.nv-noData').remove(); } //------------------------------------------------------------ //------------------------------------------------------------ // Setup Scales x = multibar.xScale(); y = multibar.yScale(); //------------------------------------------------------------ //------------------------------------------------------------ // Setup containers and skeleton of chart var wrap = container.selectAll('g.nv-wrap.nv-multiBarHorizontalChart').data([data]); var gEnter = wrap.enter().append('g').attr('class', 'nvd3 nv-wrap nv-multiBarHorizontalChart').append('g'); var g = wrap.select('g'); gEnter.append('g').attr('class', 'nv-x nv-axis'); gEnter.append('g').attr('class', 'nv-y nv-axis'); gEnter.append('g').attr('class', 'nv-barsWrap'); gEnter.append('g').attr('class', 'nv-legendWrap'); gEnter.append('g').attr('class', 'nv-controlsWrap'); //------------------------------------------------------------ //------------------------------------------------------------ // Legend if (showLegend) { legend.width(availableWidth - controlWidth()); if (multibar.barColor()) data.forEach(function(series,i) { series.color = d3.rgb('#ccc').darker(i * 1.5).toString(); }) g.select('.nv-legendWrap') .datum(data) .call(legend); if ( margin.top != legend.height()) { margin.top = legend.height() + legend.legendBelowPadding();// added legend.legendBelowPadding to allow for more spacing availableHeight = (height || parseInt(container.style('height')) || 400) - margin.top - margin.bottom; } g.select('.nv-legendWrap') .attr('transform', 'translate(' + controlWidth() + ',' + (-margin.top) +')'); } //------------------------------------------------------------ //------------------------------------------------------------ // Controls if (showControls) { var controlsData = [ { key: 'Grouped', disabled: multibar.stacked() }, { key: 'Stacked', disabled: !multibar.stacked() } ]; controls.width(controlWidth()).color(['#444', '#444', '#444']); g.select('.nv-controlsWrap') .datum(controlsData) .attr('transform', 'translate(0,' + (-margin.top) +')') .call(controls); } //------------------------------------------------------------ wrap.attr('transform', 'translate(' + margin.left + ',' + margin.top + ')'); //------------------------------------------------------------ // Main Chart Component(s) multibar .disabled(data.map(function(series) { return series.disabled })) .width(availableWidth) .height(availableHeight) .color(data.map(function(d,i) { return d.color || color(d, i); }).filter(function(d,i) { return !data[i].disabled })) var barsWrap = g.select('.nv-barsWrap') .datum(data.filter(function(d) { return !d.disabled })) d3.transition(barsWrap).call(multibar); //------------------------------------------------------------ //------------------------------------------------------------ // Setup Axes xAxis .scale(x) .ticks( availableHeight / 24 ) .tickSize(-availableWidth, 0); d3.transition(g.select('.nv-x.nv-axis')) .call(xAxis); var xTicks = g.select('.nv-x.nv-axis').selectAll('g'); xTicks .selectAll('line, text') .style('opacity', 1) yAxis .scale(y) .ticks( availableWidth / 100 ) .tickSize( -availableHeight, 0); g.select('.nv-y.nv-axis') .attr('transform', 'translate(0,' + availableHeight + ')'); d3.transition(g.select('.nv-y.nv-axis')) .call(yAxis); //------------------------------------------------------------ //============================================================ // Event Handling/Dispatching (in chart's scope) //------------------------------------------------------------ legend.dispatch.on('legendClick', function(d,i) { d.disabled = !d.disabled; if (!data.filter(function(d) { return !d.disabled }).length) { data.map(function(d) { d.disabled = false; wrap.selectAll('.nv-series').classed('disabled', false); return d; }); } state.disabled = data.map(function(d) { return !!d.disabled }); dispatch.stateChange(state); chart.update(); }); legend.dispatch.on('legendDblclick', function(d) { //Double clicking should always enable current series, and disabled all others. data.forEach(function(d) { d.disabled = true; }); d.disabled = false; state.disabled = data.map(function(d) { return !!d.disabled }); dispatch.stateChange(state); chart.update(); }); controls.dispatch.on('legendClick', function(d,i) { if (!d.disabled) return; controlsData = controlsData.map(function(s) { s.disabled = true; return s; }); d.disabled = false; switch (d.key) { case 'Grouped': multibar.stacked(false); break; case 'Stacked': multibar.stacked(true); break; } state.stacked = multibar.stacked(); dispatch.stateChange(state); chart.update(); }); dispatch.on('tooltipShow', function(e) { if (tooltips) showTooltip(e, that.parentNode); }); // Update chart from a state object passed to event handler dispatch.on('changeState', function(e) { if (typeof e.disabled !== 'undefined') { data.forEach(function(series,i) { series.disabled = e.disabled[i]; }); state.disabled = e.disabled; } if (typeof e.stacked !== 'undefined') { multibar.stacked(e.stacked); state.stacked = e.stacked; } selection.call(chart); }); //============================================================ }); return chart; } //============================================================ // Event Handling/Dispatching (out of chart's scope) //------------------------------------------------------------ multibar.dispatch.on('elementMouseover.tooltip', function(e) { e.pos = [e.pos[0] + margin.left, e.pos[1] + margin.top]; dispatch.tooltipShow(e); }); multibar.dispatch.on('elementMouseout.tooltip', function(e) { dispatch.tooltipHide(e); }); dispatch.on('tooltipHide', function() { if (tooltips) nv.tooltip.cleanup(); }); //============================================================ //============================================================ // Expose Public Variables //------------------------------------------------------------ // expose chart's sub-components chart.dispatch = dispatch; chart.multibar = multibar; chart.legend = legend; chart.xAxis = xAxis; chart.yAxis = yAxis; d3.rebind(chart, multibar, 'x', 'y', 'xDomain', 'yDomain', 'forceX', 'forceY', 'clipEdge', 'id', 'delay', 'showValues', 'valueFormat', 'stacked', 'barColor'); chart.margin = function(_) { if (!arguments.length) return margin; margin.top = typeof _.top != 'undefined' ? _.top : margin.top; margin.right = typeof _.right != 'undefined' ? _.right : margin.right; margin.bottom = typeof _.bottom != 'undefined' ? _.bottom : margin.bottom; margin.left = typeof _.left != 'undefined' ? _.left : margin.left; return chart; }; chart.width = function(_) { if (!arguments.length) return width; width = _; return chart; }; chart.height = function(_) { if (!arguments.length) return height; height = _; return chart; }; chart.color = function(_) { if (!arguments.length) return color; color = nv.utils.getColor(_); legend.color(color); return chart; }; chart.showControls = function(_) { if (!arguments.length) return showControls; showControls = _; return chart; }; chart.showLegend = function(_) { if (!arguments.length) return showLegend; showLegend = _; return chart; }; chart.tooltip = function(_) { if (!arguments.length) return tooltip; tooltip = _; return chart; }; chart.tooltips = function(_) { if (!arguments.length) return tooltips; tooltips = _; return chart; }; chart.tooltipContent = function(_) { if (!arguments.length) return tooltip; tooltip = _; return chart; }; chart.state = function(_) { if (!arguments.length) return state; state = _; return chart; }; chart.defaultState = function(_) { if (!arguments.length) return defaultState; defaultState = _; return chart; }; chart.noData = function(_) { if (!arguments.length) return noData; noData = _; return chart; }; //============================================================ return chart; } nv.models.multiChart = function() { //============================================================ // Public Variables with Default Settings //------------------------------------------------------------ var margin = {top: 30, right: 20, bottom: 50, left: 60}, color = d3.scale.category20().range(), width = null, height = null, showLegend = true, tooltips = true, tooltip = function(key, x, y, e, graph) { return '

    ' + key + '

    ' + '

    ' + y + ' at ' + x + '

    ' }, x, y; //can be accessed via chart.lines.[x/y]Scale() //============================================================ // Private Variables //------------------------------------------------------------ var x = d3.scale.linear(), yScale1 = d3.scale.linear(), yScale2 = d3.scale.linear(), lines1 = nv.models.line().yScale(yScale1), lines2 = nv.models.line().yScale(yScale2), bars1 = nv.models.multiBar().stacked(false).yScale(yScale1), bars2 = nv.models.multiBar().stacked(false).yScale(yScale2), stack1 = nv.models.stackedArea().yScale(yScale1), stack2 = nv.models.stackedArea().yScale(yScale2), xAxis = nv.models.axis().scale(x).orient('bottom').tickPadding(5), yAxis1 = nv.models.axis().scale(yScale1).orient('left'), yAxis2 = nv.models.axis().scale(yScale2).orient('right'), legend = nv.models.legend().height(30), dispatch = d3.dispatch('tooltipShow', 'tooltipHide'); var showTooltip = function(e, offsetElement) { var left = e.pos[0] + ( offsetElement.offsetLeft || 0 ), top = e.pos[1] + ( offsetElement.offsetTop || 0), x = xAxis.tickFormat()(lines1.x()(e.point, e.pointIndex)), y = ((e.series.yAxis == 2) ? yAxis2 : yAxis1).tickFormat()(lines1.y()(e.point, e.pointIndex)), content = tooltip(e.series.key, x, y, e, chart); nv.tooltip.show([left, top], content, undefined, undefined, offsetElement.offsetParent); }; function chart(selection) { selection.each(function(data) { var container = d3.select(this), that = this; chart.update = function() { container.transition().call(chart); }; chart.container = this; var availableWidth = (width || parseInt(container.style('width')) || 960) - margin.left - margin.right, availableHeight = (height || parseInt(container.style('height')) || 400) - margin.top - margin.bottom; var dataLines1 = data.filter(function(d) {return !d.disabled && d.type == 'line' && d.yAxis == 1}) var dataLines2 = data.filter(function(d) {return !d.disabled && d.type == 'line' && d.yAxis == 2}) var dataBars1 = data.filter(function(d) {return !d.disabled && d.type == 'bar' && d.yAxis == 1}) var dataBars2 = data.filter(function(d) {return !d.disabled && d.type == 'bar' && d.yAxis == 2}) var dataStack1 = data.filter(function(d) {return !d.disabled && d.type == 'area' && d.yAxis == 1}) var dataStack2 = data.filter(function(d) {return !d.disabled && d.type == 'area' && d.yAxis == 2}) var series1 = data.filter(function(d) {return !d.disabled && d.yAxis == 1}) .map(function(d) { return d.values.map(function(d,i) { return { x: d.x, y: d.y } }) }) var series2 = data.filter(function(d) {return !d.disabled && d.yAxis == 2}) .map(function(d) { return d.values.map(function(d,i) { return { x: d.x, y: d.y } }) }) x .domain(d3.extent(d3.merge(series1.concat(series2)), function(d) { return d.x } )) .range([0, availableWidth]); var wrap = container.selectAll('g.wrap.multiChart').data([data]); var gEnter = wrap.enter().append('g').attr('class', 'wrap nvd3 multiChart').append('g'); gEnter.append('g').attr('class', 'x axis'); gEnter.append('g').attr('class', 'y1 axis'); gEnter.append('g').attr('class', 'y2 axis'); gEnter.append('g').attr('class', 'lines1Wrap'); gEnter.append('g').attr('class', 'lines2Wrap'); gEnter.append('g').attr('class', 'bars1Wrap'); gEnter.append('g').attr('class', 'bars2Wrap'); gEnter.append('g').attr('class', 'stack1Wrap'); gEnter.append('g').attr('class', 'stack2Wrap'); gEnter.append('g').attr('class', 'legendWrap'); var g = wrap.select('g'); if (showLegend) { legend.width( availableWidth / 2 ); g.select('.legendWrap') .datum(data.map(function(series) { series.originalKey = series.originalKey === undefined ? series.key : series.originalKey; series.key = series.originalKey + (series.yAxis == 1 ? '' : ' (right axis)'); return series; })) .call(legend); if ( margin.top != legend.height()) { margin.top = legend.height() + legend.legendBelowPadding();// added legend.legendBelowPadding to allow for more spacing availableHeight = (height || parseInt(container.style('height')) || 400) - margin.top - margin.bottom; } g.select('.legendWrap') .attr('transform', 'translate(' + ( availableWidth / 2 ) + ',' + (-margin.top) +')'); } lines1 .width(availableWidth) .height(availableHeight) .interpolate("monotone") .color(data.map(function(d,i) { return d.color || color[i % color.length]; }).filter(function(d,i) { return !data[i].disabled && data[i].yAxis == 1 && data[i].type == 'line'})); lines2 .width(availableWidth) .height(availableHeight) .interpolate("monotone") .color(data.map(function(d,i) { return d.color || color[i % color.length]; }).filter(function(d,i) { return !data[i].disabled && data[i].yAxis == 2 && data[i].type == 'line'})); bars1 .width(availableWidth) .height(availableHeight) .color(data.map(function(d,i) { return d.color || color[i % color.length]; }).filter(function(d,i) { return !data[i].disabled && data[i].yAxis == 1 && data[i].type == 'bar'})); bars2 .width(availableWidth) .height(availableHeight) .color(data.map(function(d,i) { return d.color || color[i % color.length]; }).filter(function(d,i) { return !data[i].disabled && data[i].yAxis == 2 && data[i].type == 'bar'})); stack1 .width(availableWidth) .height(availableHeight) .color(data.map(function(d,i) { return d.color || color[i % color.length]; }).filter(function(d,i) { return !data[i].disabled && data[i].yAxis == 1 && data[i].type == 'area'})); stack2 .width(availableWidth) .height(availableHeight) .color(data.map(function(d,i) { return d.color || color[i % color.length]; }).filter(function(d,i) { return !data[i].disabled && data[i].yAxis == 2 && data[i].type == 'area'})); g.attr('transform', 'translate(' + margin.left + ',' + margin.top + ')'); var lines1Wrap = g.select('.lines1Wrap') .datum(dataLines1) var bars1Wrap = g.select('.bars1Wrap') .datum(dataBars1) var stack1Wrap = g.select('.stack1Wrap') .datum(dataStack1) var lines2Wrap = g.select('.lines2Wrap') .datum(dataLines2) var bars2Wrap = g.select('.bars2Wrap') .datum(dataBars2) var stack2Wrap = g.select('.stack2Wrap') .datum(dataStack2) var extraValue1 = dataStack1.length ? dataStack1.map(function(a){return a.values}).reduce(function(a,b){ return a.map(function(aVal,i){return {x: aVal.x, y: aVal.y + b[i].y}}) }).concat([{x:0, y:0}]) : [] var extraValue2 = dataStack2.length ? dataStack2.map(function(a){return a.values}).reduce(function(a,b){ return a.map(function(aVal,i){return {x: aVal.x, y: aVal.y + b[i].y}}) }).concat([{x:0, y:0}]) : [] yScale1 .domain(d3.extent(d3.merge(series1).concat(extraValue1), function(d) { return d.y } )) .range([0, availableHeight]) yScale2 .domain(d3.extent(d3.merge(series2).concat(extraValue2), function(d) { return d.y } )) .range([0, availableHeight]) lines1.yDomain(yScale1.domain()) bars1.yDomain(yScale1.domain()) stack1.yDomain(yScale1.domain()) lines2.yDomain(yScale2.domain()) bars2.yDomain(yScale2.domain()) stack2.yDomain(yScale2.domain()) if(dataStack1.length){d3.transition(stack1Wrap).call(stack1);} if(dataStack2.length){d3.transition(stack2Wrap).call(stack2);} if(dataBars1.length){d3.transition(bars1Wrap).call(bars1);} if(dataBars2.length){d3.transition(bars2Wrap).call(bars2);} if(dataLines1.length){d3.transition(lines1Wrap).call(lines1);} if(dataLines2.length){d3.transition(lines2Wrap).call(lines2);} xAxis .ticks( availableWidth / 100 ) .tickSize(-availableHeight, 0); g.select('.x.axis') .attr('transform', 'translate(0,' + availableHeight + ')'); d3.transition(g.select('.x.axis')) .call(xAxis); yAxis1 .ticks( availableHeight / 36 ) .tickSize( -availableWidth, 0); d3.transition(g.select('.y1.axis')) .call(yAxis1); yAxis2 .ticks( availableHeight / 36 ) .tickSize( -availableWidth, 0); d3.transition(g.select('.y2.axis')) .call(yAxis2); g.select('.y2.axis') .style('opacity', series2.length ? 1 : 0) .attr('transform', 'translate(' + x.range()[1] + ',0)'); legend.dispatch.on('legendClick', function(d,i) { d.disabled = !d.disabled; if (!data.filter(function(d) { return !d.disabled }).length) { data.map(function(d) { d.disabled = false; wrap.selectAll('.series').classed('disabled', false); return d; }); } chart.update(); }); dispatch.on('tooltipShow', function(e) { if (tooltips) showTooltip(e, that.parentNode); }); }); return chart; } //============================================================ // Event Handling/Dispatching (out of chart's scope) //------------------------------------------------------------ lines1.dispatch.on('elementMouseover.tooltip', function(e) { e.pos = [e.pos[0] + margin.left, e.pos[1] + margin.top]; dispatch.tooltipShow(e); }); lines1.dispatch.on('elementMouseout.tooltip', function(e) { dispatch.tooltipHide(e); }); lines2.dispatch.on('elementMouseover.tooltip', function(e) { e.pos = [e.pos[0] + margin.left, e.pos[1] + margin.top]; dispatch.tooltipShow(e); }); lines2.dispatch.on('elementMouseout.tooltip', function(e) { dispatch.tooltipHide(e); }); bars1.dispatch.on('elementMouseover.tooltip', function(e) { e.pos = [e.pos[0] + margin.left, e.pos[1] + margin.top]; dispatch.tooltipShow(e); }); bars1.dispatch.on('elementMouseout.tooltip', function(e) { dispatch.tooltipHide(e); }); bars2.dispatch.on('elementMouseover.tooltip', function(e) { e.pos = [e.pos[0] + margin.left, e.pos[1] + margin.top]; dispatch.tooltipShow(e); }); bars2.dispatch.on('elementMouseout.tooltip', function(e) { dispatch.tooltipHide(e); }); stack1.dispatch.on('tooltipShow', function(e) { //disable tooltips when value ~= 0 //// TODO: consider removing points from voronoi that have 0 value instead of this hack if (!Math.round(stack1.y()(e.point) * 100)) { // 100 will not be good for very small numbers... will have to think about making this valu dynamic, based on data range setTimeout(function() { d3.selectAll('.point.hover').classed('hover', false) }, 0); return false; } e.pos = [e.pos[0] + margin.left, e.pos[1] + margin.top], dispatch.tooltipShow(e); }); stack1.dispatch.on('tooltipHide', function(e) { dispatch.tooltipHide(e); }); stack2.dispatch.on('tooltipShow', function(e) { //disable tooltips when value ~= 0 //// TODO: consider removing points from voronoi that have 0 value instead of this hack if (!Math.round(stack2.y()(e.point) * 100)) { // 100 will not be good for very small numbers... will have to think about making this valu dynamic, based on data range setTimeout(function() { d3.selectAll('.point.hover').classed('hover', false) }, 0); return false; } e.pos = [e.pos[0] + margin.left, e.pos[1] + margin.top], dispatch.tooltipShow(e); }); stack2.dispatch.on('tooltipHide', function(e) { dispatch.tooltipHide(e); }); lines1.dispatch.on('elementMouseover.tooltip', function(e) { e.pos = [e.pos[0] + margin.left, e.pos[1] + margin.top]; dispatch.tooltipShow(e); }); lines1.dispatch.on('elementMouseout.tooltip', function(e) { dispatch.tooltipHide(e); }); lines2.dispatch.on('elementMouseover.tooltip', function(e) { e.pos = [e.pos[0] + margin.left, e.pos[1] + margin.top]; dispatch.tooltipShow(e); }); lines2.dispatch.on('elementMouseout.tooltip', function(e) { dispatch.tooltipHide(e); }); dispatch.on('tooltipHide', function() { if (tooltips) nv.tooltip.cleanup(); }); //============================================================ // Global getters and setters //------------------------------------------------------------ chart.dispatch = dispatch; chart.lines1 = lines1; chart.lines2 = lines2; chart.bars1 = bars1; chart.bars2 = bars2; chart.stack1 = stack1; chart.stack2 = stack2; chart.xAxis = xAxis; chart.yAxis1 = yAxis1; chart.yAxis2 = yAxis2; chart.x = function(_) { if (!arguments.length) return getX; getX = _; lines1.x(_); bars1.x(_); return chart; }; chart.y = function(_) { if (!arguments.length) return getY; getY = _; lines1.y(_); bars1.y(_); return chart; }; chart.margin = function(_) { if (!arguments.length) return margin; margin = _; return chart; }; chart.width = function(_) { if (!arguments.length) return width; width = _; return chart; }; chart.height = function(_) { if (!arguments.length) return height; height = _; return chart; }; chart.color = function(_) { if (!arguments.length) return color; color = _; legend.color(_); return chart; }; chart.showLegend = function(_) { if (!arguments.length) return showLegend; showLegend = _; return chart; }; chart.tooltips = function(_) { if (!arguments.length) return tooltips; tooltips = _; return chart; }; chart.tooltipContent = function(_) { if (!arguments.length) return tooltip; tooltip = _; return chart; }; return chart; } nv.models.ohlcBar = function() { //============================================================ // Public Variables with Default Settings //------------------------------------------------------------ var margin = {top: 0, right: 0, bottom: 0, left: 0} , width = 960 , height = 500 , id = Math.floor(Math.random() * 10000) //Create semi-unique ID in case user doesn't select one , x = d3.scale.linear() , y = d3.scale.linear() , getX = function(d) { return d.x } , getY = function(d) { return d.y } , getOpen = function(d) { return d.open } , getClose = function(d) { return d.close } , getHigh = function(d) { return d.high } , getLow = function(d) { return d.low } , forceX = [] , forceY = [] , padData = false // If true, adds half a data points width to front and back, for lining up a line chart with a bar chart , clipEdge = true , color = nv.utils.defaultColor() , xDomain , yDomain , dispatch = d3.dispatch('chartClick', 'elementClick', 'elementDblClick', 'elementMouseover', 'elementMouseout') ; //============================================================ //============================================================ // Private Variables //------------------------------------------------------------ //TODO: store old scales for transitions //============================================================ function chart(selection) { selection.each(function(data) { var availableWidth = width - margin.left - margin.right, availableHeight = height - margin.top - margin.bottom, container = d3.select(this); //------------------------------------------------------------ // Setup Scales x .domain(xDomain || d3.extent(data[0].values.map(getX).concat(forceX) )); if (padData) x.range([availableWidth * .5 / data[0].values.length, availableWidth * (data[0].values.length - .5) / data[0].values.length ]); else x.range([0, availableWidth]); y .domain(yDomain || [ d3.min(data[0].values.map(getLow).concat(forceY)), d3.max(data[0].values.map(getHigh).concat(forceY)) ]) .range([availableHeight, 0]); // If scale's domain don't have a range, slightly adjust to make one... so a chart can show a single data point if (x.domain()[0] === x.domain()[1] || y.domain()[0] === y.domain()[1]) singlePoint = true; if (x.domain()[0] === x.domain()[1]) x.domain()[0] ? x.domain([x.domain()[0] - x.domain()[0] * 0.01, x.domain()[1] + x.domain()[1] * 0.01]) : x.domain([-1,1]); if (y.domain()[0] === y.domain()[1]) y.domain()[0] ? y.domain([y.domain()[0] + y.domain()[0] * 0.01, y.domain()[1] - y.domain()[1] * 0.01]) : y.domain([-1,1]); //------------------------------------------------------------ //------------------------------------------------------------ // Setup containers and skeleton of chart var wrap = d3.select(this).selectAll('g.nv-wrap.nv-ohlcBar').data([data[0].values]); var wrapEnter = wrap.enter().append('g').attr('class', 'nvd3 nv-wrap nv-ohlcBar'); var defsEnter = wrapEnter.append('defs'); var gEnter = wrapEnter.append('g'); var g = wrap.select('g'); gEnter.append('g').attr('class', 'nv-ticks'); wrap.attr('transform', 'translate(' + margin.left + ',' + margin.top + ')'); //------------------------------------------------------------ container .on('click', function(d,i) { dispatch.chartClick({ data: d, index: i, pos: d3.event, id: id }); }); defsEnter.append('clipPath') .attr('id', 'nv-chart-clip-path-' + id) .append('rect'); wrap.select('#nv-chart-clip-path-' + id + ' rect') .attr('width', availableWidth) .attr('height', availableHeight); g .attr('clip-path', clipEdge ? 'url(#nv-chart-clip-path-' + id + ')' : ''); var ticks = wrap.select('.nv-ticks').selectAll('.nv-tick') .data(function(d) { return d }); ticks.exit().remove(); var ticksEnter = ticks.enter().append('path') .attr('class', function(d,i,j) { return (getOpen(d,i) > getClose(d,i) ? 'nv-tick negative' : 'nv-tick positive') + ' nv-tick-' + j + '-' + i }) .attr('d', function(d,i) { var w = (availableWidth / data[0].values.length) * .9; return 'm0,0l0,' + (y(getOpen(d,i)) - y(getHigh(d,i))) + 'l' + (-w/2) + ',0l' + (w/2) + ',0l0,' + (y(getLow(d,i)) - y(getOpen(d,i))) + 'l0,' + (y(getClose(d,i)) - y(getLow(d,i))) + 'l' + (w/2) + ',0l' + (-w/2) + ',0z'; }) .attr('transform', function(d,i) { return 'translate(' + x(getX(d,i)) + ',' + y(getHigh(d,i)) + ')'; }) //.attr('fill', function(d,i) { return color[0]; }) //.attr('stroke', function(d,i) { return color[0]; }) //.attr('x', 0 ) //.attr('y', function(d,i) { return y(Math.max(0, getY(d,i))) }) //.attr('height', function(d,i) { return Math.abs(y(getY(d,i)) - y(0)) }) .on('mouseover', function(d,i) { d3.select(this).classed('hover', true); dispatch.elementMouseover({ point: d, series: data[0], pos: [x(getX(d,i)), y(getY(d,i))], // TODO: Figure out why the value appears to be shifted pointIndex: i, seriesIndex: 0, e: d3.event }); }) .on('mouseout', function(d,i) { d3.select(this).classed('hover', false); dispatch.elementMouseout({ point: d, series: data[0], pointIndex: i, seriesIndex: 0, e: d3.event }); }) .on('click', function(d,i) { dispatch.elementClick({ //label: d[label], value: getY(d,i), data: d, index: i, pos: [x(getX(d,i)), y(getY(d,i))], e: d3.event, id: id }); d3.event.stopPropagation(); }) .on('dblclick', function(d,i) { dispatch.elementDblClick({ //label: d[label], value: getY(d,i), data: d, index: i, pos: [x(getX(d,i)), y(getY(d,i))], e: d3.event, id: id }); d3.event.stopPropagation(); }); ticks .attr('class', function(d,i,j) { return (getOpen(d,i) > getClose(d,i) ? 'nv-tick negative' : 'nv-tick positive') + ' nv-tick-' + j + '-' + i }) d3.transition(ticks) .attr('transform', function(d,i) { return 'translate(' + x(getX(d,i)) + ',' + y(getHigh(d,i)) + ')'; }) .attr('d', function(d,i) { var w = (availableWidth / data[0].values.length) * .9; return 'm0,0l0,' + (y(getOpen(d,i)) - y(getHigh(d,i))) + 'l' + (-w/2) + ',0l' + (w/2) + ',0l0,' + (y(getLow(d,i)) - y(getOpen(d,i))) + 'l0,' + (y(getClose(d,i)) - y(getLow(d,i))) + 'l' + (w/2) + ',0l' + (-w/2) + ',0z'; }) //.attr('width', (availableWidth / data[0].values.length) * .9 ) //d3.transition(ticks) //.attr('y', function(d,i) { return y(Math.max(0, getY(d,i))) }) //.attr('height', function(d,i) { return Math.abs(y(getY(d,i)) - y(0)) }); //.order(); // not sure if this makes any sense for this model }); return chart; } //============================================================ // Expose Public Variables //------------------------------------------------------------ chart.dispatch = dispatch; chart.x = function(_) { if (!arguments.length) return getX; getX = _; return chart; }; chart.y = function(_) { if (!arguments.length) return getY; getY = _; return chart; }; chart.open = function(_) { if (!arguments.length) return getOpen; getOpen = _; return chart; }; chart.close = function(_) { if (!arguments.length) return getClose; getClose = _; return chart; }; chart.high = function(_) { if (!arguments.length) return getHigh; getHigh = _; return chart; }; chart.low = function(_) { if (!arguments.length) return getLow; getLow = _; return chart; }; chart.margin = function(_) { if (!arguments.length) return margin; margin.top = typeof _.top != 'undefined' ? _.top : margin.top; margin.right = typeof _.right != 'undefined' ? _.right : margin.right; margin.bottom = typeof _.bottom != 'undefined' ? _.bottom : margin.bottom; margin.left = typeof _.left != 'undefined' ? _.left : margin.left; return chart; }; chart.width = function(_) { if (!arguments.length) return width; width = _; return chart; }; chart.height = function(_) { if (!arguments.length) return height; height = _; return chart; }; chart.xScale = function(_) { if (!arguments.length) return x; x = _; return chart; }; chart.yScale = function(_) { if (!arguments.length) return y; y = _; return chart; }; chart.xDomain = function(_) { if (!arguments.length) return xDomain; xDomain = _; return chart; }; chart.yDomain = function(_) { if (!arguments.length) return yDomain; yDomain = _; return chart; }; chart.forceX = function(_) { if (!arguments.length) return forceX; forceX = _; return chart; }; chart.forceY = function(_) { if (!arguments.length) return forceY; forceY = _; return chart; }; chart.padData = function(_) { if (!arguments.length) return padData; padData = _; return chart; }; chart.clipEdge = function(_) { if (!arguments.length) return clipEdge; clipEdge = _; return chart; }; chart.color = function(_) { if (!arguments.length) return color; color = nv.utils.getColor(_); return chart; }; chart.id = function(_) { if (!arguments.length) return id; id = _; return chart; }; //============================================================ return chart; } nv.models.pie = function() { //============================================================ // Public Variables with Default Settings //------------------------------------------------------------ var margin = {top: 0, right: 0, bottom: 0, left: 0} , width = 500 , height = 500 , getValues = function(d) { return d.values } , getX = function(d) { return d.x } , getY = function(d) { return d.y } , getDescription = function(d) { return d.description } , id = Math.floor(Math.random() * 10000) //Create semi-unique ID in case user doesn't select one , color = nv.utils.defaultColor() , valueFormat = d3.format(',.2f') , showLabels = true , pieLabelsOutside = true , donutLabelsOutside = false , labelThreshold = .02 //if slice percentage is under this, don't show label , donut = false , labelSunbeamLayout = false , startAngle = false , endAngle = false , donutRatio = 0.5 , dispatch = d3.dispatch('chartClick', 'elementClick', 'elementDblClick', 'elementMouseover', 'elementMouseout') ; //============================================================ function chart(selection) { selection.each(function(data) { var availableWidth = width - margin.left - margin.right, availableHeight = height - margin.top - margin.bottom, radius = Math.min(availableWidth, availableHeight) / 2, arcRadius = radius-(radius / 5), container = d3.select(this); //------------------------------------------------------------ // Setup containers and skeleton of chart //var wrap = container.selectAll('.nv-wrap.nv-pie').data([data]); var wrap = container.selectAll('.nv-wrap.nv-pie').data([getValues(data[0])]); var wrapEnter = wrap.enter().append('g').attr('class','nvd3 nv-wrap nv-pie nv-chart-' + id); var gEnter = wrapEnter.append('g'); var g = wrap.select('g'); gEnter.append('g').attr('class', 'nv-pie'); wrap.attr('transform', 'translate(' + margin.left + ',' + margin.top + ')'); g.select('.nv-pie').attr('transform', 'translate(' + availableWidth / 2 + ',' + availableHeight / 2 + ')'); //------------------------------------------------------------ container .on('click', function(d,i) { dispatch.chartClick({ data: d, index: i, pos: d3.event, id: id }); }); var arc = d3.svg.arc() .outerRadius(arcRadius); if (startAngle) arc.startAngle(startAngle) if (endAngle) arc.endAngle(endAngle); if (donut) arc.innerRadius(radius * donutRatio); // Setup the Pie chart and choose the data element var pie = d3.layout.pie() .sort(null) .value(function(d) { return d.disabled ? 0 : getY(d) }); var slices = wrap.select('.nv-pie').selectAll('.nv-slice') .data(pie); slices.exit().remove(); var ae = slices.enter().append('g') .attr('class', 'nv-slice') .on('mouseover', function(d,i){ d3.select(this).classed('hover', true); dispatch.elementMouseover({ label: getX(d.data), value: getY(d.data), point: d.data, pointIndex: i, pos: [d3.event.pageX, d3.event.pageY], id: id }); }) .on('mouseout', function(d,i){ d3.select(this).classed('hover', false); dispatch.elementMouseout({ label: getX(d.data), value: getY(d.data), point: d.data, index: i, id: id }); }) .on('click', function(d,i) { dispatch.elementClick({ label: getX(d.data), value: getY(d.data), point: d.data, index: i, pos: d3.event, id: id }); d3.event.stopPropagation(); }) .on('dblclick', function(d,i) { dispatch.elementDblClick({ label: getX(d.data), value: getY(d.data), point: d.data, index: i, pos: d3.event, id: id }); d3.event.stopPropagation(); }); slices .attr('fill', function(d,i) { return color(d, i); }) .attr('stroke', function(d,i) { return color(d, i); }); var paths = ae.append('path') .each(function(d) { this._current = d; }); //.attr('d', arc); d3.transition(slices.select('path')) .attr('d', arc) .attrTween('d', arcTween); if (showLabels) { // This does the normal label var labelsArc = d3.svg.arc().innerRadius(0); if (pieLabelsOutside){ labelsArc = arc; } if (donutLabelsOutside) { labelsArc = d3.svg.arc().outerRadius(arc.outerRadius()); } ae.append("g").classed("nv-label", true) .each(function(d, i) { var group = d3.select(this); group .attr('transform', function(d) { if (labelSunbeamLayout) { d.outerRadius = arcRadius + 10; // Set Outer Coordinate d.innerRadius = arcRadius + 15; // Set Inner Coordinate var rotateAngle = (d.startAngle + d.endAngle) / 2 * (180 / Math.PI); if ((d.startAngle+d.endAngle)/2 < Math.PI) { rotateAngle -= 90; } else { rotateAngle += 90; } return 'translate(' + labelsArc.centroid(d) + ') rotate(' + rotateAngle + ')'; } else { d.outerRadius = radius + 10; // Set Outer Coordinate d.innerRadius = radius + 15; // Set Inner Coordinate return 'translate(' + labelsArc.centroid(d) + ')' } }); group.append('rect') .style('stroke', '#fff') .style('fill', '#fff') .attr("rx", 3) .attr("ry", 3); group.append('text') .style('text-anchor', labelSunbeamLayout ? ((d.startAngle + d.endAngle) / 2 < Math.PI ? 'start' : 'end') : 'middle') //center the text on it's origin or begin/end if orthogonal aligned .style('fill', '#000') }); slices.select(".nv-label").transition() .attr('transform', function(d) { if (labelSunbeamLayout) { d.outerRadius = arcRadius + 10; // Set Outer Coordinate d.innerRadius = arcRadius + 15; // Set Inner Coordinate var rotateAngle = (d.startAngle + d.endAngle) / 2 * (180 / Math.PI); if ((d.startAngle+d.endAngle)/2 < Math.PI) { rotateAngle -= 90; } else { rotateAngle += 90; } return 'translate(' + labelsArc.centroid(d) + ') rotate(' + rotateAngle + ')'; } else { d.outerRadius = radius + 10; // Set Outer Coordinate d.innerRadius = radius + 15; // Set Inner Coordinate return 'translate(' + labelsArc.centroid(d) + ')' } }); slices.each(function(d, i) { var slice = d3.select(this); slice .select(".nv-label text") .style('text-anchor', labelSunbeamLayout ? ((d.startAngle + d.endAngle) / 2 < Math.PI ? 'start' : 'end') : 'middle') //center the text on it's origin or begin/end if orthogonal aligned .text(function(d, i) { var percent = (d.endAngle - d.startAngle) / (2 * Math.PI); return (d.value && percent > labelThreshold) ? getX(d.data) : ''; }); var textBox = slice.select('text').node().getBBox(); slice.select(".nv-label rect") .attr("width", textBox.width + 10) .attr("height", textBox.height + 10) .attr("transform", function() { return "translate(" + [textBox.x - 5, textBox.y - 5] + ")"; }); }); } // Computes the angle of an arc, converting from radians to degrees. function angle(d) { var a = (d.startAngle + d.endAngle) * 90 / Math.PI - 90; return a > 90 ? a - 180 : a; } function arcTween(a) { a.endAngle = isNaN(a.endAngle) ? 0 : a.endAngle; a.startAngle = isNaN(a.startAngle) ? 0 : a.startAngle; if (!donut) a.innerRadius = 0; var i = d3.interpolate(this._current, a); this._current = i(0); return function(t) { return arc(i(t)); }; } function tweenPie(b) { b.innerRadius = 0; var i = d3.interpolate({startAngle: 0, endAngle: 0}, b); return function(t) { return arc(i(t)); }; } }); return chart; } //============================================================ // Expose Public Variables //------------------------------------------------------------ chart.dispatch = dispatch; chart.margin = function(_) { if (!arguments.length) return margin; margin.top = typeof _.top != 'undefined' ? _.top : margin.top; margin.right = typeof _.right != 'undefined' ? _.right : margin.right; margin.bottom = typeof _.bottom != 'undefined' ? _.bottom : margin.bottom; margin.left = typeof _.left != 'undefined' ? _.left : margin.left; return chart; }; chart.width = function(_) { if (!arguments.length) return width; width = _; return chart; }; chart.height = function(_) { if (!arguments.length) return height; height = _; return chart; }; chart.values = function(_) { if (!arguments.length) return getValues; getValues = _; return chart; }; chart.x = function(_) { if (!arguments.length) return getX; getX = _; return chart; }; chart.y = function(_) { if (!arguments.length) return getY; getY = d3.functor(_); return chart; }; chart.description = function(_) { if (!arguments.length) return getDescription; getDescription = _; return chart; }; chart.showLabels = function(_) { if (!arguments.length) return showLabels; showLabels = _; return chart; }; chart.labelSunbeamLayout = function(_) { if (!arguments.length) return labelSunbeamLayout; labelSunbeamLayout = _; return chart; }; chart.donutLabelsOutside = function(_) { if (!arguments.length) return donutLabelsOutside; donutLabelsOutside = _; return chart; }; chart.pieLabelsOutside = function(_) { if (!arguments.length) return pieLabelsOutside; pieLabelsOutside = _; return chart; }; chart.donut = function(_) { if (!arguments.length) return donut; donut = _; return chart; }; chart.donutRatio = function(_) { if (!arguments.length) return donutRatio; donutRatio = _; return chart; }; chart.startAngle = function(_) { if (!arguments.length) return startAngle; startAngle = _; return chart; }; chart.endAngle = function(_) { if (!arguments.length) return endAngle; endAngle = _; return chart; }; chart.id = function(_) { if (!arguments.length) return id; id = _; return chart; }; chart.color = function(_) { if (!arguments.length) return color; color = nv.utils.getColor(_); return chart; }; chart.valueFormat = function(_) { if (!arguments.length) return valueFormat; valueFormat = _; return chart; }; chart.labelThreshold = function(_) { if (!arguments.length) return labelThreshold; labelThreshold = _; return chart; }; //============================================================ return chart; } nv.models.pieChart = function() { //============================================================ // Public Variables with Default Settings //------------------------------------------------------------ var pie = nv.models.pie() , legend = nv.models.legend() ; var margin = {top: 30, right: 20, bottom: 20, left: 20} , width = null , height = null , showLegend = true , color = nv.utils.defaultColor() , tooltips = true , tooltip = function(key, y, e, graph) { return '

    ' + key + '

    ' + '

    ' + y + '

    ' } , state = {} , defaultState = null , noData = "No Data Available." , dispatch = d3.dispatch('tooltipShow', 'tooltipHide', 'stateChange', 'changeState') ; //============================================================ //============================================================ // Private Variables //------------------------------------------------------------ var showTooltip = function(e, offsetElement) { var tooltipLabel = pie.description()(e.point) || pie.x()(e.point) var left = e.pos[0] + ( (offsetElement && offsetElement.offsetLeft) || 0 ), top = e.pos[1] + ( (offsetElement && offsetElement.offsetTop) || 0), y = pie.valueFormat()(pie.y()(e.point)), content = tooltip(tooltipLabel, y, e, chart); nv.tooltip.show([left, top], content, e.value < 0 ? 'n' : 's', null, offsetElement); }; //============================================================ function chart(selection) { selection.each(function(data) { var container = d3.select(this), that = this; var availableWidth = (width || parseInt(container.style('width')) || 960) - margin.left - margin.right, availableHeight = (height || parseInt(container.style('height')) || 400) - margin.top - margin.bottom; chart.update = function() { container.transition().call(chart); }; chart.container = this; //set state.disabled state.disabled = data[0].map(function(d) { return !!d.disabled }); if (!defaultState) { var key; defaultState = {}; for (key in state) { if (state[key] instanceof Array) defaultState[key] = state[key].slice(0); else defaultState[key] = state[key]; } } //------------------------------------------------------------ // Display No Data message if there's nothing to show. if (!data[0] || !data[0].length) { var noDataText = container.selectAll('.nv-noData').data([noData]); noDataText.enter().append('text') .attr('class', 'nvd3 nv-noData') .attr('dy', '-.7em') .style('text-anchor', 'middle'); noDataText .attr('x', margin.left + availableWidth / 2) .attr('y', margin.top + availableHeight / 2) .text(function(d) { return d }); return chart; } else { container.selectAll('.nv-noData').remove(); } //------------------------------------------------------------ //------------------------------------------------------------ // Setup containers and skeleton of chart var wrap = container.selectAll('g.nv-wrap.nv-pieChart').data([data]); var gEnter = wrap.enter().append('g').attr('class', 'nvd3 nv-wrap nv-pieChart').append('g'); var g = wrap.select('g'); gEnter.append('g').attr('class', 'nv-pieWrap'); gEnter.append('g').attr('class', 'nv-legendWrap'); //------------------------------------------------------------ //------------------------------------------------------------ // Legend if (showLegend) { legend .width( availableWidth ) .key(pie.x()); wrap.select('.nv-legendWrap') .datum(pie.values()(data[0])) .call(legend); if ( margin.top != legend.height()) { margin.top = legend.height() + legend.legendBelowPadding();// added legend.legendBelowPadding to allow for more spacing availableHeight = (height || parseInt(container.style('height')) || 400) - margin.top - margin.bottom; } wrap.select('.nv-legendWrap') .attr('transform', 'translate(0,' + (-margin.top) +')'); } //------------------------------------------------------------ wrap.attr('transform', 'translate(' + margin.left + ',' + margin.top + ')'); //------------------------------------------------------------ // Main Chart Component(s) pie .width(availableWidth) .height(availableHeight); var pieWrap = g.select('.nv-pieWrap') .datum(data); d3.transition(pieWrap).call(pie); //------------------------------------------------------------ //============================================================ // Event Handling/Dispatching (in chart's scope) //------------------------------------------------------------ legend.dispatch.on('legendClick', function(d,i, that) { d.disabled = !d.disabled; if (!pie.values()(data[0]).filter(function(d) { return !d.disabled }).length) { pie.values()(data[0]).map(function(d) { d.disabled = false; wrap.selectAll('.nv-series').classed('disabled', false); return d; }); } state.disabled = data[0].map(function(d) { return !!d.disabled }); dispatch.stateChange(state); chart.update(); }); pie.dispatch.on('elementMouseout.tooltip', function(e) { dispatch.tooltipHide(e); }); // Update chart from a state object passed to event handler dispatch.on('changeState', function(e) { if (typeof e.disabled !== 'undefined') { data[0].forEach(function(series,i) { series.disabled = e.disabled[i]; }); state.disabled = e.disabled; } chart.update(); }); //============================================================ }); return chart; } //============================================================ // Event Handling/Dispatching (out of chart's scope) //------------------------------------------------------------ pie.dispatch.on('elementMouseover.tooltip', function(e) { e.pos = [e.pos[0] + margin.left, e.pos[1] + margin.top]; dispatch.tooltipShow(e); }); dispatch.on('tooltipShow', function(e) { if (tooltips) showTooltip(e); }); dispatch.on('tooltipHide', function() { if (tooltips) nv.tooltip.cleanup(); }); //============================================================ //============================================================ // Expose Public Variables //------------------------------------------------------------ // expose chart's sub-components chart.legend = legend; chart.dispatch = dispatch; chart.pie = pie; d3.rebind(chart, pie, 'valueFormat', 'values', 'x', 'y', 'description', 'id', 'showLabels', 'donutLabelsOutside', 'pieLabelsOutside', 'donut', 'donutRatio', 'labelThreshold'); chart.margin = function(_) { if (!arguments.length) return margin; margin.top = typeof _.top != 'undefined' ? _.top : margin.top; margin.right = typeof _.right != 'undefined' ? _.right : margin.right; margin.bottom = typeof _.bottom != 'undefined' ? _.bottom : margin.bottom; margin.left = typeof _.left != 'undefined' ? _.left : margin.left; return chart; }; chart.width = function(_) { if (!arguments.length) return width; width = _; return chart; }; chart.height = function(_) { if (!arguments.length) return height; height = _; return chart; }; chart.color = function(_) { if (!arguments.length) return color; color = nv.utils.getColor(_); legend.color(color); pie.color(color); return chart; }; chart.showLegend = function(_) { if (!arguments.length) return showLegend; showLegend = _; return chart; }; chart.tooltips = function(_) { if (!arguments.length) return tooltips; tooltips = _; return chart; }; chart.tooltipContent = function(_) { if (!arguments.length) return tooltip; tooltip = _; return chart; }; chart.state = function(_) { if (!arguments.length) return state; state = _; return chart; }; chart.defaultState = function(_) { if (!arguments.length) return defaultState; defaultState = _; return chart; }; chart.noData = function(_) { if (!arguments.length) return noData; noData = _; return chart; }; //============================================================ return chart; } nv.models.scatter = function() { //============================================================ // Public Variables with Default Settings //------------------------------------------------------------ var margin = {top: 0, right: 0, bottom: 0, left: 0} , width = 960 , height = 500 , color = nv.utils.defaultColor() // chooses color , id = Math.floor(Math.random() * 100000) //Create semi-unique ID incase user doesn't select one , x = d3.scale.linear() , y = d3.scale.linear() , z = d3.scale.linear() //linear because d3.svg.shape.size is treated as area , getX = function(d) { return d.x } // accessor to get the x value , getY = function(d) { return d.y } // accessor to get the y value , getSize = function(d) { return d.size || 1} // accessor to get the point size , getShape = function(d) { return d.shape || 'circle' } // accessor to get point shape , onlyCircles = true // Set to false to use shapes , forceX = [] // List of numbers to Force into the X scale (ie. 0, or a max / min, etc.) , forceY = [] // List of numbers to Force into the Y scale , forceSize = [] // List of numbers to Force into the Size scale , interactive = true // If true, plots a voronoi overlay for advanced point intersection , pointKey = null , pointActive = function(d) { return !d.notActive } // any points that return false will be filtered out , padData = false // If true, adds half a data points width to front and back, for lining up a line chart with a bar chart , padDataOuter = .1 //outerPadding to imitate ordinal scale outer padding , clipEdge = false // if true, masks points within x and y scale , clipVoronoi = true // if true, masks each point with a circle... can turn off to slightly increase performance , clipRadius = function() { return 25 } // function to get the radius for voronoi point clips , xDomain = null // Override x domain (skips the calculation from data) , yDomain = null // Override y domain , sizeDomain = null // Override point size domain , sizeRange = null , singlePoint = false , dispatch = d3.dispatch('elementClick', 'elementMouseover', 'elementMouseout') , useVoronoi = true ; //============================================================ //============================================================ // Private Variables //------------------------------------------------------------ var x0, y0, z0 // used to store previous scales , timeoutID , needsUpdate = false // Flag for when the points are visually updating, but the interactive layer is behind, to disable tooltips ; //============================================================ function chart(selection) { selection.each(function(data) { var availableWidth = width - margin.left - margin.right, availableHeight = height - margin.top - margin.bottom, container = d3.select(this); //add series index to each data point for reference data = data.map(function(series, i) { series.values = series.values.map(function(point) { point.series = i; return point; }); return series; }); //------------------------------------------------------------ // Setup Scales // remap and flatten the data for use in calculating the scales' domains var seriesData = (xDomain && yDomain && sizeDomain) ? [] : // if we know xDomain and yDomain and sizeDomain, no need to calculate.... if Size is constant remember to set sizeDomain to speed up performance d3.merge( data.map(function(d) { return d.values.map(function(d,i) { return { x: getX(d,i), y: getY(d,i), size: getSize(d,i) } }) }) ); x .domain(xDomain || d3.extent(seriesData.map(function(d) { return d.x; }).concat(forceX))) if (padData && data[0]) x.range([(availableWidth * padDataOuter + availableWidth) / (2 *data[0].values.length), availableWidth - availableWidth * (1 + padDataOuter) / (2 * data[0].values.length) ]); //x.range([availableWidth * .5 / data[0].values.length, availableWidth * (data[0].values.length - .5) / data[0].values.length ]); else x.range([0, availableWidth]); y .domain(yDomain || d3.extent(seriesData.map(function(d) { return d.y }).concat(forceY))) .range([availableHeight, 0]); z .domain(sizeDomain || d3.extent(seriesData.map(function(d) { return d.size }).concat(forceSize))) .range(sizeRange || [16, 256]); // If scale's domain don't have a range, slightly adjust to make one... so a chart can show a single data point if (x.domain()[0] === x.domain()[1] || y.domain()[0] === y.domain()[1]) singlePoint = true; if (x.domain()[0] === x.domain()[1]) x.domain()[0] ? x.domain([x.domain()[0] - x.domain()[0] * 0.01, x.domain()[1] + x.domain()[1] * 0.01]) : x.domain([-1,1]); if (y.domain()[0] === y.domain()[1]) y.domain()[0] ? y.domain([y.domain()[0] + y.domain()[0] * 0.01, y.domain()[1] - y.domain()[1] * 0.01]) : y.domain([-1,1]); if ( isNaN(x.domain()[0])) { x.domain([-1,1]); } if ( isNaN(y.domain()[0])) { y.domain([-1,1]); } x0 = x0 || x; y0 = y0 || y; z0 = z0 || z; //------------------------------------------------------------ //------------------------------------------------------------ // Setup containers and skeleton of chart var wrap = container.selectAll('g.nv-wrap.nv-scatter').data([data]); var wrapEnter = wrap.enter().append('g').attr('class', 'nvd3 nv-wrap nv-scatter nv-chart-' + id + (singlePoint ? ' nv-single-point' : '')); var defsEnter = wrapEnter.append('defs'); var gEnter = wrapEnter.append('g'); var g = wrap.select('g'); gEnter.append('g').attr('class', 'nv-groups'); gEnter.append('g').attr('class', 'nv-point-paths'); wrap.attr('transform', 'translate(' + margin.left + ',' + margin.top + ')'); //------------------------------------------------------------ defsEnter.append('clipPath') .attr('id', 'nv-edge-clip-' + id) .append('rect'); wrap.select('#nv-edge-clip-' + id + ' rect') .attr('width', availableWidth) .attr('height', availableHeight); g .attr('clip-path', clipEdge ? 'url(#nv-edge-clip-' + id + ')' : ''); function updateInteractiveLayer() { if (!interactive) return false; var eventElements; var vertices = d3.merge(data.map(function(group, groupIndex) { return group.values .map(function(point, pointIndex) { // *Adding noise to make duplicates very unlikely // *Injecting series and point index for reference /* *Adding a 'jitter' to the points, because there's an issue in d3.geom.voronoi. */ var pX = getX(point,pointIndex) + Math.random() * 1e-7; var pY = getY(point,pointIndex) + Math.random() * 1e-7; return [x(pX), y(pY), groupIndex, pointIndex, point]; //temp hack to add noise untill I think of a better way so there are no duplicates }) .filter(function(pointArray, pointIndex) { return pointActive(pointArray[4], pointIndex); // Issue #237.. move filter to after map, so pointIndex is correct! }) }) ); //inject series and point index for reference into voronoi if (useVoronoi === true) { if (clipVoronoi) { var pointClipsEnter = wrap.select('defs').selectAll('.nv-point-clips') .data([id]) .enter(); pointClipsEnter.append('clipPath') .attr('class', 'nv-point-clips') .attr('id', 'nv-points-clip-' + id); var pointClips = wrap.select('#nv-points-clip-' + id).selectAll('circle') .data(vertices); pointClips.enter().append('circle') .attr('r', clipRadius); pointClips.exit().remove(); pointClips .attr('cx', function(d) { return d[0] }) .attr('cy', function(d) { return d[1] }); wrap.select('.nv-point-paths') .attr('clip-path', 'url(#nv-points-clip-' + id + ')'); } if(vertices.length) { // Issue #283 - Adding 2 dummy points to the voronoi b/c voronoi requires min 3 points to work vertices.push([x.range()[0] - 20, y.range()[0] - 20, null, null]); vertices.push([x.range()[1] + 20, y.range()[1] + 20, null, null]); vertices.push([x.range()[0] - 20, y.range()[0] + 20, null, null]); vertices.push([x.range()[1] + 20, y.range()[1] - 20, null, null]); } var bounds = d3.geom.polygon([ [-10,-10], [-10,height + 10], [width + 10,height + 10], [width + 10,-10] ]); var voronoi = d3.geom.voronoi(vertices).map(function(d, i) { return { 'data': bounds.clip(d), 'series': vertices[i][2], 'point': vertices[i][3] } }); var pointPaths = wrap.select('.nv-point-paths').selectAll('path') .data(voronoi); pointPaths.enter().append('path') .attr('class', function(d,i) { return 'nv-path-'+i; }); pointPaths.exit().remove(); pointPaths .attr('d', function(d) { if (d.data.length === 0) return 'M 0 0' else return 'M' + d.data.join('L') + 'Z'; }); pointPaths .on('click', function(d) { if (needsUpdate) return 0; var series = data[d.series], point = series.values[d.point]; dispatch.elementClick({ point: point, series: series, pos: [x(getX(point, d.point)) + margin.left, y(getY(point, d.point)) + margin.top], seriesIndex: d.series, pointIndex: d.point }); }) .on('mouseover', function(d) { if (needsUpdate) return 0; var series = data[d.series], point = series.values[d.point]; dispatch.elementMouseover({ point: point, series: series, pos: [x(getX(point, d.point)) + margin.left, y(getY(point, d.point)) + margin.top], seriesIndex: d.series, pointIndex: d.point }); }) .on('mouseout', function(d, i) { if (needsUpdate) return 0; var series = data[d.series], point = series.values[d.point]; dispatch.elementMouseout({ point: point, series: series, seriesIndex: d.series, pointIndex: d.point }); }); } else { /* // bring data in form needed for click handlers var dataWithPoints = vertices.map(function(d, i) { return { 'data': d, 'series': vertices[i][2], 'point': vertices[i][3] } }); */ // add event handlers to points instead voronoi paths wrap.select('.nv-groups').selectAll('.nv-group') .selectAll('.nv-point') //.data(dataWithPoints) //.style('pointer-events', 'auto') // recativate events, disabled by css .on('click', function(d,i) { //nv.log('test', d, i); if (needsUpdate || !data[d.series]) return 0; //check if this is a dummy point var series = data[d.series], point = series.values[i]; dispatch.elementClick({ point: point, series: series, pos: [x(getX(point, i)) + margin.left, y(getY(point, i)) + margin.top], seriesIndex: d.series, pointIndex: i }); }) .on('mouseover', function(d,i) { if (needsUpdate || !data[d.series]) return 0; //check if this is a dummy point var series = data[d.series], point = series.values[i]; dispatch.elementMouseover({ point: point, series: series, pos: [x(getX(point, i)) + margin.left, y(getY(point, i)) + margin.top], seriesIndex: d.series, pointIndex: i }); }) .on('mouseout', function(d,i) { if (needsUpdate || !data[d.series]) return 0; //check if this is a dummy point var series = data[d.series], point = series.values[i]; dispatch.elementMouseout({ point: point, series: series, seriesIndex: d.series, pointIndex: i }); }); } needsUpdate = false; } needsUpdate = true; var groups = wrap.select('.nv-groups').selectAll('.nv-group') .data(function(d) { return d }, function(d) { return d.key }); groups.enter().append('g') .style('stroke-opacity', 1e-6) .style('fill-opacity', 1e-6); d3.transition(groups.exit()) .style('stroke-opacity', 1e-6) .style('fill-opacity', 1e-6) .remove(); groups .attr('class', function(d,i) { return 'nv-group nv-series-' + i }) .classed('hover', function(d) { return d.hover }); d3.transition(groups) .style('fill', function(d,i) { return color(d, i) }) .style('stroke', function(d,i) { return color(d, i) }) .style('stroke-opacity', 1) .style('fill-opacity', .5); if (onlyCircles) { var points = groups.selectAll('circle.nv-point') .data(function(d) { return d.values }, pointKey); points.enter().append('circle') .attr('cx', function(d,i) { return x0(getX(d,i)) }) .attr('cy', function(d,i) { return y0(getY(d,i)) }) .attr('r', function(d,i) { return Math.sqrt(z(getSize(d,i))/Math.PI) }); points.exit().remove(); groups.exit().selectAll('path.nv-point').transition() .attr('cx', function(d,i) { return x(getX(d,i)) }) .attr('cy', function(d,i) { return y(getY(d,i)) }) .remove(); points.each(function(d,i) { d3.select(this) .classed('nv-point', true) .classed('nv-point-' + i, true); }); points.transition() .attr('cx', function(d,i) { return x(getX(d,i)) }) .attr('cy', function(d,i) { return y(getY(d,i)) }) .attr('r', function(d,i) { return Math.sqrt(z(getSize(d,i))/Math.PI) }); } else { var points = groups.selectAll('path.nv-point') .data(function(d) { return d.values }); points.enter().append('path') .attr('transform', function(d,i) { return 'translate(' + x0(getX(d,i)) + ',' + y0(getY(d,i)) + ')' }) .attr('d', d3.svg.symbol() .type(getShape) .size(function(d,i) { return z(getSize(d,i)) }) ); points.exit().remove(); d3.transition(groups.exit().selectAll('path.nv-point')) .attr('transform', function(d,i) { return 'translate(' + x(getX(d,i)) + ',' + y(getY(d,i)) + ')' }) .remove(); points.each(function(d,i) { d3.select(this) .classed('nv-point', true) .classed('nv-point-' + i, true); }); points.transition() .attr('transform', function(d,i) { //nv.log(d,i,getX(d,i), x(getX(d,i))); return 'translate(' + x(getX(d,i)) + ',' + y(getY(d,i)) + ')' }) .attr('d', d3.svg.symbol() .type(getShape) .size(function(d,i) { return z(getSize(d,i)) }) ); } // Delay updating the invisible interactive layer for smoother animation clearTimeout(timeoutID); // stop repeat calls to updateInteractiveLayer timeoutID = setTimeout(updateInteractiveLayer, 300); //updateInteractiveLayer(); //store old scales for use in transitions on update x0 = x.copy(); y0 = y.copy(); z0 = z.copy(); }); return chart; } //============================================================ // Event Handling/Dispatching (out of chart's scope) //------------------------------------------------------------ dispatch.on('elementMouseover.point', function(d) { if (interactive) d3.select('.nv-chart-' + id + ' .nv-series-' + d.seriesIndex + ' .nv-point-' + d.pointIndex) .classed('hover', true); }); dispatch.on('elementMouseout.point', function(d) { if (interactive) d3.select('.nv-chart-' + id + ' .nv-series-' + d.seriesIndex + ' .nv-point-' + d.pointIndex) .classed('hover', false); }); //============================================================ //============================================================ // Expose Public Variables //------------------------------------------------------------ chart.dispatch = dispatch; chart.x = function(_) { if (!arguments.length) return getX; getX = d3.functor(_); return chart; }; chart.y = function(_) { if (!arguments.length) return getY; getY = d3.functor(_); return chart; }; chart.size = function(_) { if (!arguments.length) return getSize; getSize = d3.functor(_); return chart; }; chart.margin = function(_) { if (!arguments.length) return margin; margin.top = typeof _.top != 'undefined' ? _.top : margin.top; margin.right = typeof _.right != 'undefined' ? _.right : margin.right; margin.bottom = typeof _.bottom != 'undefined' ? _.bottom : margin.bottom; margin.left = typeof _.left != 'undefined' ? _.left : margin.left; return chart; }; chart.width = function(_) { if (!arguments.length) return width; width = _; return chart; }; chart.height = function(_) { if (!arguments.length) return height; height = _; return chart; }; chart.xScale = function(_) { if (!arguments.length) return x; x = _; return chart; }; chart.yScale = function(_) { if (!arguments.length) return y; y = _; return chart; }; chart.zScale = function(_) { if (!arguments.length) return z; z = _; return chart; }; chart.xDomain = function(_) { if (!arguments.length) return xDomain; xDomain = _; return chart; }; chart.yDomain = function(_) { if (!arguments.length) return yDomain; yDomain = _; return chart; }; chart.sizeDomain = function(_) { if (!arguments.length) return sizeDomain; sizeDomain = _; return chart; }; chart.sizeRange = function(_) { if (!arguments.length) return sizeRange; sizeRange = _; return chart; }; chart.forceX = function(_) { if (!arguments.length) return forceX; forceX = _; return chart; }; chart.forceY = function(_) { if (!arguments.length) return forceY; forceY = _; return chart; }; chart.forceSize = function(_) { if (!arguments.length) return forceSize; forceSize = _; return chart; }; chart.interactive = function(_) { if (!arguments.length) return interactive; interactive = _; return chart; }; chart.pointKey = function(_) { if (!arguments.length) return pointKey; pointKey = _; return chart; }; chart.pointActive = function(_) { if (!arguments.length) return pointActive; pointActive = _; return chart; }; chart.padData = function(_) { if (!arguments.length) return padData; padData = _; return chart; }; chart.padDataOuter = function(_) { if (!arguments.length) return padDataOuter; padDataOuter = _; return chart; }; chart.clipEdge = function(_) { if (!arguments.length) return clipEdge; clipEdge = _; return chart; }; chart.clipVoronoi= function(_) { if (!arguments.length) return clipVoronoi; clipVoronoi = _; return chart; }; chart.useVoronoi= function(_) { if (!arguments.length) return useVoronoi; useVoronoi = _; if (useVoronoi === false) { clipVoronoi = false; } return chart; }; chart.clipRadius = function(_) { if (!arguments.length) return clipRadius; clipRadius = _; return chart; }; chart.color = function(_) { if (!arguments.length) return color; color = nv.utils.getColor(_); return chart; }; chart.shape = function(_) { if (!arguments.length) return getShape; getShape = _; return chart; }; chart.onlyCircles = function(_) { if (!arguments.length) return onlyCircles; onlyCircles = _; return chart; }; chart.id = function(_) { if (!arguments.length) return id; id = _; return chart; }; chart.singlePoint = function(_) { if (!arguments.length) return singlePoint; singlePoint = _; return chart; }; //============================================================ return chart; } nv.models.scatterChart = function() { //============================================================ // Public Variables with Default Settings //------------------------------------------------------------ var scatter = nv.models.scatter() , xAxis = nv.models.axis() , yAxis = nv.models.axis() , legend = nv.models.legend() , controls = nv.models.legend() , distX = nv.models.distribution() , distY = nv.models.distribution() ; var margin = {top: 30, right: 20, bottom: 50, left: 75} , width = null , height = null , color = nv.utils.defaultColor() , x = d3.fisheye ? d3.fisheye.scale(d3.scale.linear).distortion(0) : scatter.xScale() , y = d3.fisheye ? d3.fisheye.scale(d3.scale.linear).distortion(0) : scatter.yScale() , xPadding = 0 , yPadding = 0 , showDistX = false , showDistY = false , showLegend = true , showControls = !!d3.fisheye , fisheye = 0 , pauseFisheye = false , tooltips = true , tooltipX = function(key, x, y) { return '' + x + '' } , tooltipY = function(key, x, y) { return '' + y + '' } //, tooltip = function(key, x, y) { return '

    ' + key + '

    ' } , tooltip = null , state = {} , defaultState = null , dispatch = d3.dispatch('tooltipShow', 'tooltipHide', 'stateChange', 'changeState') , noData = "No Data Available." ; scatter .xScale(x) .yScale(y) ; xAxis .orient('bottom') .tickPadding(10) ; yAxis .orient('left') .tickPadding(10) ; distX .axis('x') ; distY .axis('y') ; //============================================================ //============================================================ // Private Variables //------------------------------------------------------------ var x0, y0; var showTooltip = function(e, offsetElement) { //TODO: make tooltip style an option between single or dual on axes (maybe on all charts with axes?) var left = e.pos[0] + ( offsetElement.offsetLeft || 0 ), top = e.pos[1] + ( offsetElement.offsetTop || 0), leftX = e.pos[0] + ( offsetElement.offsetLeft || 0 ), topX = y.range()[0] + margin.top + ( offsetElement.offsetTop || 0), leftY = x.range()[0] + margin.left + ( offsetElement.offsetLeft || 0 ), topY = e.pos[1] + ( offsetElement.offsetTop || 0), xVal = xAxis.tickFormat()(scatter.x()(e.point, e.pointIndex)), yVal = yAxis.tickFormat()(scatter.y()(e.point, e.pointIndex)); if( tooltipX != null ) nv.tooltip.show([leftX, topX], tooltipX(e.series.key, xVal, yVal, e, chart), 'n', 1, offsetElement, 'x-nvtooltip'); if( tooltipY != null ) nv.tooltip.show([leftY, topY], tooltipY(e.series.key, xVal, yVal, e, chart), 'e', 1, offsetElement, 'y-nvtooltip'); if( tooltip != null ) nv.tooltip.show([left, top], tooltip(e.series.key, xVal, yVal, e, chart), e.value < 0 ? 'n' : 's', null, offsetElement); }; var controlsData = [ { key: 'Magnify', disabled: true } ]; //============================================================ function chart(selection) { selection.each(function(data) { var container = d3.select(this), that = this; var availableWidth = (width || parseInt(container.style('width')) || 960) - margin.left - margin.right, availableHeight = (height || parseInt(container.style('height')) || 400) - margin.top - margin.bottom; chart.update = function() { container.transition().call(chart); }; // chart.container = this; //set state.disabled state.disabled = data.map(function(d) { return !!d.disabled }); if (!defaultState) { var key; defaultState = {}; for (key in state) { if (state[key] instanceof Array) defaultState[key] = state[key].slice(0); else defaultState[key] = state[key]; } } //------------------------------------------------------------ // Display noData message if there's nothing to show. if (!data || !data.length || !data.filter(function(d) { return d.values.length }).length) { var noDataText = container.selectAll('.nv-noData').data([noData]); noDataText.enter().append('text') .attr('class', 'nvd3 nv-noData') .attr('dy', '-.7em') .style('text-anchor', 'middle'); noDataText .attr('x', margin.left + availableWidth / 2) .attr('y', margin.top + availableHeight / 2) .text(function(d) { return d }); return chart; } else { container.selectAll('.nv-noData').remove(); } //------------------------------------------------------------ //------------------------------------------------------------ // Setup Scales x0 = x0 || x; y0 = y0 || y; //------------------------------------------------------------ //------------------------------------------------------------ // Setup containers and skeleton of chart var wrap = container.selectAll('g.nv-wrap.nv-scatterChart').data([data]); var wrapEnter = wrap.enter().append('g').attr('class', 'nvd3 nv-wrap nv-scatterChart nv-chart-' + scatter.id()); var gEnter = wrapEnter.append('g'); var g = wrap.select('g'); // background for pointer events gEnter.append('rect').attr('class', 'nvd3 nv-background'); gEnter.append('g').attr('class', 'nv-x nv-axis'); gEnter.append('g').attr('class', 'nv-y nv-axis'); gEnter.append('g').attr('class', 'nv-scatterWrap'); gEnter.append('g').attr('class', 'nv-distWrap'); gEnter.append('g').attr('class', 'nv-legendWrap'); gEnter.append('g').attr('class', 'nv-controlsWrap'); //------------------------------------------------------------ //------------------------------------------------------------ // Legend if (showLegend) { legend.width( availableWidth / 2 ); wrap.select('.nv-legendWrap') .datum(data) .call(legend); if ( margin.top != legend.height()) { margin.top = legend.height() + legend.legendBelowPadding();// added legend.legendBelowPadding to allow for more spacing availableHeight = (height || parseInt(container.style('height')) || 400) - margin.top - margin.bottom; } wrap.select('.nv-legendWrap') .attr('transform', 'translate(' + (availableWidth / 2) + ',' + (-margin.top) +')'); } //------------------------------------------------------------ //------------------------------------------------------------ // Controls if (showControls) { controls.width(180).color(['#444']); g.select('.nv-controlsWrap') .datum(controlsData) .attr('transform', 'translate(0,' + (-margin.top) +')') .call(controls); } //------------------------------------------------------------ wrap.attr('transform', 'translate(' + margin.left + ',' + margin.top + ')'); //------------------------------------------------------------ // Main Chart Component(s) scatter .width(availableWidth) .height(availableHeight) .color(data.map(function(d,i) { return d.color || color(d, i); }).filter(function(d,i) { return !data[i].disabled })) .xDomain(null) .yDomain(null) wrap.select('.nv-scatterWrap') .datum(data.filter(function(d) { return !d.disabled })) .call(scatter); //Adjust for x and y padding if (xPadding) { var xRange = x.domain()[1] - x.domain()[0]; scatter.xDomain([x.domain()[0] - (xPadding * xRange), x.domain()[1] + (xPadding * xRange)]); } if (yPadding) { var yRange = y.domain()[1] - y.domain()[0]; scatter.yDomain([y.domain()[0] - (yPadding * yRange), y.domain()[1] + (yPadding * yRange)]); } wrap.select('.nv-scatterWrap') .datum(data.filter(function(d) { return !d.disabled })) .call(scatter); //------------------------------------------------------------ //------------------------------------------------------------ // Setup Axes xAxis .scale(x) .ticks( xAxis.ticks() && xAxis.ticks().length ? xAxis.ticks() : availableWidth / 100 ) .tickSize( -availableHeight , 0); g.select('.nv-x.nv-axis') .attr('transform', 'translate(0,' + y.range()[0] + ')') .call(xAxis); yAxis .scale(y) .ticks( yAxis.ticks() && yAxis.ticks().length ? yAxis.ticks() : availableHeight / 36 ) .tickSize( -availableWidth, 0); g.select('.nv-y.nv-axis') .call(yAxis); if (showDistX) { distX .getData(scatter.x()) .scale(x) .width(availableWidth) .color(data.map(function(d,i) { return d.color || color(d, i); }).filter(function(d,i) { return !data[i].disabled })); gEnter.select('.nv-distWrap').append('g') .attr('class', 'nv-distributionX'); g.select('.nv-distributionX') .attr('transform', 'translate(0,' + y.range()[0] + ')') .datum(data.filter(function(d) { return !d.disabled })) .call(distX); } if (showDistY) { distY .getData(scatter.y()) .scale(y) .width(availableHeight) .color(data.map(function(d,i) { return d.color || color(d, i); }).filter(function(d,i) { return !data[i].disabled })); gEnter.select('.nv-distWrap').append('g') .attr('class', 'nv-distributionY'); g.select('.nv-distributionY') .attr('transform', 'translate(-' + distY.size() + ',0)') .datum(data.filter(function(d) { return !d.disabled })) .call(distY); } //------------------------------------------------------------ if (d3.fisheye) { g.select('.nv-background') .attr('width', availableWidth) .attr('height', availableHeight); g.select('.nv-background').on('mousemove', updateFisheye); g.select('.nv-background').on('click', function() { pauseFisheye = !pauseFisheye;}); scatter.dispatch.on('elementClick.freezeFisheye', function() { pauseFisheye = !pauseFisheye; }); } function updateFisheye() { if (pauseFisheye) { g.select('.nv-point-paths').style('pointer-events', 'all'); return false; } g.select('.nv-point-paths').style('pointer-events', 'none' ); var mouse = d3.mouse(this); x.distortion(fisheye).focus(mouse[0]); y.distortion(fisheye).focus(mouse[1]); g.select('.nv-scatterWrap') .call(scatter); g.select('.nv-x.nv-axis').call(xAxis); g.select('.nv-y.nv-axis').call(yAxis); g.select('.nv-distributionX') .datum(data.filter(function(d) { return !d.disabled })) .call(distX); g.select('.nv-distributionY') .datum(data.filter(function(d) { return !d.disabled })) .call(distY); } //============================================================ // Event Handling/Dispatching (in chart's scope) //------------------------------------------------------------ controls.dispatch.on('legendClick', function(d,i) { d.disabled = !d.disabled; fisheye = d.disabled ? 0 : 2.5; g.select('.nv-background') .style('pointer-events', d.disabled ? 'none' : 'all'); g.select('.nv-point-paths').style('pointer-events', d.disabled ? 'all' : 'none' ); if (d.disabled) { x.distortion(fisheye).focus(0); y.distortion(fisheye).focus(0); g.select('.nv-scatterWrap').call(scatter); g.select('.nv-x.nv-axis').call(xAxis); g.select('.nv-y.nv-axis').call(yAxis); } else { pauseFisheye = false; } chart.update(); }); legend.dispatch.on('legendClick', function(d,i, that) { d.disabled = !d.disabled; if (!data.filter(function(d) { return !d.disabled }).length) { data.map(function(d) { d.disabled = false; wrap.selectAll('.nv-series').classed('disabled', false); return d; }); } state.disabled = data.map(function(d) { return !!d.disabled }); dispatch.stateChange(state); chart.update(); }); legend.dispatch.on('legendDblclick', function(d) { //Double clicking should always enable current series, and disabled all others. data.forEach(function(d) { d.disabled = true; }); d.disabled = false; state.disabled = data.map(function(d) { return !!d.disabled }); dispatch.stateChange(state); chart.update(); }); /* legend.dispatch.on('legendMouseover', function(d, i) { d.hover = true; chart(selection); }); legend.dispatch.on('legendMouseout', function(d, i) { d.hover = false; chart(selection); }); */ scatter.dispatch.on('elementMouseover.tooltip', function(e) { d3.select('.nv-chart-' + scatter.id() + ' .nv-series-' + e.seriesIndex + ' .nv-distx-' + e.pointIndex) .attr('y1', function(d,i) { return e.pos[1] - availableHeight;}); d3.select('.nv-chart-' + scatter.id() + ' .nv-series-' + e.seriesIndex + ' .nv-disty-' + e.pointIndex) .attr('x2', e.pos[0] + distX.size()); e.pos = [e.pos[0] + margin.left, e.pos[1] + margin.top]; dispatch.tooltipShow(e); }); dispatch.on('tooltipShow', function(e) { if (tooltips) showTooltip(e, that.parentNode); }); // Update chart from a state object passed to event handler dispatch.on('changeState', function(e) { if (typeof e.disabled !== 'undefined') { data.forEach(function(series,i) { series.disabled = e.disabled[i]; }); state.disabled = e.disabled; } chart.update(); }); //============================================================ //store old scales for use in transitions on update x0 = x.copy(); y0 = y.copy(); }); return chart; } //============================================================ // Event Handling/Dispatching (out of chart's scope) //------------------------------------------------------------ scatter.dispatch.on('elementMouseout.tooltip', function(e) { dispatch.tooltipHide(e); d3.select('.nv-chart-' + scatter.id() + ' .nv-series-' + e.seriesIndex + ' .nv-distx-' + e.pointIndex) .attr('y1', 0); d3.select('.nv-chart-' + scatter.id() + ' .nv-series-' + e.seriesIndex + ' .nv-disty-' + e.pointIndex) .attr('x2', distY.size()); }); dispatch.on('tooltipHide', function() { if (tooltips) nv.tooltip.cleanup(); }); //============================================================ //============================================================ // Expose Public Variables //------------------------------------------------------------ // expose chart's sub-components chart.dispatch = dispatch; chart.scatter = scatter; chart.legend = legend; chart.controls = controls; chart.xAxis = xAxis; chart.yAxis = yAxis; chart.distX = distX; chart.distY = distY; d3.rebind(chart, scatter, 'id', 'interactive', 'pointActive', 'x', 'y', 'shape', 'size', 'xScale', 'yScale', 'zScale', 'xDomain', 'yDomain', 'sizeDomain', 'sizeRange', 'forceX', 'forceY', 'forceSize', 'clipVoronoi', 'clipRadius', 'useVoronoi'); chart.margin = function(_) { if (!arguments.length) return margin; margin.top = typeof _.top != 'undefined' ? _.top : margin.top; margin.right = typeof _.right != 'undefined' ? _.right : margin.right; margin.bottom = typeof _.bottom != 'undefined' ? _.bottom : margin.bottom; margin.left = typeof _.left != 'undefined' ? _.left : margin.left; return chart; }; chart.width = function(_) { if (!arguments.length) return width; width = _; return chart; }; chart.height = function(_) { if (!arguments.length) return height; height = _; return chart; }; chart.color = function(_) { if (!arguments.length) return color; color = nv.utils.getColor(_); legend.color(color); distX.color(color); distY.color(color); return chart; }; chart.showDistX = function(_) { if (!arguments.length) return showDistX; showDistX = _; return chart; }; chart.showDistY = function(_) { if (!arguments.length) return showDistY; showDistY = _; return chart; }; chart.showControls = function(_) { if (!arguments.length) return showControls; showControls = _; return chart; }; chart.showLegend = function(_) { if (!arguments.length) return showLegend; showLegend = _; return chart; }; chart.fisheye = function(_) { if (!arguments.length) return fisheye; fisheye = _; return chart; }; chart.xPadding = function(_) { if (!arguments.length) return xPadding; xPadding = _; return chart; }; chart.yPadding = function(_) { if (!arguments.length) return yPadding; yPadding = _; return chart; }; chart.tooltips = function(_) { if (!arguments.length) return tooltips; tooltips = _; return chart; }; chart.tooltipContent = function(_) { if (!arguments.length) return tooltip; tooltip = _; return chart; }; chart.tooltipXContent = function(_) { if (!arguments.length) return tooltipX; tooltipX = _; return chart; }; chart.tooltipYContent = function(_) { if (!arguments.length) return tooltipY; tooltipY = _; return chart; }; chart.state = function(_) { if (!arguments.length) return state; state = _; return chart; }; chart.defaultState = function(_) { if (!arguments.length) return defaultState; defaultState = _; return chart; }; chart.noData = function(_) { if (!arguments.length) return noData; noData = _; return chart; }; //============================================================ return chart; } nv.models.scatterPlusLineChart = function() { //============================================================ // Public Variables with Default Settings //------------------------------------------------------------ var scatter = nv.models.scatter() , xAxis = nv.models.axis() , yAxis = nv.models.axis() , legend = nv.models.legend() , controls = nv.models.legend() , distX = nv.models.distribution() , distY = nv.models.distribution() ; var margin = {top: 30, right: 20, bottom: 50, left: 75} , width = null , height = null , color = nv.utils.defaultColor() , x = d3.fisheye ? d3.fisheye.scale(d3.scale.linear).distortion(0) : scatter.xScale() , y = d3.fisheye ? d3.fisheye.scale(d3.scale.linear).distortion(0) : scatter.yScale() , showDistX = false , showDistY = false , showLegend = true , showControls = !!d3.fisheye , fisheye = 0 , pauseFisheye = false , tooltips = true , tooltipX = function(key, x, y) { return '' + x + '' } , tooltipY = function(key, x, y) { return '' + y + '' } , tooltip = function(key, x, y, date) { return '

    ' + key + '

    ' + '

    ' + date + '

    ' } //, tooltip = null , state = {} , defaultState = null , dispatch = d3.dispatch('tooltipShow', 'tooltipHide', 'stateChange', 'changeState') , noData = "No Data Available." ; scatter .xScale(x) .yScale(y) ; xAxis .orient('bottom') .tickPadding(10) ; yAxis .orient('left') .tickPadding(10) ; distX .axis('x') ; distY .axis('y') ; //============================================================ //============================================================ // Private Variables //------------------------------------------------------------ var x0, y0; var showTooltip = function(e, offsetElement) { //TODO: make tooltip style an option between single or dual on axes (maybe on all charts with axes?) var left = e.pos[0] + ( offsetElement.offsetLeft || 0 ), top = e.pos[1] + ( offsetElement.offsetTop || 0), leftX = e.pos[0] + ( offsetElement.offsetLeft || 0 ), topX = y.range()[0] + margin.top + ( offsetElement.offsetTop || 0), leftY = x.range()[0] + margin.left + ( offsetElement.offsetLeft || 0 ), topY = e.pos[1] + ( offsetElement.offsetTop || 0), xVal = xAxis.tickFormat()(scatter.x()(e.point, e.pointIndex)), yVal = yAxis.tickFormat()(scatter.y()(e.point, e.pointIndex)); if( tooltipX != null ) nv.tooltip.show([leftX, topX], tooltipX(e.series.key, xVal, yVal, e, chart), 'n', 1, offsetElement, 'x-nvtooltip'); if( tooltipY != null ) nv.tooltip.show([leftY, topY], tooltipY(e.series.key, xVal, yVal, e, chart), 'e', 1, offsetElement, 'y-nvtooltip'); if( tooltip != null ) nv.tooltip.show([left, top], tooltip(e.series.key, xVal, yVal, e.point.tooltip, e, chart), e.value < 0 ? 'n' : 's', null, offsetElement); }; var controlsData = [ { key: 'Magnify', disabled: true } ]; //============================================================ function chart(selection) { selection.each(function(data) { var container = d3.select(this), that = this; var availableWidth = (width || parseInt(container.style('width')) || 960) - margin.left - margin.right, availableHeight = (height || parseInt(container.style('height')) || 400) - margin.top - margin.bottom; chart.update = function() { container.transition().call(chart); }; chart.container = this; //set state.disabled state.disabled = data.map(function(d) { return !!d.disabled }); if (!defaultState) { var key; defaultState = {}; for (key in state) { if (state[key] instanceof Array) defaultState[key] = state[key].slice(0); else defaultState[key] = state[key]; } } //------------------------------------------------------------ // Display noData message if there's nothing to show. if (!data || !data.length || !data.filter(function(d) { return d.values.length }).length) { var noDataText = container.selectAll('.nv-noData').data([noData]); noDataText.enter().append('text') .attr('class', 'nvd3 nv-noData') .attr('dy', '-.7em') .style('text-anchor', 'middle'); noDataText .attr('x', margin.left + availableWidth / 2) .attr('y', margin.top + availableHeight / 2) .text(function(d) { return d }); return chart; } else { container.selectAll('.nv-noData').remove(); } //------------------------------------------------------------ //------------------------------------------------------------ // Setup Scales x = scatter.xScale(); y = scatter.yScale(); x0 = x0 || x; y0 = y0 || y; //------------------------------------------------------------ //------------------------------------------------------------ // Setup containers and skeleton of chart var wrap = container.selectAll('g.nv-wrap.nv-scatterChart').data([data]); var wrapEnter = wrap.enter().append('g').attr('class', 'nvd3 nv-wrap nv-scatterChart nv-chart-' + scatter.id()); var gEnter = wrapEnter.append('g'); var g = wrap.select('g') // background for pointer events gEnter.append('rect').attr('class', 'nvd3 nv-background') gEnter.append('g').attr('class', 'nv-x nv-axis'); gEnter.append('g').attr('class', 'nv-y nv-axis'); gEnter.append('g').attr('class', 'nv-scatterWrap'); gEnter.append('g').attr('class', 'nv-regressionLinesWrap'); gEnter.append('g').attr('class', 'nv-distWrap'); gEnter.append('g').attr('class', 'nv-legendWrap'); gEnter.append('g').attr('class', 'nv-controlsWrap'); wrap.attr('transform', 'translate(' + margin.left + ',' + margin.top + ')'); //------------------------------------------------------------ //------------------------------------------------------------ // Legend if (showLegend) { legend.width( availableWidth / 2 ); wrap.select('.nv-legendWrap') .datum(data) .call(legend); if ( margin.top != legend.height()) { margin.top = legend.height() + legend.legendBelowPadding();// added legend.legendBelowPadding to allow for more spacing availableHeight = (height || parseInt(container.style('height')) || 400) - margin.top - margin.bottom; } wrap.select('.nv-legendWrap') .attr('transform', 'translate(' + (availableWidth / 2) + ',' + (-margin.top) +')'); } //------------------------------------------------------------ //------------------------------------------------------------ // Controls if (showControls) { controls.width(180).color(['#444']); g.select('.nv-controlsWrap') .datum(controlsData) .attr('transform', 'translate(0,' + (-margin.top) +')') .call(controls); } //------------------------------------------------------------ //------------------------------------------------------------ // Main Chart Component(s) scatter .width(availableWidth) .height(availableHeight) .color(data.map(function(d,i) { return d.color || color(d, i); }).filter(function(d,i) { return !data[i].disabled })) wrap.select('.nv-scatterWrap') .datum(data.filter(function(d) { return !d.disabled })) .call(scatter); wrap.select('.nv-regressionLinesWrap') .attr('clip-path', 'url(#nv-edge-clip-' + scatter.id() + ')'); var regWrap = wrap.select('.nv-regressionLinesWrap').selectAll('.nv-regLines') .data(function(d) { return d }); var reglines = regWrap.enter() .append('g').attr('class', 'nv-regLines') .append('line').attr('class', 'nv-regLine') .style('stroke-opacity', 0); //d3.transition(regWrap.selectAll('.nv-regLines line')) regWrap.selectAll('.nv-regLines line') .attr('x1', x.range()[0]) .attr('x2', x.range()[1]) .attr('y1', function(d,i) { return y(x.domain()[0] * d.slope + d.intercept) }) .attr('y2', function(d,i) { return y(x.domain()[1] * d.slope + d.intercept) }) .style('stroke', function(d,i,j) { return color(d,j) }) .style('stroke-opacity', function(d,i) { return (d.disabled || typeof d.slope === 'undefined' || typeof d.intercept === 'undefined') ? 0 : 1 }); //------------------------------------------------------------ //------------------------------------------------------------ // Setup Axes xAxis .scale(x) .ticks( xAxis.ticks() ? xAxis.ticks() : availableWidth / 100 ) .tickSize( -availableHeight , 0); g.select('.nv-x.nv-axis') .attr('transform', 'translate(0,' + y.range()[0] + ')') .call(xAxis); yAxis .scale(y) .ticks( yAxis.ticks() ? yAxis.ticks() : availableHeight / 36 ) .tickSize( -availableWidth, 0); g.select('.nv-y.nv-axis') .call(yAxis); if (showDistX) { distX .getData(scatter.x()) .scale(x) .width(availableWidth) .color(data.map(function(d,i) { return d.color || color(d, i); }).filter(function(d,i) { return !data[i].disabled })); gEnter.select('.nv-distWrap').append('g') .attr('class', 'nv-distributionX'); g.select('.nv-distributionX') .attr('transform', 'translate(0,' + y.range()[0] + ')') .datum(data.filter(function(d) { return !d.disabled })) .call(distX); } if (showDistY) { distY .getData(scatter.y()) .scale(y) .width(availableHeight) .color(data.map(function(d,i) { return d.color || color(d, i); }).filter(function(d,i) { return !data[i].disabled })); gEnter.select('.nv-distWrap').append('g') .attr('class', 'nv-distributionY'); g.select('.nv-distributionY') .attr('transform', 'translate(-' + distY.size() + ',0)') .datum(data.filter(function(d) { return !d.disabled })) .call(distY); } //------------------------------------------------------------ if (d3.fisheye) { g.select('.nv-background') .attr('width', availableWidth) .attr('height', availableHeight); g.select('.nv-background').on('mousemove', updateFisheye); g.select('.nv-background').on('click', function() { pauseFisheye = !pauseFisheye;}); scatter.dispatch.on('elementClick.freezeFisheye', function() { pauseFisheye = !pauseFisheye; }); } function updateFisheye() { if (pauseFisheye) { g.select('.nv-point-paths').style('pointer-events', 'all'); return false; } g.select('.nv-point-paths').style('pointer-events', 'none' ); var mouse = d3.mouse(this); x.distortion(fisheye).focus(mouse[0]); y.distortion(fisheye).focus(mouse[1]); g.select('.nv-scatterWrap') .datum(data.filter(function(d) { return !d.disabled })) .call(scatter); g.select('.nv-x.nv-axis').call(xAxis); g.select('.nv-y.nv-axis').call(yAxis); g.select('.nv-distributionX') .datum(data.filter(function(d) { return !d.disabled })) .call(distX); g.select('.nv-distributionY') .datum(data.filter(function(d) { return !d.disabled })) .call(distY); } //============================================================ // Event Handling/Dispatching (in chart's scope) //------------------------------------------------------------ controls.dispatch.on('legendClick', function(d,i) { d.disabled = !d.disabled; fisheye = d.disabled ? 0 : 2.5; g.select('.nv-background') .style('pointer-events', d.disabled ? 'none' : 'all'); g.select('.nv-point-paths').style('pointer-events', d.disabled ? 'all' : 'none' ); if (d.disabled) { x.distortion(fisheye).focus(0); y.distortion(fisheye).focus(0); g.select('.nv-scatterWrap').call(scatter); g.select('.nv-x.nv-axis').call(xAxis); g.select('.nv-y.nv-axis').call(yAxis); } else { pauseFisheye = false; } chart.update(); }); legend.dispatch.on('legendClick', function(d,i, that) { d.disabled = !d.disabled; if (!data.filter(function(d) { return !d.disabled }).length) { data.map(function(d) { d.disabled = false; wrap.selectAll('.nv-series').classed('disabled', false); return d; }); } state.disabled = data.map(function(d) { return !!d.disabled }); dispatch.stateChange(state); chart.update(); }); legend.dispatch.on('legendDblclick', function(d) { //Double clicking should always enable current series, and disabled all others. data.forEach(function(d) { d.disabled = true; }); d.disabled = false; state.disabled = data.map(function(d) { return !!d.disabled }); dispatch.stateChange(state); chart.update(); }); /* legend.dispatch.on('legendMouseover', function(d, i) { d.hover = true; chart(selection); }); legend.dispatch.on('legendMouseout', function(d, i) { d.hover = false; chart(selection); }); */ scatter.dispatch.on('elementMouseover.tooltip', function(e) { d3.select('.nv-chart-' + scatter.id() + ' .nv-series-' + e.seriesIndex + ' .nv-distx-' + e.pointIndex) .attr('y1', e.pos[1] - availableHeight); d3.select('.nv-chart-' + scatter.id() + ' .nv-series-' + e.seriesIndex + ' .nv-disty-' + e.pointIndex) .attr('x2', e.pos[0] + distX.size()); e.pos = [e.pos[0] + margin.left, e.pos[1] + margin.top]; dispatch.tooltipShow(e); }); dispatch.on('tooltipShow', function(e) { if (tooltips) showTooltip(e, that.parentNode); }); // Update chart from a state object passed to event handler dispatch.on('changeState', function(e) { if (typeof e.disabled !== 'undefined') { data.forEach(function(series,i) { series.disabled = e.disabled[i]; }); state.disabled = e.disabled; } chart.update(); }); //============================================================ //store old scales for use in transitions on update x0 = x.copy(); y0 = y.copy(); }); return chart; } //============================================================ // Event Handling/Dispatching (out of chart's scope) //------------------------------------------------------------ scatter.dispatch.on('elementMouseout.tooltip', function(e) { dispatch.tooltipHide(e); d3.select('.nv-chart-' + scatter.id() + ' .nv-series-' + e.seriesIndex + ' .nv-distx-' + e.pointIndex) .attr('y1', 0); d3.select('.nv-chart-' + scatter.id() + ' .nv-series-' + e.seriesIndex + ' .nv-disty-' + e.pointIndex) .attr('x2', distY.size()); }); dispatch.on('tooltipHide', function() { if (tooltips) nv.tooltip.cleanup(); }); //============================================================ //============================================================ // Expose Public Variables //------------------------------------------------------------ // expose chart's sub-components chart.dispatch = dispatch; chart.scatter = scatter; chart.legend = legend; chart.controls = controls; chart.xAxis = xAxis; chart.yAxis = yAxis; chart.distX = distX; chart.distY = distY; d3.rebind(chart, scatter, 'id', 'interactive', 'pointActive', 'x', 'y', 'shape', 'size', 'xScale', 'yScale', 'zScale', 'xDomain', 'yDomain', 'sizeDomain', 'sizeRange', 'forceX', 'forceY', 'forceSize', 'clipVoronoi', 'clipRadius', 'useVoronoi'); chart.margin = function(_) { if (!arguments.length) return margin; margin.top = typeof _.top != 'undefined' ? _.top : margin.top; margin.right = typeof _.right != 'undefined' ? _.right : margin.right; margin.bottom = typeof _.bottom != 'undefined' ? _.bottom : margin.bottom; margin.left = typeof _.left != 'undefined' ? _.left : margin.left; return chart; }; chart.width = function(_) { if (!arguments.length) return width; width = _; return chart; }; chart.height = function(_) { if (!arguments.length) return height; height = _; return chart; }; chart.color = function(_) { if (!arguments.length) return color; color = nv.utils.getColor(_); legend.color(color); distX.color(color); distY.color(color); return chart; }; chart.showDistX = function(_) { if (!arguments.length) return showDistX; showDistX = _; return chart; }; chart.showDistY = function(_) { if (!arguments.length) return showDistY; showDistY = _; return chart; }; chart.showControls = function(_) { if (!arguments.length) return showControls; showControls = _; return chart; }; chart.showLegend = function(_) { if (!arguments.length) return showLegend; showLegend = _; return chart; }; chart.fisheye = function(_) { if (!arguments.length) return fisheye; fisheye = _; return chart; }; chart.tooltips = function(_) { if (!arguments.length) return tooltips; tooltips = _; return chart; }; chart.tooltipContent = function(_) { if (!arguments.length) return tooltip; tooltip = _; return chart; }; chart.tooltipXContent = function(_) { if (!arguments.length) return tooltipX; tooltipX = _; return chart; }; chart.tooltipYContent = function(_) { if (!arguments.length) return tooltipY; tooltipY = _; return chart; }; chart.state = function(_) { if (!arguments.length) return state; state = _; return chart; }; chart.defaultState = function(_) { if (!arguments.length) return defaultState; defaultState = _; return chart; }; chart.noData = function(_) { if (!arguments.length) return noData; noData = _; return chart; }; //============================================================ return chart; } nv.models.sparkline = function() { //============================================================ // Public Variables with Default Settings //------------------------------------------------------------ var margin = {top: 2, right: 0, bottom: 2, left: 0} , width = 400 , height = 32 , animate = true , x = d3.scale.linear() , y = d3.scale.linear() , getX = function(d) { return d.x } , getY = function(d) { return d.y } , color = nv.utils.getColor(['#000']) , xDomain , yDomain ; //============================================================ function chart(selection) { selection.each(function(data) { var availableWidth = width - margin.left - margin.right, availableHeight = height - margin.top - margin.bottom, container = d3.select(this); //------------------------------------------------------------ // Setup Scales x .domain(xDomain || d3.extent(data, getX )) .range([0, availableWidth]); y .domain(yDomain || d3.extent(data, getY )) .range([availableHeight, 0]); //------------------------------------------------------------ //------------------------------------------------------------ // Setup containers and skeleton of chart var wrap = container.selectAll('g.nv-wrap.nv-sparkline').data([data]); var wrapEnter = wrap.enter().append('g').attr('class', 'nvd3 nv-wrap nv-sparkline'); var gEnter = wrapEnter.append('g'); var g = wrap.select('g'); wrap.attr('transform', 'translate(' + margin.left + ',' + margin.top + ')') //------------------------------------------------------------ var paths = wrap.selectAll('path') .data(function(d) { return [d] }); paths.enter().append('path'); paths.exit().remove(); paths .style('stroke', function(d,i) { return d.color || color(d, i) }) .attr('d', d3.svg.line() .x(function(d,i) { return x(getX(d,i)) }) .y(function(d,i) { return y(getY(d,i)) }) ); // TODO: Add CURRENT data point (Need Min, Mac, Current / Most recent) var points = wrap.selectAll('circle.nv-point') .data(function(data) { var yValues = data.map(function(d, i) { return getY(d,i); }); function pointIndex(index) { if (index != -1) { var result = data[index]; result.pointIndex = index; return result; } else { return null; } } var maxPoint = pointIndex(yValues.lastIndexOf(y.domain()[1])), minPoint = pointIndex(yValues.indexOf(y.domain()[0])), currentPoint = pointIndex(yValues.length - 1); return [minPoint, maxPoint, currentPoint].filter(function (d) {return d != null;}); }); points.enter().append('circle'); points.exit().remove(); points .attr('cx', function(d,i) { return x(getX(d,d.pointIndex)) }) .attr('cy', function(d,i) { return y(getY(d,d.pointIndex)) }) .attr('r', 2) .attr('class', function(d,i) { return getX(d, d.pointIndex) == x.domain()[1] ? 'nv-point nv-currentValue' : getY(d, d.pointIndex) == y.domain()[0] ? 'nv-point nv-minValue' : 'nv-point nv-maxValue' }); }); return chart; } //============================================================ // Expose Public Variables //------------------------------------------------------------ chart.margin = function(_) { if (!arguments.length) return margin; margin.top = typeof _.top != 'undefined' ? _.top : margin.top; margin.right = typeof _.right != 'undefined' ? _.right : margin.right; margin.bottom = typeof _.bottom != 'undefined' ? _.bottom : margin.bottom; margin.left = typeof _.left != 'undefined' ? _.left : margin.left; return chart; }; chart.width = function(_) { if (!arguments.length) return width; width = _; return chart; }; chart.height = function(_) { if (!arguments.length) return height; height = _; return chart; }; chart.x = function(_) { if (!arguments.length) return getX; getX = d3.functor(_); return chart; }; chart.y = function(_) { if (!arguments.length) return getY; getY = d3.functor(_); return chart; }; chart.xScale = function(_) { if (!arguments.length) return x; x = _; return chart; }; chart.yScale = function(_) { if (!arguments.length) return y; y = _; return chart; }; chart.xDomain = function(_) { if (!arguments.length) return xDomain; xDomain = _; return chart; }; chart.yDomain = function(_) { if (!arguments.length) return yDomain; yDomain = _; return chart; }; chart.animate = function(_) { if (!arguments.length) return animate; animate = _; return chart; }; chart.color = function(_) { if (!arguments.length) return color; color = nv.utils.getColor(_); return chart; }; //============================================================ return chart; } nv.models.sparklinePlus = function() { //============================================================ // Public Variables with Default Settings //------------------------------------------------------------ var sparkline = nv.models.sparkline(); var margin = {top: 15, right: 100, bottom: 10, left: 50} , width = null , height = null , x , y , index = [] , paused = false , xTickFormat = d3.format(',r') , yTickFormat = d3.format(',.2f') , showValue = true , alignValue = true , rightAlignValue = false , noData = "No Data Available." ; //============================================================ function chart(selection) { selection.each(function(data) { var container = d3.select(this); var availableWidth = (width || parseInt(container.style('width')) || 960) - margin.left - margin.right, availableHeight = (height || parseInt(container.style('height')) || 400) - margin.top - margin.bottom; chart.update = function() { chart(selection) }; chart.container = this; //------------------------------------------------------------ // Display No Data message if there's nothing to show. if (!data || !data.length) { var noDataText = container.selectAll('.nv-noData').data([noData]); noDataText.enter().append('text') .attr('class', 'nvd3 nv-noData') .attr('dy', '-.7em') .style('text-anchor', 'middle'); noDataText .attr('x', margin.left + availableWidth / 2) .attr('y', margin.top + availableHeight / 2) .text(function(d) { return d }); return chart; } else { container.selectAll('.nv-noData').remove(); } var currentValue = sparkline.y()(data[data.length-1], data.length-1); //------------------------------------------------------------ //------------------------------------------------------------ // Setup Scales x = sparkline.xScale(); y = sparkline.yScale(); //------------------------------------------------------------ //------------------------------------------------------------ // Setup containers and skeleton of chart var wrap = container.selectAll('g.nv-wrap.nv-sparklineplus').data([data]); var wrapEnter = wrap.enter().append('g').attr('class', 'nvd3 nv-wrap nv-sparklineplus'); var gEnter = wrapEnter.append('g'); var g = wrap.select('g'); gEnter.append('g').attr('class', 'nv-sparklineWrap'); gEnter.append('g').attr('class', 'nv-valueWrap'); gEnter.append('g').attr('class', 'nv-hoverArea'); wrap.attr('transform', 'translate(' + margin.left + ',' + margin.top + ')'); //------------------------------------------------------------ //------------------------------------------------------------ // Main Chart Component(s) var sparklineWrap = g.select('.nv-sparklineWrap'); sparkline .width(availableWidth) .height(availableHeight); sparklineWrap .call(sparkline); //------------------------------------------------------------ var valueWrap = g.select('.nv-valueWrap'); var value = valueWrap.selectAll('.nv-currentValue') .data([currentValue]); value.enter().append('text').attr('class', 'nv-currentValue') .attr('dx', rightAlignValue ? -8 : 8) .attr('dy', '.9em') .style('text-anchor', rightAlignValue ? 'end' : 'start'); value .attr('x', availableWidth + (rightAlignValue ? margin.right : 0)) .attr('y', alignValue ? function(d) { return y(d) } : 0) .style('fill', sparkline.color()(data[data.length-1], data.length-1)) .text(yTickFormat(currentValue)); gEnter.select('.nv-hoverArea').append('rect') .on('mousemove', sparklineHover) .on('click', function() { paused = !paused }) .on('mouseout', function() { index = []; updateValueLine(); }); //.on('mouseout', function() { index = null; updateValueLine(); }); g.select('.nv-hoverArea rect') .attr('transform', function(d) { return 'translate(' + -margin.left + ',' + -margin.top + ')' }) .attr('width', availableWidth + margin.left + margin.right) .attr('height', availableHeight + margin.top); function updateValueLine() { //index is currently global (within the chart), may or may not keep it that way if (paused) return; var hoverValue = g.selectAll('.nv-hoverValue').data(index) var hoverEnter = hoverValue.enter() .append('g').attr('class', 'nv-hoverValue') .style('stroke-opacity', 0) .style('fill-opacity', 0); hoverValue.exit() .transition().duration(250) .style('stroke-opacity', 0) .style('fill-opacity', 0) .remove(); hoverValue .attr('transform', function(d) { return 'translate(' + x(sparkline.x()(data[d],d)) + ',0)' }) .transition().duration(250) .style('stroke-opacity', 1) .style('fill-opacity', 1); if (!index.length) return; hoverEnter.append('line') .attr('x1', 0) .attr('y1', -margin.top) .attr('x2', 0) .attr('y2', availableHeight); hoverEnter.append('text').attr('class', 'nv-xValue') .attr('x', -6) .attr('y', -margin.top) .attr('text-anchor', 'end') .attr('dy', '.9em') g.select('.nv-hoverValue .nv-xValue') .text(xTickFormat(sparkline.x()(data[index[0]], index[0]))); hoverEnter.append('text').attr('class', 'nv-yValue') .attr('x', 6) .attr('y', -margin.top) .attr('text-anchor', 'start') .attr('dy', '.9em') g.select('.nv-hoverValue .nv-yValue') .text(yTickFormat(sparkline.y()(data[index[0]], index[0]))); } function sparklineHover() { if (paused) return; var pos = d3.mouse(this)[0] - margin.left; function getClosestIndex(data, x) { var distance = Math.abs(sparkline.x()(data[0], 0) - x); var closestIndex = 0; for (var i = 0; i < data.length; i++){ if (Math.abs(sparkline.x()(data[i], i) - x) < distance) { distance = Math.abs(sparkline.x()(data[i], i) - x); closestIndex = i; } } return closestIndex; } index = [getClosestIndex(data, Math.round(x.invert(pos)))]; updateValueLine(); } }); return chart; } //============================================================ // Expose Public Variables //------------------------------------------------------------ // expose chart's sub-components chart.sparkline = sparkline; d3.rebind(chart, sparkline, 'x', 'y', 'xScale', 'yScale', 'color'); chart.margin = function(_) { if (!arguments.length) return margin; margin.top = typeof _.top != 'undefined' ? _.top : margin.top; margin.right = typeof _.right != 'undefined' ? _.right : margin.right; margin.bottom = typeof _.bottom != 'undefined' ? _.bottom : margin.bottom; margin.left = typeof _.left != 'undefined' ? _.left : margin.left; return chart; }; chart.width = function(_) { if (!arguments.length) return width; width = _; return chart; }; chart.height = function(_) { if (!arguments.length) return height; height = _; return chart; }; chart.xTickFormat = function(_) { if (!arguments.length) return xTickFormat; xTickFormat = _; return chart; }; chart.yTickFormat = function(_) { if (!arguments.length) return yTickFormat; yTickFormat = _; return chart; }; chart.showValue = function(_) { if (!arguments.length) return showValue; showValue = _; return chart; }; chart.alignValue = function(_) { if (!arguments.length) return alignValue; alignValue = _; return chart; }; chart.rightAlignValue = function(_) { if (!arguments.length) return rightAlignValue; rightAlignValue = _; return chart; }; chart.noData = function(_) { if (!arguments.length) return noData; noData = _; return chart; }; //============================================================ return chart; } nv.models.stackedArea = function() { //============================================================ // Public Variables with Default Settings //------------------------------------------------------------ var margin = {top: 0, right: 0, bottom: 0, left: 0} , width = 960 , height = 500 , color = nv.utils.defaultColor() // a function that computes the color , id = Math.floor(Math.random() * 100000) //Create semi-unique ID incase user doesn't selet one , getX = function(d) { return d.x } // accessor to get the x value from a data point , getY = function(d) { return d.y } // accessor to get the y value from a data point , style = 'stack' , offset = 'zero' , order = 'default' , interpolate = 'linear' // controls the line interpolation , clipEdge = false // if true, masks lines within x and y scale , x //can be accessed via chart.xScale() , y //can be accessed via chart.yScale() , scatter = nv.models.scatter() , dispatch = d3.dispatch('tooltipShow', 'tooltipHide', 'areaClick', 'areaMouseover', 'areaMouseout') ; scatter .size(2.2) // default size .sizeDomain([2.2,2.2]) // all the same size by default ; /************************************ * offset: * 'wiggle' (stream) * 'zero' (stacked) * 'expand' (normalize to 100%) * 'silhouette' (simple centered) * * order: * 'inside-out' (stream) * 'default' (input order) ************************************/ //============================================================ function chart(selection) { selection.each(function(data) { var availableWidth = width - margin.left - margin.right, availableHeight = height - margin.top - margin.bottom, container = d3.select(this); //------------------------------------------------------------ // Setup Scales x = scatter.xScale(); y = scatter.yScale(); //------------------------------------------------------------ // Injecting point index into each point because d3.layout.stack().out does not give index // ***Also storing getY(d,i) as stackedY so that it can be set to 0 if series is disabled data = data.map(function(aseries, i) { aseries.values = aseries.values.map(function(d, j) { d.index = j; d.stackedY = aseries.disabled ? 0 : getY(d,j); return d; }) return aseries; }); data = d3.layout.stack() .order(order) .offset(offset) .values(function(d) { return d.values }) //TODO: make values customizeable in EVERY model in this fashion .x(getX) .y(function(d) { return d.stackedY }) .out(function(d, y0, y) { d.display = { y: y, y0: y0 }; }) (data); //------------------------------------------------------------ // Setup containers and skeleton of chart var wrap = container.selectAll('g.nv-wrap.nv-stackedarea').data([data]); var wrapEnter = wrap.enter().append('g').attr('class', 'nvd3 nv-wrap nv-stackedarea'); var defsEnter = wrapEnter.append('defs'); var gEnter = wrapEnter.append('g'); var g = wrap.select('g'); gEnter.append('g').attr('class', 'nv-areaWrap'); gEnter.append('g').attr('class', 'nv-scatterWrap'); wrap.attr('transform', 'translate(' + margin.left + ',' + margin.top + ')'); //------------------------------------------------------------ scatter .width(availableWidth) .height(availableHeight) .x(getX) .y(function(d) { return d.display.y + d.display.y0 }) .forceY([0]) .color(data.map(function(d,i) { return d.color || color(d, i); }).filter(function(d,i) { return !data[i].disabled })); var scatterWrap = g.select('.nv-scatterWrap') .datum(data.filter(function(d) { return !d.disabled })) //d3.transition(scatterWrap).call(scatter); scatterWrap.call(scatter); defsEnter.append('clipPath') .attr('id', 'nv-edge-clip-' + id) .append('rect'); wrap.select('#nv-edge-clip-' + id + ' rect') .attr('width', availableWidth) .attr('height', availableHeight); g .attr('clip-path', clipEdge ? 'url(#nv-edge-clip-' + id + ')' : ''); var area = d3.svg.area() .x(function(d,i) { return x(getX(d,i)) }) .y0(function(d) { return y(d.display.y0) }) .y1(function(d) { return y(d.display.y + d.display.y0) }) .interpolate(interpolate); var zeroArea = d3.svg.area() .x(function(d,i) { return x(getX(d,i)) }) .y0(function(d) { return y(d.display.y0) }) .y1(function(d) { return y(d.display.y0) }); var path = g.select('.nv-areaWrap').selectAll('path.nv-area') .data(function(d) { return d }); //.data(function(d) { return d }, function(d) { return d.key }); path.enter().append('path').attr('class', function(d,i) { return 'nv-area nv-area-' + i }) .on('mouseover', function(d,i) { d3.select(this).classed('hover', true); dispatch.areaMouseover({ point: d, series: d.key, pos: [d3.event.pageX, d3.event.pageY], seriesIndex: i }); }) .on('mouseout', function(d,i) { d3.select(this).classed('hover', false); dispatch.areaMouseout({ point: d, series: d.key, pos: [d3.event.pageX, d3.event.pageY], seriesIndex: i }); }) .on('click', function(d,i) { d3.select(this).classed('hover', false); dispatch.areaClick({ point: d, series: d.key, pos: [d3.event.pageX, d3.event.pageY], seriesIndex: i }); }) //d3.transition(path.exit()) path.exit() .attr('d', function(d,i) { return zeroArea(d.values,i) }) .remove(); path .style('fill', function(d,i){ return d.color || color(d, i) }) .style('stroke', function(d,i){ return d.color || color(d, i) }); //d3.transition(path) path .attr('d', function(d,i) { return area(d.values,i) }) //============================================================ // Event Handling/Dispatching (in chart's scope) //------------------------------------------------------------ scatter.dispatch.on('elementMouseover.area', function(e) { g.select('.nv-chart-' + id + ' .nv-area-' + e.seriesIndex).classed('hover', true); }); scatter.dispatch.on('elementMouseout.area', function(e) { g.select('.nv-chart-' + id + ' .nv-area-' + e.seriesIndex).classed('hover', false); }); //============================================================ }); return chart; } //============================================================ // Event Handling/Dispatching (out of chart's scope) //------------------------------------------------------------ scatter.dispatch.on('elementClick.area', function(e) { dispatch.areaClick(e); }) scatter.dispatch.on('elementMouseover.tooltip', function(e) { e.pos = [e.pos[0] + margin.left, e.pos[1] + margin.top], dispatch.tooltipShow(e); }); scatter.dispatch.on('elementMouseout.tooltip', function(e) { dispatch.tooltipHide(e); }); //============================================================ //============================================================ // Global getters and setters //------------------------------------------------------------ chart.dispatch = dispatch; chart.scatter = scatter; d3.rebind(chart, scatter, 'interactive', 'size', 'xScale', 'yScale', 'zScale', 'xDomain', 'yDomain', 'sizeDomain', 'forceX', 'forceY', 'forceSize', 'clipVoronoi', 'clipRadius'); chart.x = function(_) { if (!arguments.length) return getX; getX = d3.functor(_); return chart; }; chart.y = function(_) { if (!arguments.length) return getY; getY = d3.functor(_); return chart; } chart.margin = function(_) { if (!arguments.length) return margin; margin.top = typeof _.top != 'undefined' ? _.top : margin.top; margin.right = typeof _.right != 'undefined' ? _.right : margin.right; margin.bottom = typeof _.bottom != 'undefined' ? _.bottom : margin.bottom; margin.left = typeof _.left != 'undefined' ? _.left : margin.left; return chart; }; chart.width = function(_) { if (!arguments.length) return width; width = _; return chart; }; chart.height = function(_) { if (!arguments.length) return height; height = _; return chart; }; chart.clipEdge = function(_) { if (!arguments.length) return clipEdge; clipEdge = _; return chart; }; chart.color = function(_) { if (!arguments.length) return color; color = nv.utils.getColor(_); return chart; }; chart.offset = function(_) { if (!arguments.length) return offset; offset = _; return chart; }; chart.order = function(_) { if (!arguments.length) return order; order = _; return chart; }; //shortcut for offset + order chart.style = function(_) { if (!arguments.length) return style; style = _; switch (style) { case 'stack': chart.offset('zero'); chart.order('default'); break; case 'stream': chart.offset('wiggle'); chart.order('inside-out'); break; case 'stream-center': chart.offset('silhouette'); chart.order('inside-out'); break; case 'expand': chart.offset('expand'); chart.order('default'); break; } return chart; }; chart.interpolate = function(_) { if (!arguments.length) return interpolate; interpolate = _; return interpolate; }; //============================================================ return chart; } nv.models.stackedAreaChart = function() { //============================================================ // Public Variables with Default Settings //------------------------------------------------------------ var stacked = nv.models.stackedArea() , xAxis = nv.models.axis() , yAxis = nv.models.axis() , legend = nv.models.legend() , controls = nv.models.legend() ; var margin = {top: 30, right: 25, bottom: 50, left: 60} , width = null , height = null , color = nv.utils.defaultColor() // a function that takes in d, i and returns color , showControls = true , showLegend = true , tooltips = true , tooltip = function(key, x, y, e, graph) { return '

    ' + key + '

    ' + '

    ' + y + ' on ' + x + '

    ' } , x //can be accessed via chart.xScale() , y //can be accessed via chart.yScale() , yAxisTickFormat = d3.format(',.2f') , state = { style: stacked.style() } , defaultState = null , noData = 'No Data Available.' , dispatch = d3.dispatch('tooltipShow', 'tooltipHide', 'stateChange', 'changeState') , controlWidth = 250 ; xAxis .orient('bottom') .tickPadding(7) ; yAxis .orient('left') ; stacked.scatter .pointActive(function(d) { //console.log(stacked.y()(d), !!Math.round(stacked.y()(d) * 100)); return !!Math.round(stacked.y()(d) * 100); }) ; //============================================================ //============================================================ // Private Variables //------------------------------------------------------------ var showTooltip = function(e, offsetElement) { var left = e.pos[0] + ( offsetElement.offsetLeft || 0 ), top = e.pos[1] + ( offsetElement.offsetTop || 0), x = xAxis.tickFormat()(stacked.x()(e.point, e.pointIndex)), y = yAxis.tickFormat()(stacked.y()(e.point, e.pointIndex)), content = tooltip(e.series.key, x, y, e, chart); nv.tooltip.show([left, top], content, e.value < 0 ? 'n' : 's', null, offsetElement); }; //============================================================ function chart(selection) { selection.each(function(data) { var container = d3.select(this), that = this; var availableWidth = (width || parseInt(container.style('width')) || 960) - margin.left - margin.right, availableHeight = (height || parseInt(container.style('height')) || 400) - margin.top - margin.bottom; chart.update = function() { container.transition().call(chart); }; chart.container = this; //set state.disabled state.disabled = data.map(function(d) { return !!d.disabled }); if (!defaultState) { var key; defaultState = {}; for (key in state) { if (state[key] instanceof Array) defaultState[key] = state[key].slice(0); else defaultState[key] = state[key]; } } //------------------------------------------------------------ // Display No Data message if there's nothing to show. if (!data || !data.length || !data.filter(function(d) { return d.values.length }).length) { var noDataText = container.selectAll('.nv-noData').data([noData]); noDataText.enter().append('text') .attr('class', 'nvd3 nv-noData') .attr('dy', '-.7em') .style('text-anchor', 'middle'); noDataText .attr('x', margin.left + availableWidth / 2) .attr('y', margin.top + availableHeight / 2) .text(function(d) { return d }); return chart; } else { container.selectAll('.nv-noData').remove(); } //------------------------------------------------------------ //------------------------------------------------------------ // Setup Scales x = stacked.xScale(); y = stacked.yScale(); //------------------------------------------------------------ //------------------------------------------------------------ // Setup containers and skeleton of chart var wrap = container.selectAll('g.nv-wrap.nv-stackedAreaChart').data([data]); var gEnter = wrap.enter().append('g').attr('class', 'nvd3 nv-wrap nv-stackedAreaChart').append('g'); var g = wrap.select('g'); gEnter.append('g').attr('class', 'nv-x nv-axis'); gEnter.append('g').attr('class', 'nv-y nv-axis'); gEnter.append('g').attr('class', 'nv-stackedWrap'); gEnter.append('g').attr('class', 'nv-legendWrap'); gEnter.append('g').attr('class', 'nv-controlsWrap'); //------------------------------------------------------------ //------------------------------------------------------------ // Legend if (showLegend) { legend .width( availableWidth - controlWidth ); g.select('.nv-legendWrap') .datum(data) .call(legend); if ( margin.top != legend.height()) { margin.top = legend.height() + legend.legendBelowPadding();// added legend.legendBelowPadding to allow for more spacing availableHeight = (height || parseInt(container.style('height')) || 400) - margin.top - margin.bottom; } g.select('.nv-legendWrap') .attr('transform', 'translate(' + controlWidth + ',' + (-margin.top) +')'); } //------------------------------------------------------------ //------------------------------------------------------------ // Controls if (showControls) { var controlsData = [ { key: 'Stacked', disabled: stacked.offset() != 'zero' }, { key: 'Stream', disabled: stacked.offset() != 'wiggle' }, { key: 'Expanded', disabled: stacked.offset() != 'expand' } ]; controls .width( controlWidth ) .color(['#444', '#444', '#444']); g.select('.nv-controlsWrap') .datum(controlsData) .call(controls); if ( margin.top != Math.max(controls.height(), legend.height()) ) { margin.top = Math.max(controls.height(), legend.height()); availableHeight = (height || parseInt(container.style('height')) || 400) - margin.top - margin.bottom; } g.select('.nv-controlsWrap') .attr('transform', 'translate(0,' + (-margin.top) +')'); } //------------------------------------------------------------ wrap.attr('transform', 'translate(' + margin.left + ',' + margin.top + ')'); //------------------------------------------------------------ // Main Chart Component(s) stacked .width(availableWidth) .height(availableHeight) var stackedWrap = g.select('.nv-stackedWrap') .datum(data); //d3.transition(stackedWrap).call(stacked); stackedWrap.call(stacked); //------------------------------------------------------------ //------------------------------------------------------------ // Setup Axes xAxis .scale(x) .ticks( availableWidth / 100 ) .tickSize( -availableHeight, 0); g.select('.nv-x.nv-axis') .attr('transform', 'translate(0,' + availableHeight + ')'); //d3.transition(g.select('.nv-x.nv-axis')) g.select('.nv-x.nv-axis') .transition().duration(0) .call(xAxis); yAxis .scale(y) .ticks(stacked.offset() == 'wiggle' ? 0 : availableHeight / 36) .tickSize(-availableWidth, 0) .setTickFormat(stacked.offset() == 'expand' ? d3.format('%') : yAxisTickFormat); //d3.transition(g.select('.nv-y.nv-axis')) g.select('.nv-y.nv-axis') .transition().duration(0) .call(yAxis); //------------------------------------------------------------ //============================================================ // Event Handling/Dispatching (in chart's scope) //------------------------------------------------------------ stacked.dispatch.on('areaClick.toggle', function(e) { if (data.filter(function(d) { return !d.disabled }).length === 1) data = data.map(function(d) { d.disabled = false; return d }); else data = data.map(function(d,i) { d.disabled = (i != e.seriesIndex); return d }); state.disabled = data.map(function(d) { return !!d.disabled }); dispatch.stateChange(state); //selection.transition().call(chart); chart.update(); }); legend.dispatch.on('legendClick', function(d,i) { d.disabled = !d.disabled; if (!data.filter(function(d) { return !d.disabled }).length) { data.map(function(d) { d.disabled = false; return d; }); } state.disabled = data.map(function(d) { return !!d.disabled }); dispatch.stateChange(state); //selection.transition().call(chart); chart.update(); }); legend.dispatch.on('legendDblclick', function(d) { //Double clicking should always enable current series, and disabled all others. data.forEach(function(d) { d.disabled = true; }); d.disabled = false; state.disabled = data.map(function(d) { return !!d.disabled }); dispatch.stateChange(state); chart.update(); }); controls.dispatch.on('legendClick', function(d,i) { if (!d.disabled) return; controlsData = controlsData.map(function(s) { s.disabled = true; return s; }); d.disabled = false; switch (d.key) { case 'Stacked': stacked.style('stack'); break; case 'Stream': stacked.style('stream'); break; case 'Expanded': stacked.style('expand'); break; } state.style = stacked.style(); dispatch.stateChange(state); //selection.transition().call(chart); chart.update(); }); dispatch.on('tooltipShow', function(e) { if (tooltips) showTooltip(e, that.parentNode); }); // Update chart from a state object passed to event handler dispatch.on('changeState', function(e) { if (typeof e.disabled !== 'undefined') { data.forEach(function(series,i) { series.disabled = e.disabled[i]; }); state.disabled = e.disabled; } if (typeof e.style !== 'undefined') { stacked.style(e.style); } chart.update(); }); }); return chart; } //============================================================ // Event Handling/Dispatching (out of chart's scope) //------------------------------------------------------------ stacked.dispatch.on('tooltipShow', function(e) { //disable tooltips when value ~= 0 //// TODO: consider removing points from voronoi that have 0 value instead of this hack /* if (!Math.round(stacked.y()(e.point) * 100)) { // 100 will not be good for very small numbers... will have to think about making this valu dynamic, based on data range setTimeout(function() { d3.selectAll('.point.hover').classed('hover', false) }, 0); return false; } */ e.pos = [e.pos[0] + margin.left, e.pos[1] + margin.top], dispatch.tooltipShow(e); }); stacked.dispatch.on('tooltipHide', function(e) { dispatch.tooltipHide(e); }); dispatch.on('tooltipHide', function() { if (tooltips) nv.tooltip.cleanup(); }); //============================================================ //============================================================ // Expose Public Variables //------------------------------------------------------------ // expose chart's sub-components chart.dispatch = dispatch; chart.stacked = stacked; chart.legend = legend; chart.controls = controls; chart.xAxis = xAxis; chart.yAxis = yAxis; d3.rebind(chart, stacked, 'x', 'y', 'size', 'xScale', 'yScale', 'xDomain', 'yDomain', 'sizeDomain', 'interactive', 'offset', 'order', 'style', 'clipEdge', 'forceX', 'forceY', 'forceSize', 'interpolate'); chart.margin = function(_) { if (!arguments.length) return margin; margin.top = typeof _.top != 'undefined' ? _.top : margin.top; margin.right = typeof _.right != 'undefined' ? _.right : margin.right; margin.bottom = typeof _.bottom != 'undefined' ? _.bottom : margin.bottom; margin.left = typeof _.left != 'undefined' ? _.left : margin.left; return chart; }; chart.width = function(_) { if (!arguments.length) return getWidth; width = _; return chart; }; chart.height = function(_) { if (!arguments.length) return getHeight; height = _; return chart; }; chart.color = function(_) { if (!arguments.length) return color; color = nv.utils.getColor(_); legend.color(color); stacked.color(color); return chart; }; chart.showControls = function(_) { if (!arguments.length) return showControls; showControls = _; return chart; }; chart.showLegend = function(_) { if (!arguments.length) return showLegend; showLegend = _; return chart; }; chart.tooltip = function(_) { if (!arguments.length) return tooltip; tooltip = _; return chart; }; chart.tooltips = function(_) { if (!arguments.length) return tooltips; tooltips = _; return chart; }; chart.tooltipContent = function(_) { if (!arguments.length) return tooltip; tooltip = _; return chart; }; chart.state = function(_) { if (!arguments.length) return state; state = _; return chart; }; chart.defaultState = function(_) { if (!arguments.length) return defaultState; defaultState = _; return chart; }; chart.noData = function(_) { if (!arguments.length) return noData; noData = _; return chart; }; yAxis.setTickFormat = yAxis.tickFormat; yAxis.tickFormat = function(_) { if (!arguments.length) return yAxisTickFormat; yAxisTickFormat = _; return yAxis; }; //============================================================ return chart; } })(); apache-couchdb-1.5.0/src/fauxton/assets/js/libs/backbone.js0000644000175000001440000016415212230722213020507 00000000000000// Backbone.js 1.0.0 // (c) 2010-2013 Jeremy Ashkenas, DocumentCloud Inc. // Backbone may be freely distributed under the MIT license. // For all details and documentation: // http://backbonejs.org (function(){ // Initial Setup // ------------- // Save a reference to the global object (`window` in the browser, `exports` // on the server). var root = this; // Save the previous value of the `Backbone` variable, so that it can be // restored later on, if `noConflict` is used. var previousBackbone = root.Backbone; // Create local references to array methods we'll want to use later. var array = []; var push = array.push; var slice = array.slice; var splice = array.splice; // The top-level namespace. All public Backbone classes and modules will // be attached to this. Exported for both the browser and the server. var Backbone; if (typeof exports !== 'undefined') { Backbone = exports; } else { Backbone = root.Backbone = {}; } // Current version of the library. Keep in sync with `package.json`. Backbone.VERSION = '1.0.0'; // Require Underscore, if we're on the server, and it's not already present. var _ = root._; if (!_ && (typeof require !== 'undefined')) _ = require('underscore'); // For Backbone's purposes, jQuery, Zepto, Ender, or My Library (kidding) owns // the `$` variable. Backbone.$ = root.jQuery || root.Zepto || root.ender || root.$; // Runs Backbone.js in *noConflict* mode, returning the `Backbone` variable // to its previous owner. Returns a reference to this Backbone object. Backbone.noConflict = function() { root.Backbone = previousBackbone; return this; }; // Turn on `emulateHTTP` to support legacy HTTP servers. Setting this option // will fake `"PUT"` and `"DELETE"` requests via the `_method` parameter and // set a `X-Http-Method-Override` header. Backbone.emulateHTTP = false; // Turn on `emulateJSON` to support legacy servers that can't deal with direct // `application/json` requests ... will encode the body as // `application/x-www-form-urlencoded` instead and will send the model in a // form param named `model`. Backbone.emulateJSON = false; // Backbone.Events // --------------- // A module that can be mixed in to *any object* in order to provide it with // custom events. You may bind with `on` or remove with `off` callback // functions to an event; `trigger`-ing an event fires all callbacks in // succession. // // var object = {}; // _.extend(object, Backbone.Events); // object.on('expand', function(){ alert('expanded'); }); // object.trigger('expand'); // var Events = Backbone.Events = { // Bind an event to a `callback` function. Passing `"all"` will bind // the callback to all events fired. on: function(name, callback, context) { if (!eventsApi(this, 'on', name, [callback, context]) || !callback) return this; this._events || (this._events = {}); var events = this._events[name] || (this._events[name] = []); events.push({callback: callback, context: context, ctx: context || this}); return this; }, // Bind an event to only be triggered a single time. After the first time // the callback is invoked, it will be removed. once: function(name, callback, context) { if (!eventsApi(this, 'once', name, [callback, context]) || !callback) return this; var self = this; var once = _.once(function() { self.off(name, once); callback.apply(this, arguments); }); once._callback = callback; return this.on(name, once, context); }, // Remove one or many callbacks. If `context` is null, removes all // callbacks with that function. If `callback` is null, removes all // callbacks for the event. If `name` is null, removes all bound // callbacks for all events. off: function(name, callback, context) { var retain, ev, events, names, i, l, j, k; if (!this._events || !eventsApi(this, 'off', name, [callback, context])) return this; if (!name && !callback && !context) { this._events = {}; return this; } names = name ? [name] : _.keys(this._events); for (i = 0, l = names.length; i < l; i++) { name = names[i]; if (events = this._events[name]) { this._events[name] = retain = []; if (callback || context) { for (j = 0, k = events.length; j < k; j++) { ev = events[j]; if ((callback && callback !== ev.callback && callback !== ev.callback._callback) || (context && context !== ev.context)) { retain.push(ev); } } } if (!retain.length) delete this._events[name]; } } return this; }, // Trigger one or many events, firing all bound callbacks. Callbacks are // passed the same arguments as `trigger` is, apart from the event name // (unless you're listening on `"all"`, which will cause your callback to // receive the true name of the event as the first argument). trigger: function(name) { if (!this._events) return this; var args = slice.call(arguments, 1); if (!eventsApi(this, 'trigger', name, args)) return this; var events = this._events[name]; var allEvents = this._events.all; if (events) triggerEvents(events, args); if (allEvents) triggerEvents(allEvents, arguments); return this; }, // Tell this object to stop listening to either specific events ... or // to every object it's currently listening to. stopListening: function(obj, name, callback) { var listeners = this._listeners; if (!listeners) return this; var deleteListener = !name && !callback; if (typeof name === 'object') callback = this; if (obj) (listeners = {})[obj._listenerId] = obj; for (var id in listeners) { listeners[id].off(name, callback, this); if (deleteListener) delete this._listeners[id]; } return this; } }; // Regular expression used to split event strings. var eventSplitter = /\s+/; // Implement fancy features of the Events API such as multiple event // names `"change blur"` and jQuery-style event maps `{change: action}` // in terms of the existing API. var eventsApi = function(obj, action, name, rest) { if (!name) return true; // Handle event maps. if (typeof name === 'object') { for (var key in name) { obj[action].apply(obj, [key, name[key]].concat(rest)); } return false; } // Handle space separated event names. if (eventSplitter.test(name)) { var names = name.split(eventSplitter); for (var i = 0, l = names.length; i < l; i++) { obj[action].apply(obj, [names[i]].concat(rest)); } return false; } return true; }; // A difficult-to-believe, but optimized internal dispatch function for // triggering events. Tries to keep the usual cases speedy (most internal // Backbone events have 3 arguments). var triggerEvents = function(events, args) { var ev, i = -1, l = events.length, a1 = args[0], a2 = args[1], a3 = args[2]; switch (args.length) { case 0: while (++i < l) (ev = events[i]).callback.call(ev.ctx); return; case 1: while (++i < l) (ev = events[i]).callback.call(ev.ctx, a1); return; case 2: while (++i < l) (ev = events[i]).callback.call(ev.ctx, a1, a2); return; case 3: while (++i < l) (ev = events[i]).callback.call(ev.ctx, a1, a2, a3); return; default: while (++i < l) (ev = events[i]).callback.apply(ev.ctx, args); } }; var listenMethods = {listenTo: 'on', listenToOnce: 'once'}; // Inversion-of-control versions of `on` and `once`. Tell *this* object to // listen to an event in another object ... keeping track of what it's // listening to. _.each(listenMethods, function(implementation, method) { Events[method] = function(obj, name, callback) { var listeners = this._listeners || (this._listeners = {}); var id = obj._listenerId || (obj._listenerId = _.uniqueId('l')); listeners[id] = obj; if (typeof name === 'object') callback = this; obj[implementation](name, callback, this); return this; }; }); // Aliases for backwards compatibility. Events.bind = Events.on; Events.unbind = Events.off; // Allow the `Backbone` object to serve as a global event bus, for folks who // want global "pubsub" in a convenient place. _.extend(Backbone, Events); // Backbone.Model // -------------- // Backbone **Models** are the basic data object in the framework -- // frequently representing a row in a table in a database on your server. // A discrete chunk of data and a bunch of useful, related methods for // performing computations and transformations on that data. // Create a new model with the specified attributes. A client id (`cid`) // is automatically generated and assigned for you. var Model = Backbone.Model = function(attributes, options) { var defaults; var attrs = attributes || {}; options || (options = {}); this.cid = _.uniqueId('c'); this.attributes = {}; _.extend(this, _.pick(options, modelOptions)); if (options.parse) attrs = this.parse(attrs, options) || {}; if (defaults = _.result(this, 'defaults')) { attrs = _.defaults({}, attrs, defaults); } this.set(attrs, options); this.changed = {}; this.initialize.apply(this, arguments); }; // A list of options to be attached directly to the model, if provided. var modelOptions = ['url', 'urlRoot', 'collection']; // Attach all inheritable methods to the Model prototype. _.extend(Model.prototype, Events, { // A hash of attributes whose current and previous value differ. changed: null, // The value returned during the last failed validation. validationError: null, // The default name for the JSON `id` attribute is `"id"`. MongoDB and // CouchDB users may want to set this to `"_id"`. idAttribute: 'id', // Initialize is an empty function by default. Override it with your own // initialization logic. initialize: function(){}, // Return a copy of the model's `attributes` object. toJSON: function(options) { return _.clone(this.attributes); }, // Proxy `Backbone.sync` by default -- but override this if you need // custom syncing semantics for *this* particular model. sync: function() { return Backbone.sync.apply(this, arguments); }, // Get the value of an attribute. get: function(attr) { return this.attributes[attr]; }, // Get the HTML-escaped value of an attribute. escape: function(attr) { return _.escape(this.get(attr)); }, // Returns `true` if the attribute contains a value that is not null // or undefined. has: function(attr) { return this.get(attr) != null; }, // Set a hash of model attributes on the object, firing `"change"`. This is // the core primitive operation of a model, updating the data and notifying // anyone who needs to know about the change in state. The heart of the beast. set: function(key, val, options) { var attr, attrs, unset, changes, silent, changing, prev, current; if (key == null) return this; // Handle both `"key", value` and `{key: value}` -style arguments. if (typeof key === 'object') { attrs = key; options = val; } else { (attrs = {})[key] = val; } options || (options = {}); // Run validation. if (!this._validate(attrs, options)) return false; // Extract attributes and options. unset = options.unset; silent = options.silent; changes = []; changing = this._changing; this._changing = true; if (!changing) { this._previousAttributes = _.clone(this.attributes); this.changed = {}; } current = this.attributes, prev = this._previousAttributes; // Check for changes of `id`. if (this.idAttribute in attrs) this.id = attrs[this.idAttribute]; // For each `set` attribute, update or delete the current value. for (attr in attrs) { val = attrs[attr]; if (!_.isEqual(current[attr], val)) changes.push(attr); if (!_.isEqual(prev[attr], val)) { this.changed[attr] = val; } else { delete this.changed[attr]; } unset ? delete current[attr] : current[attr] = val; } // Trigger all relevant attribute changes. if (!silent) { if (changes.length) this._pending = true; for (var i = 0, l = changes.length; i < l; i++) { this.trigger('change:' + changes[i], this, current[changes[i]], options); } } // You might be wondering why there's a `while` loop here. Changes can // be recursively nested within `"change"` events. if (changing) return this; if (!silent) { while (this._pending) { this._pending = false; this.trigger('change', this, options); } } this._pending = false; this._changing = false; return this; }, // Remove an attribute from the model, firing `"change"`. `unset` is a noop // if the attribute doesn't exist. unset: function(attr, options) { return this.set(attr, void 0, _.extend({}, options, {unset: true})); }, // Clear all attributes on the model, firing `"change"`. clear: function(options) { var attrs = {}; for (var key in this.attributes) attrs[key] = void 0; return this.set(attrs, _.extend({}, options, {unset: true})); }, // Determine if the model has changed since the last `"change"` event. // If you specify an attribute name, determine if that attribute has changed. hasChanged: function(attr) { if (attr == null) return !_.isEmpty(this.changed); return _.has(this.changed, attr); }, // Return an object containing all the attributes that have changed, or // false if there are no changed attributes. Useful for determining what // parts of a view need to be updated and/or what attributes need to be // persisted to the server. Unset attributes will be set to undefined. // You can also pass an attributes object to diff against the model, // determining if there *would be* a change. changedAttributes: function(diff) { if (!diff) return this.hasChanged() ? _.clone(this.changed) : false; var val, changed = false; var old = this._changing ? this._previousAttributes : this.attributes; for (var attr in diff) { if (_.isEqual(old[attr], (val = diff[attr]))) continue; (changed || (changed = {}))[attr] = val; } return changed; }, // Get the previous value of an attribute, recorded at the time the last // `"change"` event was fired. previous: function(attr) { if (attr == null || !this._previousAttributes) return null; return this._previousAttributes[attr]; }, // Get all of the attributes of the model at the time of the previous // `"change"` event. previousAttributes: function() { return _.clone(this._previousAttributes); }, // Fetch the model from the server. If the server's representation of the // model differs from its current attributes, they will be overridden, // triggering a `"change"` event. fetch: function(options) { options = options ? _.clone(options) : {}; if (options.parse === void 0) options.parse = true; var model = this; var success = options.success; options.success = function(resp) { if (!model.set(model.parse(resp, options), options)) return false; if (success) success(model, resp, options); model.trigger('sync', model, resp, options); }; wrapError(this, options); return this.sync('read', this, options); }, // Set a hash of model attributes, and sync the model to the server. // If the server returns an attributes hash that differs, the model's // state will be `set` again. save: function(key, val, options) { var attrs, method, xhr, attributes = this.attributes; // Handle both `"key", value` and `{key: value}` -style arguments. if (key == null || typeof key === 'object') { attrs = key; options = val; } else { (attrs = {})[key] = val; } // If we're not waiting and attributes exist, save acts as `set(attr).save(null, opts)`. if (attrs && (!options || !options.wait) && !this.set(attrs, options)) return false; options = _.extend({validate: true}, options); // Do not persist invalid models. if (!this._validate(attrs, options)) return false; // Set temporary attributes if `{wait: true}`. if (attrs && options.wait) { this.attributes = _.extend({}, attributes, attrs); } // After a successful server-side save, the client is (optionally) // updated with the server-side state. if (options.parse === void 0) options.parse = true; var model = this; var success = options.success; options.success = function(resp) { // Ensure attributes are restored during synchronous saves. model.attributes = attributes; var serverAttrs = model.parse(resp, options); if (options.wait) serverAttrs = _.extend(attrs || {}, serverAttrs); if (_.isObject(serverAttrs) && !model.set(serverAttrs, options)) { return false; } if (success) success(model, resp, options); model.trigger('sync', model, resp, options); }; wrapError(this, options); method = this.isNew() ? 'create' : (options.patch ? 'patch' : 'update'); if (method === 'patch') options.attrs = attrs; xhr = this.sync(method, this, options); // Restore attributes. if (attrs && options.wait) this.attributes = attributes; return xhr; }, // Destroy this model on the server if it was already persisted. // Optimistically removes the model from its collection, if it has one. // If `wait: true` is passed, waits for the server to respond before removal. destroy: function(options) { options = options ? _.clone(options) : {}; var model = this; var success = options.success; var destroy = function() { model.trigger('destroy', model, model.collection, options); }; options.success = function(resp) { if (options.wait || model.isNew()) destroy(); if (success) success(model, resp, options); if (!model.isNew()) model.trigger('sync', model, resp, options); }; if (this.isNew()) { options.success(); return false; } wrapError(this, options); var xhr = this.sync('delete', this, options); if (!options.wait) destroy(); return xhr; }, // Default URL for the model's representation on the server -- if you're // using Backbone's restful methods, override this to change the endpoint // that will be called. url: function() { var base = _.result(this, 'urlRoot') || _.result(this.collection, 'url') || urlError(); if (this.isNew()) return base; return base + (base.charAt(base.length - 1) === '/' ? '' : '/') + encodeURIComponent(this.id); }, // **parse** converts a response into the hash of attributes to be `set` on // the model. The default implementation is just to pass the response along. parse: function(resp, options) { return resp; }, // Create a new model with identical attributes to this one. clone: function() { return new this.constructor(this.attributes); }, // A model is new if it has never been saved to the server, and lacks an id. isNew: function() { return this.id == null; }, // Check if the model is currently in a valid state. isValid: function(options) { return this._validate({}, _.extend(options || {}, { validate: true })); }, // Run validation against the next complete set of model attributes, // returning `true` if all is well. Otherwise, fire an `"invalid"` event. _validate: function(attrs, options) { if (!options.validate || !this.validate) return true; attrs = _.extend({}, this.attributes, attrs); var error = this.validationError = this.validate(attrs, options) || null; if (!error) return true; this.trigger('invalid', this, error, _.extend(options || {}, {validationError: error})); return false; } }); // Underscore methods that we want to implement on the Model. var modelMethods = ['keys', 'values', 'pairs', 'invert', 'pick', 'omit']; // Mix in each Underscore method as a proxy to `Model#attributes`. _.each(modelMethods, function(method) { Model.prototype[method] = function() { var args = slice.call(arguments); args.unshift(this.attributes); return _[method].apply(_, args); }; }); // Backbone.Collection // ------------------- // If models tend to represent a single row of data, a Backbone Collection is // more analagous to a table full of data ... or a small slice or page of that // table, or a collection of rows that belong together for a particular reason // -- all of the messages in this particular folder, all of the documents // belonging to this particular author, and so on. Collections maintain // indexes of their models, both in order, and for lookup by `id`. // Create a new **Collection**, perhaps to contain a specific type of `model`. // If a `comparator` is specified, the Collection will maintain // its models in sort order, as they're added and removed. var Collection = Backbone.Collection = function(models, options) { options || (options = {}); if (options.url) this.url = options.url; if (options.model) this.model = options.model; if (options.comparator !== void 0) this.comparator = options.comparator; this._reset(); this.initialize.apply(this, arguments); if (models) this.reset(models, _.extend({silent: true}, options)); }; // Default options for `Collection#set`. var setOptions = {add: true, remove: true, merge: true}; var addOptions = {add: true, merge: false, remove: false}; // Define the Collection's inheritable methods. _.extend(Collection.prototype, Events, { // The default model for a collection is just a **Backbone.Model**. // This should be overridden in most cases. model: Model, // Initialize is an empty function by default. Override it with your own // initialization logic. initialize: function(){}, // The JSON representation of a Collection is an array of the // models' attributes. toJSON: function(options) { return this.map(function(model){ return model.toJSON(options); }); }, // Proxy `Backbone.sync` by default. sync: function() { return Backbone.sync.apply(this, arguments); }, // Add a model, or list of models to the set. add: function(models, options) { return this.set(models, _.defaults(options || {}, addOptions)); }, // Remove a model, or a list of models from the set. remove: function(models, options) { models = _.isArray(models) ? models.slice() : [models]; options || (options = {}); var i, l, index, model; for (i = 0, l = models.length; i < l; i++) { model = this.get(models[i]); if (!model) continue; delete this._byId[model.id]; delete this._byId[model.cid]; index = this.indexOf(model); this.models.splice(index, 1); this.length--; if (!options.silent) { options.index = index; model.trigger('remove', model, this, options); } this._removeReference(model); } return this; }, // Update a collection by `set`-ing a new list of models, adding new ones, // removing models that are no longer present, and merging models that // already exist in the collection, as necessary. Similar to **Model#set**, // the core operation for updating the data contained by the collection. set: function(models, options) { options = _.defaults(options || {}, setOptions); if (options.parse) models = this.parse(models, options); if (!_.isArray(models)) models = models ? [models] : []; var i, l, model, attrs, existing, sort; var at = options.at; var sortable = this.comparator && (at == null) && options.sort !== false; var sortAttr = _.isString(this.comparator) ? this.comparator : null; var toAdd = [], toRemove = [], modelMap = {}; // Turn bare objects into model references, and prevent invalid models // from being added. for (i = 0, l = models.length; i < l; i++) { if (!(model = this._prepareModel(models[i], options))) continue; // If a duplicate is found, prevent it from being added and // optionally merge it into the existing model. if (existing = this.get(model)) { if (options.remove) modelMap[existing.cid] = true; if (options.merge) { existing.set(model.attributes, options); if (sortable && !sort && existing.hasChanged(sortAttr)) sort = true; } // This is a new model, push it to the `toAdd` list. } else if (options.add) { toAdd.push(model); // Listen to added models' events, and index models for lookup by // `id` and by `cid`. model.on('all', this._onModelEvent, this); this._byId[model.cid] = model; if (model.id != null) this._byId[model.id] = model; } } // Remove nonexistent models if appropriate. if (options.remove) { for (i = 0, l = this.length; i < l; ++i) { if (!modelMap[(model = this.models[i]).cid]) toRemove.push(model); } if (toRemove.length) this.remove(toRemove, options); } // See if sorting is needed, update `length` and splice in new models. if (toAdd.length) { if (sortable) sort = true; this.length += toAdd.length; if (at != null) { splice.apply(this.models, [at, 0].concat(toAdd)); } else { push.apply(this.models, toAdd); } } // Silently sort the collection if appropriate. if (sort) this.sort({silent: true}); if (options.silent) return this; // Trigger `add` events. for (i = 0, l = toAdd.length; i < l; i++) { (model = toAdd[i]).trigger('add', model, this, options); } // Trigger `sort` if the collection was sorted. if (sort) this.trigger('sort', this, options); return this; }, // When you have more items than you want to add or remove individually, // you can reset the entire set with a new list of models, without firing // any granular `add` or `remove` events. Fires `reset` when finished. // Useful for bulk operations and optimizations. reset: function(models, options) { options || (options = {}); for (var i = 0, l = this.models.length; i < l; i++) { this._removeReference(this.models[i]); } options.previousModels = this.models; this._reset(); this.add(models, _.extend({silent: true}, options)); if (!options.silent) this.trigger('reset', this, options); return this; }, // Add a model to the end of the collection. push: function(model, options) { model = this._prepareModel(model, options); this.add(model, _.extend({at: this.length}, options)); return model; }, // Remove a model from the end of the collection. pop: function(options) { var model = this.at(this.length - 1); this.remove(model, options); return model; }, // Add a model to the beginning of the collection. unshift: function(model, options) { model = this._prepareModel(model, options); this.add(model, _.extend({at: 0}, options)); return model; }, // Remove a model from the beginning of the collection. shift: function(options) { var model = this.at(0); this.remove(model, options); return model; }, // Slice out a sub-array of models from the collection. slice: function(begin, end) { return this.models.slice(begin, end); }, // Get a model from the set by id. get: function(obj) { if (obj == null) return void 0; return this._byId[obj.id != null ? obj.id : obj.cid || obj]; }, // Get the model at the given index. at: function(index) { return this.models[index]; }, // Return models with matching attributes. Useful for simple cases of // `filter`. where: function(attrs, first) { if (_.isEmpty(attrs)) return first ? void 0 : []; return this[first ? 'find' : 'filter'](function(model) { for (var key in attrs) { if (attrs[key] !== model.get(key)) return false; } return true; }); }, // Return the first model with matching attributes. Useful for simple cases // of `find`. findWhere: function(attrs) { return this.where(attrs, true); }, // Force the collection to re-sort itself. You don't need to call this under // normal circumstances, as the set will maintain sort order as each item // is added. sort: function(options) { if (!this.comparator) throw new Error('Cannot sort a set without a comparator'); options || (options = {}); // Run sort based on type of `comparator`. if (_.isString(this.comparator) || this.comparator.length === 1) { this.models = this.sortBy(this.comparator, this); } else { this.models.sort(_.bind(this.comparator, this)); } if (!options.silent) this.trigger('sort', this, options); return this; }, // Figure out the smallest index at which a model should be inserted so as // to maintain order. sortedIndex: function(model, value, context) { value || (value = this.comparator); var iterator = _.isFunction(value) ? value : function(model) { return model.get(value); }; return _.sortedIndex(this.models, model, iterator, context); }, // Pluck an attribute from each model in the collection. pluck: function(attr) { return _.invoke(this.models, 'get', attr); }, // Fetch the default set of models for this collection, resetting the // collection when they arrive. If `reset: true` is passed, the response // data will be passed through the `reset` method instead of `set`. fetch: function(options) { options = options ? _.clone(options) : {}; if (options.parse === void 0) options.parse = true; var success = options.success; var collection = this; options.success = function(resp) { var method = options.reset ? 'reset' : 'set'; collection[method](resp, options); if (success) success(collection, resp, options); collection.trigger('sync', collection, resp, options); }; wrapError(this, options); return this.sync('read', this, options); }, // Create a new instance of a model in this collection. Add the model to the // collection immediately, unless `wait: true` is passed, in which case we // wait for the server to agree. create: function(model, options) { options = options ? _.clone(options) : {}; if (!(model = this._prepareModel(model, options))) return false; if (!options.wait) this.add(model, options); var collection = this; var success = options.success; options.success = function(resp) { if (options.wait) collection.add(model, options); if (success) success(model, resp, options); }; model.save(null, options); return model; }, // **parse** converts a response into a list of models to be added to the // collection. The default implementation is just to pass it through. parse: function(resp, options) { return resp; }, // Create a new collection with an identical list of models as this one. clone: function() { return new this.constructor(this.models); }, // Private method to reset all internal state. Called when the collection // is first initialized or reset. _reset: function() { this.length = 0; this.models = []; this._byId = {}; }, // Prepare a hash of attributes (or other model) to be added to this // collection. _prepareModel: function(attrs, options) { if (attrs instanceof Model) { if (!attrs.collection) attrs.collection = this; return attrs; } options || (options = {}); options.collection = this; var model = new this.model(attrs, options); if (!model._validate(attrs, options)) { this.trigger('invalid', this, attrs, options); return false; } return model; }, // Internal method to sever a model's ties to a collection. _removeReference: function(model) { if (this === model.collection) delete model.collection; model.off('all', this._onModelEvent, this); }, // Internal method called every time a model in the set fires an event. // Sets need to update their indexes when models change ids. All other // events simply proxy through. "add" and "remove" events that originate // in other collections are ignored. _onModelEvent: function(event, model, collection, options) { if ((event === 'add' || event === 'remove') && collection !== this) return; if (event === 'destroy') this.remove(model, options); if (model && event === 'change:' + model.idAttribute) { delete this._byId[model.previous(model.idAttribute)]; if (model.id != null) this._byId[model.id] = model; } this.trigger.apply(this, arguments); } }); // Underscore methods that we want to implement on the Collection. // 90% of the core usefulness of Backbone Collections is actually implemented // right here: var methods = ['forEach', 'each', 'map', 'collect', 'reduce', 'foldl', 'inject', 'reduceRight', 'foldr', 'find', 'detect', 'filter', 'select', 'reject', 'every', 'all', 'some', 'any', 'include', 'contains', 'invoke', 'max', 'min', 'toArray', 'size', 'first', 'head', 'take', 'initial', 'rest', 'tail', 'drop', 'last', 'without', 'indexOf', 'shuffle', 'lastIndexOf', 'isEmpty', 'chain']; // Mix in each Underscore method as a proxy to `Collection#models`. _.each(methods, function(method) { Collection.prototype[method] = function() { var args = slice.call(arguments); args.unshift(this.models); return _[method].apply(_, args); }; }); // Underscore methods that take a property name as an argument. var attributeMethods = ['groupBy', 'countBy', 'sortBy']; // Use attributes instead of properties. _.each(attributeMethods, function(method) { Collection.prototype[method] = function(value, context) { var iterator = _.isFunction(value) ? value : function(model) { return model.get(value); }; return _[method](this.models, iterator, context); }; }); // Backbone.View // ------------- // Backbone Views are almost more convention than they are actual code. A View // is simply a JavaScript object that represents a logical chunk of UI in the // DOM. This might be a single item, an entire list, a sidebar or panel, or // even the surrounding frame which wraps your whole app. Defining a chunk of // UI as a **View** allows you to define your DOM events declaratively, without // having to worry about render order ... and makes it easy for the view to // react to specific changes in the state of your models. // Creating a Backbone.View creates its initial element outside of the DOM, // if an existing element is not provided... var View = Backbone.View = function(options) { this.cid = _.uniqueId('view'); this._configure(options || {}); this._ensureElement(); this.initialize.apply(this, arguments); this.delegateEvents(); }; // Cached regex to split keys for `delegate`. var delegateEventSplitter = /^(\S+)\s*(.*)$/; // List of view options to be merged as properties. var viewOptions = ['model', 'collection', 'el', 'id', 'attributes', 'className', 'tagName', 'events']; // Set up all inheritable **Backbone.View** properties and methods. _.extend(View.prototype, Events, { // The default `tagName` of a View's element is `"div"`. tagName: 'div', // jQuery delegate for element lookup, scoped to DOM elements within the // current view. This should be prefered to global lookups where possible. $: function(selector) { return this.$el.find(selector); }, // Initialize is an empty function by default. Override it with your own // initialization logic. initialize: function(){}, // **render** is the core function that your view should override, in order // to populate its element (`this.el`), with the appropriate HTML. The // convention is for **render** to always return `this`. render: function() { return this; }, // Remove this view by taking the element out of the DOM, and removing any // applicable Backbone.Events listeners. remove: function() { this.$el.remove(); this.stopListening(); return this; }, // Change the view's element (`this.el` property), including event // re-delegation. setElement: function(element, delegate) { if (this.$el) this.undelegateEvents(); this.$el = element instanceof Backbone.$ ? element : Backbone.$(element); this.el = this.$el[0]; if (delegate !== false) this.delegateEvents(); return this; }, // Set callbacks, where `this.events` is a hash of // // *{"event selector": "callback"}* // // { // 'mousedown .title': 'edit', // 'click .button': 'save' // 'click .open': function(e) { ... } // } // // pairs. Callbacks will be bound to the view, with `this` set properly. // Uses event delegation for efficiency. // Omitting the selector binds the event to `this.el`. // This only works for delegate-able events: not `focus`, `blur`, and // not `change`, `submit`, and `reset` in Internet Explorer. delegateEvents: function(events) { if (!(events || (events = _.result(this, 'events')))) return this; this.undelegateEvents(); for (var key in events) { var method = events[key]; if (!_.isFunction(method)) method = this[events[key]]; if (!method) continue; var match = key.match(delegateEventSplitter); var eventName = match[1], selector = match[2]; method = _.bind(method, this); eventName += '.delegateEvents' + this.cid; if (selector === '') { this.$el.on(eventName, method); } else { this.$el.on(eventName, selector, method); } } return this; }, // Clears all callbacks previously bound to the view with `delegateEvents`. // You usually don't need to use this, but may wish to if you have multiple // Backbone views attached to the same DOM element. undelegateEvents: function() { this.$el.off('.delegateEvents' + this.cid); return this; }, // Performs the initial configuration of a View with a set of options. // Keys with special meaning *(e.g. model, collection, id, className)* are // attached directly to the view. See `viewOptions` for an exhaustive // list. _configure: function(options) { if (this.options) options = _.extend({}, _.result(this, 'options'), options); _.extend(this, _.pick(options, viewOptions)); this.options = options; }, // Ensure that the View has a DOM element to render into. // If `this.el` is a string, pass it through `$()`, take the first // matching element, and re-assign it to `el`. Otherwise, create // an element from the `id`, `className` and `tagName` properties. _ensureElement: function() { if (!this.el) { var attrs = _.extend({}, _.result(this, 'attributes')); if (this.id) attrs.id = _.result(this, 'id'); if (this.className) attrs['class'] = _.result(this, 'className'); var $el = Backbone.$('<' + _.result(this, 'tagName') + '>').attr(attrs); this.setElement($el, false); } else { this.setElement(_.result(this, 'el'), false); } } }); // Backbone.sync // ------------- // Override this function to change the manner in which Backbone persists // models to the server. You will be passed the type of request, and the // model in question. By default, makes a RESTful Ajax request // to the model's `url()`. Some possible customizations could be: // // * Use `setTimeout` to batch rapid-fire updates into a single request. // * Send up the models as XML instead of JSON. // * Persist models via WebSockets instead of Ajax. // // Turn on `Backbone.emulateHTTP` in order to send `PUT` and `DELETE` requests // as `POST`, with a `_method` parameter containing the true HTTP method, // as well as all requests with the body as `application/x-www-form-urlencoded` // instead of `application/json` with the model in a param named `model`. // Useful when interfacing with server-side languages like **PHP** that make // it difficult to read the body of `PUT` requests. Backbone.sync = function(method, model, options) { var type = methodMap[method]; // Default options, unless specified. _.defaults(options || (options = {}), { emulateHTTP: Backbone.emulateHTTP, emulateJSON: Backbone.emulateJSON }); // Default JSON-request options. var params = {type: type, dataType: 'json'}; // Ensure that we have a URL. if (!options.url) { params.url = _.result(model, 'url') || urlError(); } // Ensure that we have the appropriate request data. if (options.data == null && model && (method === 'create' || method === 'update' || method === 'patch')) { params.contentType = 'application/json'; params.data = JSON.stringify(options.attrs || model.toJSON(options)); } // For older servers, emulate JSON by encoding the request into an HTML-form. if (options.emulateJSON) { params.contentType = 'application/x-www-form-urlencoded'; params.data = params.data ? {model: params.data} : {}; } // For older servers, emulate HTTP by mimicking the HTTP method with `_method` // And an `X-HTTP-Method-Override` header. if (options.emulateHTTP && (type === 'PUT' || type === 'DELETE' || type === 'PATCH')) { params.type = 'POST'; if (options.emulateJSON) params.data._method = type; var beforeSend = options.beforeSend; options.beforeSend = function(xhr) { xhr.setRequestHeader('X-HTTP-Method-Override', type); if (beforeSend) return beforeSend.apply(this, arguments); }; } // Don't process data on a non-GET request. if (params.type !== 'GET' && !options.emulateJSON) { params.processData = false; } // If we're sending a `PATCH` request, and we're in an old Internet Explorer // that still has ActiveX enabled by default, override jQuery to use that // for XHR instead. Remove this line when jQuery supports `PATCH` on IE8. if (params.type === 'PATCH' && window.ActiveXObject && !(window.external && window.external.msActiveXFilteringEnabled)) { params.xhr = function() { return new ActiveXObject("Microsoft.XMLHTTP"); }; } // Make the request, allowing the user to override any Ajax options. var xhr = options.xhr = Backbone.ajax(_.extend(params, options)); model.trigger('request', model, xhr, options); return xhr; }; // Map from CRUD to HTTP for our default `Backbone.sync` implementation. var methodMap = { 'create': 'POST', 'update': 'PUT', 'patch': 'PATCH', 'delete': 'DELETE', 'read': 'GET' }; // Set the default implementation of `Backbone.ajax` to proxy through to `$`. // Override this if you'd like to use a different library. Backbone.ajax = function() { return Backbone.$.ajax.apply(Backbone.$, arguments); }; // Backbone.Router // --------------- // Routers map faux-URLs to actions, and fire events when routes are // matched. Creating a new one sets its `routes` hash, if not set statically. var Router = Backbone.Router = function(options) { options || (options = {}); if (options.routes) this.routes = options.routes; this._bindRoutes(); this.initialize.apply(this, arguments); }; // Cached regular expressions for matching named param parts and splatted // parts of route strings. var optionalParam = /\((.*?)\)/g; var namedParam = /(\(\?)?:\w+/g; var splatParam = /\*\w+/g; var escapeRegExp = /[\-{}\[\]+?.,\\\^$|#\s]/g; // Set up all inheritable **Backbone.Router** properties and methods. _.extend(Router.prototype, Events, { // Initialize is an empty function by default. Override it with your own // initialization logic. initialize: function(){}, // Manually bind a single named route to a callback. For example: // // this.route('search/:query/p:num', 'search', function(query, num) { // ... // }); // route: function(route, name, callback) { if (!_.isRegExp(route)) route = this._routeToRegExp(route); if (_.isFunction(name)) { callback = name; name = ''; } if (!callback) callback = this[name]; var router = this; Backbone.history.route(route, function(fragment) { var args = router._extractParameters(route, fragment); callback && callback.apply(router, args); router.trigger.apply(router, ['route:' + name].concat(args)); router.trigger('route', name, args); Backbone.history.trigger('route', router, name, args); }); return this; }, // Simple proxy to `Backbone.history` to save a fragment into the history. navigate: function(fragment, options) { Backbone.history.navigate(fragment, options); return this; }, // Bind all defined routes to `Backbone.history`. We have to reverse the // order of the routes here to support behavior where the most general // routes can be defined at the bottom of the route map. _bindRoutes: function() { if (!this.routes) return; this.routes = _.result(this, 'routes'); var route, routes = _.keys(this.routes); while ((route = routes.pop()) != null) { this.route(route, this.routes[route]); } }, // Convert a route string into a regular expression, suitable for matching // against the current location hash. _routeToRegExp: function(route) { route = route.replace(escapeRegExp, '\\$&') .replace(optionalParam, '(?:$1)?') .replace(namedParam, function(match, optional){ return optional ? match : '([^\/]+)'; }) .replace(splatParam, '(.*?)'); return new RegExp('^' + route + '$'); }, // Given a route, and a URL fragment that it matches, return the array of // extracted decoded parameters. Empty or unmatched parameters will be // treated as `null` to normalize cross-browser behavior. _extractParameters: function(route, fragment) { var params = route.exec(fragment).slice(1); return _.map(params, function(param) { return param ? decodeURIComponent(param) : null; }); } }); // Backbone.History // ---------------- // Handles cross-browser history management, based on either // [pushState](http://diveintohtml5.info/history.html) and real URLs, or // [onhashchange](https://developer.mozilla.org/en-US/docs/DOM/window.onhashchange) // and URL fragments. If the browser supports neither (old IE, natch), // falls back to polling. var History = Backbone.History = function() { this.handlers = []; _.bindAll(this, 'checkUrl'); // Ensure that `History` can be used outside of the browser. if (typeof window !== 'undefined') { this.location = window.location; this.history = window.history; } }; // Cached regex for stripping a leading hash/slash and trailing space. var routeStripper = /^[#\/]|\s+$/g; // Cached regex for stripping leading and trailing slashes. var rootStripper = /^\/+|\/+$/g; // Cached regex for detecting MSIE. var isExplorer = /msie [\w.]+/; // Cached regex for removing a trailing slash. var trailingSlash = /\/$/; // Has the history handling already been started? History.started = false; // Set up all inheritable **Backbone.History** properties and methods. _.extend(History.prototype, Events, { // The default interval to poll for hash changes, if necessary, is // twenty times a second. interval: 50, // Gets the true hash value. Cannot use location.hash directly due to bug // in Firefox where location.hash will always be decoded. getHash: function(window) { var match = (window || this).location.href.match(/#(.*)$/); return match ? match[1] : ''; }, // Get the cross-browser normalized URL fragment, either from the URL, // the hash, or the override. getFragment: function(fragment, forcePushState) { if (fragment == null) { if (this._hasPushState || !this._wantsHashChange || forcePushState) { fragment = this.location.pathname; var root = this.root.replace(trailingSlash, ''); if (!fragment.indexOf(root)) fragment = fragment.substr(root.length); } else { fragment = this.getHash(); } } return fragment.replace(routeStripper, ''); }, // Start the hash change handling, returning `true` if the current URL matches // an existing route, and `false` otherwise. start: function(options) { if (History.started) throw new Error("Backbone.history has already been started"); History.started = true; // Figure out the initial configuration. Do we need an iframe? // Is pushState desired ... is it available? this.options = _.extend({}, {root: '/'}, this.options, options); this.root = this.options.root; this._wantsHashChange = this.options.hashChange !== false; this._wantsPushState = !!this.options.pushState; this._hasPushState = !!(this.options.pushState && this.history && this.history.pushState); var fragment = this.getFragment(); var docMode = document.documentMode; var oldIE = (isExplorer.exec(navigator.userAgent.toLowerCase()) && (!docMode || docMode <= 7)); // Normalize root to always include a leading and trailing slash. this.root = ('/' + this.root + '/').replace(rootStripper, '/'); if (oldIE && this._wantsHashChange) { this.iframe = Backbone.$('') .css("opacity", "0").appendTo(document.body); if (parseInt($.browser.version)<7) { dialog.css("position", "absolute"); overlay.css("position", "absolute"); $("html,body").css({width: "100%", height: "100%"}); } } overlay.appendTo(document.body).fadeTo(100, 0.6); dialog.appendTo(document.body).addClass("loading").centerBox().fadeIn(400); $(document).keydown(function(e) { if (e.keyCode == 27) dismiss(); // dismiss on escape key }); function dismiss() { dialog.fadeOut("fast", function() { $("#dialog, #overlay, #overlay-frame").remove(); }); $(document).unbind("keydown"); } overlay.click(function() { dismiss(); }); function showError(name, message) { var input = dialog.find(":input[name=" + name + "]"); input.addClass("error").next("div.error").remove(); $('
    ').text(message).insertAfter(input); } $.get(url, function(html) { $(html).appendTo(dialog); dialog.removeClass("loading").addClass("loaded").centerBox().each(function() { options.load(dialog.children()[0]); $(":input:first", dialog).each(function() { this.focus() }); $("button.cancel", dialog).click(function() { // dismiss on cancel dismiss(); options.cancel(); }); $("form", dialog).submit(function(e) { // invoke callback on submit e.preventDefault(); dialog.find("div.error").remove().end().find(".error").removeClass("error"); var data = {}; $.each($("form :input", dialog).serializeArray(), function(i, field) { data[field.name] = field.value; }); $("form :file", dialog).each(function() { data[this.name] = this.value; // file inputs need special handling }); options.submit(data, function callback(errors) { if ($.isEmptyObject(errors)) { dismiss(); } else { for (var name in errors) { showError(name, errors[name]); } } }); return false; }); }); }); } })(jQuery); apache-couchdb-1.5.0/share/www/script/base64.js0000644000175000001440000000746312230722213016140 00000000000000/* Copyright (C) 1999 Masanao Izumo * Version: 1.0 * LastModified: Dec 25 1999 * This library is free. You can redistribute it and/or modify it. */ /* Modified by Chris Anderson to not use CommonJS */ /* Modified by Dan Webb not to require Narwhal's binary library */ var Base64 = {}; (function(exports) { var encodeChars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; var decodeChars = [ -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 62, -1, -1, -1, 63, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, -1, -1, -1, -1, -1, -1, -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, -1, -1, -1, -1, -1, -1, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, -1, -1, -1, -1, -1 ]; exports.encode = function (str) { var out, i, length; var c1, c2, c3; length = len(str); i = 0; out = []; while(i < length) { c1 = str.charCodeAt(i++) & 0xff; if(i == length) { out.push(encodeChars.charCodeAt(c1 >> 2)); out.push(encodeChars.charCodeAt((c1 & 0x3) << 4)); out.push("=".charCodeAt(0)); out.push("=".charCodeAt(0)); break; } c2 = str.charCodeAt(i++); if(i == length) { out.push(encodeChars.charCodeAt(c1 >> 2)); out.push(encodeChars.charCodeAt(((c1 & 0x3)<< 4) | ((c2 & 0xF0) >> 4))); out.push(encodeChars.charCodeAt((c2 & 0xF) << 2)); out.push("=".charCodeAt(0)); break; } c3 = str.charCodeAt(i++); out.push(encodeChars.charCodeAt(c1 >> 2)); out.push(encodeChars.charCodeAt(((c1 & 0x3)<< 4) | ((c2 & 0xF0) >> 4))); out.push(encodeChars.charCodeAt(((c2 & 0xF) << 2) | ((c3 & 0xC0) >>6))); out.push(encodeChars.charCodeAt(c3 & 0x3F)); } var str = ""; out.forEach(function(chr) { str += String.fromCharCode(chr) }); return str; }; exports.decode = function (str) { var c1, c2, c3, c4; var i, length, out; length = len(str); i = 0; out = []; while(i < length) { /* c1 */ do { c1 = decodeChars[str.charCodeAt(i++) & 0xff]; } while(i < length && c1 == -1); if(c1 == -1) break; /* c2 */ do { c2 = decodeChars[str.charCodeAt(i++) & 0xff]; } while(i < length && c2 == -1); if(c2 == -1) break; out.push(String.fromCharCode((c1 << 2) | ((c2 & 0x30) >> 4))); /* c3 */ do { c3 = str.charCodeAt(i++) & 0xff; if(c3 == 61) return out.join(''); c3 = decodeChars[c3]; } while(i < length && c3 == -1); if(c3 == -1) break; out.push(String.fromCharCode(((c2 & 0xF) << 4) | ((c3 & 0x3C) >> 2))); /* c4 */ do { c4 = str.charCodeAt(i++) & 0xff; if(c4 == 61) return out.join(''); c4 = decodeChars[c4]; } while(i < length && c4 == -1); if(c4 == -1) break; out.push(String.fromCharCode(((c3 & 0x03) << 6) | c4)); } return out.join(''); }; var len = function (object) { if (object.length !== undefined) { return object.length; } else if (object.getLength !== undefined) { return object.getLength(); } else { return undefined; } }; })(Base64); apache-couchdb-1.5.0/share/www/script/couch_tests.js0000644000175000001440000000677212230722213017401 00000000000000// 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. CouchDB.urlPrefix = ".."; var couchTests = {}; function loadTest(file) { loadScript("script/test/"+file); }; // keep first loadTest("basics.js"); // keep sorted loadTest("all_docs.js"); loadTest("attachments.js"); loadTest("attachments_multipart.js"); loadTest("attachment_names.js"); loadTest("attachment_paths.js"); loadTest("attachment_ranges.js"); loadTest("attachment_views.js"); loadTest("auth_cache.js"); loadTest("batch_save.js"); loadTest("bulk_docs.js"); loadTest("changes.js"); loadTest("coffee.js"); loadTest("compact.js"); loadTest("config.js"); loadTest("conflicts.js"); loadTest("content_negotiation.js"); loadTest("cookie_auth.js"); loadTest("copy_doc.js"); loadTest("delayed_commits.js"); loadTest("design_docs.js"); loadTest("design_options.js"); loadTest("design_paths.js"); loadTest("erlang_views.js"); loadTest("etags_head.js"); loadTest("etags_views.js"); loadTest("form_submit.js"); loadTest("http.js"); loadTest("invalid_docids.js"); loadTest("jsonp.js"); loadTest("large_docs.js"); loadTest("list_views.js"); loadTest("lots_of_docs.js"); loadTest("method_override.js"); loadTest("multiple_rows.js"); loadScript("script/oauth.js"); loadScript("script/sha1.js"); loadTest("oauth.js"); loadTest("oauth_users_db.js"); loadTest("proxyauth.js"); loadTest("purge.js"); loadTest("reader_acl.js"); loadTest("recreate_doc.js"); loadTest("reduce.js"); loadTest("reduce_builtin.js"); loadTest("reduce_false.js"); loadTest("reduce_false_temp.js"); loadTest("replication.js"); loadScript("script/replicator_db_inc.js"); loadTest("replicator_db_bad_rep_id.js"); loadTest("replicator_db_by_doc_id.js"); loadTest("replicator_db_compact_rep_db.js"); loadTest("replicator_db_continuous.js"); loadTest("replicator_db_credential_delegation.js"); loadTest("replicator_db_field_validation.js"); loadTest("replicator_db_filtered.js"); loadTest("replicator_db_identical.js"); loadTest("replicator_db_identical_continuous.js"); loadTest("replicator_db_invalid_filter.js"); loadTest("replicator_db_simple.js"); loadTest("replicator_db_successive.js"); loadTest("replicator_db_survives.js"); loadTest("replicator_db_swap_rep_db.js"); loadTest("replicator_db_update_security.js"); loadTest("replicator_db_user_ctx.js"); loadTest("replicator_db_write_auth.js"); loadTest("replicator_db_security.js"); loadTest("rev_stemming.js"); loadTest("rewrite.js"); loadTest("security_validation.js"); loadTest("show_documents.js"); loadTest("stats.js"); loadTest("update_documents.js"); loadTest("users_db.js"); loadTest("users_db_security.js"); loadTest("utf8.js"); loadTest("uuids.js"); loadTest("view_collation.js"); loadTest("view_collation_raw.js"); loadTest("view_conflicts.js"); loadTest("view_compaction.js"); loadTest("view_errors.js"); loadTest("view_include_docs.js"); loadTest("view_multi_key_all_docs.js"); loadTest("view_multi_key_design.js"); loadTest("view_multi_key_temp.js"); loadTest("view_offsets.js"); loadTest("view_pagination.js"); loadTest("view_sandboxing.js"); loadTest("view_update_seq.js"); // keep sorted apache-couchdb-1.5.0/share/www/custom_test.html0000644000175000001440000000707612230722213016451 00000000000000 Custom Test

    Overview Test Suite Custom Test

    Test Function
      
    apache-couchdb-1.5.0/share/www/couch_tests.html0000644000175000001440000000672312230722213016421 00000000000000 Test Suite

    Overview Test Suite

    Note: Each of the tests will block the browser. If the connection to your CouchDB server is slow, running the tests will take some time, and you'll not be able to do much with your browser while a test is being executed. Also: The test suite is designed to work with Firefox (with Firebug disabled). Patches are welcome for convenience compatibility with other browsers, but official support is for Firefox (latest stable version) only.

    Tests
    Name Status Elapsed Time Details
    apache-couchdb-1.5.0/share/www/verify_install.html0000644000175000001440000000703612230722213017126 00000000000000 Test Suite

    Overview Verify Install

    apache-couchdb-1.5.0/share/www/session.html0000644000175000001440000000700012230722213015546 00000000000000 Session

    Overview Session

    Establish or Modify Your Session

    Signup or Login Welcome ?!
    Logout
    Welcome ?!
    Setup more admins or Logout
    Welcome to Admin Party!
    Everyone is admin. Fix this
    apache-couchdb-1.5.0/share/Makefile.am0000644000175000001440000002137512230722213014420 00000000000000## 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. SUBDIRS = doc JS_FILE = server/main.js JS_FILE_COMPONENTS = \ server/json2.js \ server/filter.js \ server/mimeparse.js \ server/render.js \ server/state.js \ server/util.js \ server/validate.js \ server/views.js JS_FILE_COMPONENTS_LAST = server/loop.js $(JS_FILE): $(JS_FILE_COMPONENTS) $(JS_FILE_COMPONENTS_LAST) mkdir -p `dirname $(JS_FILE)` echo "// DO NOT EDIT THIS FILE BY HAND" > $@ echo >> $@ cat $^ >> $@ COFFEE_FILE = server/main-coffee.js COFFEE_FILE_COMPONENTS_LAST = server/coffee-script.js server/loop.js $(COFFEE_FILE): $(JS_FILE_COMPONENTS) $(COFFEE_FILE_COMPONENTS_LAST) mkdir -p `dirname $(COFFEE_FILE)` echo "// DO NOT EDIT THIS FILE BY HAND" > $@ echo >> $@ cat $^ >> $@ CLEANFILES = $(JS_FILE) $(COFFEE_FILE) EXTRA_DIST = $(JS_FILE_COMPONENTS) $(JS_FILE_COMPONENTS_LAST) $(COFFEE_FILE_COMPONENTS_LAST) nobase_localdata_SCRIPTS = \ $(JS_FILE) \ $(COFFEE_FILE) nobase_dist_localdata_DATA = \ www/config.html \ www/couch_tests.html \ www/custom_test.html \ www/database.html \ www/session.html \ www/dialog/_admin_party.html \ www/dialog/_change_password.html \ www/dialog/_compact_cleanup.html \ www/dialog/_create_admin.html \ www/dialog/_login.html \ www/dialog/_signup.html \ www/dialog/_create_database.html \ www/dialog/_create_config.html \ www/dialog/_delete_database.html \ www/dialog/_delete_document.html \ www/dialog/_database_security.html \ www/dialog/_share_test_reports.html \ www/dialog/_save_view_as.html \ www/dialog/_upload_attachment.html \ www/document.html \ www/fauxton/css/index.css \ www/fauxton/img/couchdb-site.png \ www/fauxton/img/couchdblogo.png \ www/fauxton/img/fontawesome-webfont.eot \ www/fauxton/img/fontawesome-webfont.svg \ www/fauxton/img/fontawesome-webfont.ttf \ www/fauxton/img/fontawesome-webfont.woff \ www/fauxton/img/FontAwesome.otf \ www/fauxton/img/fontcustom_fauxton.eot \ www/fauxton/img/fontcustom_fauxton.svg \ www/fauxton/img/fontcustom_fauxton.ttf \ www/fauxton/img/fontcustom_fauxton.woff \ www/fauxton/img/glyphicons-halflings-white.png \ www/fauxton/img/glyphicons-halflings.png \ www/fauxton/img/linen.png \ www/fauxton/img/loader.gif \ www/fauxton/img/minilogo.png \ www/fauxton/index.html \ www/fauxton/js/require.js \ www/favicon.ico \ www/image/add.png \ www/image/apply.gif \ www/image/bg.png \ www/image/cancel.gif \ www/image/compact.png \ www/image/delete-mini.png \ www/image/delete.png \ www/image/grippie.gif \ www/image/hgrad.gif \ www/image/key.png \ www/image/load.png \ www/image/logo.png \ www/image/order-asc.gif \ www/image/order-desc.gif \ www/image/path.gif \ www/image/progress.gif \ www/image/rarrow.png \ www/image/run-mini.png \ www/image/run.png \ www/image/running.png \ www/image/save.png \ www/image/sidebar-toggle.png \ www/image/spinner.gif \ www/image/spinner_33.gif \ www/image/spinner_6b.gif \ www/image/test_failure.gif \ www/image/test_success.gif \ www/image/thead-key.gif \ www/image/thead.gif \ www/image/toggle-collapse.gif \ www/image/toggle-expand.gif \ www/image/twisty.gif \ www/index.html \ www/plugins.html \ www/replicator.html \ www/script/couch.js \ www/script/couch_tests.js \ www/script/couch_test_runner.js \ www/script/futon.browse.js \ www/script/futon.format.js \ www/script/futon.js \ www/script/jquery.couch.js \ www/script/jquery.dialog.js \ www/script/jquery.editinline.js \ www/script/jquery.form.js \ www/script/jquery.js \ www/script/jquery-ui-1.8.11.custom.min.js \ www/script/jquery.resizer.js \ www/script/jquery.suggest.js \ www/script/json2.js \ www/script/jspec/jspec.css \ www/script/jspec/jspec.jquery.js \ www/script/jspec/jspec.js \ www/script/jspec/jspec.xhr.js \ www/script/oauth.js \ www/script/sha1.js \ www/script/base64.js \ www/script/test/all_docs.js \ www/script/test/attachments.js \ www/script/test/attachments_multipart.js \ www/script/test/attachment_names.js \ www/script/test/attachment_paths.js \ www/script/test/attachment_ranges.js \ www/script/test/attachment_views.js \ www/script/test/auth_cache.js \ www/script/test/basics.js \ www/script/test/batch_save.js \ www/script/test/bulk_docs.js \ www/script/test/changes.js \ www/script/test/coffee.js \ www/script/test/compact.js \ www/script/test/config.js \ www/script/test/conflicts.js \ www/script/test/content_negotiation.js \ www/script/test/cookie_auth.js \ www/script/test/copy_doc.js \ www/script/test/delayed_commits.js \ www/script/test/design_docs.js \ www/script/test/design_options.js \ www/script/test/design_paths.js \ www/script/test/erlang_views.js \ www/script/test/etags_head.js \ www/script/test/etags_views.js \ www/script/test/form_submit.js \ www/script/test/http.js \ www/script/test/invalid_docids.js \ www/script/test/jsonp.js \ www/script/test/large_docs.js \ www/script/test/list_views.js \ www/script/test/lorem.txt \ www/script/test/lorem_b64.txt \ www/script/test/lots_of_docs.js \ www/script/test/method_override.js \ www/script/test/multiple_rows.js \ www/script/test/oauth.js \ www/script/test/oauth_users_db.js \ www/script/test/proxyauth.js \ www/script/test/purge.js \ www/script/test/reader_acl.js \ www/script/test/recreate_doc.js \ www/script/test/reduce.js \ www/script/test/reduce_builtin.js \ www/script/test/reduce_false.js \ www/script/test/reduce_false_temp.js \ www/script/test/replication.js \ www/script/replicator_db_inc.js \ www/script/test/replicator_db_bad_rep_id.js \ www/script/test/replicator_db_by_doc_id.js \ www/script/test/replicator_db_compact_rep_db.js \ www/script/test/replicator_db_continuous.js \ www/script/test/replicator_db_credential_delegation.js \ www/script/test/replicator_db_field_validation.js \ www/script/test/replicator_db_filtered.js \ www/script/test/replicator_db_identical.js \ www/script/test/replicator_db_identical_continuous.js \ www/script/test/replicator_db_invalid_filter.js \ www/script/test/replicator_db_security.js \ www/script/test/replicator_db_simple.js \ www/script/test/replicator_db_successive.js \ www/script/test/replicator_db_survives.js \ www/script/test/replicator_db_swap_rep_db.js \ www/script/test/replicator_db_update_security.js \ www/script/test/replicator_db_user_ctx.js \ www/script/test/replicator_db_write_auth.js \ www/script/test/rev_stemming.js \ www/script/test/rewrite.js \ www/script/test/security_validation.js \ www/script/test/show_documents.js \ www/script/test/stats.js \ www/script/test/update_documents.js \ www/script/test/users_db.js \ www/script/test/users_db_security.js \ www/script/test/utf8.js \ www/script/test/uuids.js \ www/script/test/view_collation.js \ www/script/test/view_collation_raw.js \ www/script/test/view_conflicts.js \ www/script/test/view_compaction.js \ www/script/test/view_errors.js \ www/script/test/view_include_docs.js \ www/script/test/view_multi_key_all_docs.js \ www/script/test/view_multi_key_design.js \ www/script/test/view_multi_key_temp.js \ www/script/test/view_offsets.js \ www/script/test/view_update_seq.js \ www/script/test/view_pagination.js \ www/script/test/view_sandboxing.js \ www/spec/couch_js_class_methods_spec.js \ www/spec/couch_js_instance_methods_1_spec.js \ www/spec/couch_js_instance_methods_2_spec.js \ www/spec/couch_js_instance_methods_3_spec.js \ www/spec/custom_helpers.js \ www/spec/jquery_couch_js_class_methods_spec.js \ www/spec/jquery_couch_js_instance_methods_1_spec.js \ www/spec/jquery_couch_js_instance_methods_2_spec.js \ www/spec/jquery_couch_js_instance_methods_3_spec.js \ www/spec/run.html \ www/status.html \ www/style/jquery-ui-1.8.11.custom.css \ www/style/layout.css \ www/verify_install.html \ www/_sidebar.html apache-couchdb-1.5.0/share/Makefile.in0000644000175000001440000007766412230722242014447 00000000000000# Makefile.in generated by automake 1.11.6 from Makefile.am. # @configure_input@ # Copyright (C) 1994, 1995, 1996, 1997, 1998, 1999, 2000, 2001, 2002, # 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011 Free Software # Foundation, Inc. # This Makefile.in is free software; the Free Software Foundation # gives unlimited permission to copy and/or distribute it, # with or without modifications, as long as this notice is preserved. # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY, to the extent permitted by law; without # even the implied warranty of MERCHANTABILITY or FITNESS FOR A # PARTICULAR PURPOSE. @SET_MAKE@ VPATH = @srcdir@ am__make_dryrun = \ { \ am__dry=no; \ case $$MAKEFLAGS in \ *\\[\ \ ]*) \ echo 'am--echo: ; @echo "AM" OK' | $(MAKE) -f - 2>/dev/null \ | grep '^AM OK$$' >/dev/null || am__dry=yes;; \ *) \ for am__flg in $$MAKEFLAGS; do \ case $$am__flg in \ *=*|--*) ;; \ *n*) am__dry=yes; break;; \ esac; \ done;; \ esac; \ test $$am__dry = yes; \ } pkgdatadir = $(datadir)/@PACKAGE@ pkgincludedir = $(includedir)/@PACKAGE@ pkglibdir = $(libdir)/@PACKAGE@ pkglibexecdir = $(libexecdir)/@PACKAGE@ am__cd = CDPATH="$${ZSH_VERSION+.}$(PATH_SEPARATOR)" && cd install_sh_DATA = $(install_sh) -c -m 644 install_sh_PROGRAM = $(install_sh) -c install_sh_SCRIPT = $(install_sh) -c INSTALL_HEADER = $(INSTALL_DATA) transform = $(program_transform_name) NORMAL_INSTALL = : PRE_INSTALL = : POST_INSTALL = : NORMAL_UNINSTALL = : PRE_UNINSTALL = : POST_UNINSTALL = : build_triplet = @build@ host_triplet = @host@ subdir = share DIST_COMMON = $(nobase_dist_localdata_DATA) $(srcdir)/Makefile.am \ $(srcdir)/Makefile.in ACLOCAL_M4 = $(top_srcdir)/aclocal.m4 am__aclocal_m4_deps = $(top_srcdir)/m4/libtool.m4 \ $(top_srcdir)/m4/ltoptions.m4 $(top_srcdir)/m4/ltsugar.m4 \ $(top_srcdir)/m4/ltversion.m4 $(top_srcdir)/m4/lt~obsolete.m4 \ $(top_srcdir)/acinclude.m4 $(top_srcdir)/configure.ac am__configure_deps = $(am__aclocal_m4_deps) $(CONFIGURE_DEPENDENCIES) \ $(ACLOCAL_M4) mkinstalldirs = $(install_sh) -d CONFIG_HEADER = $(top_builddir)/config.h \ $(top_builddir)/src/snappy/google-snappy/config.h CONFIG_CLEAN_FILES = CONFIG_CLEAN_VPATH_FILES = am__vpath_adj_setup = srcdirstrip=`echo "$(srcdir)" | sed 's|.|.|g'`; am__vpath_adj = case $$p in \ $(srcdir)/*) f=`echo "$$p" | sed "s|^$$srcdirstrip/||"`;; \ *) f=$$p;; \ esac; am__strip_dir = f=`echo $$p | sed -e 's|^.*/||'`; am__install_max = 40 am__nobase_strip_setup = \ srcdirstrip=`echo "$(srcdir)" | sed 's/[].[^$$\\*|]/\\\\&/g'` am__nobase_strip = \ for p in $$list; do echo "$$p"; done | sed -e "s|$$srcdirstrip/||" am__nobase_list = $(am__nobase_strip_setup); \ for p in $$list; do echo "$$p $$p"; done | \ sed "s| $$srcdirstrip/| |;"' / .*\//!s/ .*/ ./; s,\( .*\)/[^/]*$$,\1,' | \ $(AWK) 'BEGIN { files["."] = "" } { files[$$2] = files[$$2] " " $$1; \ if (++n[$$2] == $(am__install_max)) \ { print $$2, files[$$2]; n[$$2] = 0; files[$$2] = "" } } \ END { for (dir in files) print dir, files[dir] }' am__base_list = \ sed '$$!N;$$!N;$$!N;$$!N;$$!N;$$!N;$$!N;s/\n/ /g' | \ sed '$$!N;$$!N;$$!N;$$!N;s/\n/ /g' am__uninstall_files_from_dir = { \ test -z "$$files" \ || { test ! -d "$$dir" && test ! -f "$$dir" && test ! -r "$$dir"; } \ || { echo " ( cd '$$dir' && rm -f" $$files ")"; \ $(am__cd) "$$dir" && rm -f $$files; }; \ } am__installdirs = "$(DESTDIR)$(localdatadir)" \ "$(DESTDIR)$(localdatadir)" SCRIPTS = $(nobase_localdata_SCRIPTS) SOURCES = DIST_SOURCES = RECURSIVE_TARGETS = all-recursive check-recursive dvi-recursive \ html-recursive info-recursive install-data-recursive \ install-dvi-recursive install-exec-recursive \ install-html-recursive install-info-recursive \ install-pdf-recursive install-ps-recursive install-recursive \ installcheck-recursive installdirs-recursive pdf-recursive \ ps-recursive uninstall-recursive am__can_run_installinfo = \ case $$AM_UPDATE_INFO_DIR in \ n|no|NO) false;; \ *) (install-info --version) >/dev/null 2>&1;; \ esac DATA = $(nobase_dist_localdata_DATA) RECURSIVE_CLEAN_TARGETS = mostlyclean-recursive clean-recursive \ distclean-recursive maintainer-clean-recursive AM_RECURSIVE_TARGETS = $(RECURSIVE_TARGETS:-recursive=) \ $(RECURSIVE_CLEAN_TARGETS:-recursive=) tags TAGS ctags CTAGS \ distdir ETAGS = etags CTAGS = ctags DIST_SUBDIRS = $(SUBDIRS) DISTFILES = $(DIST_COMMON) $(DIST_SOURCES) $(TEXINFOS) $(EXTRA_DIST) am__relativize = \ dir0=`pwd`; \ sed_first='s,^\([^/]*\)/.*$$,\1,'; \ sed_rest='s,^[^/]*/*,,'; \ sed_last='s,^.*/\([^/]*\)$$,\1,'; \ sed_butlast='s,/*[^/]*$$,,'; \ while test -n "$$dir1"; do \ first=`echo "$$dir1" | sed -e "$$sed_first"`; \ if test "$$first" != "."; then \ if test "$$first" = ".."; then \ dir2=`echo "$$dir0" | sed -e "$$sed_last"`/"$$dir2"; \ dir0=`echo "$$dir0" | sed -e "$$sed_butlast"`; \ else \ first2=`echo "$$dir2" | sed -e "$$sed_first"`; \ if test "$$first2" = "$$first"; then \ dir2=`echo "$$dir2" | sed -e "$$sed_rest"`; \ else \ dir2="../$$dir2"; \ fi; \ dir0="$$dir0"/"$$first"; \ fi; \ fi; \ dir1=`echo "$$dir1" | sed -e "$$sed_rest"`; \ done; \ reldir="$$dir2" ACLOCAL = @ACLOCAL@ AMTAR = @AMTAR@ AR = @AR@ AS = @AS@ AUTOCONF = @AUTOCONF@ AUTOHEADER = @AUTOHEADER@ AUTOMAKE = @AUTOMAKE@ AWK = @AWK@ CC = @CC@ CCDEPMODE = @CCDEPMODE@ CFLAGS = @CFLAGS@ CPP = @CPP@ CPPFLAGS = @CPPFLAGS@ CURL_CFLAGS = @CURL_CFLAGS@ CURL_CONFIG = @CURL_CONFIG@ CURL_LIBS = @CURL_LIBS@ CXX = @CXX@ CXXCPP = @CXXCPP@ CXXDEPMODE = @CXXDEPMODE@ CXXFLAGS = @CXXFLAGS@ CYGPATH_W = @CYGPATH_W@ DEFS = @DEFS@ DEPDIR = @DEPDIR@ DLLTOOL = @DLLTOOL@ DSYMUTIL = @DSYMUTIL@ DUMPBIN = @DUMPBIN@ ECHO_C = @ECHO_C@ ECHO_N = @ECHO_N@ ECHO_T = @ECHO_T@ EGREP = @EGREP@ ERL = @ERL@ ERLANG_FLAGS = @ERLANG_FLAGS@ ERLC = @ERLC@ ERLC_FLAGS = @ERLC_FLAGS@ ESCRIPT = @ESCRIPT@ EXEEXT = @EXEEXT@ FGREP = @FGREP@ FLAGS = @FLAGS@ GREP = @GREP@ HAS_HELP2MAN = @HAS_HELP2MAN@ HAS_INSTALLINFO = @HAS_INSTALLINFO@ HAS_MAKEINFO = @HAS_MAKEINFO@ HAS_PDFLATEX = @HAS_PDFLATEX@ HAS_SPHINX_BUILD = @HAS_SPHINX_BUILD@ ICU_BIN = @ICU_BIN@ ICU_CFLAGS = @ICU_CFLAGS@ ICU_CONFIG = @ICU_CONFIG@ ICU_CPPFLAGS = @ICU_CPPFLAGS@ ICU_CXXFLAGS = @ICU_CXXFLAGS@ ICU_LIBS = @ICU_LIBS@ INNO_COMPILER_EXECUTABLE = @INNO_COMPILER_EXECUTABLE@ INSTALL = @INSTALL@ INSTALL_DATA = @INSTALL_DATA@ INSTALL_PROGRAM = @INSTALL_PROGRAM@ INSTALL_SCRIPT = @INSTALL_SCRIPT@ INSTALL_STRIP_PROGRAM = @INSTALL_STRIP_PROGRAM@ JS_CFLAGS = @JS_CFLAGS@ JS_LIBS = @JS_LIBS@ JS_LIB_BINARY = @JS_LIB_BINARY@ LD = @LD@ LDFLAGS = @LDFLAGS@ LIBOBJS = @LIBOBJS@ LIBS = @LIBS@ LIBTOOL = @LIBTOOL@ LIPO = @LIPO@ LN_S = @LN_S@ LTLIBOBJS = @LTLIBOBJS@ MAKEINFO = @MAKEINFO@ MANIFEST_TOOL = @MANIFEST_TOOL@ MKDIR_P = @MKDIR_P@ NM = @NM@ NMEDIT = @NMEDIT@ OBJDUMP = @OBJDUMP@ OBJEXT = @OBJEXT@ OTOOL = @OTOOL@ OTOOL64 = @OTOOL64@ PACKAGE = @PACKAGE@ PACKAGE_BUGREPORT = @PACKAGE_BUGREPORT@ PACKAGE_NAME = @PACKAGE_NAME@ PACKAGE_STRING = @PACKAGE_STRING@ PACKAGE_TARNAME = @PACKAGE_TARNAME@ PACKAGE_URL = @PACKAGE_URL@ PACKAGE_VERSION = @PACKAGE_VERSION@ PATH_SEPARATOR = @PATH_SEPARATOR@ PKG_CONFIG = @PKG_CONFIG@ PKG_CONFIG_LIBDIR = @PKG_CONFIG_LIBDIR@ PKG_CONFIG_PATH = @PKG_CONFIG_PATH@ RANLIB = @RANLIB@ SED = @SED@ SET_MAKE = @SET_MAKE@ SHELL = @SHELL@ SNAPPY_MAJOR = @SNAPPY_MAJOR@ SNAPPY_MINOR = @SNAPPY_MINOR@ SNAPPY_PATCHLEVEL = @SNAPPY_PATCHLEVEL@ STRIP = @STRIP@ VERSION = @VERSION@ abs_builddir = @abs_builddir@ abs_srcdir = @abs_srcdir@ abs_top_builddir = @abs_top_builddir@ abs_top_srcdir = @abs_top_srcdir@ ac_ct_AR = @ac_ct_AR@ ac_ct_CC = @ac_ct_CC@ ac_ct_CXX = @ac_ct_CXX@ ac_ct_DUMPBIN = @ac_ct_DUMPBIN@ ac_cv_have_stddef_h = @ac_cv_have_stddef_h@ ac_cv_have_stdint_h = @ac_cv_have_stdint_h@ am__include = @am__include@ am__leading_dot = @am__leading_dot@ am__quote = @am__quote@ am__tar = @am__tar@ am__untar = @am__untar@ bindir = @bindir@ bug_uri = @bug_uri@ build = @build@ build_alias = @build_alias@ build_cpu = @build_cpu@ build_os = @build_os@ build_vendor = @build_vendor@ builddir = @builddir@ datadir = @datadir@ datarootdir = @datarootdir@ docdir = @docdir@ dvidir = @dvidir@ erlangbin = @erlangbin@ erlangversion = @erlangversion@ exec_prefix = @exec_prefix@ host = @host@ host_alias = @host_alias@ host_cpu = @host_cpu@ host_os = @host_os@ host_vendor = @host_vendor@ htmldir = @htmldir@ includedir = @includedir@ infodir = @infodir@ initdir = @initdir@ install_sh = @install_sh@ launchddir = @launchddir@ libdir = @libdir@ libexecdir = @libexecdir@ localconfdir = @localconfdir@ localdatadir = @localdatadir@ localdocdir = @localdocdir@ localedir = @localedir@ localerlanglibdir = @localerlanglibdir@ locallibbindir = @locallibbindir@ locallibdir = @locallibdir@ localstatedir = @localstatedir@ localstatelibdir = @localstatelibdir@ localstatelogdir = @localstatelogdir@ localstaterundir = @localstaterundir@ mandir = @mandir@ mkdir_p = @mkdir_p@ msvc_redist_dir = @msvc_redist_dir@ msvc_redist_name = @msvc_redist_name@ oldincludedir = @oldincludedir@ openssl_bin_dir = @openssl_bin_dir@ otp_release = @otp_release@ package_author_address = @package_author_address@ package_author_name = @package_author_name@ package_identifier = @package_identifier@ package_name = @package_name@ package_tarname = @package_tarname@ pdfdir = @pdfdir@ prefix = @prefix@ program_transform_name = @program_transform_name@ psdir = @psdir@ sbindir = @sbindir@ sharedstatedir = @sharedstatedir@ srcdir = @srcdir@ sysconfdir = @sysconfdir@ target_alias = @target_alias@ top_build_prefix = @top_build_prefix@ top_builddir = @top_builddir@ top_srcdir = @top_srcdir@ version = @version@ version_major = @version_major@ version_minor = @version_minor@ version_release = @version_release@ version_revision = @version_revision@ version_stage = @version_stage@ SUBDIRS = doc JS_FILE = server/main.js JS_FILE_COMPONENTS = \ server/json2.js \ server/filter.js \ server/mimeparse.js \ server/render.js \ server/state.js \ server/util.js \ server/validate.js \ server/views.js JS_FILE_COMPONENTS_LAST = server/loop.js COFFEE_FILE = server/main-coffee.js COFFEE_FILE_COMPONENTS_LAST = server/coffee-script.js server/loop.js CLEANFILES = $(JS_FILE) $(COFFEE_FILE) EXTRA_DIST = $(JS_FILE_COMPONENTS) $(JS_FILE_COMPONENTS_LAST) $(COFFEE_FILE_COMPONENTS_LAST) nobase_localdata_SCRIPTS = \ $(JS_FILE) \ $(COFFEE_FILE) nobase_dist_localdata_DATA = \ www/config.html \ www/couch_tests.html \ www/custom_test.html \ www/database.html \ www/session.html \ www/dialog/_admin_party.html \ www/dialog/_change_password.html \ www/dialog/_compact_cleanup.html \ www/dialog/_create_admin.html \ www/dialog/_login.html \ www/dialog/_signup.html \ www/dialog/_create_database.html \ www/dialog/_create_config.html \ www/dialog/_delete_database.html \ www/dialog/_delete_document.html \ www/dialog/_database_security.html \ www/dialog/_share_test_reports.html \ www/dialog/_save_view_as.html \ www/dialog/_upload_attachment.html \ www/document.html \ www/fauxton/css/index.css \ www/fauxton/img/couchdb-site.png \ www/fauxton/img/couchdblogo.png \ www/fauxton/img/fontawesome-webfont.eot \ www/fauxton/img/fontawesome-webfont.svg \ www/fauxton/img/fontawesome-webfont.ttf \ www/fauxton/img/fontawesome-webfont.woff \ www/fauxton/img/FontAwesome.otf \ www/fauxton/img/fontcustom_fauxton.eot \ www/fauxton/img/fontcustom_fauxton.svg \ www/fauxton/img/fontcustom_fauxton.ttf \ www/fauxton/img/fontcustom_fauxton.woff \ www/fauxton/img/glyphicons-halflings-white.png \ www/fauxton/img/glyphicons-halflings.png \ www/fauxton/img/linen.png \ www/fauxton/img/loader.gif \ www/fauxton/img/minilogo.png \ www/fauxton/index.html \ www/fauxton/js/require.js \ www/favicon.ico \ www/image/add.png \ www/image/apply.gif \ www/image/bg.png \ www/image/cancel.gif \ www/image/compact.png \ www/image/delete-mini.png \ www/image/delete.png \ www/image/grippie.gif \ www/image/hgrad.gif \ www/image/key.png \ www/image/load.png \ www/image/logo.png \ www/image/order-asc.gif \ www/image/order-desc.gif \ www/image/path.gif \ www/image/progress.gif \ www/image/rarrow.png \ www/image/run-mini.png \ www/image/run.png \ www/image/running.png \ www/image/save.png \ www/image/sidebar-toggle.png \ www/image/spinner.gif \ www/image/spinner_33.gif \ www/image/spinner_6b.gif \ www/image/test_failure.gif \ www/image/test_success.gif \ www/image/thead-key.gif \ www/image/thead.gif \ www/image/toggle-collapse.gif \ www/image/toggle-expand.gif \ www/image/twisty.gif \ www/index.html \ www/plugins.html \ www/replicator.html \ www/script/couch.js \ www/script/couch_tests.js \ www/script/couch_test_runner.js \ www/script/futon.browse.js \ www/script/futon.format.js \ www/script/futon.js \ www/script/jquery.couch.js \ www/script/jquery.dialog.js \ www/script/jquery.editinline.js \ www/script/jquery.form.js \ www/script/jquery.js \ www/script/jquery-ui-1.8.11.custom.min.js \ www/script/jquery.resizer.js \ www/script/jquery.suggest.js \ www/script/json2.js \ www/script/jspec/jspec.css \ www/script/jspec/jspec.jquery.js \ www/script/jspec/jspec.js \ www/script/jspec/jspec.xhr.js \ www/script/oauth.js \ www/script/sha1.js \ www/script/base64.js \ www/script/test/all_docs.js \ www/script/test/attachments.js \ www/script/test/attachments_multipart.js \ www/script/test/attachment_names.js \ www/script/test/attachment_paths.js \ www/script/test/attachment_ranges.js \ www/script/test/attachment_views.js \ www/script/test/auth_cache.js \ www/script/test/basics.js \ www/script/test/batch_save.js \ www/script/test/bulk_docs.js \ www/script/test/changes.js \ www/script/test/coffee.js \ www/script/test/compact.js \ www/script/test/config.js \ www/script/test/conflicts.js \ www/script/test/content_negotiation.js \ www/script/test/cookie_auth.js \ www/script/test/copy_doc.js \ www/script/test/delayed_commits.js \ www/script/test/design_docs.js \ www/script/test/design_options.js \ www/script/test/design_paths.js \ www/script/test/erlang_views.js \ www/script/test/etags_head.js \ www/script/test/etags_views.js \ www/script/test/form_submit.js \ www/script/test/http.js \ www/script/test/invalid_docids.js \ www/script/test/jsonp.js \ www/script/test/large_docs.js \ www/script/test/list_views.js \ www/script/test/lorem.txt \ www/script/test/lorem_b64.txt \ www/script/test/lots_of_docs.js \ www/script/test/method_override.js \ www/script/test/multiple_rows.js \ www/script/test/oauth.js \ www/script/test/oauth_users_db.js \ www/script/test/proxyauth.js \ www/script/test/purge.js \ www/script/test/reader_acl.js \ www/script/test/recreate_doc.js \ www/script/test/reduce.js \ www/script/test/reduce_builtin.js \ www/script/test/reduce_false.js \ www/script/test/reduce_false_temp.js \ www/script/test/replication.js \ www/script/replicator_db_inc.js \ www/script/test/replicator_db_bad_rep_id.js \ www/script/test/replicator_db_by_doc_id.js \ www/script/test/replicator_db_compact_rep_db.js \ www/script/test/replicator_db_continuous.js \ www/script/test/replicator_db_credential_delegation.js \ www/script/test/replicator_db_field_validation.js \ www/script/test/replicator_db_filtered.js \ www/script/test/replicator_db_identical.js \ www/script/test/replicator_db_identical_continuous.js \ www/script/test/replicator_db_invalid_filter.js \ www/script/test/replicator_db_security.js \ www/script/test/replicator_db_simple.js \ www/script/test/replicator_db_successive.js \ www/script/test/replicator_db_survives.js \ www/script/test/replicator_db_swap_rep_db.js \ www/script/test/replicator_db_update_security.js \ www/script/test/replicator_db_user_ctx.js \ www/script/test/replicator_db_write_auth.js \ www/script/test/rev_stemming.js \ www/script/test/rewrite.js \ www/script/test/security_validation.js \ www/script/test/show_documents.js \ www/script/test/stats.js \ www/script/test/update_documents.js \ www/script/test/users_db.js \ www/script/test/users_db_security.js \ www/script/test/utf8.js \ www/script/test/uuids.js \ www/script/test/view_collation.js \ www/script/test/view_collation_raw.js \ www/script/test/view_conflicts.js \ www/script/test/view_compaction.js \ www/script/test/view_errors.js \ www/script/test/view_include_docs.js \ www/script/test/view_multi_key_all_docs.js \ www/script/test/view_multi_key_design.js \ www/script/test/view_multi_key_temp.js \ www/script/test/view_offsets.js \ www/script/test/view_update_seq.js \ www/script/test/view_pagination.js \ www/script/test/view_sandboxing.js \ www/spec/couch_js_class_methods_spec.js \ www/spec/couch_js_instance_methods_1_spec.js \ www/spec/couch_js_instance_methods_2_spec.js \ www/spec/couch_js_instance_methods_3_spec.js \ www/spec/custom_helpers.js \ www/spec/jquery_couch_js_class_methods_spec.js \ www/spec/jquery_couch_js_instance_methods_1_spec.js \ www/spec/jquery_couch_js_instance_methods_2_spec.js \ www/spec/jquery_couch_js_instance_methods_3_spec.js \ www/spec/run.html \ www/status.html \ www/style/jquery-ui-1.8.11.custom.css \ www/style/layout.css \ www/verify_install.html \ www/_sidebar.html all: all-recursive .SUFFIXES: $(srcdir)/Makefile.in: $(srcdir)/Makefile.am $(am__configure_deps) @for dep in $?; do \ case '$(am__configure_deps)' in \ *$$dep*) \ ( cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh ) \ && { if test -f $@; then exit 0; else break; fi; }; \ exit 1;; \ esac; \ done; \ echo ' cd $(top_srcdir) && $(AUTOMAKE) --foreign share/Makefile'; \ $(am__cd) $(top_srcdir) && \ $(AUTOMAKE) --foreign share/Makefile .PRECIOUS: Makefile Makefile: $(srcdir)/Makefile.in $(top_builddir)/config.status @case '$?' in \ *config.status*) \ cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh;; \ *) \ echo ' cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ $(am__depfiles_maybe)'; \ cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ $(am__depfiles_maybe);; \ esac; $(top_builddir)/config.status: $(top_srcdir)/configure $(CONFIG_STATUS_DEPENDENCIES) cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh $(top_srcdir)/configure: $(am__configure_deps) cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh $(ACLOCAL_M4): $(am__aclocal_m4_deps) cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh $(am__aclocal_m4_deps): install-nobase_localdataSCRIPTS: $(nobase_localdata_SCRIPTS) @$(NORMAL_INSTALL) @list='$(nobase_localdata_SCRIPTS)'; test -n "$(localdatadir)" || list=; \ if test -n "$$list"; then \ echo " $(MKDIR_P) '$(DESTDIR)$(localdatadir)'"; \ $(MKDIR_P) "$(DESTDIR)$(localdatadir)" || exit 1; \ fi; \ $(am__nobase_strip_setup); \ for p in $$list; do \ if test -f "$$p"; then d=; else d="$(srcdir)/"; fi; \ if test -f "$$d$$p"; then echo "$$d$$p"; echo "$$p"; else :; fi; \ done | \ sed -e 'p;s,.*/,,;n' \ -e "s|$$srcdirstrip/||" -e 'h;s|[^/]*$$||; s|^$$|.|' \ -e 'p;x;s,.*/,,;$(transform)' | sed 'N;N;N;s,\n, ,g' | \ $(AWK) 'BEGIN { files["."] = ""; dirs["."] = 1; } \ { d=$$3; if (dirs[d] != 1) { print "d", d; dirs[d] = 1 } \ if ($$2 == $$4) { files[d] = files[d] " " $$1; \ if (++n[d] == $(am__install_max)) { \ print "f", d, files[d]; n[d] = 0; files[d] = "" } } \ else { print "f", d "/" $$4, $$1 } } \ END { for (d in files) print "f", d, files[d] }' | \ while read type dir files; do \ case $$type in \ d) echo " $(MKDIR_P) '$(DESTDIR)$(localdatadir)/$$dir'"; \ $(MKDIR_P) "$(DESTDIR)$(localdatadir)/$$dir" || exit $$?;; \ f) \ if test "$$dir" = .; then dir=; else dir=/$$dir; fi; \ test -z "$$files" || { \ echo " $(INSTALL_SCRIPT) $$files '$(DESTDIR)$(localdatadir)$$dir'"; \ $(INSTALL_SCRIPT) $$files "$(DESTDIR)$(localdatadir)$$dir" || exit $$?; \ } \ ;; esac \ ; done uninstall-nobase_localdataSCRIPTS: @$(NORMAL_UNINSTALL) @list='$(nobase_localdata_SCRIPTS)'; test -n "$(localdatadir)" || exit 0; \ $(am__nobase_strip_setup); \ files=`$(am__nobase_strip) \ -e 'h;s,.*/,,;$(transform);x;s|[^/]*$$||;G;s,\n,,'`; \ dir='$(DESTDIR)$(localdatadir)'; $(am__uninstall_files_from_dir) mostlyclean-libtool: -rm -f *.lo clean-libtool: -rm -rf .libs _libs install-nobase_dist_localdataDATA: $(nobase_dist_localdata_DATA) @$(NORMAL_INSTALL) @list='$(nobase_dist_localdata_DATA)'; test -n "$(localdatadir)" || list=; \ if test -n "$$list"; then \ echo " $(MKDIR_P) '$(DESTDIR)$(localdatadir)'"; \ $(MKDIR_P) "$(DESTDIR)$(localdatadir)" || exit 1; \ fi; \ $(am__nobase_list) | while read dir files; do \ xfiles=; for file in $$files; do \ if test -f "$$file"; then xfiles="$$xfiles $$file"; \ else xfiles="$$xfiles $(srcdir)/$$file"; fi; done; \ test -z "$$xfiles" || { \ test "x$$dir" = x. || { \ echo " $(MKDIR_P) '$(DESTDIR)$(localdatadir)/$$dir'"; \ $(MKDIR_P) "$(DESTDIR)$(localdatadir)/$$dir"; }; \ echo " $(INSTALL_DATA) $$xfiles '$(DESTDIR)$(localdatadir)/$$dir'"; \ $(INSTALL_DATA) $$xfiles "$(DESTDIR)$(localdatadir)/$$dir" || exit $$?; }; \ done uninstall-nobase_dist_localdataDATA: @$(NORMAL_UNINSTALL) @list='$(nobase_dist_localdata_DATA)'; test -n "$(localdatadir)" || list=; \ $(am__nobase_strip_setup); files=`$(am__nobase_strip)`; \ dir='$(DESTDIR)$(localdatadir)'; $(am__uninstall_files_from_dir) # This directory's subdirectories are mostly independent; you can cd # into them and run `make' without going through this Makefile. # To change the values of `make' variables: instead of editing Makefiles, # (1) if the variable is set in `config.status', edit `config.status' # (which will cause the Makefiles to be regenerated when you run `make'); # (2) otherwise, pass the desired values on the `make' command line. $(RECURSIVE_TARGETS): @fail= failcom='exit 1'; \ for f in x $$MAKEFLAGS; do \ case $$f in \ *=* | --[!k]*);; \ *k*) failcom='fail=yes';; \ esac; \ done; \ dot_seen=no; \ target=`echo $@ | sed s/-recursive//`; \ list='$(SUBDIRS)'; for subdir in $$list; do \ echo "Making $$target in $$subdir"; \ if test "$$subdir" = "."; then \ dot_seen=yes; \ local_target="$$target-am"; \ else \ local_target="$$target"; \ fi; \ ($(am__cd) $$subdir && $(MAKE) $(AM_MAKEFLAGS) $$local_target) \ || eval $$failcom; \ done; \ if test "$$dot_seen" = "no"; then \ $(MAKE) $(AM_MAKEFLAGS) "$$target-am" || exit 1; \ fi; test -z "$$fail" $(RECURSIVE_CLEAN_TARGETS): @fail= failcom='exit 1'; \ for f in x $$MAKEFLAGS; do \ case $$f in \ *=* | --[!k]*);; \ *k*) failcom='fail=yes';; \ esac; \ done; \ dot_seen=no; \ case "$@" in \ distclean-* | maintainer-clean-*) list='$(DIST_SUBDIRS)' ;; \ *) list='$(SUBDIRS)' ;; \ esac; \ rev=''; for subdir in $$list; do \ if test "$$subdir" = "."; then :; else \ rev="$$subdir $$rev"; \ fi; \ done; \ rev="$$rev ."; \ target=`echo $@ | sed s/-recursive//`; \ for subdir in $$rev; do \ echo "Making $$target in $$subdir"; \ if test "$$subdir" = "."; then \ local_target="$$target-am"; \ else \ local_target="$$target"; \ fi; \ ($(am__cd) $$subdir && $(MAKE) $(AM_MAKEFLAGS) $$local_target) \ || eval $$failcom; \ done && test -z "$$fail" tags-recursive: list='$(SUBDIRS)'; for subdir in $$list; do \ test "$$subdir" = . || ($(am__cd) $$subdir && $(MAKE) $(AM_MAKEFLAGS) tags); \ done ctags-recursive: list='$(SUBDIRS)'; for subdir in $$list; do \ test "$$subdir" = . || ($(am__cd) $$subdir && $(MAKE) $(AM_MAKEFLAGS) ctags); \ done ID: $(HEADERS) $(SOURCES) $(LISP) $(TAGS_FILES) list='$(SOURCES) $(HEADERS) $(LISP) $(TAGS_FILES)'; \ unique=`for i in $$list; do \ if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \ done | \ $(AWK) '{ files[$$0] = 1; nonempty = 1; } \ END { if (nonempty) { for (i in files) print i; }; }'`; \ mkid -fID $$unique tags: TAGS TAGS: tags-recursive $(HEADERS) $(SOURCES) $(TAGS_DEPENDENCIES) \ $(TAGS_FILES) $(LISP) set x; \ here=`pwd`; \ if ($(ETAGS) --etags-include --version) >/dev/null 2>&1; then \ include_option=--etags-include; \ empty_fix=.; \ else \ include_option=--include; \ empty_fix=; \ fi; \ list='$(SUBDIRS)'; for subdir in $$list; do \ if test "$$subdir" = .; then :; else \ test ! -f $$subdir/TAGS || \ set "$$@" "$$include_option=$$here/$$subdir/TAGS"; \ fi; \ done; \ list='$(SOURCES) $(HEADERS) $(LISP) $(TAGS_FILES)'; \ unique=`for i in $$list; do \ if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \ done | \ $(AWK) '{ files[$$0] = 1; nonempty = 1; } \ END { if (nonempty) { for (i in files) print i; }; }'`; \ shift; \ if test -z "$(ETAGS_ARGS)$$*$$unique"; then :; else \ test -n "$$unique" || unique=$$empty_fix; \ if test $$# -gt 0; then \ $(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \ "$$@" $$unique; \ else \ $(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \ $$unique; \ fi; \ fi ctags: CTAGS CTAGS: ctags-recursive $(HEADERS) $(SOURCES) $(TAGS_DEPENDENCIES) \ $(TAGS_FILES) $(LISP) list='$(SOURCES) $(HEADERS) $(LISP) $(TAGS_FILES)'; \ unique=`for i in $$list; do \ if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \ done | \ $(AWK) '{ files[$$0] = 1; nonempty = 1; } \ END { if (nonempty) { for (i in files) print i; }; }'`; \ test -z "$(CTAGS_ARGS)$$unique" \ || $(CTAGS) $(CTAGSFLAGS) $(AM_CTAGSFLAGS) $(CTAGS_ARGS) \ $$unique GTAGS: here=`$(am__cd) $(top_builddir) && pwd` \ && $(am__cd) $(top_srcdir) \ && gtags -i $(GTAGS_ARGS) "$$here" distclean-tags: -rm -f TAGS ID GTAGS GRTAGS GSYMS GPATH tags distdir: $(DISTFILES) @srcdirstrip=`echo "$(srcdir)" | sed 's/[].[^$$\\*]/\\\\&/g'`; \ topsrcdirstrip=`echo "$(top_srcdir)" | sed 's/[].[^$$\\*]/\\\\&/g'`; \ list='$(DISTFILES)'; \ dist_files=`for file in $$list; do echo $$file; done | \ sed -e "s|^$$srcdirstrip/||;t" \ -e "s|^$$topsrcdirstrip/|$(top_builddir)/|;t"`; \ case $$dist_files in \ */*) $(MKDIR_P) `echo "$$dist_files" | \ sed '/\//!d;s|^|$(distdir)/|;s,/[^/]*$$,,' | \ sort -u` ;; \ esac; \ for file in $$dist_files; do \ if test -f $$file || test -d $$file; then d=.; else d=$(srcdir); fi; \ if test -d $$d/$$file; then \ dir=`echo "/$$file" | sed -e 's,/[^/]*$$,,'`; \ if test -d "$(distdir)/$$file"; then \ find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} \;; \ fi; \ if test -d $(srcdir)/$$file && test $$d != $(srcdir); then \ cp -fpR $(srcdir)/$$file "$(distdir)$$dir" || exit 1; \ find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} \;; \ fi; \ cp -fpR $$d/$$file "$(distdir)$$dir" || exit 1; \ else \ test -f "$(distdir)/$$file" \ || cp -p $$d/$$file "$(distdir)/$$file" \ || exit 1; \ fi; \ done @list='$(DIST_SUBDIRS)'; for subdir in $$list; do \ if test "$$subdir" = .; then :; else \ $(am__make_dryrun) \ || test -d "$(distdir)/$$subdir" \ || $(MKDIR_P) "$(distdir)/$$subdir" \ || exit 1; \ dir1=$$subdir; dir2="$(distdir)/$$subdir"; \ $(am__relativize); \ new_distdir=$$reldir; \ dir1=$$subdir; dir2="$(top_distdir)"; \ $(am__relativize); \ new_top_distdir=$$reldir; \ echo " (cd $$subdir && $(MAKE) $(AM_MAKEFLAGS) top_distdir="$$new_top_distdir" distdir="$$new_distdir" \\"; \ echo " am__remove_distdir=: am__skip_length_check=: am__skip_mode_fix=: distdir)"; \ ($(am__cd) $$subdir && \ $(MAKE) $(AM_MAKEFLAGS) \ top_distdir="$$new_top_distdir" \ distdir="$$new_distdir" \ am__remove_distdir=: \ am__skip_length_check=: \ am__skip_mode_fix=: \ distdir) \ || exit 1; \ fi; \ done check-am: all-am check: check-recursive all-am: Makefile $(SCRIPTS) $(DATA) installdirs: installdirs-recursive installdirs-am: for dir in "$(DESTDIR)$(localdatadir)" "$(DESTDIR)$(localdatadir)"; do \ test -z "$$dir" || $(MKDIR_P) "$$dir"; \ done install: install-recursive install-exec: install-exec-recursive install-data: install-data-recursive uninstall: uninstall-recursive install-am: all-am @$(MAKE) $(AM_MAKEFLAGS) install-exec-am install-data-am installcheck: installcheck-recursive install-strip: if test -z '$(STRIP)'; then \ $(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(INSTALL_STRIP_PROGRAM)" \ install_sh_PROGRAM="$(INSTALL_STRIP_PROGRAM)" INSTALL_STRIP_FLAG=-s \ install; \ else \ $(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(INSTALL_STRIP_PROGRAM)" \ install_sh_PROGRAM="$(INSTALL_STRIP_PROGRAM)" INSTALL_STRIP_FLAG=-s \ "INSTALL_PROGRAM_ENV=STRIPPROG='$(STRIP)'" install; \ fi mostlyclean-generic: clean-generic: -test -z "$(CLEANFILES)" || rm -f $(CLEANFILES) distclean-generic: -test -z "$(CONFIG_CLEAN_FILES)" || rm -f $(CONFIG_CLEAN_FILES) -test . = "$(srcdir)" || test -z "$(CONFIG_CLEAN_VPATH_FILES)" || rm -f $(CONFIG_CLEAN_VPATH_FILES) maintainer-clean-generic: @echo "This command is intended for maintainers to use" @echo "it deletes files that may require special tools to rebuild." clean: clean-recursive clean-am: clean-generic clean-libtool mostlyclean-am distclean: distclean-recursive -rm -f Makefile distclean-am: clean-am distclean-generic distclean-tags dvi: dvi-recursive dvi-am: html: html-recursive html-am: info: info-recursive info-am: install-data-am: install-nobase_dist_localdataDATA \ install-nobase_localdataSCRIPTS install-dvi: install-dvi-recursive install-dvi-am: install-exec-am: install-html: install-html-recursive install-html-am: install-info: install-info-recursive install-info-am: install-man: install-pdf: install-pdf-recursive install-pdf-am: install-ps: install-ps-recursive install-ps-am: installcheck-am: maintainer-clean: maintainer-clean-recursive -rm -f Makefile maintainer-clean-am: distclean-am maintainer-clean-generic mostlyclean: mostlyclean-recursive mostlyclean-am: mostlyclean-generic mostlyclean-libtool pdf: pdf-recursive pdf-am: ps: ps-recursive ps-am: uninstall-am: uninstall-nobase_dist_localdataDATA \ uninstall-nobase_localdataSCRIPTS .MAKE: $(RECURSIVE_CLEAN_TARGETS) $(RECURSIVE_TARGETS) ctags-recursive \ install-am install-strip tags-recursive .PHONY: $(RECURSIVE_CLEAN_TARGETS) $(RECURSIVE_TARGETS) CTAGS GTAGS \ all all-am check check-am clean clean-generic clean-libtool \ ctags ctags-recursive distclean distclean-generic \ distclean-libtool distclean-tags distdir dvi dvi-am html \ html-am info info-am install install-am install-data \ install-data-am install-dvi install-dvi-am install-exec \ install-exec-am install-html install-html-am install-info \ install-info-am install-man install-nobase_dist_localdataDATA \ install-nobase_localdataSCRIPTS install-pdf install-pdf-am \ install-ps install-ps-am install-strip installcheck \ installcheck-am installdirs installdirs-am maintainer-clean \ maintainer-clean-generic mostlyclean mostlyclean-generic \ mostlyclean-libtool pdf pdf-am ps ps-am tags tags-recursive \ uninstall uninstall-am uninstall-nobase_dist_localdataDATA \ uninstall-nobase_localdataSCRIPTS $(JS_FILE): $(JS_FILE_COMPONENTS) $(JS_FILE_COMPONENTS_LAST) mkdir -p `dirname $(JS_FILE)` echo "// DO NOT EDIT THIS FILE BY HAND" > $@ echo >> $@ cat $^ >> $@ $(COFFEE_FILE): $(JS_FILE_COMPONENTS) $(COFFEE_FILE_COMPONENTS_LAST) mkdir -p `dirname $(COFFEE_FILE)` echo "// DO NOT EDIT THIS FILE BY HAND" > $@ echo >> $@ cat $^ >> $@ # Tell versions [3.59,3.63) of GNU make to not export all variables. # Otherwise a system limit (for SysV at least) may be exceeded. .NOEXPORT: apache-couchdb-1.5.0/share/server/0000755000175000001440000000000012230722306013745 500000000000000apache-couchdb-1.5.0/share/server/filter.js0000644000175000001440000000266312230722213015514 00000000000000// 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. var Filter = (function() { var view_emit = false; return { emit : function(key, value) { view_emit = true; }, filter : function(fun, ddoc, args) { var results = []; var docs = args[0]; var req = args[1]; for (var i=0; i < docs.length; i++) { results.push((fun.apply(ddoc, [docs[i], req]) && true) || false); }; respond([true, results]); }, filter_view : function(fun, ddoc, args) { // recompile var source = fun.toSource ? fun.toSource() : '(' + fun.toString() + ')'; fun = evalcx(source, filter_sandbox); var results = []; var docs = args[0]; for (var i=0; i < docs.length; i++) { view_emit = false; fun(docs[i]); results.push((view_emit && true) || false); }; respond([true, results]); } } })(); apache-couchdb-1.5.0/share/server/json2.js0000644000175000001440000004174612230722213015267 00000000000000/* http://www.JSON.org/json2.js 2010-03-20 Public Domain. NO WARRANTY EXPRESSED OR IMPLIED. USE AT YOUR OWN RISK. See http://www.JSON.org/js.html This code should be minified before deployment. See http://javascript.crockford.com/jsmin.html USE YOUR OWN COPY. IT IS EXTREMELY UNWISE TO LOAD CODE FROM SERVERS YOU DO NOT CONTROL. This file creates a global JSON object containing two methods: stringify and parse. JSON.stringify(value, replacer, space) value any JavaScript value, usually an object or array. replacer an optional parameter that determines how object values are stringified for objects. It can be a function or an array of strings. space an optional parameter that specifies the indentation of nested structures. If it is omitted, the text will be packed without extra whitespace. If it is a number, it will specify the number of spaces to indent at each level. If it is a string (such as '\t' or ' '), it contains the characters used to indent at each level. This method produces a JSON text from a JavaScript value. When an object value is found, if the object contains a toJSON method, its toJSON method will be called and the result will be stringified. A toJSON method does not serialize: it returns the value represented by the name/value pair that should be serialized, or undefined if nothing should be serialized. The toJSON method will be passed the key associated with the value, and this will be bound to the value For example, this would serialize Dates as ISO strings. Date.prototype.toJSON = function (key) { function f(n) { // Format integers to have at least two digits. return n < 10 ? '0' + n : n; } return this.getUTCFullYear() + '-' + f(this.getUTCMonth() + 1) + '-' + f(this.getUTCDate()) + 'T' + f(this.getUTCHours()) + ':' + f(this.getUTCMinutes()) + ':' + f(this.getUTCSeconds()) + 'Z'; }; You can provide an optional replacer method. It will be passed the key and value of each member, with this bound to the containing object. The value that is returned from your method will be serialized. If your method returns undefined, then the member will be excluded from the serialization. If the replacer parameter is an array of strings, then it will be used to select the members to be serialized. It filters the results such that only members with keys listed in the replacer array are stringified. Values that do not have JSON representations, such as undefined or functions, will not be serialized. Such values in objects will be dropped; in arrays they will be replaced with null. You can use a replacer function to replace those with JSON values. JSON.stringify(undefined) returns undefined. The optional space parameter produces a stringification of the value that is filled with line breaks and indentation to make it easier to read. If the space parameter is a non-empty string, then that string will be used for indentation. If the space parameter is a number, then the indentation will be that many spaces. Example: text = JSON.stringify(['e', {pluribus: 'unum'}]); // text is '["e",{"pluribus":"unum"}]' text = JSON.stringify(['e', {pluribus: 'unum'}], null, '\t'); // text is '[\n\t"e",\n\t{\n\t\t"pluribus": "unum"\n\t}\n]' text = JSON.stringify([new Date()], function (key, value) { return this[key] instanceof Date ? 'Date(' + this[key] + ')' : value; }); // text is '["Date(---current time---)"]' JSON.parse(text, reviver) This method parses a JSON text to produce an object or array. It can throw a SyntaxError exception. The optional reviver parameter is a function that can filter and transform the results. It receives each of the keys and values, and its return value is used instead of the original value. If it returns what it received, then the structure is not modified. If it returns undefined then the member is deleted. Example: // Parse the text. Values that look like ISO date strings will // be converted to Date objects. myData = JSON.parse(text, function (key, value) { var a; if (typeof value === 'string') { a = /^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2}(?:\.\d*)?)Z$/.exec(value); if (a) { return new Date(Date.UTC(+a[1], +a[2] - 1, +a[3], +a[4], +a[5], +a[6])); } } return value; }); myData = JSON.parse('["Date(09/09/2001)"]', function (key, value) { var d; if (typeof value === 'string' && value.slice(0, 5) === 'Date(' && value.slice(-1) === ')') { d = new Date(value.slice(5, -1)); if (d) { return d; } } return value; }); This is a reference implementation. You are free to copy, modify, or redistribute. */ /*jslint evil: true, strict: false */ /*members "", "\b", "\t", "\n", "\f", "\r", "\"", JSON, "\\", apply, call, charCodeAt, getUTCDate, getUTCFullYear, getUTCHours, getUTCMinutes, getUTCMonth, getUTCSeconds, hasOwnProperty, join, lastIndex, length, parse, prototype, push, replace, slice, stringify, test, toJSON, toString, valueOf */ // Create a JSON object only if one does not already exist. We create the // methods in a closure to avoid creating global variables. if (!this.JSON) { this.JSON = {}; } (function () { function f(n) { // Format integers to have at least two digits. return n < 10 ? '0' + n : n; } if (typeof Date.prototype.toJSON !== 'function') { Date.prototype.toJSON = function (key) { return isFinite(this.valueOf()) ? this.getUTCFullYear() + '-' + f(this.getUTCMonth() + 1) + '-' + f(this.getUTCDate()) + 'T' + f(this.getUTCHours()) + ':' + f(this.getUTCMinutes()) + ':' + f(this.getUTCSeconds()) + 'Z' : null; }; String.prototype.toJSON = Number.prototype.toJSON = Boolean.prototype.toJSON = function (key) { return this.valueOf(); }; } var cx = /[\u0000\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g, escapable = /[\\\"\x00-\x1f\x7f-\x9f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g, gap, indent, meta = { // table of character substitutions '\b': '\\b', '\t': '\\t', '\n': '\\n', '\f': '\\f', '\r': '\\r', '"' : '\\"', '\\': '\\\\' }, rep; function quote(string) { // If the string contains no control characters, no quote characters, and no // backslash characters, then we can safely slap some quotes around it. // Otherwise we must also replace the offending characters with safe escape // sequences. escapable.lastIndex = 0; return escapable.test(string) ? '"' + string.replace(escapable, function (a) { var c = meta[a]; return typeof c === 'string' ? c : '\\u' + ('0000' + a.charCodeAt(0).toString(16)).slice(-4); }) + '"' : '"' + string + '"'; } function str(key, holder) { // Produce a string from holder[key]. var i, // The loop counter. k, // The member key. v, // The member value. length, mind = gap, partial, value = holder[key]; // If the value has a toJSON method, call it to obtain a replacement value. if (value && typeof value === 'object' && typeof value.toJSON === 'function') { value = value.toJSON(key); } // If we were called with a replacer function, then call the replacer to // obtain a replacement value. if (typeof rep === 'function') { value = rep.call(holder, key, value); } // What happens next depends on the value's type. switch (typeof value) { case 'string': return quote(value); case 'number': // JSON numbers must be finite. Encode non-finite numbers as null. return isFinite(value) ? String(value) : 'null'; case 'boolean': case 'null': // If the value is a boolean or null, convert it to a string. Note: // typeof null does not produce 'null'. The case is included here in // the remote chance that this gets fixed someday. return String(value); // If the type is 'object', we might be dealing with an object or an array or // null. case 'object': // Due to a specification blunder in ECMAScript, typeof null is 'object', // so watch out for that case. if (!value) { return 'null'; } // Make an array to hold the partial results of stringifying this object value. gap += indent; partial = []; // Is the value an array? if (Object.prototype.toString.apply(value) === '[object Array]') { // The value is an array. Stringify every element. Use null as a placeholder // for non-JSON values. length = value.length; for (i = 0; i < length; i += 1) { partial[i] = str(i, value) || 'null'; } // Join all of the elements together, separated with commas, and wrap them in // brackets. v = partial.length === 0 ? '[]' : gap ? '[\n' + gap + partial.join(',\n' + gap) + '\n' + mind + ']' : '[' + partial.join(',') + ']'; gap = mind; return v; } // If the replacer is an array, use it to select the members to be stringified. if (rep && typeof rep === 'object') { length = rep.length; for (i = 0; i < length; i += 1) { k = rep[i]; if (typeof k === 'string') { v = str(k, value); if (v) { partial.push(quote(k) + (gap ? ': ' : ':') + v); } } } } else { // Otherwise, iterate through all of the keys in the object. for (k in value) { if (Object.hasOwnProperty.call(value, k)) { v = str(k, value); if (v) { partial.push(quote(k) + (gap ? ': ' : ':') + v); } } } } // Join all of the member texts together, separated with commas, // and wrap them in braces. v = partial.length === 0 ? '{}' : gap ? '{\n' + gap + partial.join(',\n' + gap) + '\n' + mind + '}' : '{' + partial.join(',') + '}'; gap = mind; return v; } } // If the JSON object does not yet have a stringify method, give it one. if (typeof JSON.stringify !== 'function') { JSON.stringify = function (value, replacer, space) { // The stringify method takes a value and an optional replacer, and an optional // space parameter, and returns a JSON text. The replacer can be a function // that can replace values, or an array of strings that will select the keys. // A default replacer method can be provided. Use of the space parameter can // produce text that is more easily readable. var i; gap = ''; indent = ''; // If the space parameter is a number, make an indent string containing that // many spaces. if (typeof space === 'number') { for (i = 0; i < space; i += 1) { indent += ' '; } // If the space parameter is a string, it will be used as the indent string. } else if (typeof space === 'string') { indent = space; } // If there is a replacer, it must be a function or an array. // Otherwise, throw an error. rep = replacer; if (replacer && typeof replacer !== 'function' && (typeof replacer !== 'object' || typeof replacer.length !== 'number')) { throw new Error('JSON.stringify'); } // Make a fake root object containing our value under the key of ''. // Return the result of stringifying the value. return str('', {'': value}); }; } // If the JSON object does not yet have a parse method, give it one. if (typeof JSON.parse !== 'function') { JSON.parse = function (text, reviver) { // The parse method takes a text and an optional reviver function, and returns // a JavaScript value if the text is a valid JSON text. var j; function walk(holder, key) { // The walk method is used to recursively walk the resulting structure so // that modifications can be made. var k, v, value = holder[key]; if (value && typeof value === 'object') { for (k in value) { if (Object.hasOwnProperty.call(value, k)) { v = walk(value, k); if (v !== undefined) { value[k] = v; } else { delete value[k]; } } } } return reviver.call(holder, key, value); } // Parsing happens in four stages. In the first stage, we replace certain // Unicode characters with escape sequences. JavaScript handles many characters // incorrectly, either silently deleting them, or treating them as line endings. text = String(text); cx.lastIndex = 0; if (cx.test(text)) { text = text.replace(cx, function (a) { return '\\u' + ('0000' + a.charCodeAt(0).toString(16)).slice(-4); }); } // In the second stage, we run the text against regular expressions that look // for non-JSON patterns. We are especially concerned with '()' and 'new' // because they can cause invocation, and '=' because it can cause mutation. // But just to be safe, we want to reject all unexpected forms. // We split the second stage into 4 regexp operations in order to work around // crippling inefficiencies in IE's and Safari's regexp engines. First we // replace the JSON backslash pairs with '@' (a non-JSON character). Second, we // replace all simple value tokens with ']' characters. Third, we delete all // open brackets that follow a colon or comma or that begin the text. Finally, // we look to see that the remaining characters are only whitespace or ']' or // ',' or ':' or '{' or '}'. If that is so, then the text is safe for eval. if (/^[\],:{}\s]*$/. test(text.replace(/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g, '@'). replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g, ']'). replace(/(?:^|:|,)(?:\s*\[)+/g, ''))) { // In the third stage we use the eval function to compile the text into a // JavaScript structure. The '{' operator is subject to a syntactic ambiguity // in JavaScript: it can begin a block or an object literal. We wrap the text // in parens to eliminate the ambiguity. j = eval('(' + text + ')'); // In the optional fourth stage, we recursively walk the new structure, passing // each name/value pair to a reviver function for possible transformation. return typeof reviver === 'function' ? walk({'': j}, '') : j; } // If the text is not JSON parseable, then a SyntaxError is thrown. throw new SyntaxError('JSON.parse'); }; } }()); apache-couchdb-1.5.0/share/server/loop.js0000644000175000001440000001202112230722213015165 00000000000000// 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. var sandbox = null; var filter_sandbox = null; function init_sandbox() { try { // if possible, use evalcx (not always available) sandbox = evalcx(''); sandbox.emit = Views.emit; sandbox.sum = Views.sum; sandbox.log = log; sandbox.toJSON = Couch.toJSON; sandbox.JSON = JSON; sandbox.provides = Mime.provides; sandbox.registerType = Mime.registerType; sandbox.start = Render.start; sandbox.send = Render.send; sandbox.getRow = Render.getRow; sandbox.isArray = isArray; } catch (e) { //log(e.toSource()); } }; init_sandbox(); function init_filter_sandbox() { try { filter_sandbox = evalcx(''); for (var p in sandbox) { if (sandbox.hasOwnProperty(p)) { filter_sandbox[p] = sandbox[p]; } } filter_sandbox.emit = Filter.emit; } catch(e) { log(e.toSource ? e.toSource() : e.stack); } }; init_filter_sandbox(); // Commands are in the form of json arrays: // ["commandname",..optional args...]\n // // Responses are json values followed by a new line ("\n") var DDoc = (function() { var ddoc_dispatch = { "lists" : Render.list, "shows" : Render.show, "filters" : Filter.filter, "views" : Filter.filter_view, "updates" : Render.update, "validate_doc_update" : Validate.validate }; var ddocs = {}; return { ddoc : function() { var args = []; for (var i=0; i < arguments.length; i++) { args.push(arguments[i]); }; var ddocId = args.shift(); if (ddocId == "new") { // get the real ddocId. ddocId = args.shift(); // store the ddoc, functions are lazily compiled. ddocs[ddocId] = args.shift(); print("true"); } else { // Couch makes sure we know this ddoc already. var ddoc = ddocs[ddocId]; if (!ddoc) throw(["fatal", "query_protocol_error", "uncached design doc: "+ddocId]); var funPath = args.shift(); var cmd = funPath[0]; // the first member of the fun path determines the type of operation var funArgs = args.shift(); if (ddoc_dispatch[cmd]) { // get the function, call the command with it var point = ddoc; for (var i=0; i < funPath.length; i++) { if (i+1 == funPath.length) { var fun = point[funPath[i]]; if (!fun) { throw(["error","not_found", "missing " + funPath[0] + " function " + funPath[i] + " on design doc " + ddocId]); } if (typeof fun != "function") { fun = Couch.compileFunction(fun, ddoc, funPath.join('.')); // cache the compiled fun on the ddoc point[funPath[i]] = fun; }; } else { point = point[funPath[i]]; } }; // run the correct responder with the cmd body ddoc_dispatch[cmd].apply(null, [fun, ddoc, funArgs]); } else { // unknown command, quit and hope the restarted version is better throw(["fatal", "unknown_command", "unknown ddoc command '" + cmd + "'"]); } } } }; })(); var Loop = function() { var line, cmd, cmdkey, dispatch = { "ddoc" : DDoc.ddoc, // "view" : Views.handler, "reset" : State.reset, "add_fun" : State.addFun, "add_lib" : State.addLib, "map_doc" : Views.mapDoc, "reduce" : Views.reduce, "rereduce" : Views.rereduce }; function handleError(e) { var type = e[0]; if (type == "fatal") { e[0] = "error"; // we tell the client it was a fatal error by dying respond(e); quit(-1); } else if (type == "error") { respond(e); } else if (e.error && e.reason) { // compatibility with old error format respond(["error", e.error, e.reason]); } else if (e.name) { respond(["error", e.name, e]); } else { respond(["error","unnamed_error",e.toSource ? e.toSource() : e.stack]); } }; while (line = readline()) { cmd = JSON.parse(line); State.line_length = line.length; try { cmdkey = cmd.shift(); if (dispatch[cmdkey]) { // run the correct responder with the cmd body dispatch[cmdkey].apply(null, cmd); } else { // unknown command, quit and hope the restarted version is better throw(["fatal", "unknown_command", "unknown command '" + cmdkey + "'"]); } } catch(e) { handleError(e); } }; }; Loop(); apache-couchdb-1.5.0/share/server/coffee-script.js0000644000175000001440000051174412230722213016765 00000000000000/** * CoffeeScript Compiler v1.2.0 * http://coffeescript.org * * Copyright 2011, Jeremy Ashkenas * Released under the MIT License */ (function(root){var CoffeeScript=function(){function require(a){return require[a]}require["./helpers"]=new function(){var a=this;(function(){var b,c;a.starts=function(a,b,c){return b===a.substr(c,b.length)},a.ends=function(a,b,c){var d;d=b.length;return b===a.substr(a.length-d-(c||0),d)},a.compact=function(a){var b,c,d,e;e=[];for(c=0,d=a.length;c=0)f+=1;else if(j=g[0],t.call(d,j)>=0)f-=1;a+=1}return a-1},a.prototype.removeLeadingNewlines=function(){var a,b,c,d;d=this.tokens;for(a=0,c=d.length;a=0)))return 1;d.splice(b,1);return 0})},a.prototype.closeOpenCalls=function(){var a,b;b=function(a,b){var c;return(c=a[0])===")"||c==="CALL_END"||a[0]==="OUTDENT"&&this.tag(b-1)===")"},a=function(a,b){return this.tokens[a[0]==="OUTDENT"?b-1:b][0]="CALL_END"};return this.scanTokens(function(c,d){c[0]==="CALL_START"&&this.detectEnd(d+1,b,a);return 1})},a.prototype.closeOpenIndexes=function(){var a,b;b=function(a,b){var c;return(c=a[0])==="]"||c==="INDEX_END"},a=function(a,b){return a[0]="INDEX_END"};return this.scanTokens(function(c,d){c[0]==="INDEX_START"&&this.detectEnd(d+1,b,a);return 1})},a.prototype.addImplicitBraces=function(){var a,b,c,f,g,i,j;f=[],g=null,j=null,c=!0,i=0,b=function(a,b){var d,e,f,g,i,k;i=this.tokens.slice(b+1,b+3+1||9e9),d=i[0],g=i[1],f=i[2];if("HERECOMMENT"===(d!=null?d[0]:void 0))return!1;e=a[0],t.call(l,e)>=0&&(c=!1);return(e==="TERMINATOR"||e==="OUTDENT"||t.call(h,e)>=0&&c)&&(!j&&this.tag(b-1)!==","||(g!=null?g[0]:void 0)!==":"&&((d!=null?d[0]:void 0)!=="@"||(f!=null?f[0]:void 0)!==":"))||e===","&&d&&(k=d[0])!=="IDENTIFIER"&&k!=="NUMBER"&&k!=="STRING"&&k!=="@"&&k!=="TERMINATOR"&&k!=="OUTDENT"},a=function(a,b){var c;c=["}","}",a[2]],c.generated=!0;return this.tokens.splice(b,0,c)};return this.scanTokens(function(h,i,k){var m,n,o,p,q,r,s,u;if(s=p=h[0],t.call(e,s)>=0){f.push([p==="INDENT"&&this.tag(i-1)==="{"?"{":p,i]);return 1}if(t.call(d,p)>=0){g=f.pop();return 1}if(p!==":"||(m=this.tag(i-2))!==":"&&((u=f[f.length-1])!=null?u[0]:void 0)==="{")return 1;c=!0,f.push(["{"]),n=m==="@"?i-2:i-1;while(this.tag(n-2)==="HERECOMMENT")n-=2;o=this.tag(n-1),j=!o||t.call(l,o)>=0,r=new String("{"),r.generated=!0,q=["{",r,h[2]],q.generated=!0,k.splice(n,0,q),this.detectEnd(i+2,b,a);return 2})},a.prototype.addImplicitParentheses=function(){var a,b,c,d,e;c=e=d=!1,b=function(a,b){var c,g,i,j;g=a[0];if(!e&&a.fromThen)return!0;if(g==="IF"||g==="ELSE"||g==="CATCH"||g==="->"||g==="=>"||g==="CLASS")e=!0;if(g==="IF"||g==="ELSE"||g==="SWITCH"||g==="TRY"||g==="=")d=!0;if((g==="."||g==="?."||g==="::")&&this.tag(b-1)==="OUTDENT")return!0;return!a.generated&&this.tag(b-1)!==","&&(t.call(h,g)>=0||g==="INDENT"&&!d)&&(g!=="INDENT"||(i=this.tag(b-2))!=="CLASS"&&i!=="EXTENDS"&&(j=this.tag(b-1),t.call(f,j)<0)&&(!(c=this.tokens[b+1])||!c.generated||c[0]!=="{"))},a=function(a,b){return this.tokens.splice(b,0,["CALL_END",")",a[2]])};return this.scanTokens(function(f,h,k){var m,n,o,p,q,r,s,u;q=f[0];if(q==="CLASS"||q==="IF")c=!0;r=k.slice(h-1,h+1+1||9e9),p=r[0],n=r[1],o=r[2],m=!c&&q==="INDENT"&&o&&o.generated&&o[0]==="{"&&p&&(s=p[0],t.call(i,s)>=0),e=!1,d=!1,t.call(l,q)>=0&&(c=!1),p&&!p.spaced&&q==="?"&&(f.call=!0);if(f.fromThen)return 1;if(!(m||(p!=null?p.spaced:void 0)&&(p.call||(u=p[0],t.call(i,u)>=0))&&(t.call(g,q)>=0||!f.spaced&&!f.newLine&&t.call(j,q)>=0)))return 1;k.splice(h,0,["CALL_START","(",f[2]]),this.detectEnd(h+1,b,a),p[0]==="?"&&(p[0]="FUNC_EXIST");return 2})},a.prototype.addImplicitIndentation=function(){var a,b,c,d,e;e=c=d=null,b=function(a,b){var c;return a[1]!==";"&&(c=a[0],t.call(m,c)>=0)&&(a[0]!=="ELSE"||e==="IF"||e==="THEN")},a=function(a,b){return this.tokens.splice(this.tag(b-1)===","?b-1:b,0,d)};return this.scanTokens(function(f,g,h){var i,j,k;i=f[0];if(i==="TERMINATOR"&&this.tag(g+1)==="THEN"){h.splice(g,1);return 0}if(i==="ELSE"&&this.tag(g-1)!=="OUTDENT"){h.splice.apply(h,[g,0].concat(u.call(this.indentation(f))));return 2}if(i==="CATCH"&&((j=this.tag(g+2))==="OUTDENT"||j==="TERMINATOR"||j==="FINALLY")){h.splice.apply(h,[g+2,0].concat(u.call(this.indentation(f))));return 4}if(t.call(n,i)>=0&&this.tag(g+1)!=="INDENT"&&(i!=="ELSE"||this.tag(g+1)!=="IF")){e=i,k=this.indentation(f),c=k[0],d=k[1],e==="THEN"&&(c.fromThen=!0),c.generated=d.generated=!0,h.splice(g+1,0,c),this.detectEnd(g+2,b,a),i==="THEN"&&h.splice(g,1);return 1}return 1})},a.prototype.tagPostfixConditionals=function(){var a,b,c;c=null,b=function(a,b){var c;return(c=a[0])==="TERMINATOR"||c==="INDENT"},a=function(a,b){if(a[0]!=="INDENT"||a.generated&&!a.fromThen)return c[0]="POST_"+c[0]};return this.scanTokens(function(d,e){if(d[0]!=="IF")return 1;c=d,this.detectEnd(e+1,b,a);return 1})},a.prototype.indentation=function(a){return[["INDENT",2,a[2]],["OUTDENT",2,a[2]]]},a.prototype.tag=function(a){var b;return(b=this.tokens[a])!=null?b[0]:void 0};return a}(),b=[["(",")"],["[","]"],["{","}"],["INDENT","OUTDENT"],["CALL_START","CALL_END"],["PARAM_START","PARAM_END"],["INDEX_START","INDEX_END"]],a.INVERSES=k={},e=[],d=[];for(q=0,r=b.length;q","=>","[","(","{","--","++"],j=["+","-"],f=["->","=>","{","[",","],h=["POST_IF","FOR","WHILE","UNTIL","WHEN","BY","LOOP","TERMINATOR"],n=["ELSE","->","=>","TRY","FINALLY","THEN"],m=["TERMINATOR","CATCH","FINALLY","ELSE","OUTDENT","LEADING_WHEN"],l=["TERMINATOR","INDENT","OUTDENT"]}).call(this)},require["./lexer"]=new function(){var a=this;(function(){var b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x,y,z,A,B,C,D,E,F,G,H,I,J,K,L,M,N,O,P,Q,R,S,T,U,V,W=Array.prototype.indexOf||function(a){for(var b=0,c=this.length;b=0||W.call(g,c)>=0)&&(j=c.toUpperCase(),j==="WHEN"&&(l=this.tag(),W.call(v,l)>=0)?j="LEADING_WHEN":j==="FOR"?this.seenFor=!0:j==="UNLESS"?j="IF":W.call(N,j)>=0?j="UNARY":W.call(H,j)>=0&&(j!=="INSTANCEOF"&&this.seenFor?(j="FOR"+j,this.seenFor=!1):(j="RELATION",this.value()==="!"&&(this.tokens.pop(),c="!"+c)))),W.call(["eval","arguments"].concat(t),c)>=0&&(b?(j="IDENTIFIER",c=new String(c),c.reserved=!0):W.call(I,c)>=0&&this.error('reserved word "'+c+'"')),b||(W.call(e,c)>=0&&(c=f[c]),j=function(){switch(c){case"!":return"UNARY";case"==":case"!=":return"COMPARE";case"&&":case"||":return"LOGIC";case"true":case"false":case"null":case"undefined":return"BOOL";case"break":case"continue":return"STATEMENT";default:return j}}()),this.token(j,c),a&&this.token(":",":");return d.length},a.prototype.numberToken=function(){var a,b,c,d;if(!(c=E.exec(this.chunk)))return 0;d=c[0],b=d.length;if(a=/0b([01]+)/.exec(d))d=parseInt(a[1],2).toString();this.token("NUMBER",d);return b},a.prototype.stringToken=function(){var a,b;switch(this.chunk.charAt(0)){case"'":if(!(a=L.exec(this.chunk)))return 0;this.token("STRING",(b=a[0]).replace(A,"\\\n"));break;case'"':if(!(b=this.balancedString(this.chunk,'"')))return 0;0=0))return 0;if(!(c=G.exec(this.chunk)))return 0;g=c,c=g[0],e=g[1],a=g[2],e.slice(0,2)==="/*"&&this.error("regular expressions cannot begin with `*`"),e==="//"&&(e="/(?:)/"),this.token("REGEX",""+e+a);return c.length},a.prototype.heregexToken=function(a){var b,c,d,e,f,g,h,i,j,k,l,m,n;d=a[0],b=a[1],c=a[2];if(0>b.indexOf("#{")){e=b.replace(o,"").replace(/\//g,"\\/"),e.match(/^\*/)&&this.error("regular expressions cannot begin with `*`"),this.token("REGEX","/"+(e||"(?:)")+"/"+c);return d.length}this.token("IDENTIFIER","RegExp"),this.tokens.push(["CALL_START","("]),g=[],k=this.interpolateString(b,{regex:!0});for(i=0,j=k.length;ithis.indent){if(d){this.indebt=f-this.indent,this.suppressNewlines();return b.length}a=f-this.indent+this.outdebt,this.token("INDENT",a),this.indents.push(a),this.ends.push("OUTDENT"),this.outdebt=this.indebt=0}else this.indebt=0,this.outdentToken(this.indent-f,d);this.indent=f;return b.length},a.prototype.outdentToken=function(a,b){var c,d;while(a>0)d=this.indents.length-1,this.indents[d]===void 0?a=0:this.indents[d]===this.outdebt?(a-=this.outdebt,this.outdebt=0):this.indents[d]=0)&&this.error('reserved word "'+this.value()+"\" can't be assigned");if((h=b[1])==="||"||h==="&&"){b[0]="COMPOUND_ASSIGN",b[1]+="=";return f.length}}if(f===";")this.seenFor=!1,e="TERMINATOR";else if(W.call(z,f)>=0)e="MATH";else if(W.call(i,f)>=0)e="COMPARE";else if(W.call(j,f)>=0)e="COMPOUND_ASSIGN";else if(W.call(N,f)>=0)e="UNARY";else if(W.call(K,f)>=0)e="SHIFT";else if(W.call(x,f)>=0||f==="?"&&(b!=null?b.spaced:void 0))e="LOGIC";else if(b&&!b.spaced)if(f==="("&&(k=b[0],W.call(c,k)>=0))b[0]==="?"&&(b[0]="FUNC_EXIST"),e="CALL_START";else if(f==="["&&(l=b[0],W.call(q,l)>=0)){e="INDEX_START";switch(b[0]){case"?":b[0]="INDEX_SOAK"}}switch(f){case"(":case"{":case"[":this.ends.push(r[f]);break;case")":case"}":case"]":this.pair(f)}this.token(e,f);return f.length},a.prototype.sanitizeHeredoc=function(a,b){var c,d,e,f,g;e=b.indent,d=b.herecomment;if(d){l.test(a)&&this.error('block comment cannot contain "*/", starting');if(a.indexOf("\n")<=0)return a}else while(f=m.exec(a)){c=f[1];if(e===null||0<(g=c.length)&&gh;1<=h?c++:c--){switch(d=a.charAt(c)){case"\\":c++;continue;case b:g.pop();if(!g.length)return a.slice(0,c+1);b=g[g.length-1];continue}b!=="}"||d!=='"'&&d!=="'"?b==="}"&&d==="/"&&(e=n.exec(a.slice(c))||G.exec(a.slice(c)))?c+=e[0].length-1:b==="}"&&d==="{"?g.push(b="}"):b==='"'&&f==="#"&&d==="{"&&g.push(b="}"):g.push(b=d),f=d}return this.error("missing "+g.pop()+", starting")},a.prototype.interpolateString=function(b,c){var d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t;c==null&&(c={}),e=c.heredoc,m=c.regex,o=[],l=0,f=-1;while(j=b.charAt(f+=1)){if(j==="\\"){f+=1;continue}if(j!=="#"||b.charAt(f+1)!=="{"||!(d=this.balancedString(b.slice(f+1),"}")))continue;l1&&(k.unshift(["(","(",this.line]),k.push([")",")",this.line])),o.push(["TOKENS",k])}f+=d.length,l=f+1}f>l&&l1)&&this.token("(","(");for(f=0,q=o.length;f|[-+*\/%<>&|^!?=]=|>>>=?|([-+:])\1|([&|<>])\2=?|\?\.|\.{2,3})/,O=/^[^\n\S]+/,h=/^###([^#][\s\S]*?)(?:###[^\n\S]*|(?:###)?$)|^(?:\s*#(?!##[^#]).*)+/,d=/^[-=]>/,B=/^(?:\n[^\n\S]*)+/,L=/^'[^\\']*(?:\\.[^\\']*)*'/,s=/^`[^\\`]*(?:\\.[^\\`]*)*`/,G=/^(\/(?![\s=])[^[\/\n\\]*(?:(?:\\[\s\S]|\[[^\]\n\\]*(?:\\[\s\S][^\]\n\\]*)*])[^[\/\n\\]*)*\/)([imgy]{0,4})(?!\w)/,n=/^\/{3}([\s\S]+?)\/{3}([imgy]{0,4})(?!\w)/,o=/\s+(?:#.*)?/g,A=/\n/g,m=/\n+([^\n\S]*)/g,l=/\*\//,w=/^\s*(?:,|\??\.(?![.\d])|::)/,M=/\s+$/,j=["-=","+=","/=","*=","%=","||=","&&=","?=","<<=",">>=",">>>=","&=","^=","|="],N=["!","~","NEW","TYPEOF","DELETE","DO"],x=["&&","||","&","|","^"],K=["<<",">>",">>>"],i=["==","!=","<",">","<=",">="],z=["*","/","%"],H=["IN","OF","INSTANCEOF"],b=["TRUE","FALSE","NULL","UNDEFINED"],C=["NUMBER","REGEX","BOOL","++","--","]"],D=C.concat(")","}","THIS","IDENTIFIER","STRING"),c=["IDENTIFIER","STRING","REGEX",")","]","}","?","::","@","THIS","SUPER"],q=c.concat("NUMBER","BOOL"),v=["INDENT","OUTDENT","TERMINATOR"]}).call(this)},require["./parser"]=new function(){var a=this,b=function(){var a={trace:function(){},yy:{},symbols_:{error:2,Root:3,Body:4,Block:5,TERMINATOR:6,Line:7,Expression:8,Statement:9,Return:10,Comment:11,STATEMENT:12,Value:13,Invocation:14,Code:15,Operation:16,Assign:17,If:18,Try:19,While:20,For:21,Switch:22,Class:23,Throw:24,INDENT:25,OUTDENT:26,Identifier:27,IDENTIFIER:28,AlphaNumeric:29,NUMBER:30,STRING:31,Literal:32,JS:33,REGEX:34,DEBUGGER:35,BOOL:36,Assignable:37,"=":38,AssignObj:39,ObjAssignable:40,":":41,ThisProperty:42,RETURN:43,HERECOMMENT:44,PARAM_START:45,ParamList:46,PARAM_END:47,FuncGlyph:48,"->":49,"=>":50,OptComma:51,",":52,Param:53,ParamVar:54,"...":55,Array:56,Object:57,Splat:58,SimpleAssignable:59,Accessor:60,Parenthetical:61,Range:62,This:63,".":64,"?.":65,"::":66,Index:67,INDEX_START:68,IndexValue:69,INDEX_END:70,INDEX_SOAK:71,Slice:72,"{":73,AssignList:74,"}":75,CLASS:76,EXTENDS:77,OptFuncExist:78,Arguments:79,SUPER:80,FUNC_EXIST:81,CALL_START:82,CALL_END:83,ArgList:84,THIS:85,"@":86,"[":87,"]":88,RangeDots:89,"..":90,Arg:91,SimpleArgs:92,TRY:93,Catch:94,FINALLY:95,CATCH:96,THROW:97,"(":98,")":99,WhileSource:100,WHILE:101,WHEN:102,UNTIL:103,Loop:104,LOOP:105,ForBody:106,FOR:107,ForStart:108,ForSource:109,ForVariables:110,OWN:111,ForValue:112,FORIN:113,FOROF:114,BY:115,SWITCH:116,Whens:117,ELSE:118,When:119,LEADING_WHEN:120,IfBlock:121,IF:122,POST_IF:123,UNARY:124,"-":125,"+":126,"--":127,"++":128,"?":129,MATH:130,SHIFT:131,COMPARE:132,LOGIC:133,RELATION:134,COMPOUND_ASSIGN:135,$accept:0,$end:1},terminals_:{2:"error",6:"TERMINATOR",12:"STATEMENT",25:"INDENT",26:"OUTDENT",28:"IDENTIFIER",30:"NUMBER",31:"STRING",33:"JS",34:"REGEX",35:"DEBUGGER",36:"BOOL",38:"=",41:":",43:"RETURN",44:"HERECOMMENT",45:"PARAM_START",47:"PARAM_END",49:"->",50:"=>",52:",",55:"...",64:".",65:"?.",66:"::",68:"INDEX_START",70:"INDEX_END",71:"INDEX_SOAK",73:"{",75:"}",76:"CLASS",77:"EXTENDS",80:"SUPER",81:"FUNC_EXIST",82:"CALL_START",83:"CALL_END",85:"THIS",86:"@",87:"[",88:"]",90:"..",93:"TRY",95:"FINALLY",96:"CATCH",97:"THROW",98:"(",99:")",101:"WHILE",102:"WHEN",103:"UNTIL",105:"LOOP",107:"FOR",111:"OWN",113:"FORIN",114:"FOROF",115:"BY",116:"SWITCH",118:"ELSE",120:"LEADING_WHEN",122:"IF",123:"POST_IF",124:"UNARY",125:"-",126:"+",127:"--",128:"++",129:"?",130:"MATH",131:"SHIFT",132:"COMPARE",133:"LOGIC",134:"RELATION",135:"COMPOUND_ASSIGN"},productions_:[0,[3,0],[3,1],[3,2],[4,1],[4,3],[4,2],[7,1],[7,1],[9,1],[9,1],[9,1],[8,1],[8,1],[8,1],[8,1],[8,1],[8,1],[8,1],[8,1],[8,1],[8,1],[8,1],[8,1],[5,2],[5,3],[27,1],[29,1],[29,1],[32,1],[32,1],[32,1],[32,1],[32,1],[17,3],[17,4],[17,5],[39,1],[39,3],[39,5],[39,1],[40,1],[40,1],[40,1],[10,2],[10,1],[11,1],[15,5],[15,2],[48,1],[48,1],[51,0],[51,1],[46,0],[46,1],[46,3],[53,1],[53,2],[53,3],[54,1],[54,1],[54,1],[54,1],[58,2],[59,1],[59,2],[59,2],[59,1],[37,1],[37,1],[37,1],[13,1],[13,1],[13,1],[13,1],[13,1],[60,2],[60,2],[60,2],[60,1],[60,1],[67,3],[67,2],[69,1],[69,1],[57,4],[74,0],[74,1],[74,3],[74,4],[74,6],[23,1],[23,2],[23,3],[23,4],[23,2],[23,3],[23,4],[23,5],[14,3],[14,3],[14,1],[14,2],[78,0],[78,1],[79,2],[79,4],[63,1],[63,1],[42,2],[56,2],[56,4],[89,1],[89,1],[62,5],[72,3],[72,2],[72,2],[84,1],[84,3],[84,4],[84,4],[84,6],[91,1],[91,1],[92,1],[92,3],[19,2],[19,3],[19,4],[19,5],[94,3],[24,2],[61,3],[61,5],[100,2],[100,4],[100,2],[100,4],[20,2],[20,2],[20,2],[20,1],[104,2],[104,2],[21,2],[21,2],[21,2],[106,2],[106,2],[108,2],[108,3],[112,1],[112,1],[112,1],[110,1],[110,3],[109,2],[109,2],[109,4],[109,4],[109,4],[109,6],[109,6],[22,5],[22,7],[22,4],[22,6],[117,1],[117,2],[119,3],[119,4],[121,3],[121,5],[18,1],[18,3],[18,3],[18,3],[16,2],[16,2],[16,2],[16,2],[16,2],[16,2],[16,2],[16,2],[16,3],[16,3],[16,3],[16,3],[16,3],[16,3],[16,3],[16,3],[16,5],[16,3]],performAction:function(a,b,c,d,e,f,g){var h=f.length-1;switch(e){case 1:return this.$=new d.Block;case 2:return this.$=f[h];case 3:return this.$=f[h-1];case 4:this.$=d.Block.wrap([f[h]]);break;case 5:this.$=f[h-2].push(f[h]);break;case 6:this.$=f[h-1];break;case 7:this.$=f[h];break;case 8:this.$=f[h];break;case 9:this.$=f[h];break;case 10:this.$=f[h];break;case 11:this.$=new d.Literal(f[h]);break;case 12:this.$=f[h];break;case 13:this.$=f[h];break;case 14:this.$=f[h];break;case 15:this.$=f[h];break;case 16:this.$=f[h];break;case 17:this.$=f[h];break;case 18:this.$=f[h];break;case 19:this.$=f[h];break;case 20:this.$=f[h];break;case 21:this.$=f[h];break;case 22:this.$=f[h];break;case 23:this.$=f[h];break;case 24:this.$=new d.Block;break;case 25:this.$=f[h-1];break;case 26:this.$=new d.Literal(f[h]);break;case 27:this.$=new d.Literal(f[h]);break;case 28:this.$=new d.Literal(f[h]);break;case 29:this.$=f[h];break;case 30:this.$=new d.Literal(f[h]);break;case 31:this.$=new d.Literal(f[h]);break;case 32:this.$=new d.Literal(f[h]);break;case 33:this.$=function(){var a;a=new d.Literal(f[h]),f[h]==="undefined"&&(a.isUndefined=!0);return a}();break;case 34:this.$=new d.Assign(f[h-2],f[h]);break;case 35:this.$=new d.Assign(f[h-3],f[h]);break;case 36:this.$=new d.Assign(f[h-4],f[h-1]);break;case 37:this.$=new d.Value(f[h]);break;case 38:this.$=new d.Assign(new d.Value(f[h-2]),f[h],"object");break;case 39:this.$=new d.Assign(new d.Value(f[h-4]),f[h-1],"object");break;case 40:this.$=f[h];break;case 41:this.$=f[h];break;case 42:this.$=f[h];break;case 43:this.$=f[h];break;case 44:this.$=new d.Return(f[h]);break;case 45:this.$=new d.Return;break;case 46:this.$=new d.Comment(f[h]);break;case 47:this.$=new d.Code(f[h-3],f[h],f[h-1]);break;case 48:this.$=new d.Code([],f[h],f[h-1]);break;case 49:this.$="func";break;case 50:this.$="boundfunc";break;case 51:this.$=f[h];break;case 52:this.$=f[h];break;case 53:this.$=[];break;case 54:this.$=[f[h]];break;case 55:this.$=f[h-2].concat(f[h]);break;case 56:this.$=new d.Param(f[h]);break;case 57:this.$=new d.Param(f[h-1],null,!0);break;case 58:this.$=new d.Param(f[h-2],f[h]);break;case 59:this.$=f[h];break;case 60:this.$=f[h];break;case 61:this.$=f[h];break;case 62:this.$=f[h];break;case 63:this.$=new d.Splat(f[h-1]);break;case 64:this.$=new d.Value(f[h]);break;case 65:this.$=f[h-1].add(f[h]);break;case 66:this.$=new d.Value(f[h-1],[].concat(f[h]));break;case 67:this.$=f[h];break;case 68:this.$=f[h];break;case 69:this.$=new d.Value(f[h]);break;case 70:this.$=new d.Value(f[h]);break;case 71:this.$=f[h];break;case 72:this.$=new d.Value(f[h]);break;case 73:this.$=new d.Value(f[h]);break;case 74:this.$=new d.Value(f[h]);break;case 75:this.$=f[h];break;case 76:this.$=new d.Access(f[h]);break;case 77:this.$=new d.Access(f[h],"soak");break;case 78:this.$=[new d.Access(new d.Literal("prototype")),new d.Access(f[h])];break;case 79:this.$=new d.Access(new d.Literal("prototype"));break;case 80:this.$=f[h];break;case 81:this.$=f[h-1];break;case 82:this.$=d.extend(f[h],{soak:!0});break;case 83:this.$=new d.Index(f[h]);break;case 84:this.$=new d.Slice(f[h]);break;case 85:this.$=new d.Obj(f[h-2],f[h-3].generated);break;case 86:this.$=[];break;case 87:this.$=[f[h]];break;case 88:this.$=f[h-2].concat(f[h]);break;case 89:this.$=f[h-3].concat(f[h]);break;case 90:this.$=f[h-5].concat(f[h-2]);break;case 91:this.$=new d.Class;break;case 92:this.$=new d.Class(null,null,f[h]);break;case 93:this.$=new d.Class(null,f[h]);break;case 94:this.$=new d.Class(null,f[h-1],f[h]);break;case 95:this.$=new d.Class(f[h]);break;case 96:this.$=new d.Class(f[h-1],null,f[h]);break;case 97:this.$=new d.Class(f[h-2],f[h]);break;case 98:this.$=new d.Class(f[h-3],f[h-1],f[h]);break;case 99:this.$=new d.Call(f[h-2],f[h],f[h-1]);break;case 100:this.$=new d.Call(f[h-2],f[h],f[h-1]);break;case 101:this.$=new d.Call("super",[new d.Splat(new d.Literal("arguments"))]);break;case 102:this.$=new d.Call("super",f[h]);break;case 103:this.$=!1;break;case 104:this.$=!0;break;case 105:this.$=[];break;case 106:this.$=f[h-2];break;case 107:this.$=new d.Value(new d.Literal("this"));break;case 108:this.$=new d.Value(new d.Literal("this"));break;case 109:this.$=new d.Value(new d.Literal("this"),[new d.Access(f[h])],"this");break;case 110:this.$=new d.Arr([]);break;case 111:this.$=new d.Arr(f[h-2]);break;case 112:this.$="inclusive";break;case 113:this.$="exclusive";break;case 114:this.$=new d.Range(f[h-3],f[h-1],f[h-2]);break;case 115:this.$=new d.Range(f[h-2],f[h],f[h-1]);break;case 116:this.$=new d.Range(f[h-1],null,f[h]);break;case 117:this.$=new d.Range(null,f[h],f[h-1]);break;case 118:this.$=[f[h]];break;case 119:this.$=f[h-2].concat(f[h]);break;case 120:this.$=f[h-3].concat(f[h]);break;case 121:this.$=f[h-2];break;case 122:this.$=f[h-5].concat(f[h-2]);break;case 123:this.$=f[h];break;case 124:this.$=f[h];break;case 125:this.$=f[h];break;case 126:this.$=[].concat(f[h-2],f[h]);break;case 127:this.$=new d.Try(f[h]);break;case 128:this.$=new d.Try(f[h-1],f[h][0],f[h][1]);break;case 129:this.$=new d.Try(f[h-2],null,null,f[h]);break;case 130:this.$=new d.Try(f[h-3],f[h-2][0],f[h-2][1],f[h]);break;case 131:this.$=[f[h-1],f[h]];break;case 132:this.$=new d.Throw(f[h]);break;case 133:this.$=new d.Parens(f[h-1]);break;case 134:this.$=new d.Parens(f[h-2]);break;case 135:this.$=new d.While(f[h]);break;case 136:this.$=new d.While(f[h-2],{guard:f[h]});break;case 137:this.$=new d.While(f[h],{invert:!0});break;case 138:this.$=new d.While(f[h-2],{invert:!0,guard:f[h]});break;case 139:this.$=f[h-1].addBody(f[h]);break;case 140:this.$=f[h].addBody(d.Block.wrap([f[h-1]]));break;case 141:this.$=f[h].addBody(d.Block.wrap([f[h-1]]));break;case 142:this.$=f[h];break;case 143:this.$=(new d.While(new d.Literal("true"))).addBody(f[h]);break;case 144:this.$=(new d.While(new d.Literal("true"))).addBody(d.Block.wrap([f[h]]));break;case 145:this.$=new d.For(f[h-1],f[h]);break;case 146:this.$=new d.For(f[h-1],f[h]);break;case 147:this.$=new d.For(f[h],f[h-1]);break;case 148:this.$={source:new d.Value(f[h])};break;case 149:this.$=function(){f[h].own=f[h-1].own,f[h].name=f[h-1][0],f[h].index=f[h-1][1];return f[h]}();break;case 150:this.$=f[h];break;case 151:this.$=function(){f[h].own=!0;return f[h]}();break;case 152:this.$=f[h];break;case 153:this.$=new d.Value(f[h]);break;case 154:this.$=new d.Value(f[h]);break;case 155:this.$=[f[h]];break;case 156:this.$=[f[h-2],f[h]];break;case 157:this.$={source:f[h]};break;case 158:this.$={source:f[h],object:!0};break;case 159:this.$={source:f[h-2],guard:f[h]};break;case 160:this.$={source:f[h-2],guard:f[h],object:!0};break;case 161:this.$={source:f[h-2],step:f[h]};break;case 162:this.$={source:f[h-4],guard:f[h-2],step:f[h]};break;case 163:this.$={source:f[h-4],step:f[h-2],guard:f[h]};break;case 164:this.$=new d.Switch(f[h-3],f[h-1]);break;case 165:this.$=new d.Switch(f[h-5],f[h-3],f[h-1]);break;case 166:this.$=new d.Switch(null,f[h-1]);break;case 167:this.$=new d.Switch(null,f[h-3],f[h-1]);break;case 168:this.$=f[h];break;case 169:this.$=f[h-1].concat(f[h]);break;case 170:this.$=[[f[h-1],f[h]]];break;case 171:this.$=[[f[h-2],f[h-1]]];break;case 172:this.$=new d.If(f[h-1],f[h],{type:f[h-2]});break;case 173:this.$=f[h-4].addElse(new d.If(f[h-1],f[h],{type:f[h-2]}));break;case 174:this.$=f[h];break;case 175:this.$=f[h-2].addElse(f[h]);break;case 176:this.$=new d.If(f[h],d.Block.wrap([f[h-2]]),{type:f[h-1],statement:!0});break;case 177:this.$=new d.If(f[h],d.Block.wrap([f[h-2]]),{type:f[h-1],statement:!0});break;case 178:this.$=new d.Op(f[h-1],f[h]);break;case 179:this.$=new d.Op("-",f[h]);break;case 180:this.$=new d.Op("+",f[h]);break;case 181:this.$=new d.Op("--",f[h]);break;case 182:this.$=new d.Op("++",f[h]);break;case 183:this.$=new d.Op("--",f[h-1],null,!0);break;case 184:this.$=new d.Op("++",f[h-1],null,!0);break;case 185:this.$=new d.Existence(f[h-1]);break;case 186:this.$=new d.Op("+",f[h-2],f[h]);break;case 187:this.$=new d.Op("-",f[h-2],f[h]);break;case 188:this.$=new d.Op(f[h-1],f[h-2],f[h]);break;case 189:this.$=new d.Op(f[h-1],f[h-2],f[h]);break;case 190:this.$=new d.Op(f[h-1],f[h-2],f[h]);break;case 191:this.$=new d.Op(f[h-1],f[h-2],f[h]);break;case 192:this.$=function(){return f[h-1].charAt(0)==="!"?(new d.Op(f[h-1].slice(1),f[h-2],f[h])).invert():new d.Op(f[h-1],f[h-2],f[h])}();break;case 193:this.$=new d.Assign(f[h-2],f[h],f[h-1]);break;case 194:this.$=new d.Assign(f[h-4],f[h-1],f[h-3]);break;case 195:this.$=new d.Extends(f[h-2],f[h])}},table:[{1:[2,1],3:1,4:2,5:3,7:4,8:6,9:7,10:20,11:21,12:[1,22],13:8,14:9,15:10,16:11,17:12,18:13,19:14,20:15,21:16,22:17,23:18,24:19,25:[1,5],27:60,28:[1,71],29:49,30:[1,69],31:[1,70],32:24,33:[1,50],34:[1,51],35:[1,52],36:[1,53],37:23,42:61,43:[1,45],44:[1,46],45:[1,29],48:30,49:[1,58],50:[1,59],56:47,57:48,59:36,61:25,62:26,63:27,73:[1,68],76:[1,43],80:[1,28],85:[1,56],86:[1,57],87:[1,55],93:[1,38],97:[1,44],98:[1,54],100:39,101:[1,63],103:[1,64],104:40,105:[1,65],106:41,107:[1,66],108:67,116:[1,42],121:37,122:[1,62],124:[1,31],125:[1,32],126:[1,33],127:[1,34],128:[1,35]},{1:[3]},{1:[2,2],6:[1,72]},{6:[1,73]},{1:[2,4],6:[2,4],26:[2,4],99:[2,4]},{4:75,7:4,8:6,9:7,10:20,11:21,12:[1,22],13:8,14:9,15:10,16:11,17:12,18:13,19:14,20:15,21:16,22:17,23:18,24:19,26:[1,74],27:60,28:[1,71],29:49,30:[1,69],31:[1,70],32:24,33:[1,50],34:[1,51],35:[1,52],36:[1,53],37:23,42:61,43:[1,45],44:[1,46],45:[1,29],48:30,49:[1,58],50:[1,59],56:47,57:48,59:36,61:25,62:26,63:27,73:[1,68],76:[1,43],80:[1,28],85:[1,56],86:[1,57],87:[1,55],93:[1,38],97:[1,44],98:[1,54],100:39,101:[1,63],103:[1,64],104:40,105:[1,65],106:41,107:[1,66],108:67,116:[1,42],121:37,122:[1,62],124:[1,31],125:[1,32],126:[1,33],127:[1,34],128:[1,35]},{1:[2,7],6:[2,7],26:[2,7],99:[2,7],100:85,101:[1,63],103:[1,64],106:86,107:[1,66],108:67,123:[1,84],125:[1,78],126:[1,77],129:[1,76],130:[1,79],131:[1,80],132:[1,81],133:[1,82],134:[1,83]},{1:[2,8],6:[2,8],26:[2,8],99:[2,8],100:88,101:[1,63],103:[1,64],106:89,107:[1,66],108:67,123:[1,87]},{1:[2,12],6:[2,12],25:[2,12],26:[2,12],47:[2,12],52:[2,12],55:[2,12],60:91,64:[1,93],65:[1,94],66:[1,95],67:96,68:[1,97],70:[2,12],71:[1,98],75:[2,12],78:90,81:[1,92],82:[2,103],83:[2,12],88:[2,12],90:[2,12],99:[2,12],101:[2,12],102:[2,12],103:[2,12],107:[2,12],115:[2,12],123:[2,12],125:[2,12],126:[2,12],129:[2,12],130:[2,12],131:[2,12],132:[2,12],133:[2,12],134:[2,12]},{1:[2,13],6:[2,13],25:[2,13],26:[2,13],47:[2,13],52:[2,13],55:[2,13],60:100,64:[1,93],65:[1,94],66:[1,95],67:96,68:[1,97],70:[2,13],71:[1,98],75:[2,13],78:99,81:[1,92],82:[2,103],83:[2,13],88:[2,13],90:[2,13],99:[2,13],101:[2,13],102:[2,13],103:[2,13],107:[2,13],115:[2,13],123:[2,13],125:[2,13],126:[2,13],129:[2,13],130:[2,13],131:[2,13],132:[2,13],133:[2,13],134:[2,13]},{1:[2,14],6:[2,14],25:[2,14],26:[2,14],47:[2,14],52:[2,14],55:[2,14],70:[2,14],75:[2,14],83:[2,14],88:[2,14],90:[2,14],99:[2,14],101:[2,14],102:[2,14],103:[2,14],107:[2,14],115:[2,14],123:[2,14],125:[2,14],126:[2,14],129:[2,14],130:[2,14],131:[2,14],132:[2,14],133:[2,14],134:[2,14]},{1:[2,15],6:[2,15],25:[2,15],26:[2,15],47:[2,15],52:[2,15],55:[2,15],70:[2,15],75:[2,15],83:[2,15],88:[2,15],90:[2,15],99:[2,15],101:[2,15],102:[2,15],103:[2,15],107:[2,15],115:[2,15],123:[2,15],125:[2,15],126:[2,15],129:[2,15],130:[2,15],131:[2,15],132:[2,15],133:[2,15],134:[2,15]},{1:[2,16],6:[2,16],25:[2,16],26:[2,16],47:[2,16],52:[2,16],55:[2,16],70:[2,16],75:[2,16],83:[2,16],88:[2,16],90:[2,16],99:[2,16],101:[2,16],102:[2,16],103:[2,16],107:[2,16],115:[2,16],123:[2,16],125:[2,16],126:[2,16],129:[2,16],130:[2,16],131:[2,16],132:[2,16],133:[2,16],134:[2,16]},{1:[2,17],6:[2,17],25:[2,17],26:[2,17],47:[2,17],52:[2,17],55:[2,17],70:[2,17],75:[2,17],83:[2,17],88:[2,17],90:[2,17],99:[2,17],101:[2,17],102:[2,17],103:[2,17],107:[2,17],115:[2,17],123:[2,17],125:[2,17],126:[2,17],129:[2,17],130:[2,17],131:[2,17],132:[2,17],133:[2,17],134:[2,17]},{1:[2,18],6:[2,18],25:[2,18],26:[2,18],47:[2,18],52:[2,18],55:[2,18],70:[2,18],75:[2,18],83:[2,18],88:[2,18],90:[2,18],99:[2,18],101:[2,18],102:[2,18],103:[2,18],107:[2,18],115:[2,18],123:[2,18],125:[2,18],126:[2,18],129:[2,18],130:[2,18],131:[2,18],132:[2,18],133:[2,18],134:[2,18]},{1:[2,19],6:[2,19],25:[2,19],26:[2,19],47:[2,19],52:[2,19],55:[2,19],70:[2,19],75:[2,19],83:[2,19],88:[2,19],90:[2,19],99:[2,19],101:[2,19],102:[2,19],103:[2,19],107:[2,19],115:[2,19],123:[2,19],125:[2,19],126:[2,19],129:[2,19],130:[2,19],131:[2,19],132:[2,19],133:[2,19],134:[2,19]},{1:[2,20],6:[2,20],25:[2,20],26:[2,20],47:[2,20],52:[2,20],55:[2,20],70:[2,20],75:[2,20],83:[2,20],88:[2,20],90:[2,20],99:[2,20],101:[2,20],102:[2,20],103:[2,20],107:[2,20],115:[2,20],123:[2,20],125:[2,20],126:[2,20],129:[2,20],130:[2,20],131:[2,20],132:[2,20],133:[2,20],134:[2,20]},{1:[2,21],6:[2,21],25:[2,21],26:[2,21],47:[2,21],52:[2,21],55:[2,21],70:[2,21],75:[2,21],83:[2,21],88:[2,21],90:[2,21],99:[2,21],101:[2,21],102:[2,21],103:[2,21],107:[2,21],115:[2,21],123:[2,21],125:[2,21],126:[2,21],129:[2,21],130:[2,21],131:[2,21],132:[2,21],133:[2,21],134:[2,21]},{1:[2,22],6:[2,22],25:[2,22],26:[2,22],47:[2,22],52:[2,22],55:[2,22],70:[2,22],75:[2,22],83:[2,22],88:[2,22],90:[2,22],99:[2,22],101:[2,22],102:[2,22],103:[2,22],107:[2,22],115:[2,22],123:[2,22],125:[2,22],126:[2,22],129:[2,22],130:[2,22],131:[2,22],132:[2,22],133:[2,22],134:[2,22]},{1:[2,23],6:[2,23],25:[2,23],26:[2,23],47:[2,23],52:[2,23],55:[2,23],70:[2,23],75:[2,23],83:[2,23],88:[2,23],90:[2,23],99:[2,23],101:[2,23],102:[2,23],103:[2,23],107:[2,23],115:[2,23],123:[2,23],125:[2,23],126:[2,23],129:[2,23],130:[2,23],131:[2,23],132:[2,23],133:[2,23],134:[2,23]},{1:[2,9],6:[2,9],26:[2,9],99:[2,9],101:[2,9],103:[2,9],107:[2,9],123:[2,9]},{1:[2,10],6:[2,10],26:[2,10],99:[2,10],101:[2,10],103:[2,10],107:[2,10],123:[2,10]},{1:[2,11],6:[2,11],26:[2,11],99:[2,11],101:[2,11],103:[2,11],107:[2,11],123:[2,11]},{1:[2,71],6:[2,71],25:[2,71],26:[2,71],38:[1,101],47:[2,71],52:[2,71],55:[2,71],64:[2,71],65:[2,71],66:[2,71],68:[2,71],70:[2,71],71:[2,71],75:[2,71],81:[2,71],82:[2,71],83:[2,71],88:[2,71],90:[2,71],99:[2,71],101:[2,71],102:[2,71],103:[2,71],107:[2,71],115:[2,71],123:[2,71],125:[2,71],126:[2,71],129:[2,71],130:[2,71],131:[2,71],132:[2,71],133:[2,71],134:[2,71]},{1:[2,72],6:[2,72],25:[2,72],26:[2,72],47:[2,72],52:[2,72],55:[2,72],64:[2,72],65:[2,72],66:[2,72],68:[2,72],70:[2,72],71:[2,72],75:[2,72],81:[2,72],82:[2,72],83:[2,72],88:[2,72],90:[2,72],99:[2,72],101:[2,72],102:[2,72],103:[2,72],107:[2,72],115:[2,72],123:[2,72],125:[2,72],126:[2,72],129:[2,72],130:[2,72],131:[2,72],132:[2,72],133:[2,72],134:[2,72]},{1:[2,73],6:[2,73],25:[2,73],26:[2,73],47:[2,73],52:[2,73],55:[2,73],64:[2,73],65:[2,73],66:[2,73],68:[2,73],70:[2,73],71:[2,73],75:[2,73],81:[2,73],82:[2,73],83:[2,73],88:[2,73],90:[2,73],99:[2,73],101:[2,73],102:[2,73],103:[2,73],107:[2,73],115:[2,73],123:[2,73],125:[2,73],126:[2,73],129:[2,73],130:[2,73],131:[2,73],132:[2,73],133:[2,73],134:[2,73]},{1:[2,74],6:[2,74],25:[2,74],26:[2,74],47:[2,74],52:[2,74],55:[2,74],64:[2,74],65:[2,74],66:[2,74],68:[2,74],70:[2,74],71:[2,74],75:[2,74],81:[2,74],82:[2,74],83:[2,74],88:[2,74],90:[2,74],99:[2,74],101:[2,74],102:[2,74],103:[2,74],107:[2,74],115:[2,74],123:[2,74],125:[2,74],126:[2,74],129:[2,74],130:[2,74],131:[2,74],132:[2,74],133:[2,74],134:[2,74]},{1:[2,75],6:[2,75],25:[2,75],26:[2,75],47:[2,75],52:[2,75],55:[2,75],64:[2,75],65:[2,75],66:[2,75],68:[2,75],70:[2,75],71:[2,75],75:[2,75],81:[2,75],82:[2,75],83:[2,75],88:[2,75],90:[2,75],99:[2,75],101:[2,75],102:[2,75],103:[2,75],107:[2,75],115:[2,75],123:[2,75],125:[2,75],126:[2,75],129:[2,75],130:[2,75],131:[2,75],132:[2,75],133:[2,75],134:[2,75]},{1:[2,101],6:[2,101],25:[2,101],26:[2,101],47:[2,101],52:[2,101],55:[2,101],64:[2,101],65:[2,101],66:[2,101],68:[2,101],70:[2,101],71:[2,101],75:[2,101],79:102,81:[2,101],82:[1,103],83:[2,101],88:[2,101],90:[2,101],99:[2,101],101:[2,101],102:[2,101],103:[2,101],107:[2,101],115:[2,101],123:[2,101],125:[2,101],126:[2,101],129:[2,101],130:[2,101],131:[2,101],132:[2,101],133:[2,101],134:[2,101]},{27:107,28:[1,71],42:108,46:104,47:[2,53],52:[2,53],53:105,54:106,56:109,57:110,73:[1,68],86:[1,111],87:[1,112]},{5:113,25:[1,5]},{8:114,9:115,10:20,11:21,12:[1,22],13:8,14:9,15:10,16:11,17:12,18:13,19:14,20:15,21:16,22:17,23:18,24:19,27:60,28:[1,71],29:49,30:[1,69],31:[1,70],32:24,33:[1,50],34:[1,51],35:[1,52],36:[1,53],37:23,42:61,43:[1,45],44:[1,46],45:[1,29],48:30,49:[1,58],50:[1,59],56:47,57:48,59:36,61:25,62:26,63:27,73:[1,68],76:[1,43],80:[1,28],85:[1,56],86:[1,57],87:[1,55],93:[1,38],97:[1,44],98:[1,54],100:39,101:[1,63],103:[1,64],104:40,105:[1,65],106:41,107:[1,66],108:67,116:[1,42],121:37,122:[1,62],124:[1,31],125:[1,32],126:[1,33],127:[1,34],128:[1,35]},{8:116,9:115,10:20,11:21,12:[1,22],13:8,14:9,15:10,16:11,17:12,18:13,19:14,20:15,21:16,22:17,23:18,24:19,27:60,28:[1,71],29:49,30:[1,69],31:[1,70],32:24,33:[1,50],34:[1,51],35:[1,52],36:[1,53],37:23,42:61,43:[1,45],44:[1,46],45:[1,29],48:30,49:[1,58],50:[1,59],56:47,57:48,59:36,61:25,62:26,63:27,73:[1,68],76:[1,43],80:[1,28],85:[1,56],86:[1,57],87:[1,55],93:[1,38],97:[1,44],98:[1,54],100:39,101:[1,63],103:[1,64],104:40,105:[1,65],106:41,107:[1,66],108:67,116:[1,42],121:37,122:[1,62],124:[1,31],125:[1,32],126:[1,33],127:[1,34],128:[1,35]},{8:117,9:115,10:20,11:21,12:[1,22],13:8,14:9,15:10,16:11,17:12,18:13,19:14,20:15,21:16,22:17,23:18,24:19,27:60,28:[1,71],29:49,30:[1,69],31:[1,70],32:24,33:[1,50],34:[1,51],35:[1,52],36:[1,53],37:23,42:61,43:[1,45],44:[1,46],45:[1,29],48:30,49:[1,58],50:[1,59],56:47,57:48,59:36,61:25,62:26,63:27,73:[1,68],76:[1,43],80:[1,28],85:[1,56],86:[1,57],87:[1,55],93:[1,38],97:[1,44],98:[1,54],100:39,101:[1,63],103:[1,64],104:40,105:[1,65],106:41,107:[1,66],108:67,116:[1,42],121:37,122:[1,62],124:[1,31],125:[1,32],126:[1,33],127:[1,34],128:[1,35]},{13:119,14:120,27:60,28:[1,71],29:49,30:[1,69],31:[1,70],32:24,33:[1,50],34:[1,51],35:[1,52],36:[1,53],37:121,42:61,56:47,57:48,59:118,61:25,62:26,63:27,73:[1,68],80:[1,28],85:[1,56],86:[1,57],87:[1,55],98:[1,54]},{13:119,14:120,27:60,28:[1,71],29:49,30:[1,69],31:[1,70],32:24,33:[1,50],34:[1,51],35:[1,52],36:[1,53],37:121,42:61,56:47,57:48,59:122,61:25,62:26,63:27,73:[1,68],80:[1,28],85:[1,56],86:[1,57],87:[1,55],98:[1,54]},{1:[2,68],6:[2,68],25:[2,68],26:[2,68],38:[2,68],47:[2,68],52:[2,68],55:[2,68],64:[2,68],65:[2,68],66:[2,68],68:[2,68],70:[2,68],71:[2,68],75:[2,68],77:[1,126],81:[2,68],82:[2,68],83:[2,68],88:[2,68],90:[2,68],99:[2,68],101:[2,68],102:[2,68],103:[2,68],107:[2,68],115:[2,68],123:[2,68],125:[2,68],126:[2,68],127:[1,123],128:[1,124],129:[2,68],130:[2,68],131:[2,68],132:[2,68],133:[2,68],134:[2,68],135:[1,125]},{1:[2,174],6:[2,174],25:[2,174],26:[2,174],47:[2,174],52:[2,174],55:[2,174],70:[2,174],75:[2,174],83:[2,174],88:[2,174],90:[2,174],99:[2,174],101:[2,174],102:[2,174],103:[2,174],107:[2,174],115:[2,174],118:[1,127],123:[2,174],125:[2,174],126:[2,174],129:[2,174],130:[2,174],131:[2,174],132:[2,174],133:[2,174],134:[2,174]},{5:128,25:[1,5]},{5:129,25:[1,5]},{1:[2,142],6:[2,142],25:[2,142],26:[2,142],47:[2,142],52:[2,142],55:[2,142],70:[2,142],75:[2,142],83:[2,142],88:[2,142],90:[2,142],99:[2,142],101:[2,142],102:[2,142],103:[2,142],107:[2,142],115:[2,142],123:[2,142],125:[2,142],126:[2,142],129:[2,142],130:[2,142],131:[2,142],132:[2,142],133:[2,142],134:[2,142]},{5:130,25:[1,5]},{8:131,9:115,10:20,11:21,12:[1,22],13:8,14:9,15:10,16:11,17:12,18:13,19:14,20:15,21:16,22:17,23:18,24:19,25:[1,132],27:60,28:[1,71],29:49,30:[1,69],31:[1,70],32:24,33:[1,50],34:[1,51],35:[1,52],36:[1,53],37:23,42:61,43:[1,45],44:[1,46],45:[1,29],48:30,49:[1,58],50:[1,59],56:47,57:48,59:36,61:25,62:26,63:27,73:[1,68],76:[1,43],80:[1,28],85:[1,56],86:[1,57],87:[1,55],93:[1,38],97:[1,44],98:[1,54],100:39,101:[1,63],103:[1,64],104:40,105:[1,65],106:41,107:[1,66],108:67,116:[1,42],121:37,122:[1,62],124:[1,31],125:[1,32],126:[1,33],127:[1,34],128:[1,35]},{1:[2,91],5:133,6:[2,91],13:119,14:120,25:[1,5],26:[2,91],27:60,28:[1,71],29:49,30:[1,69],31:[1,70],32:24,33:[1,50],34:[1,51],35:[1,52],36:[1,53],37:121,42:61,47:[2,91],52:[2,91],55:[2,91],56:47,57:48,59:135,61:25,62:26,63:27,70:[2,91],73:[1,68],75:[2,91],77:[1,134],80:[1,28],83:[2,91],85:[1,56],86:[1,57],87:[1,55],88:[2,91],90:[2,91],98:[1,54],99:[2,91],101:[2,91],102:[2,91],103:[2,91],107:[2,91],115:[2,91],123:[2,91],125:[2,91],126:[2,91],129:[2,91],130:[2,91],131:[2,91],132:[2,91],133:[2,91],134:[2,91]},{8:136,9:115,10:20,11:21,12:[1,22],13:8,14:9,15:10,16:11,17:12,18:13,19:14,20:15,21:16,22:17,23:18,24:19,27:60,28:[1,71],29:49,30:[1,69],31:[1,70],32:24,33:[1,50],34:[1,51],35:[1,52],36:[1,53],37:23,42:61,43:[1,45],44:[1,46],45:[1,29],48:30,49:[1,58],50:[1,59],56:47,57:48,59:36,61:25,62:26,63:27,73:[1,68],76:[1,43],80:[1,28],85:[1,56],86:[1,57],87:[1,55],93:[1,38],97:[1,44],98:[1,54],100:39,101:[1,63],103:[1,64],104:40,105:[1,65],106:41,107:[1,66],108:67,116:[1,42],121:37,122:[1,62],124:[1,31],125:[1,32],126:[1,33],127:[1,34],128:[1,35]},{1:[2,45],6:[2,45],8:137,9:115,10:20,11:21,12:[1,22],13:8,14:9,15:10,16:11,17:12,18:13,19:14,20:15,21:16,22:17,23:18,24:19,26:[2,45],27:60,28:[1,71],29:49,30:[1,69],31:[1,70],32:24,33:[1,50],34:[1,51],35:[1,52],36:[1,53],37:23,42:61,43:[1,45],44:[1,46],45:[1,29],48:30,49:[1,58],50:[1,59],56:47,57:48,59:36,61:25,62:26,63:27,73:[1,68],76:[1,43],80:[1,28],85:[1,56],86:[1,57],87:[1,55],93:[1,38],97:[1,44],98:[1,54],99:[2,45],100:39,101:[2,45],103:[2,45],104:40,105:[1,65],106:41,107:[2,45],108:67,116:[1,42],121:37,122:[1,62],123:[2,45],124:[1,31],125:[1,32],126:[1,33],127:[1,34],128:[1,35]},{1:[2,46],6:[2,46],25:[2,46],26:[2,46],52:[2,46],75:[2,46],99:[2,46],101:[2,46],103:[2,46],107:[2,46],123:[2,46]},{1:[2,69],6:[2,69],25:[2,69],26:[2,69],38:[2,69],47:[2,69],52:[2,69],55:[2,69],64:[2,69],65:[2,69],66:[2,69],68:[2,69],70:[2,69],71:[2,69],75:[2,69],81:[2,69],82:[2,69],83:[2,69],88:[2,69],90:[2,69],99:[2,69],101:[2,69],102:[2,69],103:[2,69],107:[2,69],115:[2,69],123:[2,69],125:[2,69],126:[2,69],129:[2,69],130:[2,69],131:[2,69],132:[2,69],133:[2,69],134:[2,69]},{1:[2,70],6:[2,70],25:[2,70],26:[2,70],38:[2,70],47:[2,70],52:[2,70],55:[2,70],64:[2,70],65:[2,70],66:[2,70],68:[2,70],70:[2,70],71:[2,70],75:[2,70],81:[2,70],82:[2,70],83:[2,70],88:[2,70],90:[2,70],99:[2,70],101:[2,70],102:[2,70],103:[2,70],107:[2,70],115:[2,70],123:[2,70],125:[2,70],126:[2,70],129:[2,70],130:[2,70],131:[2,70],132:[2,70],133:[2,70],134:[2,70]},{1:[2,29],6:[2,29],25:[2,29],26:[2,29],47:[2,29],52:[2,29],55:[2,29],64:[2,29],65:[2,29],66:[2,29],68:[2,29],70:[2,29],71:[2,29],75:[2,29],81:[2,29],82:[2,29],83:[2,29],88:[2,29],90:[2,29],99:[2,29],101:[2,29],102:[2,29],103:[2,29],107:[2,29],115:[2,29],123:[2,29],125:[2,29],126:[2,29],129:[2,29],130:[2,29],131:[2,29],132:[2,29],133:[2,29],134:[2,29]},{1:[2,30],6:[2,30],25:[2,30],26:[2,30],47:[2,30],52:[2,30],55:[2,30],64:[2,30],65:[2,30],66:[2,30],68:[2,30],70:[2,30],71:[2,30],75:[2,30],81:[2,30],82:[2,30],83:[2,30],88:[2,30],90:[2,30],99:[2,30],101:[2,30],102:[2,30],103:[2,30],107:[2,30],115:[2,30],123:[2,30],125:[2,30],126:[2,30],129:[2,30],130:[2,30],131:[2,30],132:[2,30],133:[2,30],134:[2,30]},{1:[2,31],6:[2,31],25:[2,31],26:[2,31],47:[2,31],52:[2,31],55:[2,31],64:[2,31],65:[2,31],66:[2,31],68:[2,31],70:[2,31],71:[2,31],75:[2,31],81:[2,31],82:[2,31],83:[2,31],88:[2,31],90:[2,31],99:[2,31],101:[2,31],102:[2,31],103:[2,31],107:[2,31],115:[2,31],123:[2,31],125:[2,31],126:[2,31],129:[2,31],130:[2,31],131:[2,31],132:[2,31],133:[2,31],134:[2,31]},{1:[2,32],6:[2,32],25:[2,32],26:[2,32],47:[2,32],52:[2,32],55:[2,32],64:[2,32],65:[2,32],66:[2,32],68:[2,32],70:[2,32],71:[2,32],75:[2,32],81:[2,32],82:[2,32],83:[2,32],88:[2,32],90:[2,32],99:[2,32],101:[2,32],102:[2,32],103:[2,32],107:[2,32],115:[2,32],123:[2,32],125:[2,32],126:[2,32],129:[2,32],130:[2,32],131:[2,32],132:[2,32],133:[2,32],134:[2,32]},{1:[2,33],6:[2,33],25:[2,33],26:[2,33],47:[2,33],52:[2,33],55:[2,33],64:[2,33],65:[2,33],66:[2,33],68:[2,33],70:[2,33],71:[2,33],75:[2,33],81:[2,33],82:[2,33],83:[2,33],88:[2,33],90:[2,33],99:[2,33],101:[2,33],102:[2,33],103:[2,33],107:[2,33],115:[2,33],123:[2,33],125:[2,33],126:[2,33],129:[2,33],130:[2,33],131:[2,33],132:[2,33],133:[2,33],134:[2,33]},{4:138,7:4,8:6,9:7,10:20,11:21,12:[1,22],13:8,14:9,15:10,16:11,17:12,18:13,19:14,20:15,21:16,22:17,23:18,24:19,25:[1,139],27:60,28:[1,71],29:49,30:[1,69],31:[1,70],32:24,33:[1,50],34:[1,51],35:[1,52],36:[1,53],37:23,42:61,43:[1,45],44:[1,46],45:[1,29],48:30,49:[1,58],50:[1,59],56:47,57:48,59:36,61:25,62:26,63:27,73:[1,68],76:[1,43],80:[1,28],85:[1,56],86:[1,57],87:[1,55],93:[1,38],97:[1,44],98:[1,54],100:39,101:[1,63],103:[1,64],104:40,105:[1,65],106:41,107:[1,66],108:67,116:[1,42],121:37,122:[1,62],124:[1,31],125:[1,32],126:[1,33],127:[1,34],128:[1,35]},{8:140,9:115,10:20,11:21,12:[1,22],13:8,14:9,15:10,16:11,17:12,18:13,19:14,20:15,21:16,22:17,23:18,24:19,25:[1,144],27:60,28:[1,71],29:49,30:[1,69],31:[1,70],32:24,33:[1,50],34:[1,51],35:[1,52],36:[1,53],37:23,42:61,43:[1,45],44:[1,46],45:[1,29],48:30,49:[1,58],50:[1,59],56:47,57:48,58:145,59:36,61:25,62:26,63:27,73:[1,68],76:[1,43],80:[1,28],84:142,85:[1,56],86:[1,57],87:[1,55],88:[1,141],91:143,93:[1,38],97:[1,44],98:[1,54],100:39,101:[1,63],103:[1,64],104:40,105:[1,65],106:41,107:[1,66],108:67,116:[1,42],121:37,122:[1,62],124:[1,31],125:[1,32],126:[1,33],127:[1,34],128:[1,35]},{1:[2,107],6:[2,107],25:[2,107],26:[2,107],47:[2,107],52:[2,107],55:[2,107],64:[2,107],65:[2,107],66:[2,107],68:[2,107],70:[2,107],71:[2,107],75:[2,107],81:[2,107],82:[2,107],83:[2,107],88:[2,107],90:[2,107],99:[2,107],101:[2,107],102:[2,107],103:[2,107],107:[2,107],115:[2,107],123:[2,107],125:[2,107],126:[2,107],129:[2,107],130:[2,107],131:[2,107],132:[2,107],133:[2,107],134:[2,107]},{1:[2,108],6:[2,108],25:[2,108],26:[2,108],27:146,28:[1,71],47:[2,108],52:[2,108],55:[2,108],64:[2,108],65:[2,108],66:[2,108],68:[2,108],70:[2,108],71:[2,108],75:[2,108],81:[2,108],82:[2,108],83:[2,108],88:[2,108],90:[2,108],99:[2,108],101:[2,108],102:[2,108],103:[2,108],107:[2,108],115:[2,108],123:[2,108],125:[2,108],126:[2,108],129:[2,108],130:[2,108],131:[2,108],132:[2,108],133:[2,108],134:[2,108]},{25:[2,49]},{25:[2,50]},{1:[2,64],6:[2,64],25:[2,64],26:[2,64],38:[2,64],47:[2,64],52:[2,64],55:[2,64],64:[2,64],65:[2,64],66:[2,64],68:[2,64],70:[2,64],71:[2,64],75:[2,64],77:[2,64],81:[2,64],82:[2,64],83:[2,64],88:[2,64],90:[2,64],99:[2,64],101:[2,64],102:[2,64],103:[2,64],107:[2,64],115:[2,64],123:[2,64],125:[2,64],126:[2,64],127:[2,64],128:[2,64],129:[2,64],130:[2,64],131:[2,64],132:[2,64],133:[2,64],134:[2,64],135:[2,64]},{1:[2,67],6:[2,67],25:[2,67],26:[2,67],38:[2,67],47:[2,67],52:[2,67],55:[2,67],64:[2,67],65:[2,67],66:[2,67],68:[2,67],70:[2,67],71:[2,67],75:[2,67],77:[2,67],81:[2,67],82:[2,67],83:[2,67],88:[2,67],90:[2,67],99:[2,67],101:[2,67],102:[2,67],103:[2,67],107:[2,67],115:[2,67],123:[2,67],125:[2,67],126:[2,67],127:[2,67],128:[2,67],129:[2,67],130:[2,67],131:[2,67],132:[2,67],133:[2,67],134:[2,67],135:[2,67]},{8:147,9:115,10:20,11:21,12:[1,22],13:8,14:9,15:10,16:11,17:12,18:13,19:14,20:15,21:16,22:17,23:18,24:19,27:60,28:[1,71],29:49,30:[1,69],31:[1,70],32:24,33:[1,50],34:[1,51],35:[1,52],36:[1,53],37:23,42:61,43:[1,45],44:[1,46],45:[1,29],48:30,49:[1,58],50:[1,59],56:47,57:48,59:36,61:25,62:26,63:27,73:[1,68],76:[1,43],80:[1,28],85:[1,56],86:[1,57],87:[1,55],93:[1,38],97:[1,44],98:[1,54],100:39,101:[1,63],103:[1,64],104:40,105:[1,65],106:41,107:[1,66],108:67,116:[1,42],121:37,122:[1,62],124:[1,31],125:[1,32],126:[1,33],127:[1,34],128:[1,35]},{8:148,9:115,10:20,11:21,12:[1,22],13:8,14:9,15:10,16:11,17:12,18:13,19:14,20:15,21:16,22:17,23:18,24:19,27:60,28:[1,71],29:49,30:[1,69],31:[1,70],32:24,33:[1,50],34:[1,51],35:[1,52],36:[1,53],37:23,42:61,43:[1,45],44:[1,46],45:[1,29],48:30,49:[1,58],50:[1,59],56:47,57:48,59:36,61:25,62:26,63:27,73:[1,68],76:[1,43],80:[1,28],85:[1,56],86:[1,57],87:[1,55],93:[1,38],97:[1,44],98:[1,54],100:39,101:[1,63],103:[1,64],104:40,105:[1,65],106:41,107:[1,66],108:67,116:[1,42],121:37,122:[1,62],124:[1,31],125:[1,32],126:[1,33],127:[1,34],128:[1,35]},{8:149,9:115,10:20,11:21,12:[1,22],13:8,14:9,15:10,16:11,17:12,18:13,19:14,20:15,21:16,22:17,23:18,24:19,27:60,28:[1,71],29:49,30:[1,69],31:[1,70],32:24,33:[1,50],34:[1,51],35:[1,52],36:[1,53],37:23,42:61,43:[1,45],44:[1,46],45:[1,29],48:30,49:[1,58],50:[1,59],56:47,57:48,59:36,61:25,62:26,63:27,73:[1,68],76:[1,43],80:[1,28],85:[1,56],86:[1,57],87:[1,55],93:[1,38],97:[1,44],98:[1,54],100:39,101:[1,63],103:[1,64],104:40,105:[1,65],106:41,107:[1,66],108:67,116:[1,42],121:37,122:[1,62],124:[1,31],125:[1,32],126:[1,33],127:[1,34],128:[1,35]},{5:150,8:151,9:115,10:20,11:21,12:[1,22],13:8,14:9,15:10,16:11,17:12,18:13,19:14,20:15,21:16,22:17,23:18,24:19,25:[1,5],27:60,28:[1,71],29:49,30:[1,69],31:[1,70],32:24,33:[1,50],34:[1,51],35:[1,52],36:[1,53],37:23,42:61,43:[1,45],44:[1,46],45:[1,29],48:30,49:[1,58],50:[1,59],56:47,57:48,59:36,61:25,62:26,63:27,73:[1,68],76:[1,43],80:[1,28],85:[1,56],86:[1,57],87:[1,55],93:[1,38],97:[1,44],98:[1,54],100:39,101:[1,63],103:[1,64],104:40,105:[1,65],106:41,107:[1,66],108:67,116:[1,42],121:37,122:[1,62],124:[1,31],125:[1,32],126:[1,33],127:[1,34],128:[1,35]},{27:156,28:[1,71],56:157,57:158,62:152,73:[1,68],87:[1,55],110:153,111:[1,154],112:155},{109:159,113:[1,160],114:[1,161]},{6:[2,86],11:165,25:[2,86],27:166,28:[1,71],29:167,30:[1,69],31:[1,70],39:163,40:164,42:168,44:[1,46],52:[2,86],74:162,75:[2,86],86:[1,111]},{1:[2,27],6:[2,27],25:[2,27],26:[2,27],41:[2,27],47:[2,27],52:[2,27],55:[2,27],64:[2,27],65:[2,27],66:[2,27],68:[2,27],70:[2,27],71:[2,27],75:[2,27],81:[2,27],82:[2,27],83:[2,27],88:[2,27],90:[2,27],99:[2,27],101:[2,27],102:[2,27],103:[2,27],107:[2,27],115:[2,27],123:[2,27],125:[2,27],126:[2,27],129:[2,27],130:[2,27],131:[2,27],132:[2,27],133:[2,27],134:[2,27]},{1:[2,28],6:[2,28],25:[2,28],26:[2,28],41:[2,28],47:[2,28],52:[2,28],55:[2,28],64:[2,28],65:[2,28],66:[2,28],68:[2,28],70:[2,28],71:[2,28],75:[2,28],81:[2,28],82:[2,28],83:[2,28],88:[2,28],90:[2,28],99:[2,28],101:[2,28],102:[2,28],103:[2,28],107:[2,28],115:[2,28],123:[2,28],125:[2,28],126:[2,28],129:[2,28],130:[2,28],131:[2,28],132:[2,28],133:[2,28],134:[2,28]},{1:[2,26],6:[2,26],25:[2,26],26:[2,26],38:[2,26],41:[2,26],47:[2,26],52:[2,26],55:[2,26],64:[2,26],65:[2,26],66:[2,26],68:[2,26],70:[2,26],71:[2,26],75:[2,26],77:[2,26],81:[2,26],82:[2,26],83:[2,26],88:[2,26],90:[2,26],99:[2,26],101:[2,26],102:[2,26],103:[2,26],107:[2,26],113:[2,26],114:[2,26],115:[2,26],123:[2,26],125:[2,26],126:[2,26],127:[2,26],128:[2,26],129:[2,26],130:[2,26],131:[2,26],132:[2,26],133:[2,26],134:[2,26],135:[2,26]},{1:[2,6],6:[2,6],7:169,8:6,9:7,10:20,11:21,12:[1,22],13:8,14:9,15:10,16:11,17:12,18:13,19:14,20:15,21:16,22:17,23:18,24:19,26:[2,6],27:60,28:[1,71],29:49,30:[1,69],31:[1,70],32:24,33:[1,50],34:[1,51],35:[1,52],36:[1,53],37:23,42:61,43:[1,45],44:[1,46],45:[1,29],48:30,49:[1,58],50:[1,59],56:47,57:48,59:36,61:25,62:26,63:27,73:[1,68],76:[1,43],80:[1,28],85:[1,56],86:[1,57],87:[1,55],93:[1,38],97:[1,44],98:[1,54],99:[2,6],100:39,101:[1,63],103:[1,64],104:40,105:[1,65],106:41,107:[1,66],108:67,116:[1,42],121:37,122:[1,62],124:[1,31],125:[1,32],126:[1,33],127:[1,34],128:[1,35]},{1:[2,3]},{1:[2,24],6:[2,24],25:[2,24],26:[2,24],47:[2,24],52:[2,24],55:[2,24],70:[2,24],75:[2,24],83:[2,24],88:[2,24],90:[2,24],95:[2,24],96:[2,24],99:[2,24],101:[2,24],102:[2,24],103:[2,24],107:[2,24],115:[2,24],118:[2,24],120:[2,24],123:[2,24],125:[2,24],126:[2,24],129:[2,24],130:[2,24],131:[2,24],132:[2,24],133:[2,24],134:[2,24]},{6:[1,72],26:[1,170]},{1:[2,185],6:[2,185],25:[2,185],26:[2,185],47:[2,185],52:[2,185],55:[2,185],70:[2,185],75:[2,185],83:[2,185],88:[2,185],90:[2,185],99:[2,185],101:[2,185],102:[2,185],103:[2,185],107:[2,185],115:[2,185],123:[2,185],125:[2,185],126:[2,185],129:[2,185],130:[2,185],131:[2,185],132:[2,185],133:[2,185],134:[2,185]},{8:171,9:115,10:20,11:21,12:[1,22],13:8,14:9,15:10,16:11,17:12,18:13,19:14,20:15,21:16,22:17,23:18,24:19,27:60,28:[1,71],29:49,30:[1,69],31:[1,70],32:24,33:[1,50],34:[1,51],35:[1,52],36:[1,53],37:23,42:61,43:[1,45],44:[1,46],45:[1,29],48:30,49:[1,58],50:[1,59],56:47,57:48,59:36,61:25,62:26,63:27,73:[1,68],76:[1,43],80:[1,28],85:[1,56],86:[1,57],87:[1,55],93:[1,38],97:[1,44],98:[1,54],100:39,101:[1,63],103:[1,64],104:40,105:[1,65],106:41,107:[1,66],108:67,116:[1,42],121:37,122:[1,62],124:[1,31],125:[1,32],126:[1,33],127:[1,34],128:[1,35]},{8:172,9:115,10:20,11:21,12:[1,22],13:8,14:9,15:10,16:11,17:12,18:13,19:14,20:15,21:16,22:17,23:18,24:19,27:60,28:[1,71],29:49,30:[1,69],31:[1,70],32:24,33:[1,50],34:[1,51],35:[1,52],36:[1,53],37:23,42:61,43:[1,45],44:[1,46],45:[1,29],48:30,49:[1,58],50:[1,59],56:47,57:48,59:36,61:25,62:26,63:27,73:[1,68],76:[1,43],80:[1,28],85:[1,56],86:[1,57],87:[1,55],93:[1,38],97:[1,44],98:[1,54],100:39,101:[1,63],103:[1,64],104:40,105:[1,65],106:41,107:[1,66],108:67,116:[1,42],121:37,122:[1,62],124:[1,31],125:[1,32],126:[1,33],127:[1,34],128:[1,35]},{8:173,9:115,10:20,11:21,12:[1,22],13:8,14:9,15:10,16:11,17:12,18:13,19:14,20:15,21:16,22:17,23:18,24:19,27:60,28:[1,71],29:49,30:[1,69],31:[1,70],32:24,33:[1,50],34:[1,51],35:[1,52],36:[1,53],37:23,42:61,43:[1,45],44:[1,46],45:[1,29],48:30,49:[1,58],50:[1,59],56:47,57:48,59:36,61:25,62:26,63:27,73:[1,68],76:[1,43],80:[1,28],85:[1,56],86:[1,57],87:[1,55],93:[1,38],97:[1,44],98:[1,54],100:39,101:[1,63],103:[1,64],104:40,105:[1,65],106:41,107:[1,66],108:67,116:[1,42],121:37,122:[1,62],124:[1,31],125:[1,32],126:[1,33],127:[1,34],128:[1,35]},{8:174,9:115,10:20,11:21,12:[1,22],13:8,14:9,15:10,16:11,17:12,18:13,19:14,20:15,21:16,22:17,23:18,24:19,27:60,28:[1,71],29:49,30:[1,69],31:[1,70],32:24,33:[1,50],34:[1,51],35:[1,52],36:[1,53],37:23,42:61,43:[1,45],44:[1,46],45:[1,29],48:30,49:[1,58],50:[1,59],56:47,57:48,59:36,61:25,62:26,63:27,73:[1,68],76:[1,43],80:[1,28],85:[1,56],86:[1,57],87:[1,55],93:[1,38],97:[1,44],98:[1,54],100:39,101:[1,63],103:[1,64],104:40,105:[1,65],106:41,107:[1,66],108:67,116:[1,42],121:37,122:[1,62],124:[1,31],125:[1,32],126:[1,33],127:[1,34],128:[1,35]},{8:175,9:115,10:20,11:21,12:[1,22],13:8,14:9,15:10,16:11,17:12,18:13,19:14,20:15,21:16,22:17,23:18,24:19,27:60,28:[1,71],29:49,30:[1,69],31:[1,70],32:24,33:[1,50],34:[1,51],35:[1,52],36:[1,53],37:23,42:61,43:[1,45],44:[1,46],45:[1,29],48:30,49:[1,58],50:[1,59],56:47,57:48,59:36,61:25,62:26,63:27,73:[1,68],76:[1,43],80:[1,28],85:[1,56],86:[1,57],87:[1,55],93:[1,38],97:[1,44],98:[1,54],100:39,101:[1,63],103:[1,64],104:40,105:[1,65],106:41,107:[1,66],108:67,116:[1,42],121:37,122:[1,62],124:[1,31],125:[1,32],126:[1,33],127:[1,34],128:[1,35]},{8:176,9:115,10:20,11:21,12:[1,22],13:8,14:9,15:10,16:11,17:12,18:13,19:14,20:15,21:16,22:17,23:18,24:19,27:60,28:[1,71],29:49,30:[1,69],31:[1,70],32:24,33:[1,50],34:[1,51],35:[1,52],36:[1,53],37:23,42:61,43:[1,45],44:[1,46],45:[1,29],48:30,49:[1,58],50:[1,59],56:47,57:48,59:36,61:25,62:26,63:27,73:[1,68],76:[1,43],80:[1,28],85:[1,56],86:[1,57],87:[1,55],93:[1,38],97:[1,44],98:[1,54],100:39,101:[1,63],103:[1,64],104:40,105:[1,65],106:41,107:[1,66],108:67,116:[1,42],121:37,122:[1,62],124:[1,31],125:[1,32],126:[1,33],127:[1,34],128:[1,35]},{8:177,9:115,10:20,11:21,12:[1,22],13:8,14:9,15:10,16:11,17:12,18:13,19:14,20:15,21:16,22:17,23:18,24:19,27:60,28:[1,71],29:49,30:[1,69],31:[1,70],32:24,33:[1,50],34:[1,51],35:[1,52],36:[1,53],37:23,42:61,43:[1,45],44:[1,46],45:[1,29],48:30,49:[1,58],50:[1,59],56:47,57:48,59:36,61:25,62:26,63:27,73:[1,68],76:[1,43],80:[1,28],85:[1,56],86:[1,57],87:[1,55],93:[1,38],97:[1,44],98:[1,54],100:39,101:[1,63],103:[1,64],104:40,105:[1,65],106:41,107:[1,66],108:67,116:[1,42],121:37,122:[1,62],124:[1,31],125:[1,32],126:[1,33],127:[1,34],128:[1,35]},{8:178,9:115,10:20,11:21,12:[1,22],13:8,14:9,15:10,16:11,17:12,18:13,19:14,20:15,21:16,22:17,23:18,24:19,27:60,28:[1,71],29:49,30:[1,69],31:[1,70],32:24,33:[1,50],34:[1,51],35:[1,52],36:[1,53],37:23,42:61,43:[1,45],44:[1,46],45:[1,29],48:30,49:[1,58],50:[1,59],56:47,57:48,59:36,61:25,62:26,63:27,73:[1,68],76:[1,43],80:[1,28],85:[1,56],86:[1,57],87:[1,55],93:[1,38],97:[1,44],98:[1,54],100:39,101:[1,63],103:[1,64],104:40,105:[1,65],106:41,107:[1,66],108:67,116:[1,42],121:37,122:[1,62],124:[1,31],125:[1,32],126:[1,33],127:[1,34],128:[1,35]},{1:[2,141],6:[2,141],25:[2,141],26:[2,141],47:[2,141],52:[2,141],55:[2,141],70:[2,141],75:[2,141],83:[2,141],88:[2,141],90:[2,141],99:[2,141],101:[2,141],102:[2,141],103:[2,141],107:[2,141],115:[2,141],123:[2,141],125:[2,141],126:[2,141],129:[2,141],130:[2,141],131:[2,141],132:[2,141],133:[2,141],134:[2,141]},{1:[2,146],6:[2,146],25:[2,146],26:[2,146],47:[2,146],52:[2,146],55:[2,146],70:[2,146],75:[2,146],83:[2,146],88:[2,146],90:[2,146],99:[2,146],101:[2,146],102:[2,146],103:[2,146],107:[2,146],115:[2,146],123:[2,146],125:[2,146],126:[2,146],129:[2,146],130:[2,146],131:[2,146],132:[2,146],133:[2,146],134:[2,146]},{8:179,9:115,10:20,11:21,12:[1,22],13:8,14:9,15:10,16:11,17:12,18:13,19:14,20:15,21:16,22:17,23:18,24:19,27:60,28:[1,71],29:49,30:[1,69],31:[1,70],32:24,33:[1,50],34:[1,51],35:[1,52],36:[1,53],37:23,42:61,43:[1,45],44:[1,46],45:[1,29],48:30,49:[1,58],50:[1,59],56:47,57:48,59:36,61:25,62:26,63:27,73:[1,68],76:[1,43],80:[1,28],85:[1,56],86:[1,57],87:[1,55],93:[1,38],97:[1,44],98:[1,54],100:39,101:[1,63],103:[1,64],104:40,105:[1,65],106:41,107:[1,66],108:67,116:[1,42],121:37,122:[1,62],124:[1,31],125:[1,32],126:[1,33],127:[1,34],128:[1,35]},{1:[2,140],6:[2,140],25:[2,140],26:[2,140],47:[2,140],52:[2,140],55:[2,140],70:[2,140],75:[2,140],83:[2,140],88:[2,140],90:[2,140],99:[2,140],101:[2,140],102:[2,140],103:[2,140],107:[2,140],115:[2,140],123:[2,140],125:[2,140],126:[2,140],129:[2,140],130:[2,140],131:[2,140],132:[2,140],133:[2,140],134:[2,140]},{1:[2,145],6:[2,145],25:[2,145],26:[2,145],47:[2,145],52:[2,145],55:[2,145],70:[2,145],75:[2,145],83:[2,145],88:[2,145],90:[2,145],99:[2,145],101:[2,145],102:[2,145],103:[2,145],107:[2,145],115:[2,145],123:[2,145],125:[2,145],126:[2,145],129:[2,145],130:[2,145],131:[2,145],132:[2,145],133:[2,145],134:[2,145]},{79:180,82:[1,103]},{1:[2,65],6:[2,65],25:[2,65],26:[2,65],38:[2,65],47:[2,65],52:[2,65],55:[2,65],64:[2,65],65:[2,65],66:[2,65],68:[2,65],70:[2,65],71:[2,65],75:[2,65],77:[2,65],81:[2,65],82:[2,65],83:[2,65],88:[2,65],90:[2,65],99:[2,65],101:[2,65],102:[2,65],103:[2,65],107:[2,65],115:[2,65],123:[2,65],125:[2,65],126:[2,65],127:[2,65],128:[2,65],129:[2,65],130:[2,65],131:[2,65],132:[2,65],133:[2,65],134:[2,65],135:[2,65]},{82:[2,104]},{27:181,28:[1,71]},{27:182,28:[1,71]},{1:[2,79],6:[2,79],25:[2,79],26:[2,79],27:183,28:[1,71],38:[2,79],47:[2,79],52:[2,79],55:[2,79],64:[2,79],65:[2,79],66:[2,79],68:[2,79],70:[2,79],71:[2,79],75:[2,79],77:[2,79],81:[2,79],82:[2,79],83:[2,79],88:[2,79],90:[2,79],99:[2,79],101:[2,79],102:[2,79],103:[2,79],107:[2,79],115:[2,79],123:[2,79],125:[2,79],126:[2,79],127:[2,79],128:[2,79],129:[2,79],130:[2,79],131:[2,79],132:[2,79],133:[2,79],134:[2,79],135:[2,79]},{1:[2,80],6:[2,80],25:[2,80],26:[2,80],38:[2,80],47:[2,80],52:[2,80],55:[2,80],64:[2,80],65:[2,80],66:[2,80],68:[2,80],70:[2,80],71:[2,80],75:[2,80],77:[2,80],81:[2,80],82:[2,80],83:[2,80],88:[2,80],90:[2,80],99:[2,80],101:[2,80],102:[2,80],103:[2,80],107:[2,80],115:[2,80],123:[2,80],125:[2,80],126:[2,80],127:[2,80],128:[2,80],129:[2,80],130:[2,80],131:[2,80],132:[2,80],133:[2,80],134:[2,80],135:[2,80]},{8:185,9:115,10:20,11:21,12:[1,22],13:8,14:9,15:10,16:11,17:12,18:13,19:14,20:15,21:16,22:17,23:18,24:19,27:60,28:[1,71],29:49,30:[1,69],31:[1,70],32:24,33:[1,50],34:[1,51],35:[1,52],36:[1,53],37:23,42:61,43:[1,45],44:[1,46],45:[1,29],48:30,49:[1,58],50:[1,59],55:[1,189],56:47,57:48,59:36,61:25,62:26,63:27,69:184,72:186,73:[1,68],76:[1,43],80:[1,28],85:[1,56],86:[1,57],87:[1,55],89:187,90:[1,188],93:[1,38],97:[1,44],98:[1,54],100:39,101:[1,63],103:[1,64],104:40,105:[1,65],106:41,107:[1,66],108:67,116:[1,42],121:37,122:[1,62],124:[1,31],125:[1,32],126:[1,33],127:[1,34],128:[1,35]},{67:190,68:[1,97],71:[1,98]},{79:191,82:[1,103]},{1:[2,66],6:[2,66],25:[2,66],26:[2,66],38:[2,66],47:[2,66],52:[2,66],55:[2,66],64:[2,66],65:[2,66],66:[2,66],68:[2,66],70:[2,66],71:[2,66],75:[2,66],77:[2,66],81:[2,66],82:[2,66],83:[2,66],88:[2,66],90:[2,66],99:[2,66],101:[2,66],102:[2,66],103:[2,66],107:[2,66],115:[2,66],123:[2,66],125:[2,66],126:[2,66],127:[2,66],128:[2,66],129:[2,66],130:[2,66],131:[2,66],132:[2,66],133:[2,66],134:[2,66],135:[2,66]},{6:[1,193],8:192,9:115,10:20,11:21,12:[1,22],13:8,14:9,15:10,16:11,17:12,18:13,19:14,20:15,21:16,22:17,23:18,24:19,25:[1,194],27:60,28:[1,71],29:49,30:[1,69],31:[1,70],32:24,33:[1,50],34:[1,51],35:[1,52],36:[1,53],37:23,42:61,43:[1,45],44:[1,46],45:[1,29],48:30,49:[1,58],50:[1,59],56:47,57:48,59:36,61:25,62:26,63:27,73:[1,68],76:[1,43],80:[1,28],85:[1,56],86:[1,57],87:[1,55],93:[1,38],97:[1,44],98:[1,54],100:39,101:[1,63],103:[1,64],104:40,105:[1,65],106:41,107:[1,66],108:67,116:[1,42],121:37,122:[1,62],124:[1,31],125:[1,32],126:[1,33],127:[1,34],128:[1,35]},{1:[2,102],6:[2,102],25:[2,102],26:[2,102],47:[2,102],52:[2,102],55:[2,102],64:[2,102],65:[2,102],66:[2,102],68:[2,102],70:[2,102],71:[2,102],75:[2,102],81:[2,102],82:[2,102],83:[2,102],88:[2,102],90:[2,102],99:[2,102],101:[2,102],102:[2,102],103:[2,102],107:[2,102],115:[2,102],123:[2,102],125:[2,102],126:[2,102],129:[2,102],130:[2,102],131:[2,102],132:[2,102],133:[2,102],134:[2,102]},{8:197,9:115,10:20,11:21,12:[1,22],13:8,14:9,15:10,16:11,17:12,18:13,19:14,20:15,21:16,22:17,23:18,24:19,25:[1,144],27:60,28:[1,71],29:49,30:[1,69],31:[1,70],32:24,33:[1,50],34:[1,51],35:[1,52],36:[1,53],37:23,42:61,43:[1,45],44:[1,46],45:[1,29],48:30,49:[1,58],50:[1,59],56:47,57:48,58:145,59:36,61:25,62:26,63:27,73:[1,68],76:[1,43],80:[1,28],83:[1,195],84:196,85:[1,56],86:[1,57],87:[1,55],91:143,93:[1,38],97:[1,44],98:[1,54],100:39,101:[1,63],103:[1,64],104:40,105:[1,65],106:41,107:[1,66],108:67,116:[1,42],121:37,122:[1,62],124:[1,31],125:[1,32],126:[1,33],127:[1,34],128:[1,35]},{47:[1,198],52:[1,199]},{47:[2,54],52:[2,54]},{38:[1,201],47:[2,56],52:[2,56],55:[1,200]},{38:[2,59],47:[2,59],52:[2,59],55:[2,59]},{38:[2,60],47:[2,60],52:[2,60],55:[2,60]},{38:[2,61],47:[2,61],52:[2,61],55:[2,61]},{38:[2,62],47:[2,62],52:[2,62],55:[2,62]},{27:146,28:[1,71]},{8:197,9:115,10:20,11:21,12:[1,22],13:8,14:9,15:10,16:11,17:12,18:13,19:14,20:15,21:16,22:17,23:18,24:19,25:[1,144],27:60,28:[1,71],29:49,30:[1,69],31:[1,70],32:24,33:[1,50],34:[1,51],35:[1,52],36:[1,53],37:23,42:61,43:[1,45],44:[1,46],45:[1,29],48:30,49:[1,58],50:[1,59],56:47,57:48,58:145,59:36,61:25,62:26,63:27,73:[1,68],76:[1,43],80:[1,28],84:142,85:[1,56],86:[1,57],87:[1,55],88:[1,141],91:143,93:[1,38],97:[1,44],98:[1,54],100:39,101:[1,63],103:[1,64],104:40,105:[1,65],106:41,107:[1,66],108:67,116:[1,42],121:37,122:[1,62],124:[1,31],125:[1,32],126:[1,33],127:[1,34],128:[1,35]},{1:[2,48],6:[2,48],25:[2,48],26:[2,48],47:[2,48],52:[2,48],55:[2,48],70:[2,48],75:[2,48],83:[2,48],88:[2,48],90:[2,48],99:[2,48],101:[2,48],102:[2,48],103:[2,48],107:[2,48],115:[2,48],123:[2,48],125:[2,48],126:[2,48],129:[2,48],130:[2,48],131:[2,48],132:[2,48],133:[2,48],134:[2,48]},{1:[2,178],6:[2,178],25:[2,178],26:[2,178],47:[2,178],52:[2,178],55:[2,178],70:[2,178],75:[2,178],83:[2,178],88:[2,178],90:[2,178],99:[2,178],100:85,101:[2,178],102:[2,178],103:[2,178],106:86,107:[2,178],108:67,115:[2,178],123:[2,178],125:[2,178],126:[2,178],129:[1,76],130:[2,178],131:[2,178],132:[2,178],133:[2,178],134:[2,178]},{100:88,101:[1,63],103:[1,64],106:89,107:[1,66],108:67,123:[1,87]},{1:[2,179],6:[2,179],25:[2,179],26:[2,179],47:[2,179],52:[2,179],55:[2,179],70:[2,179],75:[2,179],83:[2,179],88:[2,179],90:[2,179],99:[2,179],100:85,101:[2,179],102:[2,179],103:[2,179],106:86,107:[2,179],108:67,115:[2,179],123:[2,179],125:[2,179],126:[2,179],129:[1,76],130:[2,179],131:[2,179],132:[2,179],133:[2,179],134:[2,179]},{1:[2,180],6:[2,180],25:[2,180],26:[2,180],47:[2,180],52:[2,180],55:[2,180],70:[2,180],75:[2,180],83:[2,180],88:[2,180],90:[2,180],99:[2,180],100:85,101:[2,180],102:[2,180],103:[2,180],106:86,107:[2,180],108:67,115:[2,180],123:[2,180],125:[2,180],126:[2,180],129:[1,76],130:[2,180],131:[2,180],132:[2,180],133:[2,180],134:[2,180]},{1:[2,181],6:[2,181],25:[2,181],26:[2,181],47:[2,181],52:[2,181],55:[2,181],64:[2,68],65:[2,68],66:[2,68],68:[2,68],70:[2,181],71:[2,68],75:[2,181],81:[2,68],82:[2,68],83:[2,181],88:[2,181],90:[2,181],99:[2,181],101:[2,181],102:[2,181],103:[2,181],107:[2,181],115:[2,181],123:[2,181],125:[2,181],126:[2,181],129:[2,181],130:[2,181],131:[2,181],132:[2,181],133:[2,181],134:[2,181]},{60:91,64:[1,93],65:[1,94],66:[1,95],67:96,68:[1,97],71:[1,98],78:90,81:[1,92],82:[2,103]},{60:100,64:[1,93],65:[1,94],66:[1,95],67:96,68:[1,97],71:[1,98],78:99,81:[1,92],82:[2,103]},{64:[2,71],65:[2,71],66:[2,71],68:[2,71],71:[2,71],81:[2,71],82:[2,71]},{1:[2,182],6:[2,182],25:[2,182],26:[2,182],47:[2,182],52:[2,182],55:[2,182],64:[2,68],65:[2,68],66:[2,68],68:[2,68],70:[2,182],71:[2,68],75:[2,182],81:[2,68],82:[2,68],83:[2,182],88:[2,182],90:[2,182],99:[2,182],101:[2,182],102:[2,182],103:[2,182],107:[2,182],115:[2,182],123:[2,182],125:[2,182],126:[2,182],129:[2,182],130:[2,182],131:[2,182],132:[2,182],133:[2,182],134:[2,182]},{1:[2,183],6:[2,183],25:[2,183],26:[2,183],47:[2,183],52:[2,183],55:[2,183],70:[2,183],75:[2,183],83:[2,183],88:[2,183],90:[2,183],99:[2,183],101:[2,183],102:[2,183],103:[2,183],107:[2,183],115:[2,183],123:[2,183],125:[2,183],126:[2,183],129:[2,183],130:[2,183],131:[2,183],132:[2,183],133:[2,183],134:[2,183]},{1:[2,184],6:[2,184],25:[2,184],26:[2,184],47:[2,184],52:[2,184],55:[2,184],70:[2,184],75:[2,184],83:[2,184],88:[2,184],90:[2,184],99:[2,184],101:[2,184],102:[2,184],103:[2,184],107:[2,184],115:[2,184],123:[2,184],125:[2,184],126:[2,184],129:[2,184],130:[2,184],131:[2,184],132:[2,184],133:[2,184],134:[2,184]},{8:202,9:115,10:20,11:21,12:[1,22],13:8,14:9,15:10,16:11,17:12,18:13,19:14,20:15,21:16,22:17,23:18,24:19,25:[1,203],27:60,28:[1,71],29:49,30:[1,69],31:[1,70],32:24,33:[1,50],34:[1,51],35:[1,52],36:[1,53],37:23,42:61,43:[1,45],44:[1,46],45:[1,29],48:30,49:[1,58],50:[1,59],56:47,57:48,59:36,61:25,62:26,63:27,73:[1,68],76:[1,43],80:[1,28],85:[1,56],86:[1,57],87:[1,55],93:[1,38],97:[1,44],98:[1,54],100:39,101:[1,63],103:[1,64],104:40,105:[1,65],106:41,107:[1,66],108:67,116:[1,42],121:37,122:[1,62],124:[1,31],125:[1,32],126:[1,33],127:[1,34],128:[1,35]},{8:204,9:115,10:20,11:21,12:[1,22],13:8,14:9,15:10,16:11,17:12,18:13,19:14,20:15,21:16,22:17,23:18,24:19,27:60,28:[1,71],29:49,30:[1,69],31:[1,70],32:24,33:[1,50],34:[1,51],35:[1,52],36:[1,53],37:23,42:61,43:[1,45],44:[1,46],45:[1,29],48:30,49:[1,58],50:[1,59],56:47,57:48,59:36,61:25,62:26,63:27,73:[1,68],76:[1,43],80:[1,28],85:[1,56],86:[1,57],87:[1,55],93:[1,38],97:[1,44],98:[1,54],100:39,101:[1,63],103:[1,64],104:40,105:[1,65],106:41,107:[1,66],108:67,116:[1,42],121:37,122:[1,62],124:[1,31],125:[1,32],126:[1,33],127:[1,34],128:[1,35]},{5:205,25:[1,5],122:[1,206]},{1:[2,127],6:[2,127],25:[2,127],26:[2,127],47:[2,127],52:[2,127],55:[2,127],70:[2,127],75:[2,127],83:[2,127],88:[2,127],90:[2,127],94:207,95:[1,208],96:[1,209],99:[2,127],101:[2,127],102:[2,127],103:[2,127],107:[2,127],115:[2,127],123:[2,127],125:[2,127],126:[2,127],129:[2,127],130:[2,127],131:[2,127],132:[2,127],133:[2,127],134:[2,127]},{1:[2,139],6:[2,139],25:[2,139],26:[2,139],47:[2,139],52:[2,139],55:[2,139],70:[2,139],75:[2,139],83:[2,139],88:[2,139],90:[2,139],99:[2,139],101:[2,139],102:[2,139],103:[2,139],107:[2,139],115:[2,139],123:[2,139],125:[2,139],126:[2,139],129:[2,139],130:[2,139],131:[2,139],132:[2,139],133:[2,139],134:[2,139]},{1:[2,147],6:[2,147],25:[2,147],26:[2,147],47:[2,147],52:[2,147],55:[2,147],70:[2,147],75:[2,147],83:[2,147],88:[2,147],90:[2,147],99:[2,147],101:[2,147],102:[2,147],103:[2,147],107:[2,147],115:[2,147],123:[2,147],125:[2,147],126:[2,147],129:[2,147],130:[2,147],131:[2,147],132:[2,147],133:[2,147],134:[2,147]},{25:[1,210],100:85,101:[1,63],103:[1,64],106:86,107:[1,66],108:67,123:[1,84],125:[1,78],126:[1,77],129:[1,76],130:[1,79],131:[1,80],132:[1,81],133:[1,82],134:[1,83]},{117:211,119:212,120:[1,213]},{1:[2,92],6:[2,92],25:[2,92],26:[2,92],47:[2,92],52:[2,92],55:[2,92],70:[2,92],75:[2,92],83:[2,92],88:[2,92],90:[2,92],99:[2,92],101:[2,92],102:[2,92],103:[2,92],107:[2,92],115:[2,92],123:[2,92],125:[2,92],126:[2,92],129:[2,92],130:[2,92],131:[2,92],132:[2,92],133:[2,92],134:[2,92]},{8:214,9:115,10:20,11:21,12:[1,22],13:8,14:9,15:10,16:11,17:12,18:13,19:14,20:15,21:16,22:17,23:18,24:19,27:60,28:[1,71],29:49,30:[1,69],31:[1,70],32:24,33:[1,50],34:[1,51],35:[1,52],36:[1,53],37:23,42:61,43:[1,45],44:[1,46],45:[1,29],48:30,49:[1,58],50:[1,59],56:47,57:48,59:36,61:25,62:26,63:27,73:[1,68],76:[1,43],80:[1,28],85:[1,56],86:[1,57],87:[1,55],93:[1,38],97:[1,44],98:[1,54],100:39,101:[1,63],103:[1,64],104:40,105:[1,65],106:41,107:[1,66],108:67,116:[1,42],121:37,122:[1,62],124:[1,31],125:[1,32],126:[1,33],127:[1,34],128:[1,35]},{1:[2,95],5:215,6:[2,95],25:[1,5],26:[2,95],47:[2,95],52:[2,95],55:[2,95],64:[2,68],65:[2,68],66:[2,68],68:[2,68],70:[2,95],71:[2,68],75:[2,95],77:[1,216],81:[2,68],82:[2,68],83:[2,95],88:[2,95],90:[2,95],99:[2,95],101:[2,95],102:[2,95],103:[2,95],107:[2,95],115:[2,95],123:[2,95],125:[2,95],126:[2,95],129:[2,95],130:[2,95],131:[2,95],132:[2,95],133:[2,95],134:[2,95]},{1:[2,132],6:[2,132],25:[2,132],26:[2,132],47:[2,132],52:[2,132],55:[2,132],70:[2,132],75:[2,132],83:[2,132],88:[2,132],90:[2,132],99:[2,132],100:85,101:[2,132],102:[2,132],103:[2,132],106:86,107:[2,132],108:67,115:[2,132],123:[2,132],125:[1,78],126:[1,77],129:[1,76],130:[1,79],131:[1,80],132:[1,81],133:[1,82],134:[1,83]},{1:[2,44],6:[2,44],26:[2,44],99:[2,44],100:85,101:[2,44],103:[2,44],106:86,107:[2,44],108:67,123:[2,44],125:[1,78],126:[1,77],129:[1,76],130:[1,79],131:[1,80],132:[1,81],133:[1,82],134:[1,83]},{6:[1,72],99:[1,217]},{4:218,7:4,8:6,9:7,10:20,11:21,12:[1,22],13:8,14:9,15:10,16:11,17:12,18:13,19:14,20:15,21:16,22:17,23:18,24:19,27:60,28:[1,71],29:49,30:[1,69],31:[1,70],32:24,33:[1,50],34:[1,51],35:[1,52],36:[1,53],37:23,42:61,43:[1,45],44:[1,46],45:[1,29],48:30,49:[1,58],50:[1,59],56:47,57:48,59:36,61:25,62:26,63:27,73:[1,68],76:[1,43],80:[1,28],85:[1,56],86:[1,57],87:[1,55],93:[1,38],97:[1,44],98:[1,54],100:39,101:[1,63],103:[1,64],104:40,105:[1,65],106:41,107:[1,66],108:67,116:[1,42],121:37,122:[1,62],124:[1,31],125:[1,32],126:[1,33],127:[1,34],128:[1,35]},{6:[2,123],25:[2,123],52:[2,123],55:[1,220],88:[2,123],89:219,90:[1,188],100:85,101:[1,63],103:[1,64],106:86,107:[1,66],108:67,123:[1,84],125:[1,78],126:[1,77],129:[1,76],130:[1,79],131:[1,80],132:[1,81],133:[1,82],134:[1,83]},{1:[2,110],6:[2,110],25:[2,110],26:[2,110],38:[2,110],47:[2,110],52:[2,110],55:[2,110],64:[2,110],65:[2,110],66:[2,110],68:[2,110],70:[2,110],71:[2,110],75:[2,110],81:[2,110],82:[2,110],83:[2,110],88:[2,110],90:[2,110],99:[2,110],101:[2,110],102:[2,110],103:[2,110],107:[2,110],113:[2,110],114:[2,110],115:[2,110],123:[2,110],125:[2,110],126:[2,110],129:[2,110],130:[2,110],131:[2,110],132:[2,110],133:[2,110],134:[2,110]},{6:[2,51],25:[2,51],51:221,52:[1,222],88:[2,51]},{6:[2,118],25:[2,118],26:[2,118],52:[2,118],83:[2,118],88:[2,118]},{8:197,9:115,10:20,11:21,12:[1,22],13:8,14:9,15:10,16:11,17:12,18:13,19:14,20:15,21:16,22:17,23:18,24:19,25:[1,144],27:60,28:[1,71],29:49,30:[1,69],31:[1,70],32:24,33:[1,50],34:[1,51],35:[1,52],36:[1,53],37:23,42:61,43:[1,45],44:[1,46],45:[1,29],48:30,49:[1,58],50:[1,59],56:47,57:48,58:145,59:36,61:25,62:26,63:27,73:[1,68],76:[1,43],80:[1,28],84:223,85:[1,56],86:[1,57],87:[1,55],91:143,93:[1,38],97:[1,44],98:[1,54],100:39,101:[1,63],103:[1,64],104:40,105:[1,65],106:41,107:[1,66],108:67,116:[1,42],121:37,122:[1,62],124:[1,31],125:[1,32],126:[1,33],127:[1,34],128:[1,35]},{6:[2,124],25:[2,124],26:[2,124],52:[2,124],83:[2,124],88:[2,124]},{1:[2,109],6:[2,109],25:[2,109],26:[2,109],38:[2,109],41:[2,109],47:[2,109],52:[2,109],55:[2,109],64:[2,109],65:[2,109],66:[2,109],68:[2,109],70:[2,109],71:[2,109],75:[2,109],77:[2,109],81:[2,109],82:[2,109],83:[2,109],88:[2,109],90:[2,109],99:[2,109],101:[2,109],102:[2,109],103:[2,109],107:[2,109],115:[2,109],123:[2,109],125:[2,109],126:[2,109],127:[2,109],128:[2,109],129:[2,109],130:[2,109],131:[2,109],132:[2,109],133:[2,109],134:[2,109],135:[2,109]},{5:224,25:[1,5],100:85,101:[1,63],103:[1,64],106:86,107:[1,66],108:67,123:[1,84],125:[1,78],126:[1,77],129:[1,76],130:[1,79],131:[1,80],132:[1,81],133:[1,82],134:[1,83]},{1:[2,135],6:[2,135],25:[2,135],26:[2,135],47:[2,135],52:[2,135],55:[2,135],70:[2,135],75:[2,135],83:[2,135],88:[2,135],90:[2,135],99:[2,135],100:85,101:[1,63],102:[1,225],103:[1,64],106:86,107:[1,66],108:67,115:[2,135],123:[2,135],125:[1,78],126:[1,77],129:[1,76],130:[1,79],131:[1,80],132:[1,81],133:[1,82],134:[1,83]},{1:[2,137],6:[2,137],25:[2,137],26:[2,137],47:[2,137],52:[2,137],55:[2,137],70:[2,137],75:[2,137],83:[2,137],88:[2,137],90:[2,137],99:[2,137],100:85,101:[1,63],102:[1,226],103:[1,64],106:86,107:[1,66],108:67,115:[2,137],123:[2,137],125:[1,78],126:[1,77],129:[1,76],130:[1,79],131:[1,80],132:[1,81],133:[1,82],134:[1,83]},{1:[2,143],6:[2,143],25:[2,143],26:[2,143],47:[2,143],52:[2,143],55:[2,143],70:[2,143],75:[2,143],83:[2,143],88:[2,143],90:[2,143],99:[2,143],101:[2,143],102:[2,143],103:[2,143],107:[2,143],115:[2,143],123:[2,143],125:[2,143],126:[2,143],129:[2,143],130:[2,143],131:[2,143],132:[2,143],133:[2,143],134:[2,143]},{1:[2,144],6:[2,144],25:[2,144],26:[2,144],47:[2,144],52:[2,144],55:[2,144],70:[2,144],75:[2,144],83:[2,144],88:[2,144],90:[2,144],99:[2,144],100:85,101:[1,63],102:[2,144],103:[1,64],106:86,107:[1,66],108:67,115:[2,144],123:[2,144],125:[1,78],126:[1,77],129:[1,76],130:[1,79],131:[1,80],132:[1,81],133:[1,82],134:[1,83]},{1:[2,148],6:[2,148],25:[2,148],26:[2,148],47:[2,148],52:[2,148],55:[2,148],70:[2,148],75:[2,148],83:[2,148],88:[2,148],90:[2,148],99:[2,148],101:[2,148],102:[2,148],103:[2,148],107:[2,148],115:[2,148],123:[2,148],125:[2,148],126:[2,148],129:[2,148],130:[2,148],131:[2,148],132:[2,148],133:[2,148],134:[2,148]},{113:[2,150],114:[2,150]},{27:156,28:[1,71],56:157,57:158,73:[1,68],87:[1,112],110:227,112:155},{52:[1,228],113:[2,155],114:[2,155]},{52:[2,152],113:[2,152],114:[2,152]},{52:[2,153],113:[2,153],114:[2,153]},{52:[2,154],113:[2,154],114:[2,154]},{1:[2,149],6:[2,149],25:[2,149],26:[2,149],47:[2,149],52:[2,149],55:[2,149],70:[2,149],75:[2,149],83:[2,149],88:[2,149],90:[2,149],99:[2,149],101:[2,149],102:[2,149],103:[2,149],107:[2,149],115:[2,149],123:[2,149],125:[2,149],126:[2,149],129:[2,149],130:[2,149],131:[2,149],132:[2,149],133:[2,149],134:[2,149]},{8:229,9:115,10:20,11:21,12:[1,22],13:8,14:9,15:10,16:11,17:12,18:13,19:14,20:15,21:16,22:17,23:18,24:19,27:60,28:[1,71],29:49,30:[1,69],31:[1,70],32:24,33:[1,50],34:[1,51],35:[1,52],36:[1,53],37:23,42:61,43:[1,45],44:[1,46],45:[1,29],48:30,49:[1,58],50:[1,59],56:47,57:48,59:36,61:25,62:26,63:27,73:[1,68],76:[1,43],80:[1,28],85:[1,56],86:[1,57],87:[1,55],93:[1,38],97:[1,44],98:[1,54],100:39,101:[1,63],103:[1,64],104:40,105:[1,65],106:41,107:[1,66],108:67,116:[1,42],121:37,122:[1,62],124:[1,31],125:[1,32],126:[1,33],127:[1,34],128:[1,35]},{8:230,9:115,10:20,11:21,12:[1,22],13:8,14:9,15:10,16:11,17:12,18:13,19:14,20:15,21:16,22:17,23:18,24:19,27:60,28:[1,71],29:49,30:[1,69],31:[1,70],32:24,33:[1,50],34:[1,51],35:[1,52],36:[1,53],37:23,42:61,43:[1,45],44:[1,46],45:[1,29],48:30,49:[1,58],50:[1,59],56:47,57:48,59:36,61:25,62:26,63:27,73:[1,68],76:[1,43],80:[1,28],85:[1,56],86:[1,57],87:[1,55],93:[1,38],97:[1,44],98:[1,54],100:39,101:[1,63],103:[1,64],104:40,105:[1,65],106:41,107:[1,66],108:67,116:[1,42],121:37,122:[1,62],124:[1,31],125:[1,32],126:[1,33],127:[1,34],128:[1,35]},{6:[2,51],25:[2,51],51:231,52:[1,232],75:[2,51]},{6:[2,87],25:[2,87],26:[2,87],52:[2,87],75:[2,87]},{6:[2,37],25:[2,37],26:[2,37],41:[1,233],52:[2,37],75:[2,37]},{6:[2,40],25:[2,40],26:[2,40],52:[2,40],75:[2,40]},{6:[2,41],25:[2,41],26:[2,41],41:[2,41],52:[2,41],75:[2,41]},{6:[2,42],25:[2,42],26:[2,42],41:[2,42],52:[2,42],75:[2,42]},{6:[2,43],25:[2,43],26:[2,43],41:[2,43],52:[2,43],75:[2,43]},{1:[2,5],6:[2,5],26:[2,5],99:[2,5]},{1:[2,25],6:[2,25],25:[2,25],26:[2,25],47:[2,25],52:[2,25],55:[2,25],70:[2,25],75:[2,25],83:[2,25],88:[2,25],90:[2,25],95:[2,25],96:[2,25],99:[2,25],101:[2,25],102:[2,25],103:[2,25],107:[2,25],115:[2,25],118:[2,25],120:[2,25],123:[2,25],125:[2,25],126:[2,25],129:[2,25],130:[2,25],131:[2,25],132:[2,25],133:[2,25],134:[2,25]},{1:[2,186],6:[2,186],25:[2,186],26:[2,186],47:[2,186],52:[2,186],55:[2,186],70:[2,186],75:[2,186],83:[2,186],88:[2,186],90:[2,186],99:[2,186],100:85,101:[2,186],102:[2,186],103:[2,186],106:86,107:[2,186],108:67,115:[2,186],123:[2,186],125:[2,186],126:[2,186],129:[1,76],130:[1,79],131:[2,186],132:[2,186],133:[2,186],134:[2,186]},{1:[2,187],6:[2,187],25:[2,187],26:[2,187],47:[2,187],52:[2,187],55:[2,187],70:[2,187],75:[2,187],83:[2,187],88:[2,187],90:[2,187],99:[2,187],100:85,101:[2,187],102:[2,187],103:[2,187],106:86,107:[2,187],108:67,115:[2,187],123:[2,187],125:[2,187],126:[2,187],129:[1,76],130:[1,79],131:[2,187],132:[2,187],133:[2,187],134:[2,187]},{1:[2,188],6:[2,188],25:[2,188],26:[2,188],47:[2,188],52:[2,188],55:[2,188],70:[2,188],75:[2,188],83:[2,188],88:[2,188],90:[2,188],99:[2,188],100:85,101:[2,188],102:[2,188],103:[2,188],106:86,107:[2,188],108:67,115:[2,188],123:[2,188],125:[2,188],126:[2,188],129:[1,76],130:[2,188],131:[2,188],132:[2,188],133:[2,188],134:[2,188]},{1:[2,189],6:[2,189],25:[2,189],26:[2,189],47:[2,189],52:[2,189],55:[2,189],70:[2,189],75:[2,189],83:[2,189],88:[2,189],90:[2,189],99:[2,189],100:85,101:[2,189],102:[2,189],103:[2,189],106:86,107:[2,189],108:67,115:[2,189],123:[2,189],125:[1,78],126:[1,77],129:[1,76],130:[1,79],131:[2,189],132:[2,189],133:[2,189],134:[2,189]},{1:[2,190],6:[2,190],25:[2,190],26:[2,190],47:[2,190],52:[2,190],55:[2,190],70:[2,190],75:[2,190],83:[2,190],88:[2,190],90:[2,190],99:[2,190],100:85,101:[2,190],102:[2,190],103:[2,190],106:86,107:[2,190],108:67,115:[2,190],123:[2,190],125:[1,78],126:[1,77],129:[1,76],130:[1,79],131:[1,80],132:[2,190],133:[2,190],134:[1,83]},{1:[2,191],6:[2,191],25:[2,191],26:[2,191],47:[2,191],52:[2,191],55:[2,191],70:[2,191],75:[2,191],83:[2,191],88:[2,191],90:[2,191],99:[2,191],100:85,101:[2,191],102:[2,191],103:[2,191],106:86,107:[2,191],108:67,115:[2,191],123:[2,191],125:[1,78],126:[1,77],129:[1,76],130:[1,79],131:[1,80],132:[1,81],133:[2,191],134:[1,83]},{1:[2,192],6:[2,192],25:[2,192],26:[2,192],47:[2,192],52:[2,192],55:[2,192],70:[2,192],75:[2,192],83:[2,192],88:[2,192],90:[2,192],99:[2,192],100:85,101:[2,192],102:[2,192],103:[2,192],106:86,107:[2,192],108:67,115:[2,192],123:[2,192],125:[1,78],126:[1,77],129:[1,76],130:[1,79],131:[1,80],132:[2,192],133:[2,192],134:[2,192]},{1:[2,177],6:[2,177],25:[2,177],26:[2,177],47:[2,177],52:[2,177],55:[2,177],70:[2,177],75:[2,177],83:[2,177],88:[2,177],90:[2,177],99:[2,177],100:85,101:[1,63],102:[2,177],103:[1,64],106:86,107:[1,66],108:67,115:[2,177],123:[1,84],125:[1,78],126:[1,77],129:[1,76],130:[1,79],131:[1,80],132:[1,81],133:[1,82],134:[1,83]},{1:[2,176],6:[2,176],25:[2,176],26:[2,176],47:[2,176],52:[2,176],55:[2,176],70:[2,176],75:[2,176],83:[2,176],88:[2,176],90:[2,176],99:[2,176],100:85,101:[1,63],102:[2,176],103:[1,64],106:86,107:[1,66],108:67,115:[2,176],123:[1,84],125:[1,78],126:[1,77],129:[1,76],130:[1,79],131:[1,80],132:[1,81],133:[1,82],134:[1,83]},{1:[2,99],6:[2,99],25:[2,99],26:[2,99],47:[2,99],52:[2,99],55:[2,99],64:[2,99],65:[2,99],66:[2,99],68:[2,99],70:[2,99],71:[2,99],75:[2,99],81:[2,99],82:[2,99],83:[2,99],88:[2,99],90:[2,99],99:[2,99],101:[2,99],102:[2,99],103:[2,99],107:[2,99],115:[2,99],123:[2,99],125:[2,99],126:[2,99],129:[2,99],130:[2,99],131:[2,99],132:[2,99],133:[2,99],134:[2,99]},{1:[2,76],6:[2,76],25:[2,76],26:[2,76],38:[2,76],47:[2,76],52:[2,76],55:[2,76],64:[2,76],65:[2,76],66:[2,76],68:[2,76],70:[2,76],71:[2,76],75:[2,76],77:[2,76],81:[2,76],82:[2,76],83:[2,76],88:[2,76],90:[2,76],99:[2,76],101:[2,76],102:[2,76],103:[2,76],107:[2,76],115:[2,76],123:[2,76],125:[2,76],126:[2,76],127:[2,76],128:[2,76],129:[2,76],130:[2,76],131:[2,76],132:[2,76],133:[2,76],134:[2,76],135:[2,76]},{1:[2,77],6:[2,77],25:[2,77],26:[2,77],38:[2,77],47:[2,77],52:[2,77],55:[2,77],64:[2,77],65:[2,77],66:[2,77],68:[2,77],70:[2,77],71:[2,77],75:[2,77],77:[2,77],81:[2,77],82:[2,77],83:[2,77],88:[2,77],90:[2,77],99:[2,77],101:[2,77],102:[2,77],103:[2,77],107:[2,77],115:[2,77],123:[2,77],125:[2,77],126:[2,77],127:[2,77],128:[2,77],129:[2,77],130:[2,77],131:[2,77],132:[2,77],133:[2,77],134:[2,77],135:[2,77]},{1:[2,78],6:[2,78],25:[2,78],26:[2,78],38:[2,78],47:[2,78],52:[2,78],55:[2,78],64:[2,78],65:[2,78],66:[2,78],68:[2,78],70:[2,78],71:[2,78],75:[2,78],77:[2,78],81:[2,78],82:[2,78],83:[2,78],88:[2,78],90:[2,78],99:[2,78],101:[2,78],102:[2,78],103:[2,78],107:[2,78],115:[2,78],123:[2,78],125:[2,78],126:[2,78],127:[2,78],128:[2,78],129:[2,78],130:[2,78],131:[2,78],132:[2,78],133:[2,78],134:[2,78],135:[2,78]},{70:[1,234]},{55:[1,189],70:[2,83],89:235,90:[1,188],100:85,101:[1,63],103:[1,64],106:86,107:[1,66],108:67,123:[1,84],125:[1,78],126:[1,77],129:[1,76],130:[1,79],131:[1,80],132:[1,81],133:[1,82],134:[1,83]},{70:[2,84]},{8:236,9:115,10:20,11:21,12:[1,22],13:8,14:9,15:10,16:11,17:12,18:13,19:14,20:15,21:16,22:17,23:18,24:19,27:60,28:[1,71],29:49,30:[1,69],31:[1,70],32:24,33:[1,50],34:[1,51],35:[1,52],36:[1,53],37:23,42:61,43:[1,45],44:[1,46],45:[1,29],48:30,49:[1,58],50:[1,59],56:47,57:48,59:36,61:25,62:26,63:27,73:[1,68],76:[1,43],80:[1,28],85:[1,56],86:[1,57],87:[1,55],93:[1,38],97:[1,44],98:[1,54],100:39,101:[1,63],103:[1,64],104:40,105:[1,65],106:41,107:[1,66],108:67,116:[1,42],121:37,122:[1,62],124:[1,31],125:[1,32],126:[1,33],127:[1,34],128:[1,35]},{12:[2,112],28:[2,112],30:[2,112],31:[2,112],33:[2,112],34:[2,112],35:[2,112],36:[2,112],43:[2,112],44:[2,112],45:[2,112],49:[2,112],50:[2,112],70:[2,112],73:[2,112],76:[2,112],80:[2,112],85:[2,112],86:[2,112],87:[2,112],93:[2,112],97:[2,112],98:[2,112],101:[2,112],103:[2,112],105:[2,112],107:[2,112],116:[2,112],122:[2,112],124:[2,112],125:[2,112],126:[2,112],127:[2,112],128:[2,112]},{12:[2,113],28:[2,113],30:[2,113],31:[2,113],33:[2,113],34:[2,113],35:[2,113],36:[2,113],43:[2,113],44:[2,113],45:[2,113],49:[2,113],50:[2,113],70:[2,113],73:[2,113],76:[2,113],80:[2,113],85:[2,113],86:[2,113],87:[2,113],93:[2,113],97:[2,113],98:[2,113],101:[2,113],103:[2,113],105:[2,113],107:[2,113],116:[2,113],122:[2,113],124:[2,113],125:[2,113],126:[2,113],127:[2,113],128:[2,113]},{1:[2,82],6:[2,82],25:[2,82],26:[2,82],38:[2,82],47:[2,82],52:[2,82],55:[2,82],64:[2,82],65:[2,82],66:[2,82],68:[2,82],70:[2,82],71:[2,82],75:[2,82],77:[2,82],81:[2,82],82:[2,82],83:[2,82],88:[2,82],90:[2,82],99:[2,82],101:[2,82],102:[2,82],103:[2,82],107:[2,82],115:[2,82],123:[2,82],125:[2,82],126:[2,82],127:[2,82],128:[2,82],129:[2,82],130:[2,82],131:[2,82],132:[2,82],133:[2,82],134:[2,82],135:[2,82]},{1:[2,100],6:[2,100],25:[2,100],26:[2,100],47:[2,100],52:[2,100],55:[2,100],64:[2,100],65:[2,100],66:[2,100],68:[2,100],70:[2,100],71:[2,100],75:[2,100],81:[2,100],82:[2,100],83:[2,100],88:[2,100],90:[2,100],99:[2,100],101:[2,100],102:[2,100],103:[2,100],107:[2,100],115:[2,100],123:[2,100],125:[2,100],126:[2,100],129:[2,100],130:[2,100],131:[2,100],132:[2,100],133:[2,100],134:[2,100]},{1:[2,34],6:[2,34],25:[2,34],26:[2,34],47:[2,34],52:[2,34],55:[2,34],70:[2,34],75:[2,34],83:[2,34],88:[2,34],90:[2,34],99:[2,34],100:85,101:[2,34],102:[2,34],103:[2,34],106:86,107:[2,34],108:67,115:[2,34],123:[2,34],125:[1,78],126:[1,77],129:[1,76],130:[1,79],131:[1,80],132:[1,81],133:[1,82],134:[1,83]},{8:237,9:115,10:20,11:21,12:[1,22],13:8,14:9,15:10,16:11,17:12,18:13,19:14,20:15,21:16,22:17,23:18,24:19,27:60,28:[1,71],29:49,30:[1,69],31:[1,70],32:24,33:[1,50],34:[1,51],35:[1,52],36:[1,53],37:23,42:61,43:[1,45],44:[1,46],45:[1,29],48:30,49:[1,58],50:[1,59],56:47,57:48,59:36,61:25,62:26,63:27,73:[1,68],76:[1,43],80:[1,28],85:[1,56],86:[1,57],87:[1,55],93:[1,38],97:[1,44],98:[1,54],100:39,101:[1,63],103:[1,64],104:40,105:[1,65],106:41,107:[1,66],108:67,116:[1,42],121:37,122:[1,62],124:[1,31],125:[1,32],126:[1,33],127:[1,34],128:[1,35]},{8:238,9:115,10:20,11:21,12:[1,22],13:8,14:9,15:10,16:11,17:12,18:13,19:14,20:15,21:16,22:17,23:18,24:19,27:60,28:[1,71],29:49,30:[1,69],31:[1,70],32:24,33:[1,50],34:[1,51],35:[1,52],36:[1,53],37:23,42:61,43:[1,45],44:[1,46],45:[1,29],48:30,49:[1,58],50:[1,59],56:47,57:48,59:36,61:25,62:26,63:27,73:[1,68],76:[1,43],80:[1,28],85:[1,56],86:[1,57],87:[1,55],93:[1,38],97:[1,44],98:[1,54],100:39,101:[1,63],103:[1,64],104:40,105:[1,65],106:41,107:[1,66],108:67,116:[1,42],121:37,122:[1,62],124:[1,31],125:[1,32],126:[1,33],127:[1,34],128:[1,35]},{1:[2,105],6:[2,105],25:[2,105],26:[2,105],47:[2,105],52:[2,105],55:[2,105],64:[2,105],65:[2,105],66:[2,105],68:[2,105],70:[2,105],71:[2,105],75:[2,105],81:[2,105],82:[2,105],83:[2,105],88:[2,105],90:[2,105],99:[2,105],101:[2,105],102:[2,105],103:[2,105],107:[2,105],115:[2,105],123:[2,105],125:[2,105],126:[2,105],129:[2,105],130:[2,105],131:[2,105],132:[2,105],133:[2,105],134:[2,105]},{6:[2,51],25:[2,51],51:239,52:[1,222],83:[2,51]},{6:[2,123],25:[2,123],26:[2,123],52:[2,123],55:[1,240],83:[2,123],88:[2,123],100:85,101:[1,63],103:[1,64],106:86,107:[1,66],108:67,123:[1,84],125:[1,78],126:[1,77],129:[1,76],130:[1,79],131:[1,80],132:[1,81],133:[1,82],134:[1,83]},{48:241,49:[1,58],50:[1,59]},{27:107,28:[1,71],42:108,53:242,54:106,56:109,57:110,73:[1,68],86:[1,111],87:[1,112]},{47:[2,57],52:[2,57]},{8:243,9:115,10:20,11:21,12:[1,22],13:8,14:9,15:10,16:11,17:12,18:13,19:14,20:15,21:16,22:17,23:18,24:19,27:60,28:[1,71],29:49,30:[1,69],31:[1,70],32:24,33:[1,50],34:[1,51],35:[1,52],36:[1,53],37:23,42:61,43:[1,45],44:[1,46],45:[1,29],48:30,49:[1,58],50:[1,59],56:47,57:48,59:36,61:25,62:26,63:27,73:[1,68],76:[1,43],80:[1,28],85:[1,56],86:[1,57],87:[1,55],93:[1,38],97:[1,44],98:[1,54],100:39,101:[1,63],103:[1,64],104:40,105:[1,65],106:41,107:[1,66],108:67,116:[1,42],121:37,122:[1,62],124:[1,31],125:[1,32],126:[1,33],127:[1,34],128:[1,35]},{1:[2,193],6:[2,193],25:[2,193],26:[2,193],47:[2,193],52:[2,193],55:[2,193],70:[2,193],75:[2,193],83:[2,193],88:[2,193],90:[2,193],99:[2,193],100:85,101:[2,193],102:[2,193],103:[2,193],106:86,107:[2,193],108:67,115:[2,193],123:[2,193],125:[1,78],126:[1,77],129:[1,76],130:[1,79],131:[1,80],132:[1,81],133:[1,82],134:[1,83]},{8:244,9:115,10:20,11:21,12:[1,22],13:8,14:9,15:10,16:11,17:12,18:13,19:14,20:15,21:16,22:17,23:18,24:19,27:60,28:[1,71],29:49,30:[1,69],31:[1,70],32:24,33:[1,50],34:[1,51],35:[1,52],36:[1,53],37:23,42:61,43:[1,45],44:[1,46],45:[1,29],48:30,49:[1,58],50:[1,59],56:47,57:48,59:36,61:25,62:26,63:27,73:[1,68],76:[1,43],80:[1,28],85:[1,56],86:[1,57],87:[1,55],93:[1,38],97:[1,44],98:[1,54],100:39,101:[1,63],103:[1,64],104:40,105:[1,65],106:41,107:[1,66],108:67,116:[1,42],121:37,122:[1,62],124:[1,31],125:[1,32],126:[1,33],127:[1,34],128:[1,35]},{1:[2,195],6:[2,195],25:[2,195],26:[2,195],47:[2,195],52:[2,195],55:[2,195],70:[2,195],75:[2,195],83:[2,195],88:[2,195],90:[2,195],99:[2,195],100:85,101:[2,195],102:[2,195],103:[2,195],106:86,107:[2,195],108:67,115:[2,195],123:[2,195],125:[1,78],126:[1,77],129:[1,76],130:[1,79],131:[1,80],132:[1,81],133:[1,82],134:[1,83]},{1:[2,175],6:[2,175],25:[2,175],26:[2,175],47:[2,175],52:[2,175],55:[2,175],70:[2,175],75:[2,175],83:[2,175],88:[2,175],90:[2,175],99:[2,175],101:[2,175],102:[2,175],103:[2,175],107:[2,175],115:[2,175],123:[2,175],125:[2,175],126:[2,175],129:[2,175],130:[2,175],131:[2,175],132:[2,175],133:[2,175],134:[2,175]},{8:245,9:115,10:20,11:21,12:[1,22],13:8,14:9,15:10,16:11,17:12,18:13,19:14,20:15,21:16,22:17,23:18,24:19,27:60,28:[1,71],29:49,30:[1,69],31:[1,70],32:24,33:[1,50],34:[1,51],35:[1,52],36:[1,53],37:23,42:61,43:[1,45],44:[1,46],45:[1,29],48:30,49:[1,58],50:[1,59],56:47,57:48,59:36,61:25,62:26,63:27,73:[1,68],76:[1,43],80:[1,28],85:[1,56],86:[1,57],87:[1,55],93:[1,38],97:[1,44],98:[1,54],100:39,101:[1,63],103:[1,64],104:40,105:[1,65],106:41,107:[1,66],108:67,116:[1,42],121:37,122:[1,62],124:[1,31],125:[1,32],126:[1,33],127:[1,34],128:[1,35]},{1:[2,128],6:[2,128],25:[2,128],26:[2,128],47:[2,128],52:[2,128],55:[2,128],70:[2,128],75:[2,128],83:[2,128],88:[2,128],90:[2,128],95:[1,246],99:[2,128],101:[2,128],102:[2,128],103:[2,128],107:[2,128],115:[2,128],123:[2,128],125:[2,128],126:[2,128],129:[2,128],130:[2,128],131:[2,128],132:[2,128],133:[2,128],134:[2,128]},{5:247,25:[1,5]},{27:248,28:[1,71]},{117:249,119:212,120:[1,213]},{26:[1,250],118:[1,251],119:252,120:[1,213]},{26:[2,168],118:[2,168],120:[2,168]},{8:254,9:115,10:20,11:21,12:[1,22],13:8,14:9,15:10,16:11,17:12,18:13,19:14,20:15,21:16,22:17,23:18,24:19,27:60,28:[1,71],29:49,30:[1,69],31:[1,70],32:24,33:[1,50],34:[1,51],35:[1,52],36:[1,53],37:23,42:61,43:[1,45],44:[1,46],45:[1,29],48:30,49:[1,58],50:[1,59],56:47,57:48,59:36,61:25,62:26,63:27,73:[1,68],76:[1,43],80:[1,28],85:[1,56],86:[1,57],87:[1,55],92:253,93:[1,38],97:[1,44],98:[1,54],100:39,101:[1,63],103:[1,64],104:40,105:[1,65],106:41,107:[1,66],108:67,116:[1,42],121:37,122:[1,62],124:[1,31],125:[1,32],126:[1,33],127:[1,34],128:[1,35]},{1:[2,93],5:255,6:[2,93],25:[1,5],26:[2,93],47:[2,93],52:[2,93],55:[2,93],70:[2,93],75:[2,93],83:[2,93],88:[2,93],90:[2,93],99:[2,93],100:85,101:[1,63],102:[2,93],103:[1,64],106:86,107:[1,66],108:67,115:[2,93],123:[2,93],125:[1,78],126:[1,77],129:[1,76],130:[1,79],131:[1,80],132:[1,81],133:[1,82],134:[1,83]},{1:[2,96],6:[2,96],25:[2,96],26:[2,96],47:[2,96],52:[2,96],55:[2,96],70:[2,96],75:[2,96],83:[2,96],88:[2,96],90:[2,96],99:[2,96],101:[2,96],102:[2,96],103:[2,96],107:[2,96],115:[2,96],123:[2,96],125:[2,96],126:[2,96],129:[2,96],130:[2,96],131:[2,96],132:[2,96],133:[2,96],134:[2,96]},{8:256,9:115,10:20,11:21,12:[1,22],13:8,14:9,15:10,16:11,17:12,18:13,19:14,20:15,21:16,22:17,23:18,24:19,27:60,28:[1,71],29:49,30:[1,69],31:[1,70],32:24,33:[1,50],34:[1,51],35:[1,52],36:[1,53],37:23,42:61,43:[1,45],44:[1,46],45:[1,29],48:30,49:[1,58],50:[1,59],56:47,57:48,59:36,61:25,62:26,63:27,73:[1,68],76:[1,43],80:[1,28],85:[1,56],86:[1,57],87:[1,55],93:[1,38],97:[1,44],98:[1,54],100:39,101:[1,63],103:[1,64],104:40,105:[1,65],106:41,107:[1,66],108:67,116:[1,42],121:37,122:[1,62],124:[1,31],125:[1,32],126:[1,33],127:[1,34],128:[1,35]},{1:[2,133],6:[2,133],25:[2,133],26:[2,133],47:[2,133],52:[2,133],55:[2,133],64:[2,133],65:[2,133],66:[2,133],68:[2,133],70:[2,133],71:[2,133],75:[2,133],81:[2,133],82:[2,133],83:[2,133],88:[2,133],90:[2,133],99:[2,133],101:[2,133],102:[2,133],103:[2,133],107:[2,133],115:[2,133],123:[2,133],125:[2,133],126:[2,133],129:[2,133],130:[2,133],131:[2,133],132:[2,133],133:[2,133],134:[2,133]},{6:[1,72],26:[1,257]},{8:258,9:115,10:20,11:21,12:[1,22],13:8,14:9,15:10,16:11,17:12,18:13,19:14,20:15,21:16,22:17,23:18,24:19,27:60,28:[1,71],29:49,30:[1,69],31:[1,70],32:24,33:[1,50],34:[1,51],35:[1,52],36:[1,53],37:23,42:61,43:[1,45],44:[1,46],45:[1,29],48:30,49:[1,58],50:[1,59],56:47,57:48,59:36,61:25,62:26,63:27,73:[1,68],76:[1,43],80:[1,28],85:[1,56],86:[1,57],87:[1,55],93:[1,38],97:[1,44],98:[1,54],100:39,101:[1,63],103:[1,64],104:40,105:[1,65],106:41,107:[1,66],108:67,116:[1,42],121:37,122:[1,62],124:[1,31],125:[1,32],126:[1,33],127:[1,34],128:[1,35]},{6:[2,63],12:[2,113],25:[2,63],28:[2,113],30:[2,113],31:[2,113],33:[2,113],34:[2,113],35:[2,113],36:[2,113],43:[2,113],44:[2,113],45:[2,113],49:[2,113],50:[2,113],52:[2,63],73:[2,113],76:[2,113],80:[2,113],85:[2,113],86:[2,113],87:[2,113],88:[2,63],93:[2,113],97:[2,113],98:[2,113],101:[2,113],103:[2,113],105:[2,113],107:[2,113],116:[2,113],122:[2,113],124:[2,113],125:[2,113],126:[2,113],127:[2,113],128:[2,113]},{6:[1,260],25:[1,261],88:[1,259]},{6:[2,52],8:197,9:115,10:20,11:21,12:[1,22],13:8,14:9,15:10,16:11,17:12,18:13,19:14,20:15,21:16,22:17,23:18,24:19,25:[2,52],26:[2,52],27:60,28:[1,71],29:49,30:[1,69],31:[1,70],32:24,33:[1,50],34:[1,51],35:[1,52],36:[1,53],37:23,42:61,43:[1,45],44:[1,46],45:[1,29],48:30,49:[1,58],50:[1,59],56:47,57:48,58:145,59:36,61:25,62:26,63:27,73:[1,68],76:[1,43],80:[1,28],83:[2,52],85:[1,56],86:[1,57],87:[1,55],88:[2,52],91:262,93:[1,38],97:[1,44],98:[1,54],100:39,101:[1,63],103:[1,64],104:40,105:[1,65],106:41,107:[1,66],108:67,116:[1,42],121:37,122:[1,62],124:[1,31],125:[1,32],126:[1,33],127:[1,34],128:[1,35]},{6:[2,51],25:[2,51],26:[2,51],51:263,52:[1,222]},{1:[2,172],6:[2,172],25:[2,172],26:[2,172],47:[2,172],52:[2,172],55:[2,172],70:[2,172],75:[2,172],83:[2,172],88:[2,172],90:[2,172],99:[2,172],101:[2,172],102:[2,172],103:[2,172],107:[2,172],115:[2,172],118:[2,172],123:[2,172],125:[2,172],126:[2,172],129:[2,172],130:[2,172],131:[2,172],132:[2,172],133:[2,172],134:[2,172]},{8:264,9:115,10:20,11:21,12:[1,22],13:8,14:9,15:10,16:11,17:12,18:13,19:14,20:15,21:16,22:17,23:18,24:19,27:60,28:[1,71],29:49,30:[1,69],31:[1,70],32:24,33:[1,50],34:[1,51],35:[1,52],36:[1,53],37:23,42:61,43:[1,45],44:[1,46],45:[1,29],48:30,49:[1,58],50:[1,59],56:47,57:48,59:36,61:25,62:26,63:27,73:[1,68],76:[1,43],80:[1,28],85:[1,56],86:[1,57],87:[1,55],93:[1,38],97:[1,44],98:[1,54],100:39,101:[1,63],103:[1,64],104:40,105:[1,65],106:41,107:[1,66],108:67,116:[1,42],121:37,122:[1,62],124:[1,31],125:[1,32],126:[1,33],127:[1,34],128:[1,35]},{8:265,9:115,10:20,11:21,12:[1,22],13:8,14:9,15:10,16:11,17:12,18:13,19:14,20:15,21:16,22:17,23:18,24:19,27:60,28:[1,71],29:49,30:[1,69],31:[1,70],32:24,33:[1,50],34:[1,51],35:[1,52],36:[1,53],37:23,42:61,43:[1,45],44:[1,46],45:[1,29],48:30,49:[1,58],50:[1,59],56:47,57:48,59:36,61:25,62:26,63:27,73:[1,68],76:[1,43],80:[1,28],85:[1,56],86:[1,57],87:[1,55],93:[1,38],97:[1,44],98:[1,54],100:39,101:[1,63],103:[1,64],104:40,105:[1,65],106:41,107:[1,66],108:67,116:[1,42],121:37,122:[1,62],124:[1,31],125:[1,32],126:[1,33],127:[1,34],128:[1,35]},{113:[2,151],114:[2,151]},{27:156,28:[1,71],56:157,57:158,73:[1,68],87:[1,112],112:266},{1:[2,157],6:[2,157],25:[2,157],26:[2,157],47:[2,157],52:[2,157],55:[2,157],70:[2,157],75:[2,157],83:[2,157],88:[2,157],90:[2,157],99:[2,157],100:85,101:[2,157],102:[1,267],103:[2,157],106:86,107:[2,157],108:67,115:[1,268],123:[2,157],125:[1,78],126:[1,77],129:[1,76],130:[1,79],131:[1,80],132:[1,81],133:[1,82],134:[1,83]},{1:[2,158],6:[2,158],25:[2,158],26:[2,158],47:[2,158],52:[2,158],55:[2,158],70:[2,158],75:[2,158],83:[2,158],88:[2,158],90:[2,158],99:[2,158],100:85,101:[2,158],102:[1,269],103:[2,158],106:86,107:[2,158],108:67,115:[2,158],123:[2,158],125:[1,78],126:[1,77],129:[1,76],130:[1,79],131:[1,80],132:[1,81],133:[1,82],134:[1,83]},{6:[1,271],25:[1,272],75:[1,270]},{6:[2,52],11:165,25:[2,52],26:[2,52],27:166,28:[1,71],29:167,30:[1,69],31:[1,70],39:273,40:164,42:168,44:[1,46],75:[2,52],86:[1,111]},{8:274,9:115,10:20,11:21,12:[1,22],13:8,14:9,15:10,16:11,17:12,18:13,19:14,20:15,21:16,22:17,23:18,24:19,25:[1,275],27:60,28:[1,71],29:49,30:[1,69],31:[1,70],32:24,33:[1,50],34:[1,51],35:[1,52],36:[1,53],37:23,42:61,43:[1,45],44:[1,46],45:[1,29],48:30,49:[1,58],50:[1,59],56:47,57:48,59:36,61:25,62:26,63:27,73:[1,68],76:[1,43],80:[1,28],85:[1,56],86:[1,57],87:[1,55],93:[1,38],97:[1,44],98:[1,54],100:39,101:[1,63],103:[1,64],104:40,105:[1,65],106:41,107:[1,66],108:67,116:[1,42],121:37,122:[1,62],124:[1,31],125:[1,32],126:[1,33],127:[1,34],128:[1,35]},{1:[2,81],6:[2,81],25:[2,81],26:[2,81],38:[2,81],47:[2,81],52:[2,81],55:[2,81],64:[2,81],65:[2,81],66:[2,81],68:[2,81],70:[2,81],71:[2,81],75:[2,81],77:[2,81],81:[2,81],82:[2,81],83:[2,81],88:[2,81],90:[2,81],99:[2,81],101:[2,81],102:[2,81],103:[2,81],107:[2,81],115:[2,81],123:[2,81],125:[2,81],126:[2,81],127:[2,81],128:[2,81],129:[2,81],130:[2,81],131:[2,81],132:[2,81],133:[2,81],134:[2,81],135:[2,81]},{8:276,9:115,10:20,11:21,12:[1,22],13:8,14:9,15:10,16:11,17:12,18:13,19:14,20:15,21:16,22:17,23:18,24:19,27:60,28:[1,71],29:49,30:[1,69],31:[1,70],32:24,33:[1,50],34:[1,51],35:[1,52],36:[1,53],37:23,42:61,43:[1,45],44:[1,46],45:[1,29],48:30,49:[1,58],50:[1,59],56:47,57:48,59:36,61:25,62:26,63:27,70:[2,116],73:[1,68],76:[1,43],80:[1,28],85:[1,56],86:[1,57],87:[1,55],93:[1,38],97:[1,44],98:[1,54],100:39,101:[1,63],103:[1,64],104:40,105:[1,65],106:41,107:[1,66],108:67,116:[1,42],121:37,122:[1,62],124:[1,31],125:[1,32],126:[1,33],127:[1,34],128:[1,35]},{70:[2,117],100:85,101:[1,63],103:[1,64],106:86,107:[1,66],108:67,123:[1,84],125:[1,78],126:[1,77],129:[1,76],130:[1,79],131:[1,80],132:[1,81],133:[1,82],134:[1,83]},{1:[2,35],6:[2,35],25:[2,35],26:[2,35],47:[2,35],52:[2,35],55:[2,35],70:[2,35],75:[2,35],83:[2,35],88:[2,35],90:[2,35],99:[2,35],100:85,101:[2,35],102:[2,35],103:[2,35],106:86,107:[2,35],108:67,115:[2,35],123:[2,35],125:[1,78],126:[1,77],129:[1,76],130:[1,79],131:[1,80],132:[1,81],133:[1,82],134:[1,83]},{26:[1,277],100:85,101:[1,63],103:[1,64],106:86,107:[1,66],108:67,123:[1,84],125:[1,78],126:[1,77],129:[1,76],130:[1,79],131:[1,80],132:[1,81],133:[1,82],134:[1,83]},{6:[1,260],25:[1,261],83:[1,278]},{6:[2,63],25:[2,63],26:[2,63],52:[2,63],83:[2,63],88:[2,63]},{5:279,25:[1,5]},{47:[2,55],52:[2,55]},{47:[2,58],52:[2,58],100:85,101:[1,63],103:[1,64],106:86,107:[1,66],108:67,123:[1,84],125:[1,78],126:[1,77],129:[1,76],130:[1,79],131:[1,80],132:[1,81],133:[1,82],134:[1,83]},{26:[1,280],100:85,101:[1,63],103:[1,64],106:86,107:[1,66],108:67,123:[1,84],125:[1,78],126:[1,77],129:[1,76],130:[1,79],131:[1,80],132:[1,81],133:[1,82],134:[1,83]},{5:281,25:[1,5],100:85,101:[1,63],103:[1,64],106:86,107:[1,66],108:67,123:[1,84],125:[1,78],126:[1,77],129:[1,76],130:[1,79],131:[1,80],132:[1,81],133:[1,82],134:[1,83]},{5:282,25:[1,5]},{1:[2,129],6:[2,129],25:[2,129],26:[2,129],47:[2,129],52:[2,129],55:[2,129],70:[2,129],75:[2,129],83:[2,129],88:[2,129],90:[2,129],99:[2,129],101:[2,129],102:[2,129],103:[2,129],107:[2,129],115:[2,129],123:[2,129],125:[2,129],126:[2,129],129:[2,129],130:[2,129],131:[2,129],132:[2,129],133:[2,129],134:[2,129]},{5:283,25:[1,5]},{26:[1,284],118:[1,285],119:252,120:[1,213]},{1:[2,166],6:[2,166],25:[2,166],26:[2,166],47:[2,166],52:[2,166],55:[2,166],70:[2,166],75:[2,166],83:[2,166],88:[2,166],90:[2,166],99:[2,166],101:[2,166],102:[2,166],103:[2,166],107:[2,166],115:[2,166],123:[2,166],125:[2,166],126:[2,166],129:[2,166],130:[2,166],131:[2,166],132:[2,166],133:[2,166],134:[2,166]},{5:286,25:[1,5]},{26:[2,169],118:[2,169],120:[2,169]},{5:287,25:[1,5],52:[1,288]},{25:[2,125],52:[2,125],100:85,101:[1,63],103:[1,64],106:86,107:[1,66],108:67,123:[1,84],125:[1,78],126:[1,77],129:[1,76],130:[1,79],131:[1,80],132:[1,81],133:[1,82],134:[1,83]},{1:[2,94],6:[2,94],25:[2,94],26:[2,94],47:[2,94],52:[2,94],55:[2,94],70:[2,94],75:[2,94],83:[2,94],88:[2,94],90:[2,94],99:[2,94],101:[2,94],102:[2,94],103:[2,94],107:[2,94],115:[2,94],123:[2,94],125:[2,94],126:[2,94],129:[2,94],130:[2,94],131:[2,94],132:[2,94],133:[2,94],134:[2,94]},{1:[2,97],5:289,6:[2,97],25:[1,5],26:[2,97],47:[2,97],52:[2,97],55:[2,97],70:[2,97],75:[2,97],83:[2,97],88:[2,97],90:[2,97],99:[2,97],100:85,101:[1,63],102:[2,97],103:[1,64],106:86,107:[1,66],108:67,115:[2,97],123:[2,97],125:[1,78],126:[1,77],129:[1,76],130:[1,79],131:[1,80],132:[1,81],133:[1,82],134:[1,83]},{99:[1,290]},{88:[1,291],100:85,101:[1,63],103:[1,64],106:86,107:[1,66],108:67,123:[1,84],125:[1,78],126:[1,77],129:[1,76],130:[1,79],131:[1,80],132:[1,81],133:[1,82],134:[1,83]},{1:[2,111],6:[2,111],25:[2,111],26:[2,111],38:[2,111],47:[2,111],52:[2,111],55:[2,111],64:[2,111],65:[2,111],66:[2,111],68:[2,111],70:[2,111],71:[2,111],75:[2,111],81:[2,111],82:[2,111],83:[2,111],88:[2,111],90:[2,111],99:[2,111],101:[2,111],102:[2,111],103:[2,111],107:[2,111],113:[2,111],114:[2,111],115:[2,111],123:[2,111],125:[2,111],126:[2,111],129:[2,111],130:[2,111],131:[2,111],132:[2,111],133:[2,111],134:[2,111]},{8:197,9:115,10:20,11:21,12:[1,22],13:8,14:9,15:10,16:11,17:12,18:13,19:14,20:15,21:16,22:17,23:18,24:19,27:60,28:[1,71],29:49,30:[1,69],31:[1,70],32:24,33:[1,50],34:[1,51],35:[1,52],36:[1,53],37:23,42:61,43:[1,45],44:[1,46],45:[1,29],48:30,49:[1,58],50:[1,59],56:47,57:48,58:145,59:36,61:25,62:26,63:27,73:[1,68],76:[1,43],80:[1,28],85:[1,56],86:[1,57],87:[1,55],91:292,93:[1,38],97:[1,44],98:[1,54],100:39,101:[1,63],103:[1,64],104:40,105:[1,65],106:41,107:[1,66],108:67,116:[1,42],121:37,122:[1,62],124:[1,31],125:[1,32],126:[1,33],127:[1,34],128:[1,35]},{8:197,9:115,10:20,11:21,12:[1,22],13:8,14:9,15:10,16:11,17:12,18:13,19:14,20:15,21:16,22:17,23:18,24:19,25:[1,144],27:60,28:[1,71],29:49,30:[1,69],31:[1,70],32:24,33:[1,50],34:[1,51],35:[1,52],36:[1,53],37:23,42:61,43:[1,45],44:[1,46],45:[1,29],48:30,49:[1,58],50:[1,59],56:47,57:48,58:145,59:36,61:25,62:26,63:27,73:[1,68],76:[1,43],80:[1,28],84:293,85:[1,56],86:[1,57],87:[1,55],91:143,93:[1,38],97:[1,44],98:[1,54],100:39,101:[1,63],103:[1,64],104:40,105:[1,65],106:41,107:[1,66],108:67,116:[1,42],121:37,122:[1,62],124:[1,31],125:[1,32],126:[1,33],127:[1,34],128:[1,35]},{6:[2,119],25:[2,119],26:[2,119],52:[2,119],83:[2,119],88:[2,119]},{6:[1,260],25:[1,261],26:[1,294]},{1:[2,136],6:[2,136],25:[2,136],26:[2,136],47:[2,136],52:[2,136],55:[2,136],70:[2,136],75:[2,136],83:[2,136],88:[2,136],90:[2,136],99:[2,136],100:85,101:[1,63],102:[2,136],103:[1,64],106:86,107:[1,66],108:67,115:[2,136],123:[2,136],125:[1,78],126:[1,77],129:[1,76],130:[1,79],131:[1,80],132:[1,81],133:[1,82],134:[1,83]},{1:[2,138],6:[2,138],25:[2,138],26:[2,138],47:[2,138],52:[2,138],55:[2,138],70:[2,138],75:[2,138],83:[2,138],88:[2,138],90:[2,138],99:[2,138],100:85,101:[1,63],102:[2,138],103:[1,64],106:86,107:[1,66],108:67,115:[2,138],123:[2,138],125:[1,78],126:[1,77],129:[1,76],130:[1,79],131:[1,80],132:[1,81],133:[1,82],134:[1,83]},{113:[2,156],114:[2,156]},{8:295,9:115,10:20,11:21,12:[1,22],13:8,14:9,15:10,16:11,17:12,18:13,19:14,20:15,21:16,22:17,23:18,24:19,27:60,28:[1,71],29:49,30:[1,69],31:[1,70],32:24,33:[1,50],34:[1,51],35:[1,52],36:[1,53],37:23,42:61,43:[1,45],44:[1,46],45:[1,29],48:30,49:[1,58],50:[1,59],56:47,57:48,59:36,61:25,62:26,63:27,73:[1,68],76:[1,43],80:[1,28],85:[1,56],86:[1,57],87:[1,55],93:[1,38],97:[1,44],98:[1,54],100:39,101:[1,63],103:[1,64],104:40,105:[1,65],106:41,107:[1,66],108:67,116:[1,42],121:37,122:[1,62],124:[1,31],125:[1,32],126:[1,33],127:[1,34],128:[1,35]},{8:296,9:115,10:20,11:21,12:[1,22],13:8,14:9,15:10,16:11,17:12,18:13,19:14,20:15,21:16,22:17,23:18,24:19,27:60,28:[1,71],29:49,30:[1,69],31:[1,70],32:24,33:[1,50],34:[1,51],35:[1,52],36:[1,53],37:23,42:61,43:[1,45],44:[1,46],45:[1,29],48:30,49:[1,58],50:[1,59],56:47,57:48,59:36,61:25,62:26,63:27,73:[1,68],76:[1,43],80:[1,28],85:[1,56],86:[1,57],87:[1,55],93:[1,38],97:[1,44],98:[1,54],100:39,101:[1,63],103:[1,64],104:40,105:[1,65],106:41,107:[1,66],108:67,116:[1,42],121:37,122:[1,62],124:[1,31],125:[1,32],126:[1,33],127:[1,34],128:[1,35]},{8:297,9:115,10:20,11:21,12:[1,22],13:8,14:9,15:10,16:11,17:12,18:13,19:14,20:15,21:16,22:17,23:18,24:19,27:60,28:[1,71],29:49,30:[1,69],31:[1,70],32:24,33:[1,50],34:[1,51],35:[1,52],36:[1,53],37:23,42:61,43:[1,45],44:[1,46],45:[1,29],48:30,49:[1,58],50:[1,59],56:47,57:48,59:36,61:25,62:26,63:27,73:[1,68],76:[1,43],80:[1,28],85:[1,56],86:[1,57],87:[1,55],93:[1,38],97:[1,44],98:[1,54],100:39,101:[1,63],103:[1,64],104:40,105:[1,65],106:41,107:[1,66],108:67,116:[1,42],121:37,122:[1,62],124:[1,31],125:[1,32],126:[1,33],127:[1,34],128:[1,35]},{1:[2,85],6:[2,85],25:[2,85],26:[2,85],38:[2,85],47:[2,85],52:[2,85],55:[2,85],64:[2,85],65:[2,85],66:[2,85],68:[2,85],70:[2,85],71:[2,85],75:[2,85],81:[2,85],82:[2,85],83:[2,85],88:[2,85],90:[2,85],99:[2,85],101:[2,85],102:[2,85],103:[2,85],107:[2,85],113:[2,85],114:[2,85],115:[2,85],123:[2,85],125:[2,85],126:[2,85],129:[2,85],130:[2,85],131:[2,85],132:[2,85],133:[2,85],134:[2,85]},{11:165,27:166,28:[1,71],29:167,30:[1,69],31:[1,70],39:298,40:164,42:168,44:[1,46],86:[1,111]},{6:[2,86],11:165,25:[2,86],26:[2,86],27:166,28:[1,71],29:167,30:[1,69],31:[1,70],39:163,40:164,42:168,44:[1,46],52:[2,86],74:299,86:[1,111]},{6:[2,88],25:[2,88],26:[2,88],52:[2,88],75:[2,88]},{6:[2,38],25:[2,38],26:[2,38],52:[2,38],75:[2,38],100:85,101:[1,63],103:[1,64],106:86,107:[1,66],108:67,123:[1,84],125:[1,78],126:[1,77],129:[1,76],130:[1,79],131:[1,80],132:[1,81],133:[1,82],134:[1,83]},{8:300,9:115,10:20,11:21,12:[1,22],13:8,14:9,15:10,16:11,17:12,18:13,19:14,20:15,21:16,22:17,23:18,24:19,27:60,28:[1,71],29:49,30:[1,69],31:[1,70],32:24,33:[1,50],34:[1,51],35:[1,52],36:[1,53],37:23,42:61,43:[1,45],44:[1,46],45:[1,29],48:30,49:[1,58],50:[1,59],56:47,57:48,59:36,61:25,62:26,63:27,73:[1,68],76:[1,43],80:[1,28],85:[1,56],86:[1,57],87:[1,55],93:[1,38],97:[1,44],98:[1,54],100:39,101:[1,63],103:[1,64],104:40,105:[1,65],106:41,107:[1,66],108:67,116:[1,42],121:37,122:[1,62],124:[1,31],125:[1,32],126:[1,33],127:[1,34],128:[1,35]},{70:[2,115],100:85,101:[1,63],103:[1,64],106:86,107:[1,66],108:67,123:[1,84],125:[1,78],126:[1,77],129:[1,76],130:[1,79],131:[1,80],132:[1,81],133:[1,82],134:[1,83]},{1:[2,36],6:[2,36],25:[2,36],26:[2,36],47:[2,36],52:[2,36],55:[2,36],70:[2,36],75:[2,36],83:[2,36],88:[2,36],90:[2,36],99:[2,36],101:[2,36],102:[2,36],103:[2,36],107:[2,36],115:[2,36],123:[2,36],125:[2,36],126:[2,36],129:[2,36],130:[2,36],131:[2,36],132:[2,36],133:[2,36],134:[2,36]},{1:[2,106],6:[2,106],25:[2,106],26:[2,106],47:[2,106],52:[2,106],55:[2,106],64:[2,106],65:[2,106],66:[2,106],68:[2,106],70:[2,106],71:[2,106],75:[2,106],81:[2,106],82:[2,106],83:[2,106],88:[2,106],90:[2,106],99:[2,106],101:[2,106],102:[2,106],103:[2,106],107:[2,106],115:[2,106],123:[2,106],125:[2,106],126:[2,106],129:[2,106],130:[2,106],131:[2,106],132:[2,106],133:[2,106],134:[2,106]},{1:[2,47],6:[2,47],25:[2,47],26:[2,47],47:[2,47],52:[2,47],55:[2,47],70:[2,47],75:[2,47],83:[2,47],88:[2,47],90:[2,47],99:[2,47],101:[2,47],102:[2,47],103:[2,47],107:[2,47],115:[2,47],123:[2,47],125:[2,47],126:[2,47],129:[2,47],130:[2,47],131:[2,47],132:[2,47],133:[2,47],134:[2,47]},{1:[2,194],6:[2,194],25:[2,194],26:[2,194],47:[2,194],52:[2,194],55:[2,194],70:[2,194],75:[2,194],83:[2,194],88:[2,194],90:[2,194],99:[2,194],101:[2,194],102:[2,194],103:[2,194],107:[2,194],115:[2,194],123:[2,194],125:[2,194],126:[2,194],129:[2,194],130:[2,194],131:[2,194],132:[2,194],133:[2,194],134:[2,194]},{1:[2,173],6:[2,173],25:[2,173],26:[2,173],47:[2,173],52:[2,173],55:[2,173],70:[2,173],75:[2,173],83:[2,173],88:[2,173],90:[2,173],99:[2,173],101:[2,173],102:[2,173],103:[2,173],107:[2,173],115:[2,173],118:[2,173],123:[2,173],125:[2,173],126:[2,173],129:[2,173],130:[2,173],131:[2,173],132:[2,173],133:[2,173],134:[2,173]},{1:[2,130],6:[2,130],25:[2,130],26:[2,130],47:[2,130],52:[2,130],55:[2,130],70:[2,130],75:[2,130],83:[2,130],88:[2,130],90:[2,130],99:[2,130],101:[2,130],102:[2,130],103:[2,130],107:[2,130],115:[2,130],123:[2,130],125:[2,130],126:[2,130],129:[2,130],130:[2,130],131:[2,130],132:[2,130],133:[2,130],134:[2,130]},{1:[2,131],6:[2,131],25:[2,131],26:[2,131],47:[2,131],52:[2,131],55:[2,131],70:[2,131],75:[2,131],83:[2,131],88:[2,131],90:[2,131],95:[2,131],99:[2,131],101:[2,131],102:[2,131],103:[2,131],107:[2,131],115:[2,131],123:[2,131],125:[2,131],126:[2,131],129:[2,131],130:[2,131],131:[2,131],132:[2,131],133:[2,131],134:[2,131]},{1:[2,164],6:[2,164],25:[2,164],26:[2,164],47:[2,164],52:[2,164],55:[2,164],70:[2,164],75:[2,164],83:[2,164],88:[2,164],90:[2,164],99:[2,164],101:[2,164],102:[2,164],103:[2,164],107:[2,164],115:[2,164],123:[2,164],125:[2,164],126:[2,164],129:[2,164],130:[2,164],131:[2,164],132:[2,164],133:[2,164],134:[2,164]},{5:301,25:[1,5]},{26:[1,302]},{6:[1,303],26:[2,170],118:[2,170],120:[2,170]},{8:304,9:115,10:20,11:21,12:[1,22],13:8,14:9,15:10,16:11,17:12,18:13,19:14,20:15,21:16,22:17,23:18,24:19,27:60,28:[1,71],29:49,30:[1,69],31:[1,70],32:24,33:[1,50],34:[1,51],35:[1,52],36:[1,53],37:23,42:61,43:[1,45],44:[1,46],45:[1,29],48:30,49:[1,58],50:[1,59],56:47,57:48,59:36,61:25,62:26,63:27,73:[1,68],76:[1,43],80:[1,28],85:[1,56],86:[1,57],87:[1,55],93:[1,38],97:[1,44],98:[1,54],100:39,101:[1,63],103:[1,64],104:40,105:[1,65],106:41,107:[1,66],108:67,116:[1,42],121:37,122:[1,62],124:[1,31],125:[1,32],126:[1,33],127:[1,34],128:[1,35]},{1:[2,98],6:[2,98],25:[2,98],26:[2,98],47:[2,98],52:[2,98],55:[2,98],70:[2,98],75:[2,98],83:[2,98],88:[2,98],90:[2,98],99:[2,98],101:[2,98],102:[2,98],103:[2,98],107:[2,98],115:[2,98],123:[2,98],125:[2,98],126:[2,98],129:[2,98],130:[2,98],131:[2,98],132:[2,98],133:[2,98],134:[2,98]},{1:[2,134],6:[2,134],25:[2,134],26:[2,134],47:[2,134],52:[2,134],55:[2,134],64:[2,134],65:[2,134],66:[2,134],68:[2,134],70:[2,134],71:[2,134],75:[2,134],81:[2,134],82:[2,134],83:[2,134],88:[2,134],90:[2,134],99:[2,134],101:[2,134],102:[2,134],103:[2,134],107:[2,134],115:[2,134],123:[2,134],125:[2,134],126:[2,134],129:[2,134],130:[2,134],131:[2,134],132:[2,134],133:[2,134],134:[2,134]},{1:[2,114],6:[2,114],25:[2,114],26:[2,114],47:[2,114],52:[2,114],55:[2,114],64:[2,114],65:[2,114],66:[2,114],68:[2,114],70:[2,114],71:[2,114],75:[2,114],81:[2,114],82:[2,114],83:[2,114],88:[2,114],90:[2,114],99:[2,114],101:[2,114],102:[2,114],103:[2,114],107:[2,114],115:[2,114],123:[2,114],125:[2,114],126:[2,114],129:[2,114],130:[2,114],131:[2,114],132:[2,114],133:[2,114],134:[2,114]},{6:[2,120],25:[2,120],26:[2,120],52:[2,120],83:[2,120],88:[2,120]},{6:[2,51],25:[2,51],26:[2,51],51:305,52:[1,222]},{6:[2,121],25:[2,121],26:[2,121],52:[2,121],83:[2,121],88:[2,121]},{1:[2,159],6:[2,159],25:[2,159],26:[2,159],47:[2,159],52:[2,159],55:[2,159],70:[2,159],75:[2,159],83:[2,159],88:[2,159],90:[2,159],99:[2,159],100:85,101:[2,159],102:[2,159],103:[2,159],106:86,107:[2,159],108:67,115:[1,306],123:[2,159],125:[1,78],126:[1,77],129:[1,76],130:[1,79],131:[1,80],132:[1,81],133:[1,82],134:[1,83]},{1:[2,161],6:[2,161],25:[2,161],26:[2,161],47:[2,161],52:[2,161],55:[2,161],70:[2,161],75:[2,161],83:[2,161],88:[2,161],90:[2,161],99:[2,161],100:85,101:[2,161],102:[1,307],103:[2,161],106:86,107:[2,161],108:67,115:[2,161],123:[2,161],125:[1,78],126:[1,77],129:[1,76],130:[1,79],131:[1,80],132:[1,81],133:[1,82],134:[1,83]},{1:[2,160],6:[2,160],25:[2,160],26:[2,160],47:[2,160],52:[2,160],55:[2,160],70:[2,160],75:[2,160],83:[2,160],88:[2,160],90:[2,160],99:[2,160],100:85,101:[2,160],102:[2,160],103:[2,160],106:86,107:[2,160],108:67,115:[2,160],123:[2,160],125:[1,78],126:[1,77],129:[1,76],130:[1,79],131:[1,80],132:[1,81],133:[1,82],134:[1,83]},{6:[2,89],25:[2,89],26:[2,89],52:[2,89],75:[2,89]},{6:[2,51],25:[2,51],26:[2,51],51:308,52:[1,232]},{26:[1,309],100:85,101:[1,63],103:[1,64],106:86,107:[1,66],108:67,123:[1,84],125:[1,78],126:[1,77],129:[1,76],130:[1,79],131:[1,80],132:[1,81],133:[1,82],134:[1,83]},{26:[1,310]},{1:[2,167],6:[2,167],25:[2,167],26:[2,167],47:[2,167],52:[2,167],55:[2,167],70:[2,167],75:[2,167],83:[2,167],88:[2,167],90:[2,167],99:[2,167],101:[2,167],102:[2,167],103:[2,167],107:[2,167],115:[2,167],123:[2,167],125:[2,167],126:[2,167],129:[2,167],130:[2,167],131:[2,167],132:[2,167],133:[2,167],134:[2,167]},{26:[2,171],118:[2,171],120:[2,171]},{25:[2,126],52:[2,126],100:85,101:[1,63],103:[1,64],106:86,107:[1,66],108:67,123:[1,84],125:[1,78],126:[1,77],129:[1,76],130:[1,79],131:[1,80],132:[1,81],133:[1,82],134:[1,83]},{6:[1,260],25:[1,261],26:[1,311]},{8:312,9:115,10:20,11:21,12:[1,22],13:8,14:9,15:10,16:11,17:12,18:13,19:14,20:15,21:16,22:17,23:18,24:19,27:60,28:[1,71],29:49,30:[1,69],31:[1,70],32:24,33:[1,50],34:[1,51],35:[1,52],36:[1,53],37:23,42:61,43:[1,45],44:[1,46],45:[1,29],48:30,49:[1,58],50:[1,59],56:47,57:48,59:36,61:25,62:26,63:27,73:[1,68],76:[1,43],80:[1,28],85:[1,56],86:[1,57],87:[1,55],93:[1,38],97:[1,44],98:[1,54],100:39,101:[1,63],103:[1,64],104:40,105:[1,65],106:41,107:[1,66],108:67,116:[1,42],121:37,122:[1,62],124:[1,31],125:[1,32],126:[1,33],127:[1,34],128:[1,35]},{8:313,9:115,10:20,11:21,12:[1,22],13:8,14:9,15:10,16:11,17:12,18:13,19:14,20:15,21:16,22:17,23:18,24:19,27:60,28:[1,71],29:49,30:[1,69],31:[1,70],32:24,33:[1,50],34:[1,51],35:[1,52],36:[1,53],37:23,42:61,43:[1,45],44:[1,46],45:[1,29],48:30,49:[1,58],50:[1,59],56:47,57:48,59:36,61:25,62:26,63:27,73:[1,68],76:[1,43],80:[1,28],85:[1,56],86:[1,57],87:[1,55],93:[1,38],97:[1,44],98:[1,54],100:39,101:[1,63],103:[1,64],104:40,105:[1,65],106:41,107:[1,66],108:67,116:[1,42],121:37,122:[1,62],124:[1,31],125:[1,32],126:[1,33],127:[1,34],128:[1,35]},{6:[1,271],25:[1,272],26:[1,314]},{6:[2,39],25:[2,39],26:[2,39],52:[2,39],75:[2,39]},{1:[2,165],6:[2,165],25:[2,165],26:[2,165],47:[2,165],52:[2,165],55:[2,165],70:[2,165],75:[2,165],83:[2,165],88:[2,165],90:[2,165],99:[2,165],101:[2,165],102:[2,165],103:[2,165],107:[2,165],115:[2,165],123:[2,165],125:[2,165],126:[2,165],129:[2,165],130:[2,165],131:[2,165],132:[2,165],133:[2,165],134:[2,165]},{6:[2,122],25:[2,122],26:[2,122],52:[2,122],83:[2,122],88:[2,122]},{1:[2,162],6:[2,162],25:[2,162],26:[2,162],47:[2,162],52:[2,162],55:[2,162],70:[2,162],75:[2,162],83:[2,162],88:[2,162],90:[2,162],99:[2,162],100:85,101:[2,162],102:[2,162],103:[2,162],106:86,107:[2,162],108:67,115:[2,162],123:[2,162],125:[1,78],126:[1,77],129:[1,76],130:[1,79],131:[1,80],132:[1,81],133:[1,82],134:[1,83]},{1:[2,163],6:[2,163],25:[2,163],26:[2,163],47:[2,163],52:[2,163],55:[2,163],70:[2,163],75:[2,163],83:[2,163],88:[2,163],90:[2,163],99:[2,163],100:85,101:[2,163],102:[2,163],103:[2,163],106:86,107:[2,163],108:67,115:[2,163],123:[2,163],125:[1,78],126:[1,77],129:[1,76],130:[1,79],131:[1,80],132:[1,81],133:[1,82],134:[1,83]},{6:[2,90],25:[2,90],26:[2,90],52:[2,90],75:[2,90]}],defaultActions:{58:[2,49],59:[2,50],73:[2,3],92:[2,104],186:[2,84]},parseError:function(a,b){throw new Error(a)},parse:function(a){function o(){var a;a=b.lexer.lex()||1,typeof a!="number"&&(a=b.symbols_[a]||a);return a}function n(a){c.length=c.length-2*a,d.length=d.length-a,e.length=e.length-a}var b=this,c=[0],d=[null],e=[],f=this.table,g="",h=0,i=0,j=0,k=2,l=1;this.lexer.setInput(a),this.lexer.yy=this.yy,this.yy.lexer=this.lexer,typeof this.lexer.yylloc=="undefined"&&(this.lexer.yylloc={});var m=this.lexer.yylloc;e.push(m),typeof this.yy.parseError=="function"&&(this.parseError=this.yy.parseError);var p,q,r,s,t,u,v={},w,x,y,z;for(;;){r=c[c.length-1],this.defaultActions[r]?s=this.defaultActions[r]:(p==null&&(p=o()),s=f[r]&&f[r][p]);if(typeof s=="undefined"||!s.length||!s[0]){if(!j){z=[];for(w in f[r])this.terminals_[w]&&w>2&&z.push("'"+this.terminals_[w]+"'");var A="";this.lexer.showPosition?A="Parse error on line "+(h+1)+":\n"+this.lexer.showPosition()+"\nExpecting "+z.join(", "):A="Parse error on line "+(h+1)+": Unexpected "+(p==1?"end of input":"'"+(this.terminals_[p]||p)+"'"),this.parseError(A,{text:this.lexer.match,token:this.terminals_[p]||p,line:this.lexer.yylineno,loc:m,expected:z})}if(j==3){if(p==l)throw new Error(A||"Parsing halted.");i=this.lexer.yyleng,g=this.lexer.yytext,h=this.lexer.yylineno,m=this.lexer.yylloc,p=o()}for(;;){if(k.toString()in f[r])break;if(r==0)throw new Error(A||"Parsing halted.");n(1),r=c[c.length-1]}q=p,p=k,r=c[c.length-1],s=f[r]&&f[r][k],j=3}if(s[0]instanceof Array&&s.length>1)throw new Error("Parse Error: multiple actions possible at state: "+r+", token: "+p);switch(s[0]){case 1:c.push(p),d.push(this.lexer.yytext),e.push(this.lexer.yylloc),c.push(s[1]),p=null,q?(p=q,q=null):(i=this.lexer.yyleng,g=this.lexer.yytext,h=this.lexer.yylineno,m=this.lexer.yylloc,j>0&&j--);break;case 2:x=this.productions_[s[1]][1],v.$=d[d.length-x],v._$={first_line:e[e.length-(x||1)].first_line,last_line:e[e.length-1].last_line,first_column:e[e.length-(x||1)].first_column,last_column:e[e.length-1].last_column},u=this.performAction.call(v,g,i,h,this.yy,s[1],d,e);if(typeof u!="undefined")return u;x&&(c=c.slice(0,-1*x*2),d=d.slice(0,-1*x),e=e.slice(0,-1*x)),c.push(this.productions_[s[1]][0]),d.push(v.$),e.push(v._$),y=f[c[c.length-2]][c[c.length-1]],c.push(y);break;case 3:return!0}}return!0}};return a}();typeof require!="undefined"&&typeof a!="undefined"&&(a.parser=b,a.parse=function(){return b.parse.apply(b,arguments)},a.main=function(b){if(!b[1])throw new Error("Usage: "+b[0]+" FILE");if(typeof process!="undefined")var c=require("fs").readFileSync(require("path").join(process.cwd(),b[1]),"utf8");else var d=require("file").path(require("file").cwd()),c=d.join(b[1]).read({charset:"utf-8"});return a.parser.parse(c)},typeof module!="undefined"&&require.main===module&&a.main(typeof process!="undefined"?process.argv.slice(1):require("system").args))},require["./scope"]=new function(){var a=this;(function(){var b,c,d,e;e=require("./helpers"),c=e.extend,d=e.last,a.Scope=b=function(){function a(b,c,d){this.parent=b,this.expressions=c,this.method=d,this.variables=[{name:"arguments",type:"arguments"}],this.positions={},this.parent||(a.root=this)}a.root=null,a.prototype.add=function(a,b,c){if(this.shared&&!c)return this.parent.add(a,b,c);return Object.prototype.hasOwnProperty.call(this.positions,a)?this.variables[this.positions[a]].type=b:this.positions[a]=this.variables.push({name:a,type:b})-1},a.prototype.find=function(a,b){if(this.check(a,b))return!0;this.add(a,"var");return!1},a.prototype.parameter=function(a){if(!this.shared||!this.parent.check(a,!0))return this.add(a,"param")},a.prototype.check=function(a,b){var c,d;c=!!this.type(a);if(c||b)return c;return(d=this.parent)!=null?!!d.check(a):!!void 0},a.prototype.temporary=function(a,b){return a.length>1?"_"+a+(b>1?b:""):"_"+(b+parseInt(a,36)).toString(36).replace(/\d/g,"a")},a.prototype.type=function(a){var b,c,d,e;e=this.variables;for(c=0,d=e.length;c1&&a.level>=w?"("+c+")":c},b.prototype.compileRoot=function(a){var b,c,d,e,f,g;a.indent=a.bare?"":Q,a.scope=new M(null,this,null),a.level=z,this.spaced=!0,e="",a.bare||(f=function(){var a,b,e;b=this.expressions,e=[];for(d=0,a=b.length;d=u?"(void 0)":"void 0":this.value==="this"?((c=a.scope.method)!=null?c.bound:void 0)?a.scope.method.context:this.value:this.value.reserved&&(d=""+this.value)!=="eval"&&d!=="arguments"?'"'+this.value+'"':this.value;return this.isStatement()?""+this.tab+b+";":b},b.prototype.toString=function(){return' "'+this.value+'"'};return b}(e),a.Return=K=function(a){function b(a){a&&!a.unwrap().isUndefined&&(this.expression=a)}bj(b,a),b.prototype.children=["expression"],b.prototype.isStatement=X,b.prototype.makeReturn=R,b.prototype.jumps=R,b.prototype.compile=function(a,c){var d,e;d=(e=this.expression)!=null?e.makeReturn():void 0;return!d||d instanceof b?b.__super__.compile.call(this,a,c):d.compile(a,c)},b.prototype.compileNode=function(a){return this.tab+("return"+[this.expression?" "+this.expression.compile(a,y):void 0]+";")};return b}(e),a.Value=V=function(a){function b(a,c,d){if(!c&&a instanceof b)return a;this.base=a,this.properties=c||[],d&&(this[d]=!0);return this}bj(b,a),b.prototype.children=["base","properties"],b.prototype.add=function(a){this.properties=this.properties.concat(a);return this},b.prototype.hasProperties=function(){return!!this.properties.length},b.prototype.isArray=function(){return!this.properties.length&&this.base instanceof c},b.prototype.isComplex=function(){return this.hasProperties()||this.base.isComplex()},b.prototype.isAssignable=function(){return this.hasProperties()||this.base.isAssignable()},b.prototype.isSimpleNumber=function(){return this.base instanceof A&&L.test(this.base.value)},b.prototype.isAtomic=function(){var a,b,c,d;d=this.properties.concat(this.base);for(b=0,c=d.length;b"+this.equals],h=l[0],e=l[1],c=this.stepNum?+this.stepNum>0?""+h+" "+this.toVar:""+e+" "+this.toVar:g?(m=[+this.fromNum,+this.toNum],d=m[0],j=m[1],m,d<=j?""+h+" "+j:""+e+" "+j):(b=""+this.fromVar+" <= "+this.toVar,""+b+" ? "+h+" "+this.toVar+" : "+e+" "+this.toVar),i=this.stepVar?""+f+" += "+this.stepVar:g?d<=j?""+f+"++":""+f+"--":""+b+" ? "+f+"++ : "+f+"--";return""+k+"; "+c+"; "+i},b.prototype.compileArray=function(a){var b,c,d,e,f,g,h,i,j,k,l,m,n,o,p;if(this.fromNum&&this.toNum&&Math.abs(this.fromNum-this.toNum)<=20){j=function(){p=[];for(var a=n=+this.fromNum,b=+this.toNum;n<=b?a<=b:a>=b;n<=b?a++:a--)p.push(a);return p}.apply(this),this.exclusive&&j.pop();return"["+j.join(", ")+"]"}g=this.tab+Q,f=a.scope.freeVariable("i"),k=a.scope.freeVariable("results"),i="\n"+g+k+" = [];",this.fromNum&&this.toNum?(a.index=f,c=this.compileNode(a)):(l=""+f+" = "+this.fromC+(this.toC!==this.toVar?", "+this.toC:""),d=""+this.fromVar+" <= "+this.toVar,c="var "+l+"; "+d+" ? "+f+" <"+this.equals+" "+this.toVar+" : "+f+" >"+this.equals+" "+this.toVar+"; "+d+" ? "+f+"++ : "+f+"--"),h="{ "+k+".push("+f+"); }\n"+g+"return "+k+";\n"+a.indent,e=function(a){return a!=null?a.contains(function(a){return a instanceof A&&a.value==="arguments"&&!a.asKey}):void 0};if(e(this.from)||e(this.to))b=", arguments";return"(function() {"+i+"\n"+g+"for ("+c+")"+h+"}).apply(this"+(b!=null?b:"")+")"};return b}(e),a.Slice=N=function(a){function b(a){this.range=a,b.__super__.constructor.call(this)}bj(b,a),b.prototype.children=["range"],b.prototype.compileNode=function(a){var b,c,d,e,f,g;g=this.range,e=g.to,c=g.from,d=c&&c.compile(a,y)||"0",b=e&&e.compile(a,u),e&&(!!this.range.exclusive||+b!==-1)&&(f=", "+(this.range.exclusive?b:L.test(b)?(+b+1).toString():""+b+" + 1 || 9e9"));return".slice("+d+(f||"")+")"};return b}(e),a.Obj=E=function(a){function b(a,b){this.generated=b!=null?b:!1,this.objects=this.properties=a||[]}bj(b,a),b.prototype.children=["properties"],b.prototype.compileNode=function(a){var b,c,e,f,g,h,i,j,l,m,n;l=this.properties;if(!l.length)return this.front?"({})":"{}";if(this.generated)for(m=0,n=l.length;m=0?"[\n"+a.indent+b+"\n"+this.tab+"]":"["+b+"]"},b.prototype.assigns=function(a){var b,c,d,e;e=this.objects;for(c=0,d=e.length;c=0},c.prototype.assigns=function(a){return this[this.context==="object"?"value":"variable"].assigns(a)},c.prototype.unfoldSoak=function(a){return bf(a,this,"variable")},c.prototype.compileNode=function(a){var b,c,d,e,f,g,h,i,k;if(b=this.variable instanceof V){if(this.variable.isArray()||this.variable.isObject())return this.compilePatternMatch(a);if(this.variable.isSplice())return this.compileSplice(a);if((g=this.context)==="||="||g==="&&="||g==="?=")return this.compileConditional(a)}d=this.variable.compile(a,w);if(!this.context){if(!(f=this.variable.unwrapAll()).isAssignable())throw SyntaxError('"'+this.variable.compile(a)+'" cannot be assigned.');if(typeof f.hasProperties=="function"?!f.hasProperties():!void 0)this.param?a.scope.add(d,"var"):a.scope.find(d)}this.value instanceof j&&(c=B.exec(d))&&(c[1]&&(this.value.klass=c[1]),this.value.name=(h=(i=(k=c[2])!=null?k:c[3])!=null?i:c[4])!=null?h:c[5]),e=this.value.compile(a,w);if(this.context==="object")return""+d+": "+e;e=d+(" "+(this.context||"=")+" ")+e;return a.level<=w?e:"("+e+")"},c.prototype.compilePatternMatch=function(a){var d,e,f,g,h,i,j,k,l,m,n,p,q,r,s,u,v,y,B,C,D,E,F,G,J,K;s=a.level===z,v=this.value,m=this.variable.base.objects;if(!(n=m.length)){f=v.compile(a);return a.level>=x?"("+f+")":f}i=this.variable.isObject();if(s&&n===1&&!((l=m[0])instanceof O)){l instanceof c?(C=l,D=C.variable,h=D.base,l=C.value):l.base instanceof H?(E=(new V(l.unwrapAll())).cacheReference(a),l=E[0],h=E[1]):h=i?l["this"]?l.properties[0].name:l:new A(0),d=o.test(h.unwrap().value||0),v=new V(v),v.properties.push(new(d?b:t)(h));if(F=l.unwrap().value,bk.call(["arguments","eval"].concat(I),F)>=0)throw new SyntaxError("assignment to a reserved word: "+l.compile(a)+" = "+v.compile(a));return(new c(l,v,null,{param:this.param})).compile(a,z)}y=v.compile(a,w),e=[],r=!1;if(!o.test(y)||this.variable.assigns(y))e.push(""+(p=a.scope.freeVariable("ref"))+" = "+y),y=p;for(g=0,B=m.length;g=0)throw new SyntaxError("assignment to a reserved word: "+l.compile(a)+" = "+u.compile(a));e.push((new c(l,u,null,{param:this.param,subpattern:!0})).compile(a,w))}!s&&!this.subpattern&&e.push(y),f=e.join(", ");return a.level=0&&(a.isExistentialEquals=!0);return(new F(this.context.slice(0,-1),b,new c(d,this.value,"="))).compile(a)},c.prototype.compileSplice=function(a){var b,c,d,e,f,g,h,i,j,k,l,m;k=this.variable.properties.pop().range,d=k.from,h=k.to,c=k.exclusive,g=this.variable.compile(a),l=(d!=null?d.cache(a,x):void 0)||["0","0"],e=l[0],f=l[1],h?(d!=null?d.isSimpleNumber():void 0)&&h.isSimpleNumber()?(h=+h.compile(a)- +f,c||(h+=1)):(h=h.compile(a,u)+" - "+f,c||(h+=" + 1")):h="9e9",m=this.value.cache(a,w),i=m[0],j=m[1],b="[].splice.apply("+g+", ["+e+", "+h+"].concat("+i+")), "+j;return a.level>z?"("+b+")":b};return c}(e),a.Code=j=function(a){function b(a,b,c){this.params=a||[],this.body=b||new f,this.bound=c==="boundfunc",this.bound&&(this.context="_this")}bj(b,a),b.prototype.children=["params","body"],b.prototype.isStatement=function(){return!!this.ctor},b.prototype.jumps=D,b.prototype.compileNode=function(a){var b,e,f,g,h,i,j,k,l,m,n,o,p,q,s,t,v,w,x,y,z,B,C,D,E;a.scope=new M(a.scope,this.body,this),a.scope.shared=Z(a,"sharedScope"),a.indent+=Q,delete a.bare,o=[],e=[],z=this.params;for(q=0,v=z.length;q=u?"("+b+")":b},b.prototype.traverseChildren=function(a,c){if(a)return b.__super__.traverseChildren.call(this,a,c)};return b}(e),a.Param=G=function(a){function b(a,b,c){this.name=a,this.value=b,this.splat=c}bj(b,a),b.prototype.children=["name","value"],b.prototype.compile=function(a){return this.name.compile(a,w)},b.prototype.asReference=function(a){var b;if(this.reference)return this.reference;b=this.name,b["this"]?(b=b.properties[0].name,b.value.reserved&&(b=new A("_"+b.value))):b.isComplex()&&(b=new A(a.scope.freeVariable("arg"))),b=new V(b),this.splat&&(b=new O(b));return this.reference=b},b.prototype.isComplex=function(){return this.name.isComplex()};return b}(e),a.Splat=O=function(a){function b(a){this.name=a.compile?a:new A(a)}bj(b,a),b.prototype.children=["name"],b.prototype.isAssignable=X,b.prototype.assigns=function(a){return this.name.assigns(a)},b.prototype.compile=function(a){return this.index!=null?this.compileParam(a):this.name.compile(a)},b.prototype.unwrap=function(){return this.name},b.compileSplattedArray=function(a,c,d){var e,f,g,h,i,j,k;i=-1;while((j=c[++i])&&!(j instanceof b))continue;if(i>=c.length)return"";if(c.length===1){g=c[0].compile(a,w);if(d)return g;return""+bg("slice")+".call("+g+")"}e=c.slice(i);for(h=0,k=e.length;h1?b.expressions.unshift(new r((new H(this.guard)).invert(),new A("continue"))):this.guard&&(b=f.wrap([new r(this.guard,b)]))),b="\n"+b.compile(a,z)+"\n"+this.tab),c=e+this.tab+("while ("+this.condition.compile(a,y)+") {"+b+"}"),this.returns&&(c+="\n"+this.tab+"return "+d+";");return c};return b}(e),a.Op=F=function(a){function e(a,c,d,e){var f;if(a==="in")return new s(c,d);if(a==="do"){f=new g(c,c.params||[]),f["do"]=!0;return f}if(a==="new"){if(c instanceof g&&!c["do"]&&!c.isNew)return c.newInstance();if(c instanceof j&&c.bound||c["do"])c=new H(c)}this.operator=b[a]||a,this.first=c,this.second=d,this.flip=!!e;return this}var b,c;bj(e,a),b={"==":"===","!=":"!==",of:"in"},c={"!==":"===","===":"!=="},e.prototype.children=["first","second"],e.prototype.isSimpleNumber=D,e.prototype.isUnary=function(){return!this.second},e.prototype.isComplex=function(){var a;return!this.isUnary()||(a=this.operator)!=="+"&&a!=="-"||this.first.isComplex()},e.prototype.isChainable=function(){var a;return(a=this.operator)==="<"||a===">"||a===">="||a==="<="||a==="==="||a==="!=="},e.prototype.invert=function(){var a,b,d,f,g;if(this.isChainable()&&this.first.isChainable()){a=!0,b=this;while(b&&b.operator)a&&(a=b.operator in c),b=b.first;if(!a)return(new H(this)).invert();b=this;while(b&&b.operator)b.invert=!b.invert,b.operator=c[b.operator],b=b.first;return this}if(f=c[this.operator]){this.operator=f,this.first.unwrap()instanceof e&&this.first.invert();return this}return this.second?(new H(this)).invert():this.operator==="!"&&(d=this.first.unwrap())instanceof e&&((g=d.operator)==="!"||g==="in"||g==="instanceof")?d:new e("!",this)},e.prototype.unfoldSoak=function(a){var b;return((b=this.operator)==="++"||b==="--"||b==="delete")&&bf(a,this,"first")},e.prototype.compileNode=function(a){var b,c;c=this.isChainable()&&this.first.isChainable(),c||(this.first.front=this.front);if(this.isUnary())return this.compileUnary(a);if(c)return this.compileChain(a);if(this.operator==="?")return this.compileExistence(a);b=this.first.compile(a,x)+" "+this.operator+" "+this.second.compile(a,x);return a.level<=x?b:"("+b+")"},e.prototype.compileChain=function(a){var b,c,d,e;e=this.first.second.cache(a),this.first.second=e[0],d=e[1],c=this.first.compile(a,x),b=""+c+" "+(this.invert?"&&":"||")+" "+d.compile(a)+" "+this.operator+" "+this.second.compile(a,x);return"("+b+")"},e.prototype.compileExistence=function(a){var b,c;this.first.isComplex()&&a.level>z?(c=new A(a.scope.freeVariable("ref")),b=new H(new d(c,this.first))):(b=this.first,c=b);return(new r(new l(b),c,{type:"if"})).addElse(this.second).compile(a)},e.prototype.compileUnary=function(a){var b,c,d;c=[b=this.operator],d=b==="+"||b==="-",(b==="new"||b==="typeof"||b==="delete"||d&&this.first instanceof e&&this.first.operator===b)&&c.push(" ");if(d&&this.first instanceof e||b==="new"&&this.first.isStatement(a))this.first=new H(this.first);c.push(this.first.compile(a,x)),this.flip&&c.reverse();return c.join("")},e.prototype.toString=function(a){return e.__super__.toString.call(this,a,this.constructor.name+" "+this.operator)};return e}(e),a.In=s=function(a){function b(a,b){this.object=a,this.array=b}bj(b,a),b.prototype.children=["object","array"],b.prototype.invert=C,b.prototype.compileNode=function(a){var b,c,d,e,f;if(this.array instanceof V&&this.array.isArray()){f=this.array.base.objects;for(d=0,e=f.length;d= 0");if(d===c)return b;b=d+", "+b;return a.level1?b.expressions.unshift(new r((new H(this.guard)).invert(),new A("continue"))):this.guard&&(b=f.wrap([new r(this.guard,b)]))),this.pattern&&b.expressions.unshift(new d(this.name,new A(""+D+"["+k+"]"))),c+=this.pluckDirectCall(a,b),p&&(E="\n"+i+p+";"),this.object&&(e=""+k+" in "+D,this.own&&(h="\n"+i+"if (!"+bg("hasProp")+".call("+D+", "+k+")) continue;")),b=b.compile(bc(a,{indent:i}),z),b&&(b="\n"+b+"\n");return""+c+(s||"")+this.tab+"for ("+e+") {"+h+E+b+this.tab+"}"+(t||"")},b.prototype.pluckDirectCall=function(a,b){var c,e,f,h,i,k,l,m,n,o,p,q,r,s;e="",n=b.expressions;for(i=0,m=n.length;if.length+d.length)return""+this.tab+"if ("+f+") "+d.replace(/^\s+/,"");d&&(d="\n"+d+"\n"+this.tab),h="if ("+f+") {"+d+"}",e||(h=this.tab+h);if(!this.elseBody)return h;return h+" else "+(this.isChain?(a.indent=this.tab,a.chainChild=!0,this.elseBody.unwrap().compile(a,z)):"{\n"+this.elseBody.compile(a,z)+"\n"+this.tab+"}")},b.prototype.compileExpression=function(a){var b,c,d,e;e=this.condition.compile(a,v),c=this.bodyNode().compile(a,w),b=this.elseBodyNode()?this.elseBodyNode().compile(a,w):"void 0",d=""+e+" ? "+c+" : "+b;return a.level>=v?"("+d+")":d},b.prototype.unfoldSoak=function(){return this.soak&&this};return b}(e),i={wrap:function(a,c,d){var e,h,i,k,l;if(a.jumps())return a;i=new j([],f.wrap([a])),e=[];if((k=a.contains(this.literalArgs))||a.contains(this.literalThis))l=new A(k?"apply":"call"),e=[new A("this")],k&&e.push(new A("arguments")),i=new V(i,[new b(l)]);i.noReturn=d,h=new g(i,e);return c?f.wrap([h]):h},literalArgs:function(a){return a instanceof A&&a.value==="arguments"&&!a.asKey},literalThis:function(a){return a instanceof A&&a.value==="this"&&!a.asKey||a instanceof j&&a.bound}},bf=function(a,b,c){var d;if(!!(d=b[c].unfoldSoak(a))){b[c]=d.body,d.body=new V(b);return d}},U={"extends":function(){return"function(child, parent) { for (var key in parent) { if ("+bg("hasProp")+".call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor; child.__super__ = parent.prototype; return child; }"},bind:function(){return"function(fn, me){ return function(){ return fn.apply(me, arguments); }; }"},indexOf:function(){return"Array.prototype.indexOf || function(item) { for (var i = 0, l = this.length; i < l; i++) { if (i in this && this[i] === item) return i; } return -1; }"},hasProp:function(){return"Object.prototype.hasOwnProperty"},slice:function(){return"Array.prototype.slice"}},z=1,y=2,w=3,v=4,x=5,u=6,Q=" ",p="[$A-Za-z_\\x7f-\\uffff][$\\w\\x7f-\\uffff]*",o=RegExp("^"+p+"$"),L=/^[+-]?\d+$/,B=RegExp("^(?:("+p+")\\.prototype(?:\\.("+p+")|\\[(\"(?:[^\\\\\"\\r\\n]|\\\\.)*\"|'(?:[^\\\\'\\r\\n]|\\\\.)*')\\]|\\[(0x[\\da-fA-F]+|\\d*\\.?\\d+(?:[eE][+-]?\\d+)?)\\]))|("+p+")$"),q=/^['"]/,bg=function(a){var b;b="__"+a,M.root.assign(b,U[a]());return b},bd=function(a,b){a=a.replace(/\n/g,"$&"+b);return a.replace(/\s+$/,"")}}).call(this)},require["./coffee-script"]=new function(){var a=this;(function(){var b,c,d,e,f,g,h,i,j,k=Object.prototype.hasOwnProperty;e=require("fs"),h=require("path"),j=require("./lexer"),b=j.Lexer,c=j.RESERVED,g=require("./parser").parser,i=require("vm"),require.extensions?require.extensions[".coffee"]=function(a,b){var c;c=d(e.readFileSync(b,"utf8"),{filename:b});return a._compile(c,b)}:require.registerExtension&&require.registerExtension(".coffee",function(a){return d(a)}),a.VERSION="1.2.0",a.RESERVED=c,a.helpers=require("./helpers"),a.compile=d=function(b,c){var d;c==null&&(c={}),d=a.helpers.merge;try{return g.parse(f.tokenize(b)).compile(d({},c))}catch(e){c.filename&&(e.message="In "+c.filename+", "+e.message);throw e}},a.tokens=function(a,b){return f.tokenize(a,b)},a.nodes=function(a,b){return typeof a=="string"?g.parse(f.tokenize(a,b)):g.parse(a)},a.run=function(a,b){var c;c=require.main,c.filename=process.argv[1]=b.filename?e.realpathSync(b.filename):".",c.moduleCache&&(c.moduleCache={}),c.paths=require("module")._nodeModulePaths(h.dirname(b.filename));return h.extname(c.filename)!==".coffee"||require.extensions?c._compile(d(a,b),c.filename):c._compile(a,c.filename)},a.eval=function(a,b){var c,e,f,g,j,l,m,n,o,p,q,r,s,t;b==null&&(b={});if(!!(a=a.trim())){e=i.Script;if(e){if(b.sandbox!=null){if(b.sandbox instanceof e.createContext().constructor)m=b.sandbox;else{m=e.createContext(),r=b.sandbox;for(g in r){if(!k.call(r,g))continue;n=r[g],m[g]=n}}m.global=m.root=m.GLOBAL=m}else m=global;m.__filename=b.filename||"eval",m.__dirname=h.dirname(m.__filename);if(m===global&&!m.module&&!m.require){c=require("module"),m.module=q=new c(b.modulename||"eval"),m.require=t=function(a){return c._load(a,q,!0)},q.filename=m.__filename,s=Object.getOwnPropertyNames(require);for(o=0,p=s.length;o, targeting the Spidermonkey runtime. // // To run the tests, open mimeparse-js-test.html in a browser. // Ported from version 0.1.2 // Comments are mostly excerpted from the original. var Mimeparse = (function() { // private helpers function strip(string) { return string.replace(/^\s+/, '').replace(/\s+$/, ''); }; function parseRanges(ranges) { var parsedRanges = [], rangeParts = ranges.split(","); for (var i=0; i < rangeParts.length; i++) { parsedRanges.push(publicMethods.parseMediaRange(rangeParts[i])); }; return parsedRanges; }; var publicMethods = { // Carves up a mime-type and returns an Array of the // [type, subtype, params] where "params" is a Hash of all // the parameters for the media range. // // For example, the media range "application/xhtml;q=0.5" would // get parsed into: // // ["application", "xhtml", { "q" : "0.5" }] parseMimeType : function(mimeType) { var fullType, typeParts, params = {}, parts = mimeType.split(';'); for (var i=0; i < parts.length; i++) { var p = parts[i].split('='); if (p.length == 2) { params[strip(p[0])] = strip(p[1]); } }; fullType = parts[0].replace(/^\s+/, '').replace(/\s+$/, ''); if (fullType == '*') fullType = '*/*'; typeParts = fullType.split('/'); return [typeParts[0], typeParts[1], params]; }, // Carves up a media range and returns an Array of the // [type, subtype, params] where "params" is a Object with // all the parameters for the media range. // // For example, the media range "application/*;q=0.5" would // get parsed into: // // ["application", "*", { "q" : "0.5" }] // // In addition this function also guarantees that there // is a value for "q" in the params dictionary, filling it // in with a proper default if necessary. parseMediaRange : function(range) { var q, parsedType = this.parseMimeType(range); if (!parsedType[2]['q']) { parsedType[2]['q'] = '1'; } else { q = parseFloat(parsedType[2]['q']); if (isNaN(q)) { parsedType[2]['q'] = '1'; } else if (q > 1 || q < 0) { parsedType[2]['q'] = '1'; } } return parsedType; }, // Find the best match for a given mime-type against // a list of media_ranges that have already been // parsed by parseMediaRange(). Returns an array of // the fitness value and the value of the 'q' quality // parameter of the best match, or (-1, 0) if no match // was found. Just as for qualityParsed(), 'parsed_ranges' // must be a list of parsed media ranges. fitnessAndQualityParsed : function(mimeType, parsedRanges) { var bestFitness = -1, bestFitQ = 0, target = this.parseMediaRange(mimeType); var targetType = target[0], targetSubtype = target[1], targetParams = target[2]; for (var i=0; i < parsedRanges.length; i++) { var parsed = parsedRanges[i]; var type = parsed[0], subtype = parsed[1], params = parsed[2]; if ((type == targetType || type == "*" || targetType == "*") && (subtype == targetSubtype || subtype == "*" || targetSubtype == "*")) { var matchCount = 0; for (var param in targetParams) { if (param != 'q' && params[param] && params[param] == targetParams[param]) { matchCount += 1; } } var fitness = (type == targetType) ? 100 : 0; fitness += (subtype == targetSubtype) ? 10 : 0; fitness += matchCount; if (fitness > bestFitness) { bestFitness = fitness; bestFitQ = params["q"]; } } }; return [bestFitness, parseFloat(bestFitQ)]; }, // Find the best match for a given mime-type against // a list of media_ranges that have already been // parsed by parseMediaRange(). Returns the // 'q' quality parameter of the best match, 0 if no // match was found. This function bahaves the same as quality() // except that 'parsedRanges' must be a list of // parsed media ranges. qualityParsed : function(mimeType, parsedRanges) { return this.fitnessAndQualityParsed(mimeType, parsedRanges)[1]; }, // Returns the quality 'q' of a mime-type when compared // against the media-ranges in ranges. For example: // // >>> Mimeparse.quality('text/html','text/*;q=0.3, text/html;q=0.7, text/html;level=1, text/html;level=2;q=0.4, */*;q=0.5') // 0.7 quality : function(mimeType, ranges) { return this.qualityParsed(mimeType, parseRanges(ranges)); }, // Takes a list of supported mime-types and finds the best // match for all the media-ranges listed in header. The value of // header must be a string that conforms to the format of the // HTTP Accept: header. The value of 'supported' is a list of // mime-types. // // >>> bestMatch(['application/xbel+xml', 'text/xml'], 'text/*;q=0.5,*/*; q=0.1') // 'text/xml' bestMatch : function(supported, header) { var parsedHeader = parseRanges(header); var weighted = []; for (var i=0; i < supported.length; i++) { weighted.push([publicMethods.fitnessAndQualityParsed(supported[i], parsedHeader), i, supported[i]]); }; weighted.sort(); return weighted[weighted.length-1][0][1] ? weighted[weighted.length-1][2] : ''; } }; return publicMethods; })(); apache-couchdb-1.5.0/share/server/state.js0000644000175000001440000000203512230722213015340 00000000000000// 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. var State = { reset : function(config) { // clear the globals and run gc State.funs = []; State.lib = null; State.query_config = config || {}; init_sandbox(); gc(); print("true"); // indicates success }, addFun : function(newFun) { // Compile to a function and add it to funs array State.funs.push(Couch.compileFunction(newFun, {views : {lib : State.lib}})); print("true"); }, addLib : function(lib) { State.lib = lib; print("true"); } }; apache-couchdb-1.5.0/share/server/util.js0000644000175000001440000001263112230722213015200 00000000000000// 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. var resolveModule = function(names, mod, root) { if (names.length == 0) { if (typeof mod.current != "string") { throw ["error","invalid_require_path", 'Must require a JavaScript string, not: '+(typeof mod.current)]; } return { current : mod.current, parent : mod.parent, id : mod.id, exports : {} }; } // we need to traverse the path var n = names.shift(); if (n == '..') { if (!(mod.parent && mod.parent.parent)) { throw ["error", "invalid_require_path", 'Object has no parent '+JSON.stringify(mod.current)]; } return resolveModule(names, { id : mod.id.slice(0, mod.id.lastIndexOf('/')), parent : mod.parent.parent, current : mod.parent.current }); } else if (n == '.') { if (!mod.parent) { throw ["error", "invalid_require_path", 'Object has no parent '+JSON.stringify(mod.current)]; } return resolveModule(names, { parent : mod.parent, current : mod.current, id : mod.id }); } else if (root) { mod = {current : root}; } if (mod.current[n] === undefined) { throw ["error", "invalid_require_path", 'Object has no property "'+n+'". '+JSON.stringify(mod.current)]; } return resolveModule(names, { current : mod.current[n], parent : mod, id : mod.id ? mod.id + '/' + n : n }); }; var Couch = { // moving this away from global so we can move to json2.js later toJSON : function (val) { return JSON.stringify(val); }, compileFunction : function(source, ddoc, name) { if (!source) throw(["error","not_found","missing function"]); var evaluate_function_source = function(source, evalFunction, sandbox) { sandbox = sandbox || {}; if(typeof CoffeeScript === "undefined") { return evalFunction(source, sandbox, name); } else { var coffee = CoffeeScript.compile(source, {bare: true}); return evalFunction(coffee, sandbox, name); } } try { if (sandbox) { if (ddoc) { if (!ddoc._module_cache) { ddoc._module_cache = {}; } var require = function(name, module) { module = module || {}; var newModule = resolveModule(name.split('/'), module.parent, ddoc); if (!ddoc._module_cache.hasOwnProperty(newModule.id)) { // create empty exports object before executing the module, // stops circular requires from filling the stack ddoc._module_cache[newModule.id] = {}; var s = "function (module, exports, require) { " + newModule.current + "\n }"; try { var func = sandbox ? evalcx(s, sandbox, newModule.id) : eval(s); func.apply(sandbox, [newModule, newModule.exports, function(name) { return require(name, newModule); }]); } catch(e) { throw [ "error", "compilation_error", "Module require('" +name+ "') raised error " + (e.toSource ? e.toSource() : e.stack) ]; } ddoc._module_cache[newModule.id] = newModule.exports; } return ddoc._module_cache[newModule.id]; }; sandbox.require = require; } var functionObject = evaluate_function_source(source, evalcx, sandbox); } else { var functionObject = evaluate_function_source(source, eval); } } catch (err) { throw([ "error", "compilation_error", (err.toSource ? err.toSource() : err.stack) + " (" + source + ")" ]); }; if (typeof(functionObject) == "function") { return functionObject; } else { throw(["error","compilation_error", "Expression does not eval to a function. (" + source.toString() + ")"]); }; }, recursivelySeal : function(obj) { // seal() is broken in current Spidermonkey try { seal(obj); } catch (x) { // Sealing of arrays broken in some SpiderMonkey versions. // https://bugzilla.mozilla.org/show_bug.cgi?id=449657 } for (var propname in obj) { if (typeof obj[propname] == "object") { arguments.callee(obj[propname]); } } } }; // prints the object as JSON, and rescues and logs any toJSON() related errors function respond(obj) { try { print(Couch.toJSON(obj)); } catch(e) { log("Error converting object to JSON: " + e.toString()); log("error on obj: "+ (obj.toSource ? obj.toSource() : obj.toString())); } }; function log(message) { // idea: query_server_config option for log level if (typeof message == "xml") { message = message.toXMLString(); } else if (typeof message != "string") { message = Couch.toJSON(message); } respond(["log", String(message)]); }; function isArray(obj) { return toString.call(obj) === "[object Array]"; } apache-couchdb-1.5.0/share/server/render.js0000644000175000001440000002405012230722213015500 00000000000000// 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. var Mime = (function() { // registerType(name, mime-type, mime-type, ...) // // Available in query server sandbox. TODO: The list is cleared on reset. // This registers a particular name with the set of mimetypes it can handle. // Whoever registers last wins. // // Example: // registerType("html", "text/html; charset=utf-8"); var mimesByKey = {}; var keysByMime = {}; function registerType() { var mimes = [], key = arguments[0]; for (var i=1; i < arguments.length; i++) { mimes.push(arguments[i]); }; mimesByKey[key] = mimes; for (var i=0; i < mimes.length; i++) { keysByMime[mimes[i]] = key; }; } // Some default types // Ported from Ruby on Rails // Build list of Mime types for HTTP responses // http://www.iana.org/assignments/media-types/ // http://dev.rubyonrails.org/svn/rails/trunk/actionpack/lib/action_controller/mime_types.rb registerType("all", "*/*"); registerType("text", "text/plain; charset=utf-8", "txt"); registerType("html", "text/html; charset=utf-8"); registerType("xhtml", "application/xhtml+xml", "xhtml"); registerType("xml", "application/xml", "text/xml", "application/x-xml"); registerType("js", "text/javascript", "application/javascript", "application/x-javascript"); registerType("css", "text/css"); registerType("ics", "text/calendar"); registerType("csv", "text/csv"); registerType("rss", "application/rss+xml"); registerType("atom", "application/atom+xml"); registerType("yaml", "application/x-yaml", "text/yaml"); // just like Rails registerType("multipart_form", "multipart/form-data"); registerType("url_encoded_form", "application/x-www-form-urlencoded"); // http://www.ietf.org/rfc/rfc4627.txt registerType("json", "application/json", "text/x-json"); var mimeFuns = []; function provides(type, fun) { Mime.providesUsed = true; mimeFuns.push([type, fun]); }; function resetProvides() { // set globals Mime.providesUsed = false; mimeFuns = []; Mime.responseContentType = null; }; function runProvides(req, ddoc) { var supportedMimes = [], bestFun, bestKey = null, accept = req.headers["Accept"]; if (req.query && req.query.format) { bestKey = req.query.format; Mime.responseContentType = mimesByKey[bestKey][0]; } else if (accept) { // log("using accept header: "+accept); mimeFuns.reverse().forEach(function(mimeFun) { var mimeKey = mimeFun[0]; if (mimesByKey[mimeKey]) { supportedMimes = supportedMimes.concat(mimesByKey[mimeKey]); } }); Mime.responseContentType = Mimeparse.bestMatch(supportedMimes, accept); bestKey = keysByMime[Mime.responseContentType]; } else { // just do the first one bestKey = mimeFuns[0][0]; Mime.responseContentType = mimesByKey[bestKey][0]; } if (bestKey) { for (var i=0; i < mimeFuns.length; i++) { if (mimeFuns[i][0] == bestKey) { bestFun = mimeFuns[i][1]; break; } }; }; if (bestFun) { return bestFun.call(ddoc); } else { var supportedTypes = mimeFuns.map(function(mf) { return mimesByKey[mf[0]].join(', ') || mf[0]; }); throw(["error","not_acceptable", "Content-Type "+(accept||bestKey)+" not supported, try one of: "+supportedTypes.join(', ')]); } }; return { registerType : registerType, provides : provides, resetProvides : resetProvides, runProvides : runProvides }; })(); //// //// Render dispatcher //// //// //// //// var Render = (function() { var new_header = false; var chunks = []; // Start chunks var startResp = {}; function start(resp) { startResp = resp || {}; new_header = true; }; function sendStart() { startResp = applyContentType((startResp || {}), Mime.responseContentType); respond(["start", chunks, startResp]); chunks = []; startResp = {}; new_header = false; } function applyContentType(resp, responseContentType) { resp["headers"] = resp["headers"] || {}; if (responseContentType) { resp["headers"]["Content-Type"] = resp["headers"]["Content-Type"] || responseContentType; } return resp; } function send(chunk) { chunks.push(chunk.toString()); }; function blowChunks(label) { if (new_header) { respond([label||"chunks", chunks, startResp]); new_header = false; } else { respond([label||"chunks", chunks]); } chunks = []; }; var gotRow = false, lastRow = false; function getRow() { if (lastRow) return null; if (!gotRow) { gotRow = true; sendStart(); } else { blowChunks(); } var json = JSON.parse(readline()); if (json[0] == "list_end") { lastRow = true; return null; } if (json[0] != "list_row") { throw(["fatal", "list_error", "not a row '" + json[0] + "'"]); } return json[1]; }; function maybeWrapResponse(resp) { var type = typeof resp; if ((type == "string") || (type == "xml")) { return {body:resp}; } else { return resp; } }; // from http://javascript.crockford.com/remedial.html function typeOf(value) { var s = typeof value; if (s === 'object') { if (value) { if (value instanceof Array) { s = 'array'; } } else { s = 'null'; } } return s; }; function isDocRequestPath(info) { var path = info.path; return path.length > 5; }; function runShow(fun, ddoc, args) { try { resetList(); Mime.resetProvides(); var resp = fun.apply(ddoc, args) || {}; resp = maybeWrapResponse(resp); // handle list() style API if (chunks.length && chunks.length > 0) { resp.headers = resp.headers || {}; for(var header in startResp) { resp.headers[header] = startResp[header]; } resp.body = chunks.join("") + (resp.body || ""); resetList(); } if (Mime.providesUsed) { var provided_resp = Mime.runProvides(args[1], ddoc) || {}; provided_resp = maybeWrapResponse(provided_resp); resp.body = (resp.body || "") + chunks.join(""); resp.body += provided_resp.body || ""; resp = applyContentType(resp, Mime.responseContentType); resetList(); } var type = typeOf(resp); if (type == 'object' || type == 'string') { respond(["resp", maybeWrapResponse(resp)]); } else { throw(["error", "render_error", "undefined response from show function"]); } } catch(e) { if (args[0] === null && isDocRequestPath(args[1])) { throw(["error", "not_found", "document not found"]); } else { renderError(e, fun.toString()); } } }; function runUpdate(fun, ddoc, args) { try { var method = args[1].method; // for analytics logging applications you might want to remove the next line if (method == "GET") throw(["error","method_not_allowed","Update functions do not allow GET"]); var result = fun.apply(ddoc, args); var doc = result[0]; var resp = result[1]; var type = typeOf(resp); if (type == 'object' || type == 'string') { respond(["up", doc, maybeWrapResponse(resp)]); } else { throw(["error", "render_error", "undefined response from update function"]); } } catch(e) { renderError(e, fun.toString()); } }; function resetList() { gotRow = false; lastRow = false; chunks = []; startResp = {}; new_header = false; }; function runList(listFun, ddoc, args) { try { Mime.resetProvides(); resetList(); var head = args[0]; var req = args[1]; var tail = listFun.apply(ddoc, args); if (Mime.providesUsed) { tail = Mime.runProvides(req, ddoc); } if (!gotRow) getRow(); if (typeof tail != "undefined") { chunks.push(tail); } blowChunks("end"); } catch(e) { renderError(e, listFun.toString()); } }; function renderError(e, funSrc) { if (e.error && e.reason || e[0] == "error" || e[0] == "fatal") { throw(e); } else { var logMessage = "function raised error: " + (e.toSource ? e.toSource() : e.toString()) + " \n" + "stacktrace: " + e.stack; log(logMessage); throw(["error", "render_error", logMessage]); } }; function escapeHTML(string) { return string && string.replace(/&/g, "&") .replace(//g, ">"); }; return { start : start, send : send, getRow : getRow, show : function(fun, ddoc, args) { // var showFun = Couch.compileFunction(funSrc); runShow(fun, ddoc, args); }, update : function(fun, ddoc, args) { // var upFun = Couch.compileFunction(funSrc); runUpdate(fun, ddoc, args); }, list : function(fun, ddoc, args) { runList(fun, ddoc, args); } }; })(); // send = Render.send; // getRow = Render.getRow; // start = Render.start; // unused. this will be handled in the Erlang side of things. // function htmlRenderError(e, funSrc) { // var msg = ["

    Render Error

    ", // "

    JavaScript function raised error: ", // e.toString(), // "

    Stacktrace:

    ",
    //     escapeHTML(e.stack),
    //     "

    Function source:

    ",
    //     escapeHTML(funSrc),
    //     "
    "].join(''); // return {body:msg}; // }; apache-couchdb-1.5.0/share/server/validate.js0000644000175000001440000000143212230722213016011 00000000000000// 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. var Validate = { validate : function(fun, ddoc, args) { try { fun.apply(ddoc, args); respond(1); } catch (error) { if (error.name && error.stack) { throw error; } respond(error); } } }; apache-couchdb-1.5.0/share/server/views.js0000644000175000001440000001075712230722213015367 00000000000000// 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. var Views = (function() { var map_results = []; // holds temporary emitted values during doc map function runReduce(reduceFuns, keys, values, rereduce) { for (var i in reduceFuns) { reduceFuns[i] = Couch.compileFunction(reduceFuns[i]); }; var reductions = new Array(reduceFuns.length); for(var i = 0; i < reduceFuns.length; i++) { try { reductions[i] = reduceFuns[i](keys, values, rereduce); } catch (err) { handleViewError(err); // if the error is not fatal, ignore the results and continue reductions[i] = null; } }; var reduce_line = Couch.toJSON(reductions); var reduce_length = reduce_line.length; // TODO make reduce_limit config into a number if (State.query_config && State.query_config.reduce_limit && reduce_length > 200 && ((reduce_length * 2) > State.line_length)) { var reduce_preview = "Current output: '"+(reduce_line.substring(0,100) + "'... (first 100 of "+reduce_length+" bytes)"); throw(["error", "reduce_overflow_error", "Reduce output must shrink more rapidly: "+reduce_preview]); } else { print("[true," + reduce_line + "]"); } }; function handleViewError(err, doc) { if (err == "fatal_error") { // Only if it's a "fatal_error" do we exit. What's a fatal error? // That's for the query to decide. // // This will make it possible for queries to completely error out, // by catching their own local exception and rethrowing a // fatal_error. But by default if they don't do error handling we // just eat the exception and carry on. // // In this case we abort map processing but don't destroy the // JavaScript process. If you need to destroy the JavaScript // process, throw the error form matched by the block below. throw(["error", "map_runtime_error", "function raised 'fatal_error'"]); } else if (err[0] == "fatal") { // Throwing errors of the form ["fatal","error_key","reason"] // will kill the OS process. This is not normally what you want. throw(err); } var message = "function raised exception " + (err.toSource ? err.toSource() : err.stack); if (doc) message += " with doc._id " + doc._id; log(message); }; return { // view helper functions emit : function(key, value) { map_results.push([key, value]); }, sum : function(values) { var rv = 0; for (var i in values) { rv += values[i]; } return rv; }, reduce : function(reduceFuns, kvs) { var keys = new Array(kvs.length); var values = new Array(kvs.length); for(var i = 0; i < kvs.length; i++) { keys[i] = kvs[i][0]; values[i] = kvs[i][1]; } runReduce(reduceFuns, keys, values, false); }, rereduce : function(reduceFuns, values) { runReduce(reduceFuns, null, values, true); }, mapDoc : function(doc) { // Compute all the map functions against the document. // // Each function can output multiple key/value pairs for each document. // // Example output of map_doc after three functions set by add_fun cmds: // [ // [["Key","Value"]], <- fun 1 returned 1 key value // [], <- fun 2 returned 0 key values // [["Key1","Value1"],["Key2","Value2"]] <- fun 3 returned 2 key values // ] // Couch.recursivelySeal(doc); var buf = []; for (var i = 0; i < State.funs.length; i++) { map_results = []; try { State.funs[i](doc); buf.push(Couch.toJSON(map_results)); } catch (err) { handleViewError(err, doc); // If the error is not fatal, we treat the doc as if it // did not emit anything, by buffering an empty array. buf.push("[]"); } } print("[" + buf.join(", ") + "]"); } }; })(); apache-couchdb-1.5.0/utils/0000755000175000001440000000000012230722613012476 500000000000000apache-couchdb-1.5.0/utils/Makefile.am0000644000175000001440000000354012230722213014450 00000000000000## 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. noinst_SCRIPTS = run CLEANFILES = $(noinst_SCRIPTS) transform = @program_transform_name@ couchdb_command_name = `echo couchdb | sed '$(transform)'` run: ../bin/couchdb.tpl sed -e "s|%ERL%|$(ERL)|g" \ -e "s|%ICU_CONFIG%|$(ICU_CONFIG)|g" \ -e "s|%bindir%|$(abs_top_builddir)/bin|g" \ -e "s|%defaultini%|default_dev.ini|g" \ -e "s|%localini%|local_dev.ini|g" \ -e "s|%localerlanglibdir%|$(abs_top_builddir)\/src \ -pa $(abs_top_builddir)\/src\/couchdb \ -pa $(abs_top_builddir)\/src\/ejson \ -pa $(abs_top_builddir)\/src\/erlang-oauth \ -pa $(abs_top_builddir)\/src\/ibrowse \ -pa $(abs_top_builddir)\/src\/mochiweb \ -pa $(abs_top_builddir)\/src\/snappy|g" \ -e "s|%localconfdir%|$(abs_top_builddir)/etc/couchdb|g" \ -e "s|%localstatelogdir%|$(abs_top_builddir)/tmp/log|g" \ -e "s|%localstatelibdir%|$(abs_top_builddir)/tmp/lib|g" \ -e "s|%localstatedir%|$(abs_top_builddir)/tmp|g" \ -e "s|%locallibdir%|$(abs_top_builddir)/tmp|g" \ -e "s|%bug_uri%|@bug_uri@|g" \ -e "s|%package_author_address%|@package_author_address@|g" \ -e "s|%package_author_name%|@package_author_name@|g" \ -e "s|%package_name%|@package_name@|g" \ -e "s|%version%|@version@|g" \ -e "s|%couchdb_command_name%|$(couchdb_command_name)|g" > \ $@ < $< chmod +x $@ apache-couchdb-1.5.0/utils/Makefile.in0000644000175000001440000003263612230722245014476 00000000000000# Makefile.in generated by automake 1.11.6 from Makefile.am. # @configure_input@ # Copyright (C) 1994, 1995, 1996, 1997, 1998, 1999, 2000, 2001, 2002, # 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011 Free Software # Foundation, Inc. # This Makefile.in is free software; the Free Software Foundation # gives unlimited permission to copy and/or distribute it, # with or without modifications, as long as this notice is preserved. # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY, to the extent permitted by law; without # even the implied warranty of MERCHANTABILITY or FITNESS FOR A # PARTICULAR PURPOSE. @SET_MAKE@ VPATH = @srcdir@ am__make_dryrun = \ { \ am__dry=no; \ case $$MAKEFLAGS in \ *\\[\ \ ]*) \ echo 'am--echo: ; @echo "AM" OK' | $(MAKE) -f - 2>/dev/null \ | grep '^AM OK$$' >/dev/null || am__dry=yes;; \ *) \ for am__flg in $$MAKEFLAGS; do \ case $$am__flg in \ *=*|--*) ;; \ *n*) am__dry=yes; break;; \ esac; \ done;; \ esac; \ test $$am__dry = yes; \ } pkgdatadir = $(datadir)/@PACKAGE@ pkgincludedir = $(includedir)/@PACKAGE@ pkglibdir = $(libdir)/@PACKAGE@ pkglibexecdir = $(libexecdir)/@PACKAGE@ am__cd = CDPATH="$${ZSH_VERSION+.}$(PATH_SEPARATOR)" && cd install_sh_DATA = $(install_sh) -c -m 644 install_sh_PROGRAM = $(install_sh) -c install_sh_SCRIPT = $(install_sh) -c INSTALL_HEADER = $(INSTALL_DATA) NORMAL_INSTALL = : PRE_INSTALL = : POST_INSTALL = : NORMAL_UNINSTALL = : PRE_UNINSTALL = : POST_UNINSTALL = : build_triplet = @build@ host_triplet = @host@ subdir = utils DIST_COMMON = $(srcdir)/Makefile.am $(srcdir)/Makefile.in ACLOCAL_M4 = $(top_srcdir)/aclocal.m4 am__aclocal_m4_deps = $(top_srcdir)/m4/libtool.m4 \ $(top_srcdir)/m4/ltoptions.m4 $(top_srcdir)/m4/ltsugar.m4 \ $(top_srcdir)/m4/ltversion.m4 $(top_srcdir)/m4/lt~obsolete.m4 \ $(top_srcdir)/acinclude.m4 $(top_srcdir)/configure.ac am__configure_deps = $(am__aclocal_m4_deps) $(CONFIGURE_DEPENDENCIES) \ $(ACLOCAL_M4) mkinstalldirs = $(install_sh) -d CONFIG_HEADER = $(top_builddir)/config.h \ $(top_builddir)/src/snappy/google-snappy/config.h CONFIG_CLEAN_FILES = CONFIG_CLEAN_VPATH_FILES = SCRIPTS = $(noinst_SCRIPTS) SOURCES = DIST_SOURCES = am__can_run_installinfo = \ case $$AM_UPDATE_INFO_DIR in \ n|no|NO) false;; \ *) (install-info --version) >/dev/null 2>&1;; \ esac DISTFILES = $(DIST_COMMON) $(DIST_SOURCES) $(TEXINFOS) $(EXTRA_DIST) transform = @program_transform_name@ ACLOCAL = @ACLOCAL@ AMTAR = @AMTAR@ AR = @AR@ AS = @AS@ AUTOCONF = @AUTOCONF@ AUTOHEADER = @AUTOHEADER@ AUTOMAKE = @AUTOMAKE@ AWK = @AWK@ CC = @CC@ CCDEPMODE = @CCDEPMODE@ CFLAGS = @CFLAGS@ CPP = @CPP@ CPPFLAGS = @CPPFLAGS@ CURL_CFLAGS = @CURL_CFLAGS@ CURL_CONFIG = @CURL_CONFIG@ CURL_LIBS = @CURL_LIBS@ CXX = @CXX@ CXXCPP = @CXXCPP@ CXXDEPMODE = @CXXDEPMODE@ CXXFLAGS = @CXXFLAGS@ CYGPATH_W = @CYGPATH_W@ DEFS = @DEFS@ DEPDIR = @DEPDIR@ DLLTOOL = @DLLTOOL@ DSYMUTIL = @DSYMUTIL@ DUMPBIN = @DUMPBIN@ ECHO_C = @ECHO_C@ ECHO_N = @ECHO_N@ ECHO_T = @ECHO_T@ EGREP = @EGREP@ ERL = @ERL@ ERLANG_FLAGS = @ERLANG_FLAGS@ ERLC = @ERLC@ ERLC_FLAGS = @ERLC_FLAGS@ ESCRIPT = @ESCRIPT@ EXEEXT = @EXEEXT@ FGREP = @FGREP@ FLAGS = @FLAGS@ GREP = @GREP@ HAS_HELP2MAN = @HAS_HELP2MAN@ HAS_INSTALLINFO = @HAS_INSTALLINFO@ HAS_MAKEINFO = @HAS_MAKEINFO@ HAS_PDFLATEX = @HAS_PDFLATEX@ HAS_SPHINX_BUILD = @HAS_SPHINX_BUILD@ ICU_BIN = @ICU_BIN@ ICU_CFLAGS = @ICU_CFLAGS@ ICU_CONFIG = @ICU_CONFIG@ ICU_CPPFLAGS = @ICU_CPPFLAGS@ ICU_CXXFLAGS = @ICU_CXXFLAGS@ ICU_LIBS = @ICU_LIBS@ INNO_COMPILER_EXECUTABLE = @INNO_COMPILER_EXECUTABLE@ INSTALL = @INSTALL@ INSTALL_DATA = @INSTALL_DATA@ INSTALL_PROGRAM = @INSTALL_PROGRAM@ INSTALL_SCRIPT = @INSTALL_SCRIPT@ INSTALL_STRIP_PROGRAM = @INSTALL_STRIP_PROGRAM@ JS_CFLAGS = @JS_CFLAGS@ JS_LIBS = @JS_LIBS@ JS_LIB_BINARY = @JS_LIB_BINARY@ LD = @LD@ LDFLAGS = @LDFLAGS@ LIBOBJS = @LIBOBJS@ LIBS = @LIBS@ LIBTOOL = @LIBTOOL@ LIPO = @LIPO@ LN_S = @LN_S@ LTLIBOBJS = @LTLIBOBJS@ MAKEINFO = @MAKEINFO@ MANIFEST_TOOL = @MANIFEST_TOOL@ MKDIR_P = @MKDIR_P@ NM = @NM@ NMEDIT = @NMEDIT@ OBJDUMP = @OBJDUMP@ OBJEXT = @OBJEXT@ OTOOL = @OTOOL@ OTOOL64 = @OTOOL64@ PACKAGE = @PACKAGE@ PACKAGE_BUGREPORT = @PACKAGE_BUGREPORT@ PACKAGE_NAME = @PACKAGE_NAME@ PACKAGE_STRING = @PACKAGE_STRING@ PACKAGE_TARNAME = @PACKAGE_TARNAME@ PACKAGE_URL = @PACKAGE_URL@ PACKAGE_VERSION = @PACKAGE_VERSION@ PATH_SEPARATOR = @PATH_SEPARATOR@ PKG_CONFIG = @PKG_CONFIG@ PKG_CONFIG_LIBDIR = @PKG_CONFIG_LIBDIR@ PKG_CONFIG_PATH = @PKG_CONFIG_PATH@ RANLIB = @RANLIB@ SED = @SED@ SET_MAKE = @SET_MAKE@ SHELL = @SHELL@ SNAPPY_MAJOR = @SNAPPY_MAJOR@ SNAPPY_MINOR = @SNAPPY_MINOR@ SNAPPY_PATCHLEVEL = @SNAPPY_PATCHLEVEL@ STRIP = @STRIP@ VERSION = @VERSION@ abs_builddir = @abs_builddir@ abs_srcdir = @abs_srcdir@ abs_top_builddir = @abs_top_builddir@ abs_top_srcdir = @abs_top_srcdir@ ac_ct_AR = @ac_ct_AR@ ac_ct_CC = @ac_ct_CC@ ac_ct_CXX = @ac_ct_CXX@ ac_ct_DUMPBIN = @ac_ct_DUMPBIN@ ac_cv_have_stddef_h = @ac_cv_have_stddef_h@ ac_cv_have_stdint_h = @ac_cv_have_stdint_h@ am__include = @am__include@ am__leading_dot = @am__leading_dot@ am__quote = @am__quote@ am__tar = @am__tar@ am__untar = @am__untar@ bindir = @bindir@ bug_uri = @bug_uri@ build = @build@ build_alias = @build_alias@ build_cpu = @build_cpu@ build_os = @build_os@ build_vendor = @build_vendor@ builddir = @builddir@ datadir = @datadir@ datarootdir = @datarootdir@ docdir = @docdir@ dvidir = @dvidir@ erlangbin = @erlangbin@ erlangversion = @erlangversion@ exec_prefix = @exec_prefix@ host = @host@ host_alias = @host_alias@ host_cpu = @host_cpu@ host_os = @host_os@ host_vendor = @host_vendor@ htmldir = @htmldir@ includedir = @includedir@ infodir = @infodir@ initdir = @initdir@ install_sh = @install_sh@ launchddir = @launchddir@ libdir = @libdir@ libexecdir = @libexecdir@ localconfdir = @localconfdir@ localdatadir = @localdatadir@ localdocdir = @localdocdir@ localedir = @localedir@ localerlanglibdir = @localerlanglibdir@ locallibbindir = @locallibbindir@ locallibdir = @locallibdir@ localstatedir = @localstatedir@ localstatelibdir = @localstatelibdir@ localstatelogdir = @localstatelogdir@ localstaterundir = @localstaterundir@ mandir = @mandir@ mkdir_p = @mkdir_p@ msvc_redist_dir = @msvc_redist_dir@ msvc_redist_name = @msvc_redist_name@ oldincludedir = @oldincludedir@ openssl_bin_dir = @openssl_bin_dir@ otp_release = @otp_release@ package_author_address = @package_author_address@ package_author_name = @package_author_name@ package_identifier = @package_identifier@ package_name = @package_name@ package_tarname = @package_tarname@ pdfdir = @pdfdir@ prefix = @prefix@ program_transform_name = @program_transform_name@ psdir = @psdir@ sbindir = @sbindir@ sharedstatedir = @sharedstatedir@ srcdir = @srcdir@ sysconfdir = @sysconfdir@ target_alias = @target_alias@ top_build_prefix = @top_build_prefix@ top_builddir = @top_builddir@ top_srcdir = @top_srcdir@ version = @version@ version_major = @version_major@ version_minor = @version_minor@ version_release = @version_release@ version_revision = @version_revision@ version_stage = @version_stage@ noinst_SCRIPTS = run CLEANFILES = $(noinst_SCRIPTS) couchdb_command_name = `echo couchdb | sed '$(transform)'` all: all-am .SUFFIXES: $(srcdir)/Makefile.in: $(srcdir)/Makefile.am $(am__configure_deps) @for dep in $?; do \ case '$(am__configure_deps)' in \ *$$dep*) \ ( cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh ) \ && { if test -f $@; then exit 0; else break; fi; }; \ exit 1;; \ esac; \ done; \ echo ' cd $(top_srcdir) && $(AUTOMAKE) --foreign utils/Makefile'; \ $(am__cd) $(top_srcdir) && \ $(AUTOMAKE) --foreign utils/Makefile .PRECIOUS: Makefile Makefile: $(srcdir)/Makefile.in $(top_builddir)/config.status @case '$?' in \ *config.status*) \ cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh;; \ *) \ echo ' cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ $(am__depfiles_maybe)'; \ cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ $(am__depfiles_maybe);; \ esac; $(top_builddir)/config.status: $(top_srcdir)/configure $(CONFIG_STATUS_DEPENDENCIES) cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh $(top_srcdir)/configure: $(am__configure_deps) cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh $(ACLOCAL_M4): $(am__aclocal_m4_deps) cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh $(am__aclocal_m4_deps): mostlyclean-libtool: -rm -f *.lo clean-libtool: -rm -rf .libs _libs tags: TAGS TAGS: ctags: CTAGS CTAGS: distdir: $(DISTFILES) @srcdirstrip=`echo "$(srcdir)" | sed 's/[].[^$$\\*]/\\\\&/g'`; \ topsrcdirstrip=`echo "$(top_srcdir)" | sed 's/[].[^$$\\*]/\\\\&/g'`; \ list='$(DISTFILES)'; \ dist_files=`for file in $$list; do echo $$file; done | \ sed -e "s|^$$srcdirstrip/||;t" \ -e "s|^$$topsrcdirstrip/|$(top_builddir)/|;t"`; \ case $$dist_files in \ */*) $(MKDIR_P) `echo "$$dist_files" | \ sed '/\//!d;s|^|$(distdir)/|;s,/[^/]*$$,,' | \ sort -u` ;; \ esac; \ for file in $$dist_files; do \ if test -f $$file || test -d $$file; then d=.; else d=$(srcdir); fi; \ if test -d $$d/$$file; then \ dir=`echo "/$$file" | sed -e 's,/[^/]*$$,,'`; \ if test -d "$(distdir)/$$file"; then \ find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} \;; \ fi; \ if test -d $(srcdir)/$$file && test $$d != $(srcdir); then \ cp -fpR $(srcdir)/$$file "$(distdir)$$dir" || exit 1; \ find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} \;; \ fi; \ cp -fpR $$d/$$file "$(distdir)$$dir" || exit 1; \ else \ test -f "$(distdir)/$$file" \ || cp -p $$d/$$file "$(distdir)/$$file" \ || exit 1; \ fi; \ done check-am: all-am check: check-am all-am: Makefile $(SCRIPTS) installdirs: install: install-am install-exec: install-exec-am install-data: install-data-am uninstall: uninstall-am install-am: all-am @$(MAKE) $(AM_MAKEFLAGS) install-exec-am install-data-am installcheck: installcheck-am install-strip: if test -z '$(STRIP)'; then \ $(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(INSTALL_STRIP_PROGRAM)" \ install_sh_PROGRAM="$(INSTALL_STRIP_PROGRAM)" INSTALL_STRIP_FLAG=-s \ install; \ else \ $(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(INSTALL_STRIP_PROGRAM)" \ install_sh_PROGRAM="$(INSTALL_STRIP_PROGRAM)" INSTALL_STRIP_FLAG=-s \ "INSTALL_PROGRAM_ENV=STRIPPROG='$(STRIP)'" install; \ fi mostlyclean-generic: clean-generic: -test -z "$(CLEANFILES)" || rm -f $(CLEANFILES) distclean-generic: -test -z "$(CONFIG_CLEAN_FILES)" || rm -f $(CONFIG_CLEAN_FILES) -test . = "$(srcdir)" || test -z "$(CONFIG_CLEAN_VPATH_FILES)" || rm -f $(CONFIG_CLEAN_VPATH_FILES) maintainer-clean-generic: @echo "This command is intended for maintainers to use" @echo "it deletes files that may require special tools to rebuild." clean: clean-am clean-am: clean-generic clean-libtool mostlyclean-am distclean: distclean-am -rm -f Makefile distclean-am: clean-am distclean-generic dvi: dvi-am dvi-am: html: html-am html-am: info: info-am info-am: install-data-am: install-dvi: install-dvi-am install-dvi-am: install-exec-am: install-html: install-html-am install-html-am: install-info: install-info-am install-info-am: install-man: install-pdf: install-pdf-am install-pdf-am: install-ps: install-ps-am install-ps-am: installcheck-am: maintainer-clean: maintainer-clean-am -rm -f Makefile maintainer-clean-am: distclean-am maintainer-clean-generic mostlyclean: mostlyclean-am mostlyclean-am: mostlyclean-generic mostlyclean-libtool pdf: pdf-am pdf-am: ps: ps-am ps-am: uninstall-am: .MAKE: install-am install-strip .PHONY: all all-am check check-am clean clean-generic clean-libtool \ distclean distclean-generic distclean-libtool distdir dvi \ dvi-am html html-am info info-am install install-am \ install-data install-data-am install-dvi install-dvi-am \ install-exec install-exec-am install-html install-html-am \ install-info install-info-am install-man install-pdf \ install-pdf-am install-ps install-ps-am install-strip \ installcheck installcheck-am installdirs maintainer-clean \ maintainer-clean-generic mostlyclean mostlyclean-generic \ mostlyclean-libtool pdf pdf-am ps ps-am uninstall uninstall-am run: ../bin/couchdb.tpl sed -e "s|%ERL%|$(ERL)|g" \ -e "s|%ICU_CONFIG%|$(ICU_CONFIG)|g" \ -e "s|%bindir%|$(abs_top_builddir)/bin|g" \ -e "s|%defaultini%|default_dev.ini|g" \ -e "s|%localini%|local_dev.ini|g" \ -e "s|%localerlanglibdir%|$(abs_top_builddir)\/src \ -pa $(abs_top_builddir)\/src\/couchdb \ -pa $(abs_top_builddir)\/src\/ejson \ -pa $(abs_top_builddir)\/src\/erlang-oauth \ -pa $(abs_top_builddir)\/src\/ibrowse \ -pa $(abs_top_builddir)\/src\/mochiweb \ -pa $(abs_top_builddir)\/src\/snappy|g" \ -e "s|%localconfdir%|$(abs_top_builddir)/etc/couchdb|g" \ -e "s|%localstatelogdir%|$(abs_top_builddir)/tmp/log|g" \ -e "s|%localstatelibdir%|$(abs_top_builddir)/tmp/lib|g" \ -e "s|%localstatedir%|$(abs_top_builddir)/tmp|g" \ -e "s|%locallibdir%|$(abs_top_builddir)/tmp|g" \ -e "s|%bug_uri%|@bug_uri@|g" \ -e "s|%package_author_address%|@package_author_address@|g" \ -e "s|%package_author_name%|@package_author_name@|g" \ -e "s|%package_name%|@package_name@|g" \ -e "s|%version%|@version@|g" \ -e "s|%couchdb_command_name%|$(couchdb_command_name)|g" > \ $@ < $< chmod +x $@ # Tell versions [3.59,3.63) of GNU make to not export all variables. # Otherwise a system limit (for SysV at least) may be exceeded. .NOEXPORT: apache-couchdb-1.5.0/THANKS0000644000175000001440000001342312230722214012171 00000000000000Apache CouchDB THANKS ===================== A number of people have contributed to Apache CouchDB by reporting problems, suggesting improvements or submitting changes. Some of these people are: * William Beh * Dirk Schalge * Roger Leigh * Sam Ruby * Carlos Valiente * Till Klampaeckel * Jim Lindley * Yoan Blanc * Michael Gottesman * Mark Baran * Michael Hendricks * Antony Blakey * Paul Carey * Hunter Morris * Brian Palmer * Maximillian Dornseif * Eric Casteleijn * Maarten Thibaut * Florian Ebeling * Volker Mische * Brian Candler * Brad Anderson * Nick Gerakines * Kevin Ilchmann JĆørgensen * Sebastian Cohnen * Sven Helmberger * Dan Walters * Curt Arnold * Gustavo Niemeyer * Joshua Bronson * Kostis Sagonas * Matthew Hooker * Ilia Cheishvili * Lena Herrmann * Jack Moffit * Damjan Georgievski * Jan Kassens * James Marca * Matt Goodall * Joel Clark * Matt Lyon * mikeal * Joscha Feth * Jarrod Roberson * Jae Kwon * Gavin Sherry * Timothy Smith * Martin Haaß * Hans Ulrich Niedermann * Dmitry Unkovsky * Zachary Zolton * Brian Jenkins * Paul Bonser * Caleb Land * Juhani RƤnkimies * Kev Jackson * Jonathan D. Knezek * David Rose * Lim Yue Chuan * David Davis * Klaus Trainer * Juuso VƤƤnƤnen * Jeff Zellner * Benjamin Young * Gabriel Farrell * Mike Leddy * Wayne Conrad * Thomas Vander Stichele * Felix Hummel * Tim Smith * Dipesh Patel * Sam Bisbee * Nathan Vander Wilt * Caolan McMahon * Andrey Somov * Chris Coulson * Trond Norbye * Christopher Bonhage * Christian Carter * Lukasz Mielicki * Omar Yasin * Simon Leblanc * Rogutės Sparnuotos * Gavin McDonald * Fedor Indutny * Tim Blair * Tady Walsh * Sam Rijs * Adam Kocoloski * Adam Lofts * Alexander Dorofeev * Alexander Shorin * Andrey Somov * Anthony S Baker * Ben Reser * Benjamin Nortier * Bob Dionne * Bob Ippolito * Caleb Case * Christopher Bonhage * Dale Harvey * Damjan Georgievski * Dirkjan Ochtman * Dustin Sallings * Ewan McDougall * Fedor Indutny * Filippo Fadda 107 Garren Smith * Jakub * Jason Smith (work) * Jason Smith (work) * Jason Smith (work) * Joel Reed * Johannes J. Schmidt * Keks Keksov * Klaus Trainer * Magnus Hoff * Martin Higham * Michael Jackson * Michael Rhodes * Michael Wallace * Mike McKay * Mike Wallace * NickNorth * Paul J. Davis * Paul Mietz Egli * Peter Lemenkov * Robin Berjon * Ronny Pfannschmidt 91 Russell Branca * Ryan Ramage 74 Simon Metson 10 Simon Metson * Sriram Melkote * Stefan Kƶgl * Sven Lito * Volker Mische * Wei Cao * Wendall Cada * nvdev * sean barclay 54 suelockwood For a list of authors see the `AUTHORS` file. apache-couchdb-1.5.0/configure0000755000175000001440000242746012230722247013207 00000000000000#! /bin/sh # From configure.ac 1.5.0. # Guess values for system-dependent variables and create Makefiles. # Generated by GNU Autoconf 2.69 for Apache CouchDB 1.5.0. # # Report bugs to . # # # Copyright (C) 1992-1996, 1998-2012 Free Software Foundation, Inc. # # # This configure script is free software; the Free Software Foundation # gives unlimited permission to copy, distribute and modify it. ## -------------------- ## ## M4sh Initialization. ## ## -------------------- ## # Be more Bourne compatible DUALCASE=1; export DUALCASE # for MKS sh if test -n "${ZSH_VERSION+set}" && (emulate sh) >/dev/null 2>&1; then : emulate sh NULLCMD=: # Pre-4.2 versions of Zsh do word splitting on ${1+"$@"}, which # is contrary to our usage. Disable this feature. alias -g '${1+"$@"}'='"$@"' setopt NO_GLOB_SUBST else case `(set -o) 2>/dev/null` in #( *posix*) : set -o posix ;; #( *) : ;; esac fi as_nl=' ' export as_nl # Printing a long string crashes Solaris 7 /usr/bin/printf. as_echo='\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\' as_echo=$as_echo$as_echo$as_echo$as_echo$as_echo as_echo=$as_echo$as_echo$as_echo$as_echo$as_echo$as_echo # Prefer a ksh shell builtin over an external printf program on Solaris, # but without wasting forks for bash or zsh. if test -z "$BASH_VERSION$ZSH_VERSION" \ && (test "X`print -r -- $as_echo`" = "X$as_echo") 2>/dev/null; then as_echo='print -r --' as_echo_n='print -rn --' elif (test "X`printf %s $as_echo`" = "X$as_echo") 2>/dev/null; then as_echo='printf %s\n' as_echo_n='printf %s' else if test "X`(/usr/ucb/echo -n -n $as_echo) 2>/dev/null`" = "X-n $as_echo"; then as_echo_body='eval /usr/ucb/echo -n "$1$as_nl"' as_echo_n='/usr/ucb/echo -n' else as_echo_body='eval expr "X$1" : "X\\(.*\\)"' as_echo_n_body='eval arg=$1; case $arg in #( *"$as_nl"*) expr "X$arg" : "X\\(.*\\)$as_nl"; arg=`expr "X$arg" : ".*$as_nl\\(.*\\)"`;; esac; expr "X$arg" : "X\\(.*\\)" | tr -d "$as_nl" ' export as_echo_n_body as_echo_n='sh -c $as_echo_n_body as_echo' fi export as_echo_body as_echo='sh -c $as_echo_body as_echo' fi # The user is always right. if test "${PATH_SEPARATOR+set}" != set; then PATH_SEPARATOR=: (PATH='/bin;/bin'; FPATH=$PATH; sh -c :) >/dev/null 2>&1 && { (PATH='/bin:/bin'; FPATH=$PATH; sh -c :) >/dev/null 2>&1 || PATH_SEPARATOR=';' } fi # IFS # We need space, tab and new line, in precisely that order. Quoting is # there to prevent editors from complaining about space-tab. # (If _AS_PATH_WALK were called with IFS unset, it would disable word # splitting by setting IFS to empty value.) IFS=" "" $as_nl" # Find who we are. Look in the path if we contain no directory separator. as_myself= case $0 in #(( *[\\/]* ) as_myself=$0 ;; *) as_save_IFS=$IFS; IFS=$PATH_SEPARATOR for as_dir in $PATH do IFS=$as_save_IFS test -z "$as_dir" && as_dir=. test -r "$as_dir/$0" && as_myself=$as_dir/$0 && break done IFS=$as_save_IFS ;; esac # We did not find ourselves, most probably we were run as `sh COMMAND' # in which case we are not to be found in the path. if test "x$as_myself" = x; then as_myself=$0 fi if test ! -f "$as_myself"; then $as_echo "$as_myself: error: cannot find myself; rerun with an absolute file name" >&2 exit 1 fi # Unset variables that we do not need and which cause bugs (e.g. in # pre-3.0 UWIN ksh). But do not cause bugs in bash 2.01; the "|| exit 1" # suppresses any "Segmentation fault" message there. '((' could # trigger a bug in pdksh 5.2.14. for as_var in BASH_ENV ENV MAIL MAILPATH do eval test x\${$as_var+set} = xset \ && ( (unset $as_var) || exit 1) >/dev/null 2>&1 && unset $as_var || : done PS1='$ ' PS2='> ' PS4='+ ' # NLS nuisances. LC_ALL=C export LC_ALL LANGUAGE=C export LANGUAGE # CDPATH. (unset CDPATH) >/dev/null 2>&1 && unset CDPATH # Use a proper internal environment variable to ensure we don't fall # into an infinite loop, continuously re-executing ourselves. if test x"${_as_can_reexec}" != xno && test "x$CONFIG_SHELL" != x; then _as_can_reexec=no; export _as_can_reexec; # We cannot yet assume a decent shell, so we have to provide a # neutralization value for shells without unset; and this also # works around shells that cannot unset nonexistent variables. # Preserve -v and -x to the replacement shell. BASH_ENV=/dev/null ENV=/dev/null (unset BASH_ENV) >/dev/null 2>&1 && unset BASH_ENV ENV case $- in # (((( *v*x* | *x*v* ) as_opts=-vx ;; *v* ) as_opts=-v ;; *x* ) as_opts=-x ;; * ) as_opts= ;; esac exec $CONFIG_SHELL $as_opts "$as_myself" ${1+"$@"} # Admittedly, this is quite paranoid, since all the known shells bail # out after a failed `exec'. $as_echo "$0: could not re-execute with $CONFIG_SHELL" >&2 as_fn_exit 255 fi # We don't want this to propagate to other subprocesses. { _as_can_reexec=; unset _as_can_reexec;} if test "x$CONFIG_SHELL" = x; then as_bourne_compatible="if test -n \"\${ZSH_VERSION+set}\" && (emulate sh) >/dev/null 2>&1; then : emulate sh NULLCMD=: # Pre-4.2 versions of Zsh do word splitting on \${1+\"\$@\"}, which # is contrary to our usage. Disable this feature. alias -g '\${1+\"\$@\"}'='\"\$@\"' setopt NO_GLOB_SUBST else case \`(set -o) 2>/dev/null\` in #( *posix*) : set -o posix ;; #( *) : ;; esac fi " as_required="as_fn_return () { (exit \$1); } as_fn_success () { as_fn_return 0; } as_fn_failure () { as_fn_return 1; } as_fn_ret_success () { return 0; } as_fn_ret_failure () { return 1; } exitcode=0 as_fn_success || { exitcode=1; echo as_fn_success failed.; } as_fn_failure && { exitcode=1; echo as_fn_failure succeeded.; } as_fn_ret_success || { exitcode=1; echo as_fn_ret_success failed.; } as_fn_ret_failure && { exitcode=1; echo as_fn_ret_failure succeeded.; } if ( set x; as_fn_ret_success y && test x = \"\$1\" ); then : else exitcode=1; echo positional parameters were not saved. fi test x\$exitcode = x0 || exit 1 test -x / || exit 1" as_suggested=" as_lineno_1=";as_suggested=$as_suggested$LINENO;as_suggested=$as_suggested" as_lineno_1a=\$LINENO as_lineno_2=";as_suggested=$as_suggested$LINENO;as_suggested=$as_suggested" as_lineno_2a=\$LINENO eval 'test \"x\$as_lineno_1'\$as_run'\" != \"x\$as_lineno_2'\$as_run'\" && test \"x\`expr \$as_lineno_1'\$as_run' + 1\`\" = \"x\$as_lineno_2'\$as_run'\"' || exit 1 test \$(( 1 + 1 )) = 2 || exit 1 test -n \"\${ZSH_VERSION+set}\${BASH_VERSION+set}\" || ( ECHO='\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\' ECHO=\$ECHO\$ECHO\$ECHO\$ECHO\$ECHO ECHO=\$ECHO\$ECHO\$ECHO\$ECHO\$ECHO\$ECHO PATH=/empty FPATH=/empty; export PATH FPATH test \"X\`printf %s \$ECHO\`\" = \"X\$ECHO\" \\ || test \"X\`print -r -- \$ECHO\`\" = \"X\$ECHO\" ) || exit 1" if (eval "$as_required") 2>/dev/null; then : as_have_required=yes else as_have_required=no fi if test x$as_have_required = xyes && (eval "$as_suggested") 2>/dev/null; then : else as_save_IFS=$IFS; IFS=$PATH_SEPARATOR as_found=false for as_dir in /bin$PATH_SEPARATOR/usr/bin$PATH_SEPARATOR$PATH do IFS=$as_save_IFS test -z "$as_dir" && as_dir=. as_found=: case $as_dir in #( /*) for as_base in sh bash ksh sh5; do # Try only shells that exist, to save several forks. as_shell=$as_dir/$as_base if { test -f "$as_shell" || test -f "$as_shell.exe"; } && { $as_echo "$as_bourne_compatible""$as_required" | as_run=a "$as_shell"; } 2>/dev/null; then : CONFIG_SHELL=$as_shell as_have_required=yes if { $as_echo "$as_bourne_compatible""$as_suggested" | as_run=a "$as_shell"; } 2>/dev/null; then : break 2 fi fi done;; esac as_found=false done $as_found || { if { test -f "$SHELL" || test -f "$SHELL.exe"; } && { $as_echo "$as_bourne_compatible""$as_required" | as_run=a "$SHELL"; } 2>/dev/null; then : CONFIG_SHELL=$SHELL as_have_required=yes fi; } IFS=$as_save_IFS if test "x$CONFIG_SHELL" != x; then : export CONFIG_SHELL # We cannot yet assume a decent shell, so we have to provide a # neutralization value for shells without unset; and this also # works around shells that cannot unset nonexistent variables. # Preserve -v and -x to the replacement shell. BASH_ENV=/dev/null ENV=/dev/null (unset BASH_ENV) >/dev/null 2>&1 && unset BASH_ENV ENV case $- in # (((( *v*x* | *x*v* ) as_opts=-vx ;; *v* ) as_opts=-v ;; *x* ) as_opts=-x ;; * ) as_opts= ;; esac exec $CONFIG_SHELL $as_opts "$as_myself" ${1+"$@"} # Admittedly, this is quite paranoid, since all the known shells bail # out after a failed `exec'. $as_echo "$0: could not re-execute with $CONFIG_SHELL" >&2 exit 255 fi if test x$as_have_required = xno; then : $as_echo "$0: This script requires a shell more modern than all" $as_echo "$0: the shells that I found on your system." if test x${ZSH_VERSION+set} = xset ; then $as_echo "$0: In particular, zsh $ZSH_VERSION has bugs and should" $as_echo "$0: be upgraded to zsh 4.3.4 or later." else $as_echo "$0: Please tell bug-autoconf@gnu.org and https://issues.apache.org/jira/browse/COUCHDB $0: about your system, including any error possibly output $0: before this message. Then install a modern shell, or $0: manually run the script under such a shell if you do $0: have one." fi exit 1 fi fi fi SHELL=${CONFIG_SHELL-/bin/sh} export SHELL # Unset more variables known to interfere with behavior of common tools. CLICOLOR_FORCE= GREP_OPTIONS= unset CLICOLOR_FORCE GREP_OPTIONS ## --------------------- ## ## M4sh Shell Functions. ## ## --------------------- ## # as_fn_unset VAR # --------------- # Portably unset VAR. as_fn_unset () { { eval $1=; unset $1;} } as_unset=as_fn_unset # as_fn_set_status STATUS # ----------------------- # Set $? to STATUS, without forking. as_fn_set_status () { return $1 } # as_fn_set_status # as_fn_exit STATUS # ----------------- # Exit the shell with STATUS, even in a "trap 0" or "set -e" context. as_fn_exit () { set +e as_fn_set_status $1 exit $1 } # as_fn_exit # as_fn_mkdir_p # ------------- # Create "$as_dir" as a directory, including parents if necessary. as_fn_mkdir_p () { case $as_dir in #( -*) as_dir=./$as_dir;; esac test -d "$as_dir" || eval $as_mkdir_p || { as_dirs= while :; do case $as_dir in #( *\'*) as_qdir=`$as_echo "$as_dir" | sed "s/'/'\\\\\\\\''/g"`;; #'( *) as_qdir=$as_dir;; esac as_dirs="'$as_qdir' $as_dirs" as_dir=`$as_dirname -- "$as_dir" || $as_expr X"$as_dir" : 'X\(.*[^/]\)//*[^/][^/]*/*$' \| \ X"$as_dir" : 'X\(//\)[^/]' \| \ X"$as_dir" : 'X\(//\)$' \| \ X"$as_dir" : 'X\(/\)' \| . 2>/dev/null || $as_echo X"$as_dir" | sed '/^X\(.*[^/]\)\/\/*[^/][^/]*\/*$/{ s//\1/ q } /^X\(\/\/\)[^/].*/{ s//\1/ q } /^X\(\/\/\)$/{ s//\1/ q } /^X\(\/\).*/{ s//\1/ q } s/.*/./; q'` test -d "$as_dir" && break done test -z "$as_dirs" || eval "mkdir $as_dirs" } || test -d "$as_dir" || as_fn_error $? "cannot create directory $as_dir" } # as_fn_mkdir_p # as_fn_executable_p FILE # ----------------------- # Test if FILE is an executable regular file. as_fn_executable_p () { test -f "$1" && test -x "$1" } # as_fn_executable_p # as_fn_append VAR VALUE # ---------------------- # Append the text in VALUE to the end of the definition contained in VAR. Take # advantage of any shell optimizations that allow amortized linear growth over # repeated appends, instead of the typical quadratic growth present in naive # implementations. if (eval "as_var=1; as_var+=2; test x\$as_var = x12") 2>/dev/null; then : eval 'as_fn_append () { eval $1+=\$2 }' else as_fn_append () { eval $1=\$$1\$2 } fi # as_fn_append # as_fn_arith ARG... # ------------------ # Perform arithmetic evaluation on the ARGs, and store the result in the # global $as_val. Take advantage of shells that can avoid forks. The arguments # must be portable across $(()) and expr. if (eval "test \$(( 1 + 1 )) = 2") 2>/dev/null; then : eval 'as_fn_arith () { as_val=$(( $* )) }' else as_fn_arith () { as_val=`expr "$@" || test $? -eq 1` } fi # as_fn_arith # as_fn_error STATUS ERROR [LINENO LOG_FD] # ---------------------------------------- # Output "`basename $0`: error: ERROR" to stderr. If LINENO and LOG_FD are # provided, also output the error to LOG_FD, referencing LINENO. Then exit the # script with STATUS, using 1 if that was 0. as_fn_error () { as_status=$1; test $as_status -eq 0 && as_status=1 if test "$4"; then as_lineno=${as_lineno-"$3"} as_lineno_stack=as_lineno_stack=$as_lineno_stack $as_echo "$as_me:${as_lineno-$LINENO}: error: $2" >&$4 fi $as_echo "$as_me: error: $2" >&2 as_fn_exit $as_status } # as_fn_error if expr a : '\(a\)' >/dev/null 2>&1 && test "X`expr 00001 : '.*\(...\)'`" = X001; then as_expr=expr else as_expr=false fi if (basename -- /) >/dev/null 2>&1 && test "X`basename -- / 2>&1`" = "X/"; then as_basename=basename else as_basename=false fi if (as_dir=`dirname -- /` && test "X$as_dir" = X/) >/dev/null 2>&1; then as_dirname=dirname else as_dirname=false fi as_me=`$as_basename -- "$0" || $as_expr X/"$0" : '.*/\([^/][^/]*\)/*$' \| \ X"$0" : 'X\(//\)$' \| \ X"$0" : 'X\(/\)' \| . 2>/dev/null || $as_echo X/"$0" | sed '/^.*\/\([^/][^/]*\)\/*$/{ s//\1/ q } /^X\/\(\/\/\)$/{ s//\1/ q } /^X\/\(\/\).*/{ s//\1/ q } s/.*/./; q'` # Avoid depending upon Character Ranges. as_cr_letters='abcdefghijklmnopqrstuvwxyz' as_cr_LETTERS='ABCDEFGHIJKLMNOPQRSTUVWXYZ' as_cr_Letters=$as_cr_letters$as_cr_LETTERS as_cr_digits='0123456789' as_cr_alnum=$as_cr_Letters$as_cr_digits as_lineno_1=$LINENO as_lineno_1a=$LINENO as_lineno_2=$LINENO as_lineno_2a=$LINENO eval 'test "x$as_lineno_1'$as_run'" != "x$as_lineno_2'$as_run'" && test "x`expr $as_lineno_1'$as_run' + 1`" = "x$as_lineno_2'$as_run'"' || { # Blame Lee E. McMahon (1931-1989) for sed's syntax. :-) sed -n ' p /[$]LINENO/= ' <$as_myself | sed ' s/[$]LINENO.*/&-/ t lineno b :lineno N :loop s/[$]LINENO\([^'$as_cr_alnum'_].*\n\)\(.*\)/\2\1\2/ t loop s/-\n.*// ' >$as_me.lineno && chmod +x "$as_me.lineno" || { $as_echo "$as_me: error: cannot create $as_me.lineno; rerun with a POSIX shell" >&2; as_fn_exit 1; } # If we had to re-execute with $CONFIG_SHELL, we're ensured to have # already done that, so ensure we don't try to do so again and fall # in an infinite loop. This has already happened in practice. _as_can_reexec=no; export _as_can_reexec # Don't try to exec as it changes $[0], causing all sort of problems # (the dirname of $[0] is not the place where we might find the # original and so on. Autoconf is especially sensitive to this). . "./$as_me.lineno" # Exit status is that of the last command. exit } ECHO_C= ECHO_N= ECHO_T= case `echo -n x` in #((((( -n*) case `echo 'xy\c'` in *c*) ECHO_T=' ';; # ECHO_T is single tab character. xy) ECHO_C='\c';; *) echo `echo ksh88 bug on AIX 6.1` > /dev/null ECHO_T=' ';; esac;; *) ECHO_N='-n';; esac rm -f conf$$ conf$$.exe conf$$.file if test -d conf$$.dir; then rm -f conf$$.dir/conf$$.file else rm -f conf$$.dir mkdir conf$$.dir 2>/dev/null fi if (echo >conf$$.file) 2>/dev/null; then if ln -s conf$$.file conf$$ 2>/dev/null; then as_ln_s='ln -s' # ... but there are two gotchas: # 1) On MSYS, both `ln -s file dir' and `ln file dir' fail. # 2) DJGPP < 2.04 has no symlinks; `ln -s' creates a wrapper executable. # In both cases, we have to default to `cp -pR'. ln -s conf$$.file conf$$.dir 2>/dev/null && test ! -f conf$$.exe || as_ln_s='cp -pR' elif ln conf$$.file conf$$ 2>/dev/null; then as_ln_s=ln else as_ln_s='cp -pR' fi else as_ln_s='cp -pR' fi rm -f conf$$ conf$$.exe conf$$.dir/conf$$.file conf$$.file rmdir conf$$.dir 2>/dev/null if mkdir -p . 2>/dev/null; then as_mkdir_p='mkdir -p "$as_dir"' else test -d ./-p && rmdir ./-p as_mkdir_p=false fi as_test_x='test -x' as_executable_p=as_fn_executable_p # Sed expression to map a string onto a valid CPP name. as_tr_cpp="eval sed 'y%*$as_cr_letters%P$as_cr_LETTERS%;s%[^_$as_cr_alnum]%_%g'" # Sed expression to map a string onto a valid variable name. as_tr_sh="eval sed 'y%*+%pp%;s%[^_$as_cr_alnum]%_%g'" SHELL=${CONFIG_SHELL-/bin/sh} test -n "$DJDIR" || exec 7<&0 &1 # Name of the host. # hostname on some systems (SVR3.2, old GNU/Linux) returns a bogus exit status, # so uname gets run too. ac_hostname=`(hostname || uname -n) 2>/dev/null | sed 1q` # # Initializations. # ac_default_prefix=/usr/local ac_clean_files= ac_config_libobj_dir=. LIBOBJS= cross_compiling=no subdirs= MFLAGS= MAKEFLAGS= # Identity of this package. PACKAGE_NAME='Apache CouchDB' PACKAGE_TARNAME='apache-couchdb' PACKAGE_VERSION='1.5.0' PACKAGE_STRING='Apache CouchDB 1.5.0' PACKAGE_BUGREPORT='https://issues.apache.org/jira/browse/COUCHDB' PACKAGE_URL='' # Factoring default headers for most tests. ac_includes_default="\ #include #ifdef HAVE_SYS_TYPES_H # include #endif #ifdef HAVE_SYS_STAT_H # include #endif #ifdef STDC_HEADERS # include # include #else # ifdef HAVE_STDLIB_H # include # endif #endif #ifdef HAVE_STRING_H # if !defined STDC_HEADERS && defined HAVE_MEMORY_H # include # endif # include #endif #ifdef HAVE_STRINGS_H # include #endif #ifdef HAVE_INTTYPES_H # include #endif #ifdef HAVE_STDINT_H # include #endif #ifdef HAVE_UNISTD_H # include #endif" ac_subst_vars='am__EXEEXT_FALSE am__EXEEXT_TRUE LTLIBOBJS LIBOBJS abs_top_builddir abs_top_srcdir localerlanglibdir locallibbindir erlangbin erlangversion localstaterundir localstatelogdir localstatelibdir locallibdir localdocdir localdatadir localconfdir bug_uri version_release version_stage version_revision version_minor version_major version package_name package_tarname package_identifier package_author_address package_author_name STRICTNESS_FALSE STRICTNESS_TRUE TESTS_FALSE TESTS_TRUE BUILD_HTML_FALSE BUILD_HTML_TRUE BUILD_PDF_FALSE BUILD_PDF_TRUE BUILD_INFO_FALSE BUILD_INFO_TRUE BUILD_MAN_FALSE BUILD_MAN_TRUE USE_CURL_FALSE USE_CURL_TRUE USE_NATIVE_MOCHIJSON_FALSE USE_NATIVE_MOCHIJSON_TRUE LAUNCHD_FALSE LAUNCHD_TRUE INIT_FALSE INIT_TRUE HAS_SPHINX_BUILD HAS_INSTALLINFO HAS_MAKEINFO HAS_PDFLATEX HAS_HELP2MAN launchddir initdir ERLC USE_EJSON_COMPARE_NIF_FALSE USE_EJSON_COMPARE_NIF_TRUE USE_OTP_NIFS_FALSE USE_OTP_NIFS_TRUE otp_release CURL_LIBS CURL_CFLAGS CURL_CONFIG ICU_BIN ICU_LIBS ICU_CXXFLAGS ICU_CFLAGS ICU_CPPFLAGS ICU_CONFIG msvc_redist_name msvc_redist_dir INNO_COMPILER_EXECUTABLE openssl_bin_dir JS_LIB_BINARY WINDOWS_FALSE WINDOWS_TRUE FLAGS ERLC_FLAGS JS_LIBS JS_CFLAGS ERLANG_FLAGS ESCRIPT ERL SNAPPY_PATCHLEVEL SNAPPY_MINOR SNAPPY_MAJOR ac_cv_have_stddef_h ac_cv_have_stdint_h CXXCPP am__fastdepCXX_FALSE am__fastdepCXX_TRUE CXXDEPMODE ac_ct_CXX CXXFLAGS CXX PKG_CONFIG_LIBDIR PKG_CONFIG_PATH PKG_CONFIG OTOOL64 OTOOL LIPO NMEDIT DSYMUTIL MANIFEST_TOOL RANLIB ac_ct_AR AR LN_S NM ac_ct_DUMPBIN DUMPBIN LD FGREP SED host_os host_vendor host_cpu host build_os build_vendor build_cpu build LIBTOOL OBJDUMP DLLTOOL AS EGREP GREP CPP am__fastdepCC_FALSE am__fastdepCC_TRUE CCDEPMODE am__nodep AMDEPBACKSLASH AMDEP_FALSE AMDEP_TRUE am__quote am__include DEPDIR OBJEXT EXEEXT ac_ct_CC CPPFLAGS LDFLAGS CFLAGS CC am__untar am__tar AMTAR am__leading_dot SET_MAKE AWK mkdir_p MKDIR_P INSTALL_STRIP_PROGRAM STRIP install_sh MAKEINFO AUTOHEADER AUTOMAKE AUTOCONF ACLOCAL VERSION PACKAGE CYGPATH_W am__isrc INSTALL_DATA INSTALL_SCRIPT INSTALL_PROGRAM target_alias host_alias build_alias LIBS ECHO_T ECHO_N ECHO_C DEFS mandir localedir libdir psdir pdfdir dvidir htmldir infodir docdir oldincludedir includedir localstatedir sharedstatedir sysconfdir datadir datarootdir libexecdir sbindir bindir program_transform_name prefix exec_prefix PACKAGE_URL PACKAGE_BUGREPORT PACKAGE_STRING PACKAGE_VERSION PACKAGE_TARNAME PACKAGE_NAME PATH_SEPARATOR SHELL' ac_subst_files='' ac_user_opts=' enable_option_checking enable_dependency_tracking enable_shared enable_static with_pic enable_fast_install with_gnu_ld with_sysroot enable_libtool_lock with_erlang with_js_include with_js_lib enable_js_trunk with_openssl_bin_dir with_msvc_redist_dir with_win32_icu_binaries with_win32_curl with_curl_prefix with_curl_exec_prefix enable_init enable_launchd enable_native_mochijson enable_tests enable_docs enable_strictness ' ac_precious_vars='build_alias host_alias target_alias CC CFLAGS LDFLAGS LIBS CPPFLAGS CPP PKG_CONFIG PKG_CONFIG_PATH PKG_CONFIG_LIBDIR CXX CXXFLAGS CCC CXXCPP JS_CFLAGS JS_LIBS ERLC_FLAGS FLAGS CURL_CONFIG CURL_CFLAGS CURL_LIBS ERL ERLC' # Initialize some variables set by options. ac_init_help= ac_init_version=false ac_unrecognized_opts= ac_unrecognized_sep= # The variables have the same names as the options, with # dashes changed to underlines. cache_file=/dev/null exec_prefix=NONE no_create= no_recursion= prefix=NONE program_prefix=NONE program_suffix=NONE program_transform_name=s,x,x, silent= site= srcdir= verbose= x_includes=NONE x_libraries=NONE # Installation directory options. # These are left unexpanded so users can "make install exec_prefix=/foo" # and all the variables that are supposed to be based on exec_prefix # by default will actually change. # Use braces instead of parens because sh, perl, etc. also accept them. # (The list follows the same order as the GNU Coding Standards.) bindir='${exec_prefix}/bin' sbindir='${exec_prefix}/sbin' libexecdir='${exec_prefix}/libexec' datarootdir='${prefix}/share' datadir='${datarootdir}' sysconfdir='${prefix}/etc' sharedstatedir='${prefix}/com' localstatedir='${prefix}/var' includedir='${prefix}/include' oldincludedir='/usr/include' docdir='${datarootdir}/doc/${PACKAGE_TARNAME}' infodir='${datarootdir}/info' htmldir='${docdir}' dvidir='${docdir}' pdfdir='${docdir}' psdir='${docdir}' libdir='${exec_prefix}/lib' localedir='${datarootdir}/locale' mandir='${datarootdir}/man' ac_prev= ac_dashdash= for ac_option do # If the previous option needs an argument, assign it. if test -n "$ac_prev"; then eval $ac_prev=\$ac_option ac_prev= continue fi case $ac_option in *=?*) ac_optarg=`expr "X$ac_option" : '[^=]*=\(.*\)'` ;; *=) ac_optarg= ;; *) ac_optarg=yes ;; esac # Accept the important Cygnus configure options, so we can diagnose typos. case $ac_dashdash$ac_option in --) ac_dashdash=yes ;; -bindir | --bindir | --bindi | --bind | --bin | --bi) ac_prev=bindir ;; -bindir=* | --bindir=* | --bindi=* | --bind=* | --bin=* | --bi=*) bindir=$ac_optarg ;; -build | --build | --buil | --bui | --bu) ac_prev=build_alias ;; -build=* | --build=* | --buil=* | --bui=* | --bu=*) build_alias=$ac_optarg ;; -cache-file | --cache-file | --cache-fil | --cache-fi \ | --cache-f | --cache- | --cache | --cach | --cac | --ca | --c) ac_prev=cache_file ;; -cache-file=* | --cache-file=* | --cache-fil=* | --cache-fi=* \ | --cache-f=* | --cache-=* | --cache=* | --cach=* | --cac=* | --ca=* | --c=*) cache_file=$ac_optarg ;; --config-cache | -C) cache_file=config.cache ;; -datadir | --datadir | --datadi | --datad) ac_prev=datadir ;; -datadir=* | --datadir=* | --datadi=* | --datad=*) datadir=$ac_optarg ;; -datarootdir | --datarootdir | --datarootdi | --datarootd | --dataroot \ | --dataroo | --dataro | --datar) ac_prev=datarootdir ;; -datarootdir=* | --datarootdir=* | --datarootdi=* | --datarootd=* \ | --dataroot=* | --dataroo=* | --dataro=* | --datar=*) datarootdir=$ac_optarg ;; -disable-* | --disable-*) ac_useropt=`expr "x$ac_option" : 'x-*disable-\(.*\)'` # Reject names that are not valid shell variable names. expr "x$ac_useropt" : ".*[^-+._$as_cr_alnum]" >/dev/null && as_fn_error $? "invalid feature name: $ac_useropt" ac_useropt_orig=$ac_useropt ac_useropt=`$as_echo "$ac_useropt" | sed 's/[-+.]/_/g'` case $ac_user_opts in *" "enable_$ac_useropt" "*) ;; *) ac_unrecognized_opts="$ac_unrecognized_opts$ac_unrecognized_sep--disable-$ac_useropt_orig" ac_unrecognized_sep=', ';; esac eval enable_$ac_useropt=no ;; -docdir | --docdir | --docdi | --doc | --do) ac_prev=docdir ;; -docdir=* | --docdir=* | --docdi=* | --doc=* | --do=*) docdir=$ac_optarg ;; -dvidir | --dvidir | --dvidi | --dvid | --dvi | --dv) ac_prev=dvidir ;; -dvidir=* | --dvidir=* | --dvidi=* | --dvid=* | --dvi=* | --dv=*) dvidir=$ac_optarg ;; -enable-* | --enable-*) ac_useropt=`expr "x$ac_option" : 'x-*enable-\([^=]*\)'` # Reject names that are not valid shell variable names. expr "x$ac_useropt" : ".*[^-+._$as_cr_alnum]" >/dev/null && as_fn_error $? "invalid feature name: $ac_useropt" ac_useropt_orig=$ac_useropt ac_useropt=`$as_echo "$ac_useropt" | sed 's/[-+.]/_/g'` case $ac_user_opts in *" "enable_$ac_useropt" "*) ;; *) ac_unrecognized_opts="$ac_unrecognized_opts$ac_unrecognized_sep--enable-$ac_useropt_orig" ac_unrecognized_sep=', ';; esac eval enable_$ac_useropt=\$ac_optarg ;; -exec-prefix | --exec_prefix | --exec-prefix | --exec-prefi \ | --exec-pref | --exec-pre | --exec-pr | --exec-p | --exec- \ | --exec | --exe | --ex) ac_prev=exec_prefix ;; -exec-prefix=* | --exec_prefix=* | --exec-prefix=* | --exec-prefi=* \ | --exec-pref=* | --exec-pre=* | --exec-pr=* | --exec-p=* | --exec-=* \ | --exec=* | --exe=* | --ex=*) exec_prefix=$ac_optarg ;; -gas | --gas | --ga | --g) # Obsolete; use --with-gas. with_gas=yes ;; -help | --help | --hel | --he | -h) ac_init_help=long ;; -help=r* | --help=r* | --hel=r* | --he=r* | -hr*) ac_init_help=recursive ;; -help=s* | --help=s* | --hel=s* | --he=s* | -hs*) ac_init_help=short ;; -host | --host | --hos | --ho) ac_prev=host_alias ;; -host=* | --host=* | --hos=* | --ho=*) host_alias=$ac_optarg ;; -htmldir | --htmldir | --htmldi | --htmld | --html | --htm | --ht) ac_prev=htmldir ;; -htmldir=* | --htmldir=* | --htmldi=* | --htmld=* | --html=* | --htm=* \ | --ht=*) htmldir=$ac_optarg ;; -includedir | --includedir | --includedi | --included | --include \ | --includ | --inclu | --incl | --inc) ac_prev=includedir ;; -includedir=* | --includedir=* | --includedi=* | --included=* | --include=* \ | --includ=* | --inclu=* | --incl=* | --inc=*) includedir=$ac_optarg ;; -infodir | --infodir | --infodi | --infod | --info | --inf) ac_prev=infodir ;; -infodir=* | --infodir=* | --infodi=* | --infod=* | --info=* | --inf=*) infodir=$ac_optarg ;; -libdir | --libdir | --libdi | --libd) ac_prev=libdir ;; -libdir=* | --libdir=* | --libdi=* | --libd=*) libdir=$ac_optarg ;; -libexecdir | --libexecdir | --libexecdi | --libexecd | --libexec \ | --libexe | --libex | --libe) ac_prev=libexecdir ;; -libexecdir=* | --libexecdir=* | --libexecdi=* | --libexecd=* | --libexec=* \ | --libexe=* | --libex=* | --libe=*) libexecdir=$ac_optarg ;; -localedir | --localedir | --localedi | --localed | --locale) ac_prev=localedir ;; -localedir=* | --localedir=* | --localedi=* | --localed=* | --locale=*) localedir=$ac_optarg ;; -localstatedir | --localstatedir | --localstatedi | --localstated \ | --localstate | --localstat | --localsta | --localst | --locals) ac_prev=localstatedir ;; -localstatedir=* | --localstatedir=* | --localstatedi=* | --localstated=* \ | --localstate=* | --localstat=* | --localsta=* | --localst=* | --locals=*) localstatedir=$ac_optarg ;; -mandir | --mandir | --mandi | --mand | --man | --ma | --m) ac_prev=mandir ;; -mandir=* | --mandir=* | --mandi=* | --mand=* | --man=* | --ma=* | --m=*) mandir=$ac_optarg ;; -nfp | --nfp | --nf) # Obsolete; use --without-fp. with_fp=no ;; -no-create | --no-create | --no-creat | --no-crea | --no-cre \ | --no-cr | --no-c | -n) no_create=yes ;; -no-recursion | --no-recursion | --no-recursio | --no-recursi \ | --no-recurs | --no-recur | --no-recu | --no-rec | --no-re | --no-r) no_recursion=yes ;; -oldincludedir | --oldincludedir | --oldincludedi | --oldincluded \ | --oldinclude | --oldinclud | --oldinclu | --oldincl | --oldinc \ | --oldin | --oldi | --old | --ol | --o) ac_prev=oldincludedir ;; -oldincludedir=* | --oldincludedir=* | --oldincludedi=* | --oldincluded=* \ | --oldinclude=* | --oldinclud=* | --oldinclu=* | --oldincl=* | --oldinc=* \ | --oldin=* | --oldi=* | --old=* | --ol=* | --o=*) oldincludedir=$ac_optarg ;; -prefix | --prefix | --prefi | --pref | --pre | --pr | --p) ac_prev=prefix ;; -prefix=* | --prefix=* | --prefi=* | --pref=* | --pre=* | --pr=* | --p=*) prefix=$ac_optarg ;; -program-prefix | --program-prefix | --program-prefi | --program-pref \ | --program-pre | --program-pr | --program-p) ac_prev=program_prefix ;; -program-prefix=* | --program-prefix=* | --program-prefi=* \ | --program-pref=* | --program-pre=* | --program-pr=* | --program-p=*) program_prefix=$ac_optarg ;; -program-suffix | --program-suffix | --program-suffi | --program-suff \ | --program-suf | --program-su | --program-s) ac_prev=program_suffix ;; -program-suffix=* | --program-suffix=* | --program-suffi=* \ | --program-suff=* | --program-suf=* | --program-su=* | --program-s=*) program_suffix=$ac_optarg ;; -program-transform-name | --program-transform-name \ | --program-transform-nam | --program-transform-na \ | --program-transform-n | --program-transform- \ | --program-transform | --program-transfor \ | --program-transfo | --program-transf \ | --program-trans | --program-tran \ | --progr-tra | --program-tr | --program-t) ac_prev=program_transform_name ;; -program-transform-name=* | --program-transform-name=* \ | --program-transform-nam=* | --program-transform-na=* \ | --program-transform-n=* | --program-transform-=* \ | --program-transform=* | --program-transfor=* \ | --program-transfo=* | --program-transf=* \ | --program-trans=* | --program-tran=* \ | --progr-tra=* | --program-tr=* | --program-t=*) program_transform_name=$ac_optarg ;; -pdfdir | --pdfdir | --pdfdi | --pdfd | --pdf | --pd) ac_prev=pdfdir ;; -pdfdir=* | --pdfdir=* | --pdfdi=* | --pdfd=* | --pdf=* | --pd=*) pdfdir=$ac_optarg ;; -psdir | --psdir | --psdi | --psd | --ps) ac_prev=psdir ;; -psdir=* | --psdir=* | --psdi=* | --psd=* | --ps=*) psdir=$ac_optarg ;; -q | -quiet | --quiet | --quie | --qui | --qu | --q \ | -silent | --silent | --silen | --sile | --sil) silent=yes ;; -sbindir | --sbindir | --sbindi | --sbind | --sbin | --sbi | --sb) ac_prev=sbindir ;; -sbindir=* | --sbindir=* | --sbindi=* | --sbind=* | --sbin=* \ | --sbi=* | --sb=*) sbindir=$ac_optarg ;; -sharedstatedir | --sharedstatedir | --sharedstatedi \ | --sharedstated | --sharedstate | --sharedstat | --sharedsta \ | --sharedst | --shareds | --shared | --share | --shar \ | --sha | --sh) ac_prev=sharedstatedir ;; -sharedstatedir=* | --sharedstatedir=* | --sharedstatedi=* \ | --sharedstated=* | --sharedstate=* | --sharedstat=* | --sharedsta=* \ | --sharedst=* | --shareds=* | --shared=* | --share=* | --shar=* \ | --sha=* | --sh=*) sharedstatedir=$ac_optarg ;; -site | --site | --sit) ac_prev=site ;; -site=* | --site=* | --sit=*) site=$ac_optarg ;; -srcdir | --srcdir | --srcdi | --srcd | --src | --sr) ac_prev=srcdir ;; -srcdir=* | --srcdir=* | --srcdi=* | --srcd=* | --src=* | --sr=*) srcdir=$ac_optarg ;; -sysconfdir | --sysconfdir | --sysconfdi | --sysconfd | --sysconf \ | --syscon | --sysco | --sysc | --sys | --sy) ac_prev=sysconfdir ;; -sysconfdir=* | --sysconfdir=* | --sysconfdi=* | --sysconfd=* | --sysconf=* \ | --syscon=* | --sysco=* | --sysc=* | --sys=* | --sy=*) sysconfdir=$ac_optarg ;; -target | --target | --targe | --targ | --tar | --ta | --t) ac_prev=target_alias ;; -target=* | --target=* | --targe=* | --targ=* | --tar=* | --ta=* | --t=*) target_alias=$ac_optarg ;; -v | -verbose | --verbose | --verbos | --verbo | --verb) verbose=yes ;; -version | --version | --versio | --versi | --vers | -V) ac_init_version=: ;; -with-* | --with-*) ac_useropt=`expr "x$ac_option" : 'x-*with-\([^=]*\)'` # Reject names that are not valid shell variable names. expr "x$ac_useropt" : ".*[^-+._$as_cr_alnum]" >/dev/null && as_fn_error $? "invalid package name: $ac_useropt" ac_useropt_orig=$ac_useropt ac_useropt=`$as_echo "$ac_useropt" | sed 's/[-+.]/_/g'` case $ac_user_opts in *" "with_$ac_useropt" "*) ;; *) ac_unrecognized_opts="$ac_unrecognized_opts$ac_unrecognized_sep--with-$ac_useropt_orig" ac_unrecognized_sep=', ';; esac eval with_$ac_useropt=\$ac_optarg ;; -without-* | --without-*) ac_useropt=`expr "x$ac_option" : 'x-*without-\(.*\)'` # Reject names that are not valid shell variable names. expr "x$ac_useropt" : ".*[^-+._$as_cr_alnum]" >/dev/null && as_fn_error $? "invalid package name: $ac_useropt" ac_useropt_orig=$ac_useropt ac_useropt=`$as_echo "$ac_useropt" | sed 's/[-+.]/_/g'` case $ac_user_opts in *" "with_$ac_useropt" "*) ;; *) ac_unrecognized_opts="$ac_unrecognized_opts$ac_unrecognized_sep--without-$ac_useropt_orig" ac_unrecognized_sep=', ';; esac eval with_$ac_useropt=no ;; --x) # Obsolete; use --with-x. with_x=yes ;; -x-includes | --x-includes | --x-include | --x-includ | --x-inclu \ | --x-incl | --x-inc | --x-in | --x-i) ac_prev=x_includes ;; -x-includes=* | --x-includes=* | --x-include=* | --x-includ=* | --x-inclu=* \ | --x-incl=* | --x-inc=* | --x-in=* | --x-i=*) x_includes=$ac_optarg ;; -x-libraries | --x-libraries | --x-librarie | --x-librari \ | --x-librar | --x-libra | --x-libr | --x-lib | --x-li | --x-l) ac_prev=x_libraries ;; -x-libraries=* | --x-libraries=* | --x-librarie=* | --x-librari=* \ | --x-librar=* | --x-libra=* | --x-libr=* | --x-lib=* | --x-li=* | --x-l=*) x_libraries=$ac_optarg ;; -*) as_fn_error $? "unrecognized option: \`$ac_option' Try \`$0 --help' for more information" ;; *=*) ac_envvar=`expr "x$ac_option" : 'x\([^=]*\)='` # Reject names that are not valid shell variable names. case $ac_envvar in #( '' | [0-9]* | *[!_$as_cr_alnum]* ) as_fn_error $? "invalid variable name: \`$ac_envvar'" ;; esac eval $ac_envvar=\$ac_optarg export $ac_envvar ;; *) # FIXME: should be removed in autoconf 3.0. $as_echo "$as_me: WARNING: you should use --build, --host, --target" >&2 expr "x$ac_option" : ".*[^-._$as_cr_alnum]" >/dev/null && $as_echo "$as_me: WARNING: invalid host type: $ac_option" >&2 : "${build_alias=$ac_option} ${host_alias=$ac_option} ${target_alias=$ac_option}" ;; esac done if test -n "$ac_prev"; then ac_option=--`echo $ac_prev | sed 's/_/-/g'` as_fn_error $? "missing argument to $ac_option" fi if test -n "$ac_unrecognized_opts"; then case $enable_option_checking in no) ;; fatal) as_fn_error $? "unrecognized options: $ac_unrecognized_opts" ;; *) $as_echo "$as_me: WARNING: unrecognized options: $ac_unrecognized_opts" >&2 ;; esac fi # Check all directory arguments for consistency. for ac_var in exec_prefix prefix bindir sbindir libexecdir datarootdir \ datadir sysconfdir sharedstatedir localstatedir includedir \ oldincludedir docdir infodir htmldir dvidir pdfdir psdir \ libdir localedir mandir do eval ac_val=\$$ac_var # Remove trailing slashes. case $ac_val in */ ) ac_val=`expr "X$ac_val" : 'X\(.*[^/]\)' \| "X$ac_val" : 'X\(.*\)'` eval $ac_var=\$ac_val;; esac # Be sure to have absolute directory names. case $ac_val in [\\/$]* | ?:[\\/]* ) continue;; NONE | '' ) case $ac_var in *prefix ) continue;; esac;; esac as_fn_error $? "expected an absolute directory name for --$ac_var: $ac_val" done # There might be people who depend on the old broken behavior: `$host' # used to hold the argument of --host etc. # FIXME: To remove some day. build=$build_alias host=$host_alias target=$target_alias # FIXME: To remove some day. if test "x$host_alias" != x; then if test "x$build_alias" = x; then cross_compiling=maybe elif test "x$build_alias" != "x$host_alias"; then cross_compiling=yes fi fi ac_tool_prefix= test -n "$host_alias" && ac_tool_prefix=$host_alias- test "$silent" = yes && exec 6>/dev/null ac_pwd=`pwd` && test -n "$ac_pwd" && ac_ls_di=`ls -di .` && ac_pwd_ls_di=`cd "$ac_pwd" && ls -di .` || as_fn_error $? "working directory cannot be determined" test "X$ac_ls_di" = "X$ac_pwd_ls_di" || as_fn_error $? "pwd does not report name of working directory" # Find the source files, if location was not specified. if test -z "$srcdir"; then ac_srcdir_defaulted=yes # Try the directory containing this script, then the parent directory. ac_confdir=`$as_dirname -- "$as_myself" || $as_expr X"$as_myself" : 'X\(.*[^/]\)//*[^/][^/]*/*$' \| \ X"$as_myself" : 'X\(//\)[^/]' \| \ X"$as_myself" : 'X\(//\)$' \| \ X"$as_myself" : 'X\(/\)' \| . 2>/dev/null || $as_echo X"$as_myself" | sed '/^X\(.*[^/]\)\/\/*[^/][^/]*\/*$/{ s//\1/ q } /^X\(\/\/\)[^/].*/{ s//\1/ q } /^X\(\/\/\)$/{ s//\1/ q } /^X\(\/\).*/{ s//\1/ q } s/.*/./; q'` srcdir=$ac_confdir if test ! -r "$srcdir/$ac_unique_file"; then srcdir=.. fi else ac_srcdir_defaulted=no fi if test ! -r "$srcdir/$ac_unique_file"; then test "$ac_srcdir_defaulted" = yes && srcdir="$ac_confdir or .." as_fn_error $? "cannot find sources ($ac_unique_file) in $srcdir" fi ac_msg="sources are in $srcdir, but \`cd $srcdir' does not work" ac_abs_confdir=`( cd "$srcdir" && test -r "./$ac_unique_file" || as_fn_error $? "$ac_msg" pwd)` # When building in place, set srcdir=. if test "$ac_abs_confdir" = "$ac_pwd"; then srcdir=. fi # Remove unnecessary trailing slashes from srcdir. # Double slashes in file names in object file debugging info # mess up M-x gdb in Emacs. case $srcdir in */) srcdir=`expr "X$srcdir" : 'X\(.*[^/]\)' \| "X$srcdir" : 'X\(.*\)'`;; esac for ac_var in $ac_precious_vars; do eval ac_env_${ac_var}_set=\${${ac_var}+set} eval ac_env_${ac_var}_value=\$${ac_var} eval ac_cv_env_${ac_var}_set=\${${ac_var}+set} eval ac_cv_env_${ac_var}_value=\$${ac_var} done # # Report the --help message. # if test "$ac_init_help" = "long"; then # Omit some internal or obsolete options to make the list less imposing. # This message is too long to be a string in the A/UX 3.1 sh. cat <<_ACEOF \`configure' configures Apache CouchDB 1.5.0 to adapt to many kinds of systems. Usage: $0 [OPTION]... [VAR=VALUE]... To assign environment variables (e.g., CC, CFLAGS...), specify them as VAR=VALUE. See below for descriptions of some of the useful variables. Defaults for the options are specified in brackets. Configuration: -h, --help display this help and exit --help=short display options specific to this package --help=recursive display the short help of all the included packages -V, --version display version information and exit -q, --quiet, --silent do not print \`checking ...' messages --cache-file=FILE cache test results in FILE [disabled] -C, --config-cache alias for \`--cache-file=config.cache' -n, --no-create do not create output files --srcdir=DIR find the sources in DIR [configure dir or \`..'] Installation directories: --prefix=PREFIX install architecture-independent files in PREFIX [$ac_default_prefix] --exec-prefix=EPREFIX install architecture-dependent files in EPREFIX [PREFIX] By default, \`make install' will install all the files in \`$ac_default_prefix/bin', \`$ac_default_prefix/lib' etc. You can specify an installation prefix other than \`$ac_default_prefix' using \`--prefix', for instance \`--prefix=\$HOME'. For better control, use the options below. Fine tuning of the installation directories: --bindir=DIR user executables [EPREFIX/bin] --sbindir=DIR system admin executables [EPREFIX/sbin] --libexecdir=DIR program executables [EPREFIX/libexec] --sysconfdir=DIR read-only single-machine data [PREFIX/etc] --sharedstatedir=DIR modifiable architecture-independent data [PREFIX/com] --localstatedir=DIR modifiable single-machine data [PREFIX/var] --libdir=DIR object code libraries [EPREFIX/lib] --includedir=DIR C header files [PREFIX/include] --oldincludedir=DIR C header files for non-gcc [/usr/include] --datarootdir=DIR read-only arch.-independent data root [PREFIX/share] --datadir=DIR read-only architecture-independent data [DATAROOTDIR] --infodir=DIR info documentation [DATAROOTDIR/info] --localedir=DIR locale-dependent data [DATAROOTDIR/locale] --mandir=DIR man documentation [DATAROOTDIR/man] --docdir=DIR documentation root [DATAROOTDIR/doc/apache-couchdb] --htmldir=DIR html documentation [DOCDIR] --dvidir=DIR dvi documentation [DOCDIR] --pdfdir=DIR pdf documentation [DOCDIR] --psdir=DIR ps documentation [DOCDIR] _ACEOF cat <<\_ACEOF Program names: --program-prefix=PREFIX prepend PREFIX to installed program names --program-suffix=SUFFIX append SUFFIX to installed program names --program-transform-name=PROGRAM run sed PROGRAM on installed program names System types: --build=BUILD configure for building on BUILD [guessed] --host=HOST cross-compile to build programs to run on HOST [BUILD] _ACEOF fi if test -n "$ac_init_help"; then case $ac_init_help in short | recursive ) echo "Configuration of Apache CouchDB 1.5.0:";; esac cat <<\_ACEOF Optional Features: --disable-option-checking ignore unrecognized --enable/--with options --disable-FEATURE do not include FEATURE (same as --enable-FEATURE=no) --enable-FEATURE[=ARG] include FEATURE [ARG=yes] --disable-dependency-tracking speeds up one-time build --enable-dependency-tracking do not reject slow dependency extractors --enable-shared[=PKGS] build shared libraries [default=yes] --enable-static[=PKGS] build static libraries [default=no] --enable-fast-install[=PKGS] optimize for fast installation [default=yes] --disable-libtool-lock avoid locking (might break parallel builds) --enable-js-trunk allow use of SpiderMonkey versions newer than js185-1.0.0 --disable-init don't install init script where applicable --disable-launchd don't install launchd configuration where applicable --enable-native-mochijson compile mochijson to native code (EXPERIMENTAL) --disable-tests skip tests during build --disable-docs skip docs during build --enable-strictness exit when optional checks fail Optional Packages: --with-PACKAGE[=ARG] use PACKAGE [ARG=yes] --without-PACKAGE do not use PACKAGE (same as --with-PACKAGE=no) --with-pic[=PKGS] try to use only PIC/non-PIC objects [default=use both] --with-gnu-ld assume the C compiler uses GNU ld [default=no] --with-sysroot=DIR Search for dependent libraries within DIR (or the compiler's sysroot if not specified). --with-erlang=PATH set PATH to the Erlang include directory --with-js-include=PATH set PATH to the SpiderMonkey include directory --with-js-lib=PATH set PATH to the SpiderMonkey library directory --with-openssl-bin-dir=PATH path to the open ssl binaries for distribution on Windows --with-msvc-redist-dir=PATH path to the msvc redistributables for the Windows platform --with-win32-icu-binaries=PATH set PATH to the Win32 native ICU binaries directory --with-win32-curl=PATH set PATH to the Win32 native curl directory --with-curl-prefix=PREFIX Prefix where curl is installed (optional) --with-curl-exec-prefix=EPREFIX Exec prefix where curl is installed (optional) Some influential environment variables: CC C compiler command CFLAGS C compiler flags LDFLAGS linker flags, e.g. -L if you have libraries in a nonstandard directory LIBS libraries to pass to the linker, e.g. -l CPPFLAGS (Objective) C/C++ preprocessor flags, e.g. -I if you have headers in a nonstandard directory CPP C preprocessor PKG_CONFIG path to pkg-config utility PKG_CONFIG_PATH directories to add to pkg-config's search path PKG_CONFIG_LIBDIR path overriding pkg-config's built-in search path CXX C++ compiler command CXXFLAGS C++ compiler flags CXXCPP C++ preprocessor JS_CFLAGS C compiler flags for JS, overriding pkg-config JS_LIBS linker flags for JS, overriding pkg-config ERLC_FLAGS general flags to prepend to ERLC_FLAGS FLAGS general flags to prepend to LDFLAGS and CPPFLAGS CURL_CONFIG config script used for curl CURL_CFLAGS CFLAGS used for curl CURL_LIBS LIBS used for curl ERL path to the `erl' executable ERLC path to the `erlc' executable Use these variables to override the choices made by `configure' or to help it to find libraries and programs with nonstandard names/locations. Report bugs to . _ACEOF ac_status=$? fi if test "$ac_init_help" = "recursive"; then # If there are subdirs, report their specific --help. for ac_dir in : $ac_subdirs_all; do test "x$ac_dir" = x: && continue test -d "$ac_dir" || { cd "$srcdir" && ac_pwd=`pwd` && srcdir=. && test -d "$ac_dir"; } || continue ac_builddir=. case "$ac_dir" in .) ac_dir_suffix= ac_top_builddir_sub=. ac_top_build_prefix= ;; *) ac_dir_suffix=/`$as_echo "$ac_dir" | sed 's|^\.[\\/]||'` # A ".." for each directory in $ac_dir_suffix. ac_top_builddir_sub=`$as_echo "$ac_dir_suffix" | sed 's|/[^\\/]*|/..|g;s|/||'` case $ac_top_builddir_sub in "") ac_top_builddir_sub=. ac_top_build_prefix= ;; *) ac_top_build_prefix=$ac_top_builddir_sub/ ;; esac ;; esac ac_abs_top_builddir=$ac_pwd ac_abs_builddir=$ac_pwd$ac_dir_suffix # for backward compatibility: ac_top_builddir=$ac_top_build_prefix case $srcdir in .) # We are building in place. ac_srcdir=. ac_top_srcdir=$ac_top_builddir_sub ac_abs_top_srcdir=$ac_pwd ;; [\\/]* | ?:[\\/]* ) # Absolute name. ac_srcdir=$srcdir$ac_dir_suffix; ac_top_srcdir=$srcdir ac_abs_top_srcdir=$srcdir ;; *) # Relative name. ac_srcdir=$ac_top_build_prefix$srcdir$ac_dir_suffix ac_top_srcdir=$ac_top_build_prefix$srcdir ac_abs_top_srcdir=$ac_pwd/$srcdir ;; esac ac_abs_srcdir=$ac_abs_top_srcdir$ac_dir_suffix cd "$ac_dir" || { ac_status=$?; continue; } # Check for guested configure. if test -f "$ac_srcdir/configure.gnu"; then echo && $SHELL "$ac_srcdir/configure.gnu" --help=recursive elif test -f "$ac_srcdir/configure"; then echo && $SHELL "$ac_srcdir/configure" --help=recursive else $as_echo "$as_me: WARNING: no configuration information is in $ac_dir" >&2 fi || ac_status=$? cd "$ac_pwd" || { ac_status=$?; break; } done fi test -n "$ac_init_help" && exit $ac_status if $ac_init_version; then cat <<\_ACEOF Apache CouchDB configure 1.5.0 generated by GNU Autoconf 2.69 Copyright (C) 2012 Free Software Foundation, Inc. This configure script is free software; the Free Software Foundation gives unlimited permission to copy, distribute and modify it. _ACEOF exit fi ## ------------------------ ## ## Autoconf initialization. ## ## ------------------------ ## # ac_fn_c_try_compile LINENO # -------------------------- # Try to compile conftest.$ac_ext, and return whether this succeeded. ac_fn_c_try_compile () { as_lineno=${as_lineno-"$1"} as_lineno_stack=as_lineno_stack=$as_lineno_stack rm -f conftest.$ac_objext if { { ac_try="$ac_compile" case "(($ac_try" in *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac eval ac_try_echo="\"\$as_me:${as_lineno-$LINENO}: $ac_try_echo\"" $as_echo "$ac_try_echo"; } >&5 (eval "$ac_compile") 2>conftest.err ac_status=$? if test -s conftest.err; then grep -v '^ *+' conftest.err >conftest.er1 cat conftest.er1 >&5 mv -f conftest.er1 conftest.err fi $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 test $ac_status = 0; } && { test -z "$ac_c_werror_flag" || test ! -s conftest.err } && test -s conftest.$ac_objext; then : ac_retval=0 else $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 ac_retval=1 fi eval $as_lineno_stack; ${as_lineno_stack:+:} unset as_lineno as_fn_set_status $ac_retval } # ac_fn_c_try_compile # ac_fn_c_try_cpp LINENO # ---------------------- # Try to preprocess conftest.$ac_ext, and return whether this succeeded. ac_fn_c_try_cpp () { as_lineno=${as_lineno-"$1"} as_lineno_stack=as_lineno_stack=$as_lineno_stack if { { ac_try="$ac_cpp conftest.$ac_ext" case "(($ac_try" in *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac eval ac_try_echo="\"\$as_me:${as_lineno-$LINENO}: $ac_try_echo\"" $as_echo "$ac_try_echo"; } >&5 (eval "$ac_cpp conftest.$ac_ext") 2>conftest.err ac_status=$? if test -s conftest.err; then grep -v '^ *+' conftest.err >conftest.er1 cat conftest.er1 >&5 mv -f conftest.er1 conftest.err fi $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 test $ac_status = 0; } > conftest.i && { test -z "$ac_c_preproc_warn_flag$ac_c_werror_flag" || test ! -s conftest.err }; then : ac_retval=0 else $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 ac_retval=1 fi eval $as_lineno_stack; ${as_lineno_stack:+:} unset as_lineno as_fn_set_status $ac_retval } # ac_fn_c_try_cpp # ac_fn_c_check_header_mongrel LINENO HEADER VAR INCLUDES # ------------------------------------------------------- # Tests whether HEADER exists, giving a warning if it cannot be compiled using # the include files in INCLUDES and setting the cache variable VAR # accordingly. ac_fn_c_check_header_mongrel () { as_lineno=${as_lineno-"$1"} as_lineno_stack=as_lineno_stack=$as_lineno_stack if eval \${$3+:} false; then : { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $2" >&5 $as_echo_n "checking for $2... " >&6; } if eval \${$3+:} false; then : $as_echo_n "(cached) " >&6 fi eval ac_res=\$$3 { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_res" >&5 $as_echo "$ac_res" >&6; } else # Is the header compilable? { $as_echo "$as_me:${as_lineno-$LINENO}: checking $2 usability" >&5 $as_echo_n "checking $2 usability... " >&6; } cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ $4 #include <$2> _ACEOF if ac_fn_c_try_compile "$LINENO"; then : ac_header_compiler=yes else ac_header_compiler=no fi rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_header_compiler" >&5 $as_echo "$ac_header_compiler" >&6; } # Is the header present? { $as_echo "$as_me:${as_lineno-$LINENO}: checking $2 presence" >&5 $as_echo_n "checking $2 presence... " >&6; } cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ #include <$2> _ACEOF if ac_fn_c_try_cpp "$LINENO"; then : ac_header_preproc=yes else ac_header_preproc=no fi rm -f conftest.err conftest.i conftest.$ac_ext { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_header_preproc" >&5 $as_echo "$ac_header_preproc" >&6; } # So? What about this header? case $ac_header_compiler:$ac_header_preproc:$ac_c_preproc_warn_flag in #(( yes:no: ) { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: $2: accepted by the compiler, rejected by the preprocessor!" >&5 $as_echo "$as_me: WARNING: $2: accepted by the compiler, rejected by the preprocessor!" >&2;} { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: $2: proceeding with the compiler's result" >&5 $as_echo "$as_me: WARNING: $2: proceeding with the compiler's result" >&2;} ;; no:yes:* ) { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: $2: present but cannot be compiled" >&5 $as_echo "$as_me: WARNING: $2: present but cannot be compiled" >&2;} { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: $2: check for missing prerequisite headers?" >&5 $as_echo "$as_me: WARNING: $2: check for missing prerequisite headers?" >&2;} { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: $2: see the Autoconf documentation" >&5 $as_echo "$as_me: WARNING: $2: see the Autoconf documentation" >&2;} { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: $2: section \"Present But Cannot Be Compiled\"" >&5 $as_echo "$as_me: WARNING: $2: section \"Present But Cannot Be Compiled\"" >&2;} { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: $2: proceeding with the compiler's result" >&5 $as_echo "$as_me: WARNING: $2: proceeding with the compiler's result" >&2;} ( $as_echo "## ------------------------------------------------------------ ## ## Report this to https://issues.apache.org/jira/browse/COUCHDB ## ## ------------------------------------------------------------ ##" ) | sed "s/^/$as_me: WARNING: /" >&2 ;; esac { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $2" >&5 $as_echo_n "checking for $2... " >&6; } if eval \${$3+:} false; then : $as_echo_n "(cached) " >&6 else eval "$3=\$ac_header_compiler" fi eval ac_res=\$$3 { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_res" >&5 $as_echo "$ac_res" >&6; } fi eval $as_lineno_stack; ${as_lineno_stack:+:} unset as_lineno } # ac_fn_c_check_header_mongrel # ac_fn_c_try_run LINENO # ---------------------- # Try to link conftest.$ac_ext, and return whether this succeeded. Assumes # that executables *can* be run. ac_fn_c_try_run () { as_lineno=${as_lineno-"$1"} as_lineno_stack=as_lineno_stack=$as_lineno_stack if { { ac_try="$ac_link" case "(($ac_try" in *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac eval ac_try_echo="\"\$as_me:${as_lineno-$LINENO}: $ac_try_echo\"" $as_echo "$ac_try_echo"; } >&5 (eval "$ac_link") 2>&5 ac_status=$? $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 test $ac_status = 0; } && { ac_try='./conftest$ac_exeext' { { case "(($ac_try" in *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac eval ac_try_echo="\"\$as_me:${as_lineno-$LINENO}: $ac_try_echo\"" $as_echo "$ac_try_echo"; } >&5 (eval "$ac_try") 2>&5 ac_status=$? $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 test $ac_status = 0; }; }; then : ac_retval=0 else $as_echo "$as_me: program exited with status $ac_status" >&5 $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 ac_retval=$ac_status fi rm -rf conftest.dSYM conftest_ipa8_conftest.oo eval $as_lineno_stack; ${as_lineno_stack:+:} unset as_lineno as_fn_set_status $ac_retval } # ac_fn_c_try_run # ac_fn_c_check_header_compile LINENO HEADER VAR INCLUDES # ------------------------------------------------------- # Tests whether HEADER exists and can be compiled using the include files in # INCLUDES, setting the cache variable VAR accordingly. ac_fn_c_check_header_compile () { as_lineno=${as_lineno-"$1"} as_lineno_stack=as_lineno_stack=$as_lineno_stack { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $2" >&5 $as_echo_n "checking for $2... " >&6; } if eval \${$3+:} false; then : $as_echo_n "(cached) " >&6 else cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ $4 #include <$2> _ACEOF if ac_fn_c_try_compile "$LINENO"; then : eval "$3=yes" else eval "$3=no" fi rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext fi eval ac_res=\$$3 { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_res" >&5 $as_echo "$ac_res" >&6; } eval $as_lineno_stack; ${as_lineno_stack:+:} unset as_lineno } # ac_fn_c_check_header_compile # ac_fn_c_try_link LINENO # ----------------------- # Try to link conftest.$ac_ext, and return whether this succeeded. ac_fn_c_try_link () { as_lineno=${as_lineno-"$1"} as_lineno_stack=as_lineno_stack=$as_lineno_stack rm -f conftest.$ac_objext conftest$ac_exeext if { { ac_try="$ac_link" case "(($ac_try" in *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac eval ac_try_echo="\"\$as_me:${as_lineno-$LINENO}: $ac_try_echo\"" $as_echo "$ac_try_echo"; } >&5 (eval "$ac_link") 2>conftest.err ac_status=$? if test -s conftest.err; then grep -v '^ *+' conftest.err >conftest.er1 cat conftest.er1 >&5 mv -f conftest.er1 conftest.err fi $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 test $ac_status = 0; } && { test -z "$ac_c_werror_flag" || test ! -s conftest.err } && test -s conftest$ac_exeext && { test "$cross_compiling" = yes || test -x conftest$ac_exeext }; then : ac_retval=0 else $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 ac_retval=1 fi # Delete the IPA/IPO (Inter Procedural Analysis/Optimization) information # created by the PGI compiler (conftest_ipa8_conftest.oo), as it would # interfere with the next link command; also delete a directory that is # left behind by Apple's compiler. We do this before executing the actions. rm -rf conftest.dSYM conftest_ipa8_conftest.oo eval $as_lineno_stack; ${as_lineno_stack:+:} unset as_lineno as_fn_set_status $ac_retval } # ac_fn_c_try_link # ac_fn_c_check_func LINENO FUNC VAR # ---------------------------------- # Tests whether FUNC exists, setting the cache variable VAR accordingly ac_fn_c_check_func () { as_lineno=${as_lineno-"$1"} as_lineno_stack=as_lineno_stack=$as_lineno_stack { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $2" >&5 $as_echo_n "checking for $2... " >&6; } if eval \${$3+:} false; then : $as_echo_n "(cached) " >&6 else cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ /* Define $2 to an innocuous variant, in case declares $2. For example, HP-UX 11i declares gettimeofday. */ #define $2 innocuous_$2 /* System header to define __stub macros and hopefully few prototypes, which can conflict with char $2 (); below. Prefer to if __STDC__ is defined, since exists even on freestanding compilers. */ #ifdef __STDC__ # include #else # include #endif #undef $2 /* Override any GCC internal prototype to avoid an error. Use char because int might match the return type of a GCC builtin and then its argument prototype would still apply. */ #ifdef __cplusplus extern "C" #endif char $2 (); /* The GNU C library defines this for functions which it implements to always fail with ENOSYS. Some functions are actually named something starting with __ and the normal name is an alias. */ #if defined __stub_$2 || defined __stub___$2 choke me #endif int main () { return $2 (); ; return 0; } _ACEOF if ac_fn_c_try_link "$LINENO"; then : eval "$3=yes" else eval "$3=no" fi rm -f core conftest.err conftest.$ac_objext \ conftest$ac_exeext conftest.$ac_ext fi eval ac_res=\$$3 { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_res" >&5 $as_echo "$ac_res" >&6; } eval $as_lineno_stack; ${as_lineno_stack:+:} unset as_lineno } # ac_fn_c_check_func # ac_fn_cxx_try_compile LINENO # ---------------------------- # Try to compile conftest.$ac_ext, and return whether this succeeded. ac_fn_cxx_try_compile () { as_lineno=${as_lineno-"$1"} as_lineno_stack=as_lineno_stack=$as_lineno_stack rm -f conftest.$ac_objext if { { ac_try="$ac_compile" case "(($ac_try" in *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac eval ac_try_echo="\"\$as_me:${as_lineno-$LINENO}: $ac_try_echo\"" $as_echo "$ac_try_echo"; } >&5 (eval "$ac_compile") 2>conftest.err ac_status=$? if test -s conftest.err; then grep -v '^ *+' conftest.err >conftest.er1 cat conftest.er1 >&5 mv -f conftest.er1 conftest.err fi $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 test $ac_status = 0; } && { test -z "$ac_cxx_werror_flag" || test ! -s conftest.err } && test -s conftest.$ac_objext; then : ac_retval=0 else $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 ac_retval=1 fi eval $as_lineno_stack; ${as_lineno_stack:+:} unset as_lineno as_fn_set_status $ac_retval } # ac_fn_cxx_try_compile # ac_fn_cxx_try_cpp LINENO # ------------------------ # Try to preprocess conftest.$ac_ext, and return whether this succeeded. ac_fn_cxx_try_cpp () { as_lineno=${as_lineno-"$1"} as_lineno_stack=as_lineno_stack=$as_lineno_stack if { { ac_try="$ac_cpp conftest.$ac_ext" case "(($ac_try" in *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac eval ac_try_echo="\"\$as_me:${as_lineno-$LINENO}: $ac_try_echo\"" $as_echo "$ac_try_echo"; } >&5 (eval "$ac_cpp conftest.$ac_ext") 2>conftest.err ac_status=$? if test -s conftest.err; then grep -v '^ *+' conftest.err >conftest.er1 cat conftest.er1 >&5 mv -f conftest.er1 conftest.err fi $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 test $ac_status = 0; } > conftest.i && { test -z "$ac_cxx_preproc_warn_flag$ac_cxx_werror_flag" || test ! -s conftest.err }; then : ac_retval=0 else $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 ac_retval=1 fi eval $as_lineno_stack; ${as_lineno_stack:+:} unset as_lineno as_fn_set_status $ac_retval } # ac_fn_cxx_try_cpp # ac_fn_cxx_try_link LINENO # ------------------------- # Try to link conftest.$ac_ext, and return whether this succeeded. ac_fn_cxx_try_link () { as_lineno=${as_lineno-"$1"} as_lineno_stack=as_lineno_stack=$as_lineno_stack rm -f conftest.$ac_objext conftest$ac_exeext if { { ac_try="$ac_link" case "(($ac_try" in *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac eval ac_try_echo="\"\$as_me:${as_lineno-$LINENO}: $ac_try_echo\"" $as_echo "$ac_try_echo"; } >&5 (eval "$ac_link") 2>conftest.err ac_status=$? if test -s conftest.err; then grep -v '^ *+' conftest.err >conftest.er1 cat conftest.er1 >&5 mv -f conftest.er1 conftest.err fi $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 test $ac_status = 0; } && { test -z "$ac_cxx_werror_flag" || test ! -s conftest.err } && test -s conftest$ac_exeext && { test "$cross_compiling" = yes || test -x conftest$ac_exeext }; then : ac_retval=0 else $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 ac_retval=1 fi # Delete the IPA/IPO (Inter Procedural Analysis/Optimization) information # created by the PGI compiler (conftest_ipa8_conftest.oo), as it would # interfere with the next link command; also delete a directory that is # left behind by Apple's compiler. We do this before executing the actions. rm -rf conftest.dSYM conftest_ipa8_conftest.oo eval $as_lineno_stack; ${as_lineno_stack:+:} unset as_lineno as_fn_set_status $ac_retval } # ac_fn_cxx_try_link # ac_fn_cxx_try_run LINENO # ------------------------ # Try to link conftest.$ac_ext, and return whether this succeeded. Assumes # that executables *can* be run. ac_fn_cxx_try_run () { as_lineno=${as_lineno-"$1"} as_lineno_stack=as_lineno_stack=$as_lineno_stack if { { ac_try="$ac_link" case "(($ac_try" in *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac eval ac_try_echo="\"\$as_me:${as_lineno-$LINENO}: $ac_try_echo\"" $as_echo "$ac_try_echo"; } >&5 (eval "$ac_link") 2>&5 ac_status=$? $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 test $ac_status = 0; } && { ac_try='./conftest$ac_exeext' { { case "(($ac_try" in *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac eval ac_try_echo="\"\$as_me:${as_lineno-$LINENO}: $ac_try_echo\"" $as_echo "$ac_try_echo"; } >&5 (eval "$ac_try") 2>&5 ac_status=$? $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 test $ac_status = 0; }; }; then : ac_retval=0 else $as_echo "$as_me: program exited with status $ac_status" >&5 $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 ac_retval=$ac_status fi rm -rf conftest.dSYM conftest_ipa8_conftest.oo eval $as_lineno_stack; ${as_lineno_stack:+:} unset as_lineno as_fn_set_status $ac_retval } # ac_fn_cxx_try_run # ac_fn_cxx_check_header_mongrel LINENO HEADER VAR INCLUDES # --------------------------------------------------------- # Tests whether HEADER exists, giving a warning if it cannot be compiled using # the include files in INCLUDES and setting the cache variable VAR # accordingly. ac_fn_cxx_check_header_mongrel () { as_lineno=${as_lineno-"$1"} as_lineno_stack=as_lineno_stack=$as_lineno_stack if eval \${$3+:} false; then : { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $2" >&5 $as_echo_n "checking for $2... " >&6; } if eval \${$3+:} false; then : $as_echo_n "(cached) " >&6 fi eval ac_res=\$$3 { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_res" >&5 $as_echo "$ac_res" >&6; } else # Is the header compilable? { $as_echo "$as_me:${as_lineno-$LINENO}: checking $2 usability" >&5 $as_echo_n "checking $2 usability... " >&6; } cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ $4 #include <$2> _ACEOF if ac_fn_cxx_try_compile "$LINENO"; then : ac_header_compiler=yes else ac_header_compiler=no fi rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_header_compiler" >&5 $as_echo "$ac_header_compiler" >&6; } # Is the header present? { $as_echo "$as_me:${as_lineno-$LINENO}: checking $2 presence" >&5 $as_echo_n "checking $2 presence... " >&6; } cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ #include <$2> _ACEOF if ac_fn_cxx_try_cpp "$LINENO"; then : ac_header_preproc=yes else ac_header_preproc=no fi rm -f conftest.err conftest.i conftest.$ac_ext { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_header_preproc" >&5 $as_echo "$ac_header_preproc" >&6; } # So? What about this header? case $ac_header_compiler:$ac_header_preproc:$ac_cxx_preproc_warn_flag in #(( yes:no: ) { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: $2: accepted by the compiler, rejected by the preprocessor!" >&5 $as_echo "$as_me: WARNING: $2: accepted by the compiler, rejected by the preprocessor!" >&2;} { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: $2: proceeding with the compiler's result" >&5 $as_echo "$as_me: WARNING: $2: proceeding with the compiler's result" >&2;} ;; no:yes:* ) { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: $2: present but cannot be compiled" >&5 $as_echo "$as_me: WARNING: $2: present but cannot be compiled" >&2;} { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: $2: check for missing prerequisite headers?" >&5 $as_echo "$as_me: WARNING: $2: check for missing prerequisite headers?" >&2;} { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: $2: see the Autoconf documentation" >&5 $as_echo "$as_me: WARNING: $2: see the Autoconf documentation" >&2;} { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: $2: section \"Present But Cannot Be Compiled\"" >&5 $as_echo "$as_me: WARNING: $2: section \"Present But Cannot Be Compiled\"" >&2;} { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: $2: proceeding with the compiler's result" >&5 $as_echo "$as_me: WARNING: $2: proceeding with the compiler's result" >&2;} ( $as_echo "## ------------------------------------------------------------ ## ## Report this to https://issues.apache.org/jira/browse/COUCHDB ## ## ------------------------------------------------------------ ##" ) | sed "s/^/$as_me: WARNING: /" >&2 ;; esac { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $2" >&5 $as_echo_n "checking for $2... " >&6; } if eval \${$3+:} false; then : $as_echo_n "(cached) " >&6 else eval "$3=\$ac_header_compiler" fi eval ac_res=\$$3 { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_res" >&5 $as_echo "$ac_res" >&6; } fi eval $as_lineno_stack; ${as_lineno_stack:+:} unset as_lineno } # ac_fn_cxx_check_header_mongrel # ac_fn_cxx_check_func LINENO FUNC VAR # ------------------------------------ # Tests whether FUNC exists, setting the cache variable VAR accordingly ac_fn_cxx_check_func () { as_lineno=${as_lineno-"$1"} as_lineno_stack=as_lineno_stack=$as_lineno_stack { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $2" >&5 $as_echo_n "checking for $2... " >&6; } if eval \${$3+:} false; then : $as_echo_n "(cached) " >&6 else cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ /* Define $2 to an innocuous variant, in case declares $2. For example, HP-UX 11i declares gettimeofday. */ #define $2 innocuous_$2 /* System header to define __stub macros and hopefully few prototypes, which can conflict with char $2 (); below. Prefer to if __STDC__ is defined, since exists even on freestanding compilers. */ #ifdef __STDC__ # include #else # include #endif #undef $2 /* Override any GCC internal prototype to avoid an error. Use char because int might match the return type of a GCC builtin and then its argument prototype would still apply. */ #ifdef __cplusplus extern "C" #endif char $2 (); /* The GNU C library defines this for functions which it implements to always fail with ENOSYS. Some functions are actually named something starting with __ and the normal name is an alias. */ #if defined __stub_$2 || defined __stub___$2 choke me #endif int main () { return $2 (); ; return 0; } _ACEOF if ac_fn_cxx_try_link "$LINENO"; then : eval "$3=yes" else eval "$3=no" fi rm -f core conftest.err conftest.$ac_objext \ conftest$ac_exeext conftest.$ac_ext fi eval ac_res=\$$3 { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_res" >&5 $as_echo "$ac_res" >&6; } eval $as_lineno_stack; ${as_lineno_stack:+:} unset as_lineno } # ac_fn_cxx_check_func # ac_fn_cxx_check_type LINENO TYPE VAR INCLUDES # --------------------------------------------- # Tests whether TYPE exists after having included INCLUDES, setting cache # variable VAR accordingly. ac_fn_cxx_check_type () { as_lineno=${as_lineno-"$1"} as_lineno_stack=as_lineno_stack=$as_lineno_stack { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $2" >&5 $as_echo_n "checking for $2... " >&6; } if eval \${$3+:} false; then : $as_echo_n "(cached) " >&6 else eval "$3=no" cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ $4 int main () { if (sizeof ($2)) return 0; ; return 0; } _ACEOF if ac_fn_cxx_try_compile "$LINENO"; then : cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ $4 int main () { if (sizeof (($2))) return 0; ; return 0; } _ACEOF if ac_fn_cxx_try_compile "$LINENO"; then : else eval "$3=yes" fi rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext fi rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext fi eval ac_res=\$$3 { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_res" >&5 $as_echo "$ac_res" >&6; } eval $as_lineno_stack; ${as_lineno_stack:+:} unset as_lineno } # ac_fn_cxx_check_type cat >config.log <<_ACEOF This file contains any messages produced by compilers while running configure, to aid debugging if configure makes a mistake. It was created by Apache CouchDB $as_me 1.5.0, which was generated by GNU Autoconf 2.69. Invocation command line was $ $0 $@ _ACEOF exec 5>>config.log { cat <<_ASUNAME ## --------- ## ## Platform. ## ## --------- ## hostname = `(hostname || uname -n) 2>/dev/null | sed 1q` uname -m = `(uname -m) 2>/dev/null || echo unknown` uname -r = `(uname -r) 2>/dev/null || echo unknown` uname -s = `(uname -s) 2>/dev/null || echo unknown` uname -v = `(uname -v) 2>/dev/null || echo unknown` /usr/bin/uname -p = `(/usr/bin/uname -p) 2>/dev/null || echo unknown` /bin/uname -X = `(/bin/uname -X) 2>/dev/null || echo unknown` /bin/arch = `(/bin/arch) 2>/dev/null || echo unknown` /usr/bin/arch -k = `(/usr/bin/arch -k) 2>/dev/null || echo unknown` /usr/convex/getsysinfo = `(/usr/convex/getsysinfo) 2>/dev/null || echo unknown` /usr/bin/hostinfo = `(/usr/bin/hostinfo) 2>/dev/null || echo unknown` /bin/machine = `(/bin/machine) 2>/dev/null || echo unknown` /usr/bin/oslevel = `(/usr/bin/oslevel) 2>/dev/null || echo unknown` /bin/universe = `(/bin/universe) 2>/dev/null || echo unknown` _ASUNAME as_save_IFS=$IFS; IFS=$PATH_SEPARATOR for as_dir in $PATH do IFS=$as_save_IFS test -z "$as_dir" && as_dir=. $as_echo "PATH: $as_dir" done IFS=$as_save_IFS } >&5 cat >&5 <<_ACEOF ## ----------- ## ## Core tests. ## ## ----------- ## _ACEOF # Keep a trace of the command line. # Strip out --no-create and --no-recursion so they do not pile up. # Strip out --silent because we don't want to record it for future runs. # Also quote any args containing shell meta-characters. # Make two passes to allow for proper duplicate-argument suppression. ac_configure_args= ac_configure_args0= ac_configure_args1= ac_must_keep_next=false for ac_pass in 1 2 do for ac_arg do case $ac_arg in -no-create | --no-c* | -n | -no-recursion | --no-r*) continue ;; -q | -quiet | --quiet | --quie | --qui | --qu | --q \ | -silent | --silent | --silen | --sile | --sil) continue ;; *\'*) ac_arg=`$as_echo "$ac_arg" | sed "s/'/'\\\\\\\\''/g"` ;; esac case $ac_pass in 1) as_fn_append ac_configure_args0 " '$ac_arg'" ;; 2) as_fn_append ac_configure_args1 " '$ac_arg'" if test $ac_must_keep_next = true; then ac_must_keep_next=false # Got value, back to normal. else case $ac_arg in *=* | --config-cache | -C | -disable-* | --disable-* \ | -enable-* | --enable-* | -gas | --g* | -nfp | --nf* \ | -q | -quiet | --q* | -silent | --sil* | -v | -verb* \ | -with-* | --with-* | -without-* | --without-* | --x) case "$ac_configure_args0 " in "$ac_configure_args1"*" '$ac_arg' "* ) continue ;; esac ;; -* ) ac_must_keep_next=true ;; esac fi as_fn_append ac_configure_args " '$ac_arg'" ;; esac done done { ac_configure_args0=; unset ac_configure_args0;} { ac_configure_args1=; unset ac_configure_args1;} # When interrupted or exit'd, cleanup temporary files, and complete # config.log. We remove comments because anyway the quotes in there # would cause problems or look ugly. # WARNING: Use '\'' to represent an apostrophe within the trap. # WARNING: Do not start the trap code with a newline, due to a FreeBSD 4.0 bug. trap 'exit_status=$? # Save into config.log some information that might help in debugging. { echo $as_echo "## ---------------- ## ## Cache variables. ## ## ---------------- ##" echo # The following way of writing the cache mishandles newlines in values, ( for ac_var in `(set) 2>&1 | sed -n '\''s/^\([a-zA-Z_][a-zA-Z0-9_]*\)=.*/\1/p'\''`; do eval ac_val=\$$ac_var case $ac_val in #( *${as_nl}*) case $ac_var in #( *_cv_*) { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: cache variable $ac_var contains a newline" >&5 $as_echo "$as_me: WARNING: cache variable $ac_var contains a newline" >&2;} ;; esac case $ac_var in #( _ | IFS | as_nl) ;; #( BASH_ARGV | BASH_SOURCE) eval $ac_var= ;; #( *) { eval $ac_var=; unset $ac_var;} ;; esac ;; esac done (set) 2>&1 | case $as_nl`(ac_space='\'' '\''; set) 2>&1` in #( *${as_nl}ac_space=\ *) sed -n \ "s/'\''/'\''\\\\'\'''\''/g; s/^\\([_$as_cr_alnum]*_cv_[_$as_cr_alnum]*\\)=\\(.*\\)/\\1='\''\\2'\''/p" ;; #( *) sed -n "/^[_$as_cr_alnum]*_cv_[_$as_cr_alnum]*=/p" ;; esac | sort ) echo $as_echo "## ----------------- ## ## Output variables. ## ## ----------------- ##" echo for ac_var in $ac_subst_vars do eval ac_val=\$$ac_var case $ac_val in *\'\''*) ac_val=`$as_echo "$ac_val" | sed "s/'\''/'\''\\\\\\\\'\'''\''/g"`;; esac $as_echo "$ac_var='\''$ac_val'\''" done | sort echo if test -n "$ac_subst_files"; then $as_echo "## ------------------- ## ## File substitutions. ## ## ------------------- ##" echo for ac_var in $ac_subst_files do eval ac_val=\$$ac_var case $ac_val in *\'\''*) ac_val=`$as_echo "$ac_val" | sed "s/'\''/'\''\\\\\\\\'\'''\''/g"`;; esac $as_echo "$ac_var='\''$ac_val'\''" done | sort echo fi if test -s confdefs.h; then $as_echo "## ----------- ## ## confdefs.h. ## ## ----------- ##" echo cat confdefs.h echo fi test "$ac_signal" != 0 && $as_echo "$as_me: caught signal $ac_signal" $as_echo "$as_me: exit $exit_status" } >&5 rm -f core *.core core.conftest.* && rm -f -r conftest* confdefs* conf$$* $ac_clean_files && exit $exit_status ' 0 for ac_signal in 1 2 13 15; do trap 'ac_signal='$ac_signal'; as_fn_exit 1' $ac_signal done ac_signal=0 # confdefs.h avoids OS command line length limits that DEFS can exceed. rm -f -r conftest* confdefs.h $as_echo "/* confdefs.h */" > confdefs.h # Predefined preprocessor variables. cat >>confdefs.h <<_ACEOF #define PACKAGE_NAME "$PACKAGE_NAME" _ACEOF cat >>confdefs.h <<_ACEOF #define PACKAGE_TARNAME "$PACKAGE_TARNAME" _ACEOF cat >>confdefs.h <<_ACEOF #define PACKAGE_VERSION "$PACKAGE_VERSION" _ACEOF cat >>confdefs.h <<_ACEOF #define PACKAGE_STRING "$PACKAGE_STRING" _ACEOF cat >>confdefs.h <<_ACEOF #define PACKAGE_BUGREPORT "$PACKAGE_BUGREPORT" _ACEOF cat >>confdefs.h <<_ACEOF #define PACKAGE_URL "$PACKAGE_URL" _ACEOF # Let the site file select an alternate cache file if it wants to. # Prefer an explicitly selected file to automatically selected ones. ac_site_file1=NONE ac_site_file2=NONE if test -n "$CONFIG_SITE"; then # We do not want a PATH search for config.site. case $CONFIG_SITE in #(( -*) ac_site_file1=./$CONFIG_SITE;; */*) ac_site_file1=$CONFIG_SITE;; *) ac_site_file1=./$CONFIG_SITE;; esac elif test "x$prefix" != xNONE; then ac_site_file1=$prefix/share/config.site ac_site_file2=$prefix/etc/config.site else ac_site_file1=$ac_default_prefix/share/config.site ac_site_file2=$ac_default_prefix/etc/config.site fi for ac_site_file in "$ac_site_file1" "$ac_site_file2" do test "x$ac_site_file" = xNONE && continue if test /dev/null != "$ac_site_file" && test -r "$ac_site_file"; then { $as_echo "$as_me:${as_lineno-$LINENO}: loading site script $ac_site_file" >&5 $as_echo "$as_me: loading site script $ac_site_file" >&6;} sed 's/^/| /' "$ac_site_file" >&5 . "$ac_site_file" \ || { { $as_echo "$as_me:${as_lineno-$LINENO}: error: in \`$ac_pwd':" >&5 $as_echo "$as_me: error: in \`$ac_pwd':" >&2;} as_fn_error $? "failed to load site script $ac_site_file See \`config.log' for more details" "$LINENO" 5; } fi done if test -r "$cache_file"; then # Some versions of bash will fail to source /dev/null (special files # actually), so we avoid doing that. DJGPP emulates it as a regular file. if test /dev/null != "$cache_file" && test -f "$cache_file"; then { $as_echo "$as_me:${as_lineno-$LINENO}: loading cache $cache_file" >&5 $as_echo "$as_me: loading cache $cache_file" >&6;} case $cache_file in [\\/]* | ?:[\\/]* ) . "$cache_file";; *) . "./$cache_file";; esac fi else { $as_echo "$as_me:${as_lineno-$LINENO}: creating cache $cache_file" >&5 $as_echo "$as_me: creating cache $cache_file" >&6;} >$cache_file fi # Check that the precious variables saved in the cache have kept the same # value. ac_cache_corrupted=false for ac_var in $ac_precious_vars; do eval ac_old_set=\$ac_cv_env_${ac_var}_set eval ac_new_set=\$ac_env_${ac_var}_set eval ac_old_val=\$ac_cv_env_${ac_var}_value eval ac_new_val=\$ac_env_${ac_var}_value case $ac_old_set,$ac_new_set in set,) { $as_echo "$as_me:${as_lineno-$LINENO}: error: \`$ac_var' was set to \`$ac_old_val' in the previous run" >&5 $as_echo "$as_me: error: \`$ac_var' was set to \`$ac_old_val' in the previous run" >&2;} ac_cache_corrupted=: ;; ,set) { $as_echo "$as_me:${as_lineno-$LINENO}: error: \`$ac_var' was not set in the previous run" >&5 $as_echo "$as_me: error: \`$ac_var' was not set in the previous run" >&2;} ac_cache_corrupted=: ;; ,);; *) if test "x$ac_old_val" != "x$ac_new_val"; then # differences in whitespace do not lead to failure. ac_old_val_w=`echo x $ac_old_val` ac_new_val_w=`echo x $ac_new_val` if test "$ac_old_val_w" != "$ac_new_val_w"; then { $as_echo "$as_me:${as_lineno-$LINENO}: error: \`$ac_var' has changed since the previous run:" >&5 $as_echo "$as_me: error: \`$ac_var' has changed since the previous run:" >&2;} ac_cache_corrupted=: else { $as_echo "$as_me:${as_lineno-$LINENO}: warning: ignoring whitespace changes in \`$ac_var' since the previous run:" >&5 $as_echo "$as_me: warning: ignoring whitespace changes in \`$ac_var' since the previous run:" >&2;} eval $ac_var=\$ac_old_val fi { $as_echo "$as_me:${as_lineno-$LINENO}: former value: \`$ac_old_val'" >&5 $as_echo "$as_me: former value: \`$ac_old_val'" >&2;} { $as_echo "$as_me:${as_lineno-$LINENO}: current value: \`$ac_new_val'" >&5 $as_echo "$as_me: current value: \`$ac_new_val'" >&2;} fi;; esac # Pass precious variables to config.status. if test "$ac_new_set" = set; then case $ac_new_val in *\'*) ac_arg=$ac_var=`$as_echo "$ac_new_val" | sed "s/'/'\\\\\\\\''/g"` ;; *) ac_arg=$ac_var=$ac_new_val ;; esac case " $ac_configure_args " in *" '$ac_arg' "*) ;; # Avoid dups. Use of quotes ensures accuracy. *) as_fn_append ac_configure_args " '$ac_arg'" ;; esac fi done if $ac_cache_corrupted; then { $as_echo "$as_me:${as_lineno-$LINENO}: error: in \`$ac_pwd':" >&5 $as_echo "$as_me: error: in \`$ac_pwd':" >&2;} { $as_echo "$as_me:${as_lineno-$LINENO}: error: changes in the environment can compromise the build" >&5 $as_echo "$as_me: error: changes in the environment can compromise the build" >&2;} as_fn_error $? "run \`make distclean' and/or \`rm $cache_file' and start over" "$LINENO" 5 fi ## -------------------- ## ## Main body of script. ## ## -------------------- ## ac_ext=c ac_cpp='$CPP $CPPFLAGS' ac_compile='$CC -c $CFLAGS $CPPFLAGS conftest.$ac_ext >&5' ac_link='$CC -o conftest$ac_exeext $CFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5' ac_compiler_gnu=$ac_cv_c_compiler_gnu ac_aux_dir= for ac_dir in build-aux "$srcdir"/build-aux; do if test -f "$ac_dir/install-sh"; then ac_aux_dir=$ac_dir ac_install_sh="$ac_aux_dir/install-sh -c" break elif test -f "$ac_dir/install.sh"; then ac_aux_dir=$ac_dir ac_install_sh="$ac_aux_dir/install.sh -c" break elif test -f "$ac_dir/shtool"; then ac_aux_dir=$ac_dir ac_install_sh="$ac_aux_dir/shtool install -c" break fi done if test -z "$ac_aux_dir"; then as_fn_error $? "cannot find install-sh, install.sh, or shtool in build-aux \"$srcdir\"/build-aux" "$LINENO" 5 fi # These three variables are undocumented and unsupported, # and are intended to be withdrawn in a future Autoconf release. # They can cause serious problems if a builder's source tree is in a directory # whose full name contains unusual characters. ac_config_guess="$SHELL $ac_aux_dir/config.guess" # Please don't use this var. ac_config_sub="$SHELL $ac_aux_dir/config.sub" # Please don't use this var. ac_configure="$SHELL $ac_aux_dir/configure" # Please don't use this var. ac_config_headers="$ac_config_headers config.h" ac_config_headers="$ac_config_headers src/snappy/google-snappy/config.h" am__api_version='1.11' # Find a good install program. We prefer a C program (faster), # so one script is as good as another. But avoid the broken or # incompatible versions: # SysV /etc/install, /usr/sbin/install # SunOS /usr/etc/install # IRIX /sbin/install # AIX /bin/install # AmigaOS /C/install, which installs bootblocks on floppy discs # AIX 4 /usr/bin/installbsd, which doesn't work without a -g flag # AFS /usr/afsws/bin/install, which mishandles nonexistent args # SVR4 /usr/ucb/install, which tries to use the nonexistent group "staff" # OS/2's system install, which has a completely different semantic # ./install, which can be erroneously created by make from ./install.sh. # Reject install programs that cannot install multiple files. { $as_echo "$as_me:${as_lineno-$LINENO}: checking for a BSD-compatible install" >&5 $as_echo_n "checking for a BSD-compatible install... " >&6; } if test -z "$INSTALL"; then if ${ac_cv_path_install+:} false; then : $as_echo_n "(cached) " >&6 else as_save_IFS=$IFS; IFS=$PATH_SEPARATOR for as_dir in $PATH do IFS=$as_save_IFS test -z "$as_dir" && as_dir=. # Account for people who put trailing slashes in PATH elements. case $as_dir/ in #(( ./ | .// | /[cC]/* | \ /etc/* | /usr/sbin/* | /usr/etc/* | /sbin/* | /usr/afsws/bin/* | \ ?:[\\/]os2[\\/]install[\\/]* | ?:[\\/]OS2[\\/]INSTALL[\\/]* | \ /usr/ucb/* ) ;; *) # OSF1 and SCO ODT 3.0 have their own names for install. # Don't use installbsd from OSF since it installs stuff as root # by default. for ac_prog in ginstall scoinst install; do for ac_exec_ext in '' $ac_executable_extensions; do if as_fn_executable_p "$as_dir/$ac_prog$ac_exec_ext"; then if test $ac_prog = install && grep dspmsg "$as_dir/$ac_prog$ac_exec_ext" >/dev/null 2>&1; then # AIX install. It has an incompatible calling convention. : elif test $ac_prog = install && grep pwplus "$as_dir/$ac_prog$ac_exec_ext" >/dev/null 2>&1; then # program-specific install script used by HP pwplus--don't use. : else rm -rf conftest.one conftest.two conftest.dir echo one > conftest.one echo two > conftest.two mkdir conftest.dir if "$as_dir/$ac_prog$ac_exec_ext" -c conftest.one conftest.two "`pwd`/conftest.dir" && test -s conftest.one && test -s conftest.two && test -s conftest.dir/conftest.one && test -s conftest.dir/conftest.two then ac_cv_path_install="$as_dir/$ac_prog$ac_exec_ext -c" break 3 fi fi fi done done ;; esac done IFS=$as_save_IFS rm -rf conftest.one conftest.two conftest.dir fi if test "${ac_cv_path_install+set}" = set; then INSTALL=$ac_cv_path_install else # As a last resort, use the slow shell script. Don't cache a # value for INSTALL within a source directory, because that will # break other packages using the cache if that directory is # removed, or if the value is a relative name. INSTALL=$ac_install_sh fi fi { $as_echo "$as_me:${as_lineno-$LINENO}: result: $INSTALL" >&5 $as_echo "$INSTALL" >&6; } # Use test -z because SunOS4 sh mishandles braces in ${var-val}. # It thinks the first close brace ends the variable substitution. test -z "$INSTALL_PROGRAM" && INSTALL_PROGRAM='${INSTALL}' test -z "$INSTALL_SCRIPT" && INSTALL_SCRIPT='${INSTALL}' test -z "$INSTALL_DATA" && INSTALL_DATA='${INSTALL} -m 644' { $as_echo "$as_me:${as_lineno-$LINENO}: checking whether build environment is sane" >&5 $as_echo_n "checking whether build environment is sane... " >&6; } # Just in case sleep 1 echo timestamp > conftest.file # Reject unsafe characters in $srcdir or the absolute working directory # name. Accept space and tab only in the latter. am_lf=' ' case `pwd` in *[\\\"\#\$\&\'\`$am_lf]*) as_fn_error $? "unsafe absolute working directory name" "$LINENO" 5;; esac case $srcdir in *[\\\"\#\$\&\'\`$am_lf\ \ ]*) as_fn_error $? "unsafe srcdir value: \`$srcdir'" "$LINENO" 5;; esac # Do `set' in a subshell so we don't clobber the current shell's # arguments. Must try -L first in case configure is actually a # symlink; some systems play weird games with the mod time of symlinks # (eg FreeBSD returns the mod time of the symlink's containing # directory). if ( set X `ls -Lt "$srcdir/configure" conftest.file 2> /dev/null` if test "$*" = "X"; then # -L didn't work. set X `ls -t "$srcdir/configure" conftest.file` fi rm -f conftest.file if test "$*" != "X $srcdir/configure conftest.file" \ && test "$*" != "X conftest.file $srcdir/configure"; then # If neither matched, then we have a broken ls. This can happen # if, for instance, CONFIG_SHELL is bash and it inherits a # broken ls alias from the environment. This has actually # happened. Such a system could not be considered "sane". as_fn_error $? "ls -t appears to fail. Make sure there is not a broken alias in your environment" "$LINENO" 5 fi test "$2" = conftest.file ) then # Ok. : else as_fn_error $? "newly created file is older than distributed files! Check your system clock" "$LINENO" 5 fi { $as_echo "$as_me:${as_lineno-$LINENO}: result: yes" >&5 $as_echo "yes" >&6; } test "$program_prefix" != NONE && program_transform_name="s&^&$program_prefix&;$program_transform_name" # Use a double $ so make ignores it. test "$program_suffix" != NONE && program_transform_name="s&\$&$program_suffix&;$program_transform_name" # Double any \ or $. # By default was `s,x,x', remove it if useless. ac_script='s/[\\$]/&&/g;s/;s,x,x,$//' program_transform_name=`$as_echo "$program_transform_name" | sed "$ac_script"` # expand $ac_aux_dir to an absolute path am_aux_dir=`cd $ac_aux_dir && pwd` if test x"${MISSING+set}" != xset; then case $am_aux_dir in *\ * | *\ *) MISSING="\${SHELL} \"$am_aux_dir/missing\"" ;; *) MISSING="\${SHELL} $am_aux_dir/missing" ;; esac fi # Use eval to expand $SHELL if eval "$MISSING --run true"; then am_missing_run="$MISSING --run " else am_missing_run= { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: \`missing' script is too old or missing" >&5 $as_echo "$as_me: WARNING: \`missing' script is too old or missing" >&2;} fi if test x"${install_sh}" != xset; then case $am_aux_dir in *\ * | *\ *) install_sh="\${SHELL} '$am_aux_dir/install-sh'" ;; *) install_sh="\${SHELL} $am_aux_dir/install-sh" esac fi # Installed binaries are usually stripped using `strip' when the user # run `make install-strip'. However `strip' might not be the right # tool to use in cross-compilation environments, therefore Automake # will honor the `STRIP' environment variable to overrule this program. if test "$cross_compiling" != no; then if test -n "$ac_tool_prefix"; then # Extract the first word of "${ac_tool_prefix}strip", so it can be a program name with args. set dummy ${ac_tool_prefix}strip; ac_word=$2 { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 $as_echo_n "checking for $ac_word... " >&6; } if ${ac_cv_prog_STRIP+:} false; then : $as_echo_n "(cached) " >&6 else if test -n "$STRIP"; then ac_cv_prog_STRIP="$STRIP" # Let the user override the test. else as_save_IFS=$IFS; IFS=$PATH_SEPARATOR for as_dir in $PATH do IFS=$as_save_IFS test -z "$as_dir" && as_dir=. for ac_exec_ext in '' $ac_executable_extensions; do if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then ac_cv_prog_STRIP="${ac_tool_prefix}strip" $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5 break 2 fi done done IFS=$as_save_IFS fi fi STRIP=$ac_cv_prog_STRIP if test -n "$STRIP"; then { $as_echo "$as_me:${as_lineno-$LINENO}: result: $STRIP" >&5 $as_echo "$STRIP" >&6; } else { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 $as_echo "no" >&6; } fi fi if test -z "$ac_cv_prog_STRIP"; then ac_ct_STRIP=$STRIP # Extract the first word of "strip", so it can be a program name with args. set dummy strip; ac_word=$2 { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 $as_echo_n "checking for $ac_word... " >&6; } if ${ac_cv_prog_ac_ct_STRIP+:} false; then : $as_echo_n "(cached) " >&6 else if test -n "$ac_ct_STRIP"; then ac_cv_prog_ac_ct_STRIP="$ac_ct_STRIP" # Let the user override the test. else as_save_IFS=$IFS; IFS=$PATH_SEPARATOR for as_dir in $PATH do IFS=$as_save_IFS test -z "$as_dir" && as_dir=. for ac_exec_ext in '' $ac_executable_extensions; do if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then ac_cv_prog_ac_ct_STRIP="strip" $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5 break 2 fi done done IFS=$as_save_IFS fi fi ac_ct_STRIP=$ac_cv_prog_ac_ct_STRIP if test -n "$ac_ct_STRIP"; then { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_ct_STRIP" >&5 $as_echo "$ac_ct_STRIP" >&6; } else { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 $as_echo "no" >&6; } fi if test "x$ac_ct_STRIP" = x; then STRIP=":" else case $cross_compiling:$ac_tool_warned in yes:) { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: using cross tools not prefixed with host triplet" >&5 $as_echo "$as_me: WARNING: using cross tools not prefixed with host triplet" >&2;} ac_tool_warned=yes ;; esac STRIP=$ac_ct_STRIP fi else STRIP="$ac_cv_prog_STRIP" fi fi INSTALL_STRIP_PROGRAM="\$(install_sh) -c -s" { $as_echo "$as_me:${as_lineno-$LINENO}: checking for a thread-safe mkdir -p" >&5 $as_echo_n "checking for a thread-safe mkdir -p... " >&6; } if test -z "$MKDIR_P"; then if ${ac_cv_path_mkdir+:} false; then : $as_echo_n "(cached) " >&6 else as_save_IFS=$IFS; IFS=$PATH_SEPARATOR for as_dir in $PATH$PATH_SEPARATOR/opt/sfw/bin do IFS=$as_save_IFS test -z "$as_dir" && as_dir=. for ac_prog in mkdir gmkdir; do for ac_exec_ext in '' $ac_executable_extensions; do as_fn_executable_p "$as_dir/$ac_prog$ac_exec_ext" || continue case `"$as_dir/$ac_prog$ac_exec_ext" --version 2>&1` in #( 'mkdir (GNU coreutils) '* | \ 'mkdir (coreutils) '* | \ 'mkdir (fileutils) '4.1*) ac_cv_path_mkdir=$as_dir/$ac_prog$ac_exec_ext break 3;; esac done done done IFS=$as_save_IFS fi test -d ./--version && rmdir ./--version if test "${ac_cv_path_mkdir+set}" = set; then MKDIR_P="$ac_cv_path_mkdir -p" else # As a last resort, use the slow shell script. Don't cache a # value for MKDIR_P within a source directory, because that will # break other packages using the cache if that directory is # removed, or if the value is a relative name. MKDIR_P="$ac_install_sh -d" fi fi { $as_echo "$as_me:${as_lineno-$LINENO}: result: $MKDIR_P" >&5 $as_echo "$MKDIR_P" >&6; } mkdir_p="$MKDIR_P" case $mkdir_p in [\\/$]* | ?:[\\/]*) ;; */*) mkdir_p="\$(top_builddir)/$mkdir_p" ;; esac for ac_prog in gawk mawk nawk awk do # Extract the first word of "$ac_prog", so it can be a program name with args. set dummy $ac_prog; ac_word=$2 { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 $as_echo_n "checking for $ac_word... " >&6; } if ${ac_cv_prog_AWK+:} false; then : $as_echo_n "(cached) " >&6 else if test -n "$AWK"; then ac_cv_prog_AWK="$AWK" # Let the user override the test. else as_save_IFS=$IFS; IFS=$PATH_SEPARATOR for as_dir in $PATH do IFS=$as_save_IFS test -z "$as_dir" && as_dir=. for ac_exec_ext in '' $ac_executable_extensions; do if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then ac_cv_prog_AWK="$ac_prog" $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5 break 2 fi done done IFS=$as_save_IFS fi fi AWK=$ac_cv_prog_AWK if test -n "$AWK"; then { $as_echo "$as_me:${as_lineno-$LINENO}: result: $AWK" >&5 $as_echo "$AWK" >&6; } else { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 $as_echo "no" >&6; } fi test -n "$AWK" && break done { $as_echo "$as_me:${as_lineno-$LINENO}: checking whether ${MAKE-make} sets \$(MAKE)" >&5 $as_echo_n "checking whether ${MAKE-make} sets \$(MAKE)... " >&6; } set x ${MAKE-make} ac_make=`$as_echo "$2" | sed 's/+/p/g; s/[^a-zA-Z0-9_]/_/g'` if eval \${ac_cv_prog_make_${ac_make}_set+:} false; then : $as_echo_n "(cached) " >&6 else cat >conftest.make <<\_ACEOF SHELL = /bin/sh all: @echo '@@@%%%=$(MAKE)=@@@%%%' _ACEOF # GNU make sometimes prints "make[1]: Entering ...", which would confuse us. case `${MAKE-make} -f conftest.make 2>/dev/null` in *@@@%%%=?*=@@@%%%*) eval ac_cv_prog_make_${ac_make}_set=yes;; *) eval ac_cv_prog_make_${ac_make}_set=no;; esac rm -f conftest.make fi if eval test \$ac_cv_prog_make_${ac_make}_set = yes; then { $as_echo "$as_me:${as_lineno-$LINENO}: result: yes" >&5 $as_echo "yes" >&6; } SET_MAKE= else { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 $as_echo "no" >&6; } SET_MAKE="MAKE=${MAKE-make}" fi rm -rf .tst 2>/dev/null mkdir .tst 2>/dev/null if test -d .tst; then am__leading_dot=. else am__leading_dot=_ fi rmdir .tst 2>/dev/null if test "`cd $srcdir && pwd`" != "`pwd`"; then # Use -I$(srcdir) only when $(srcdir) != ., so that make's output # is not polluted with repeated "-I." am__isrc=' -I$(srcdir)' # test to see if srcdir already configured if test -f $srcdir/config.status; then as_fn_error $? "source directory already configured; run \"make distclean\" there first" "$LINENO" 5 fi fi # test whether we have cygpath if test -z "$CYGPATH_W"; then if (cygpath --version) >/dev/null 2>/dev/null; then CYGPATH_W='cygpath -w' else CYGPATH_W=echo fi fi # Define the identity of the package. PACKAGE='apache-couchdb' VERSION='1.5.0' cat >>confdefs.h <<_ACEOF #define PACKAGE "$PACKAGE" _ACEOF cat >>confdefs.h <<_ACEOF #define VERSION "$VERSION" _ACEOF # Some tools Automake needs. ACLOCAL=${ACLOCAL-"${am_missing_run}aclocal-${am__api_version}"} AUTOCONF=${AUTOCONF-"${am_missing_run}autoconf"} AUTOMAKE=${AUTOMAKE-"${am_missing_run}automake-${am__api_version}"} AUTOHEADER=${AUTOHEADER-"${am_missing_run}autoheader"} MAKEINFO=${MAKEINFO-"${am_missing_run}makeinfo"} # We need awk for the "check" target. The system "awk" is bad on # some platforms. # Always define AMTAR for backward compatibility. Yes, it's still used # in the wild :-( We should find a proper way to deprecate it ... AMTAR='$${TAR-tar}' am__tar='$${TAR-tar} chof - "$$tardir"' am__untar='$${TAR-tar} xf -' DEPDIR="${am__leading_dot}deps" ac_config_commands="$ac_config_commands depfiles" am_make=${MAKE-make} cat > confinc << 'END' am__doit: @echo this is the am__doit target .PHONY: am__doit END # If we don't find an include directive, just comment out the code. { $as_echo "$as_me:${as_lineno-$LINENO}: checking for style of include used by $am_make" >&5 $as_echo_n "checking for style of include used by $am_make... " >&6; } am__include="#" am__quote= _am_result=none # First try GNU make style include. echo "include confinc" > confmf # Ignore all kinds of additional output from `make'. case `$am_make -s -f confmf 2> /dev/null` in #( *the\ am__doit\ target*) am__include=include am__quote= _am_result=GNU ;; esac # Now try BSD make style include. if test "$am__include" = "#"; then echo '.include "confinc"' > confmf case `$am_make -s -f confmf 2> /dev/null` in #( *the\ am__doit\ target*) am__include=.include am__quote="\"" _am_result=BSD ;; esac fi { $as_echo "$as_me:${as_lineno-$LINENO}: result: $_am_result" >&5 $as_echo "$_am_result" >&6; } rm -f confinc confmf # Check whether --enable-dependency-tracking was given. if test "${enable_dependency_tracking+set}" = set; then : enableval=$enable_dependency_tracking; fi if test "x$enable_dependency_tracking" != xno; then am_depcomp="$ac_aux_dir/depcomp" AMDEPBACKSLASH='\' am__nodep='_no' fi if test "x$enable_dependency_tracking" != xno; then AMDEP_TRUE= AMDEP_FALSE='#' else AMDEP_TRUE='#' AMDEP_FALSE= fi ac_ext=c ac_cpp='$CPP $CPPFLAGS' ac_compile='$CC -c $CFLAGS $CPPFLAGS conftest.$ac_ext >&5' ac_link='$CC -o conftest$ac_exeext $CFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5' ac_compiler_gnu=$ac_cv_c_compiler_gnu if test -n "$ac_tool_prefix"; then # Extract the first word of "${ac_tool_prefix}gcc", so it can be a program name with args. set dummy ${ac_tool_prefix}gcc; ac_word=$2 { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 $as_echo_n "checking for $ac_word... " >&6; } if ${ac_cv_prog_CC+:} false; then : $as_echo_n "(cached) " >&6 else if test -n "$CC"; then ac_cv_prog_CC="$CC" # Let the user override the test. else as_save_IFS=$IFS; IFS=$PATH_SEPARATOR for as_dir in $PATH do IFS=$as_save_IFS test -z "$as_dir" && as_dir=. for ac_exec_ext in '' $ac_executable_extensions; do if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then ac_cv_prog_CC="${ac_tool_prefix}gcc" $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5 break 2 fi done done IFS=$as_save_IFS fi fi CC=$ac_cv_prog_CC if test -n "$CC"; then { $as_echo "$as_me:${as_lineno-$LINENO}: result: $CC" >&5 $as_echo "$CC" >&6; } else { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 $as_echo "no" >&6; } fi fi if test -z "$ac_cv_prog_CC"; then ac_ct_CC=$CC # Extract the first word of "gcc", so it can be a program name with args. set dummy gcc; ac_word=$2 { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 $as_echo_n "checking for $ac_word... " >&6; } if ${ac_cv_prog_ac_ct_CC+:} false; then : $as_echo_n "(cached) " >&6 else if test -n "$ac_ct_CC"; then ac_cv_prog_ac_ct_CC="$ac_ct_CC" # Let the user override the test. else as_save_IFS=$IFS; IFS=$PATH_SEPARATOR for as_dir in $PATH do IFS=$as_save_IFS test -z "$as_dir" && as_dir=. for ac_exec_ext in '' $ac_executable_extensions; do if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then ac_cv_prog_ac_ct_CC="gcc" $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5 break 2 fi done done IFS=$as_save_IFS fi fi ac_ct_CC=$ac_cv_prog_ac_ct_CC if test -n "$ac_ct_CC"; then { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_ct_CC" >&5 $as_echo "$ac_ct_CC" >&6; } else { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 $as_echo "no" >&6; } fi if test "x$ac_ct_CC" = x; then CC="" else case $cross_compiling:$ac_tool_warned in yes:) { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: using cross tools not prefixed with host triplet" >&5 $as_echo "$as_me: WARNING: using cross tools not prefixed with host triplet" >&2;} ac_tool_warned=yes ;; esac CC=$ac_ct_CC fi else CC="$ac_cv_prog_CC" fi if test -z "$CC"; then if test -n "$ac_tool_prefix"; then # Extract the first word of "${ac_tool_prefix}cc", so it can be a program name with args. set dummy ${ac_tool_prefix}cc; ac_word=$2 { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 $as_echo_n "checking for $ac_word... " >&6; } if ${ac_cv_prog_CC+:} false; then : $as_echo_n "(cached) " >&6 else if test -n "$CC"; then ac_cv_prog_CC="$CC" # Let the user override the test. else as_save_IFS=$IFS; IFS=$PATH_SEPARATOR for as_dir in $PATH do IFS=$as_save_IFS test -z "$as_dir" && as_dir=. for ac_exec_ext in '' $ac_executable_extensions; do if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then ac_cv_prog_CC="${ac_tool_prefix}cc" $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5 break 2 fi done done IFS=$as_save_IFS fi fi CC=$ac_cv_prog_CC if test -n "$CC"; then { $as_echo "$as_me:${as_lineno-$LINENO}: result: $CC" >&5 $as_echo "$CC" >&6; } else { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 $as_echo "no" >&6; } fi fi fi if test -z "$CC"; then # Extract the first word of "cc", so it can be a program name with args. set dummy cc; ac_word=$2 { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 $as_echo_n "checking for $ac_word... " >&6; } if ${ac_cv_prog_CC+:} false; then : $as_echo_n "(cached) " >&6 else if test -n "$CC"; then ac_cv_prog_CC="$CC" # Let the user override the test. else ac_prog_rejected=no as_save_IFS=$IFS; IFS=$PATH_SEPARATOR for as_dir in $PATH do IFS=$as_save_IFS test -z "$as_dir" && as_dir=. for ac_exec_ext in '' $ac_executable_extensions; do if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then if test "$as_dir/$ac_word$ac_exec_ext" = "/usr/ucb/cc"; then ac_prog_rejected=yes continue fi ac_cv_prog_CC="cc" $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5 break 2 fi done done IFS=$as_save_IFS if test $ac_prog_rejected = yes; then # We found a bogon in the path, so make sure we never use it. set dummy $ac_cv_prog_CC shift if test $# != 0; then # We chose a different compiler from the bogus one. # However, it has the same basename, so the bogon will be chosen # first if we set CC to just the basename; use the full file name. shift ac_cv_prog_CC="$as_dir/$ac_word${1+' '}$@" fi fi fi fi CC=$ac_cv_prog_CC if test -n "$CC"; then { $as_echo "$as_me:${as_lineno-$LINENO}: result: $CC" >&5 $as_echo "$CC" >&6; } else { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 $as_echo "no" >&6; } fi fi if test -z "$CC"; then if test -n "$ac_tool_prefix"; then for ac_prog in cl.exe do # Extract the first word of "$ac_tool_prefix$ac_prog", so it can be a program name with args. set dummy $ac_tool_prefix$ac_prog; ac_word=$2 { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 $as_echo_n "checking for $ac_word... " >&6; } if ${ac_cv_prog_CC+:} false; then : $as_echo_n "(cached) " >&6 else if test -n "$CC"; then ac_cv_prog_CC="$CC" # Let the user override the test. else as_save_IFS=$IFS; IFS=$PATH_SEPARATOR for as_dir in $PATH do IFS=$as_save_IFS test -z "$as_dir" && as_dir=. for ac_exec_ext in '' $ac_executable_extensions; do if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then ac_cv_prog_CC="$ac_tool_prefix$ac_prog" $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5 break 2 fi done done IFS=$as_save_IFS fi fi CC=$ac_cv_prog_CC if test -n "$CC"; then { $as_echo "$as_me:${as_lineno-$LINENO}: result: $CC" >&5 $as_echo "$CC" >&6; } else { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 $as_echo "no" >&6; } fi test -n "$CC" && break done fi if test -z "$CC"; then ac_ct_CC=$CC for ac_prog in cl.exe do # Extract the first word of "$ac_prog", so it can be a program name with args. set dummy $ac_prog; ac_word=$2 { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 $as_echo_n "checking for $ac_word... " >&6; } if ${ac_cv_prog_ac_ct_CC+:} false; then : $as_echo_n "(cached) " >&6 else if test -n "$ac_ct_CC"; then ac_cv_prog_ac_ct_CC="$ac_ct_CC" # Let the user override the test. else as_save_IFS=$IFS; IFS=$PATH_SEPARATOR for as_dir in $PATH do IFS=$as_save_IFS test -z "$as_dir" && as_dir=. for ac_exec_ext in '' $ac_executable_extensions; do if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then ac_cv_prog_ac_ct_CC="$ac_prog" $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5 break 2 fi done done IFS=$as_save_IFS fi fi ac_ct_CC=$ac_cv_prog_ac_ct_CC if test -n "$ac_ct_CC"; then { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_ct_CC" >&5 $as_echo "$ac_ct_CC" >&6; } else { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 $as_echo "no" >&6; } fi test -n "$ac_ct_CC" && break done if test "x$ac_ct_CC" = x; then CC="" else case $cross_compiling:$ac_tool_warned in yes:) { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: using cross tools not prefixed with host triplet" >&5 $as_echo "$as_me: WARNING: using cross tools not prefixed with host triplet" >&2;} ac_tool_warned=yes ;; esac CC=$ac_ct_CC fi fi fi test -z "$CC" && { { $as_echo "$as_me:${as_lineno-$LINENO}: error: in \`$ac_pwd':" >&5 $as_echo "$as_me: error: in \`$ac_pwd':" >&2;} as_fn_error $? "no acceptable C compiler found in \$PATH See \`config.log' for more details" "$LINENO" 5; } # Provide some information about the compiler. $as_echo "$as_me:${as_lineno-$LINENO}: checking for C compiler version" >&5 set X $ac_compile ac_compiler=$2 for ac_option in --version -v -V -qversion; do { { ac_try="$ac_compiler $ac_option >&5" case "(($ac_try" in *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac eval ac_try_echo="\"\$as_me:${as_lineno-$LINENO}: $ac_try_echo\"" $as_echo "$ac_try_echo"; } >&5 (eval "$ac_compiler $ac_option >&5") 2>conftest.err ac_status=$? if test -s conftest.err; then sed '10a\ ... rest of stderr output deleted ... 10q' conftest.err >conftest.er1 cat conftest.er1 >&5 fi rm -f conftest.er1 conftest.err $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 test $ac_status = 0; } done cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ int main () { ; return 0; } _ACEOF ac_clean_files_save=$ac_clean_files ac_clean_files="$ac_clean_files a.out a.out.dSYM a.exe b.out" # Try to create an executable without -o first, disregard a.out. # It will help us diagnose broken compilers, and finding out an intuition # of exeext. { $as_echo "$as_me:${as_lineno-$LINENO}: checking whether the C compiler works" >&5 $as_echo_n "checking whether the C compiler works... " >&6; } ac_link_default=`$as_echo "$ac_link" | sed 's/ -o *conftest[^ ]*//'` # The possible output files: ac_files="a.out conftest.exe conftest a.exe a_out.exe b.out conftest.*" ac_rmfiles= for ac_file in $ac_files do case $ac_file in *.$ac_ext | *.xcoff | *.tds | *.d | *.pdb | *.xSYM | *.bb | *.bbg | *.map | *.inf | *.dSYM | *.o | *.obj ) ;; * ) ac_rmfiles="$ac_rmfiles $ac_file";; esac done rm -f $ac_rmfiles if { { ac_try="$ac_link_default" case "(($ac_try" in *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac eval ac_try_echo="\"\$as_me:${as_lineno-$LINENO}: $ac_try_echo\"" $as_echo "$ac_try_echo"; } >&5 (eval "$ac_link_default") 2>&5 ac_status=$? $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 test $ac_status = 0; }; then : # Autoconf-2.13 could set the ac_cv_exeext variable to `no'. # So ignore a value of `no', otherwise this would lead to `EXEEXT = no' # in a Makefile. We should not override ac_cv_exeext if it was cached, # so that the user can short-circuit this test for compilers unknown to # Autoconf. for ac_file in $ac_files '' do test -f "$ac_file" || continue case $ac_file in *.$ac_ext | *.xcoff | *.tds | *.d | *.pdb | *.xSYM | *.bb | *.bbg | *.map | *.inf | *.dSYM | *.o | *.obj ) ;; [ab].out ) # We found the default executable, but exeext='' is most # certainly right. break;; *.* ) if test "${ac_cv_exeext+set}" = set && test "$ac_cv_exeext" != no; then :; else ac_cv_exeext=`expr "$ac_file" : '[^.]*\(\..*\)'` fi # We set ac_cv_exeext here because the later test for it is not # safe: cross compilers may not add the suffix if given an `-o' # argument, so we may need to know it at that point already. # Even if this section looks crufty: it has the advantage of # actually working. break;; * ) break;; esac done test "$ac_cv_exeext" = no && ac_cv_exeext= else ac_file='' fi if test -z "$ac_file"; then : { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 $as_echo "no" >&6; } $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 { { $as_echo "$as_me:${as_lineno-$LINENO}: error: in \`$ac_pwd':" >&5 $as_echo "$as_me: error: in \`$ac_pwd':" >&2;} as_fn_error 77 "C compiler cannot create executables See \`config.log' for more details" "$LINENO" 5; } else { $as_echo "$as_me:${as_lineno-$LINENO}: result: yes" >&5 $as_echo "yes" >&6; } fi { $as_echo "$as_me:${as_lineno-$LINENO}: checking for C compiler default output file name" >&5 $as_echo_n "checking for C compiler default output file name... " >&6; } { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_file" >&5 $as_echo "$ac_file" >&6; } ac_exeext=$ac_cv_exeext rm -f -r a.out a.out.dSYM a.exe conftest$ac_cv_exeext b.out ac_clean_files=$ac_clean_files_save { $as_echo "$as_me:${as_lineno-$LINENO}: checking for suffix of executables" >&5 $as_echo_n "checking for suffix of executables... " >&6; } if { { ac_try="$ac_link" case "(($ac_try" in *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac eval ac_try_echo="\"\$as_me:${as_lineno-$LINENO}: $ac_try_echo\"" $as_echo "$ac_try_echo"; } >&5 (eval "$ac_link") 2>&5 ac_status=$? $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 test $ac_status = 0; }; then : # If both `conftest.exe' and `conftest' are `present' (well, observable) # catch `conftest.exe'. For instance with Cygwin, `ls conftest' will # work properly (i.e., refer to `conftest.exe'), while it won't with # `rm'. for ac_file in conftest.exe conftest conftest.*; do test -f "$ac_file" || continue case $ac_file in *.$ac_ext | *.xcoff | *.tds | *.d | *.pdb | *.xSYM | *.bb | *.bbg | *.map | *.inf | *.dSYM | *.o | *.obj ) ;; *.* ) ac_cv_exeext=`expr "$ac_file" : '[^.]*\(\..*\)'` break;; * ) break;; esac done else { { $as_echo "$as_me:${as_lineno-$LINENO}: error: in \`$ac_pwd':" >&5 $as_echo "$as_me: error: in \`$ac_pwd':" >&2;} as_fn_error $? "cannot compute suffix of executables: cannot compile and link See \`config.log' for more details" "$LINENO" 5; } fi rm -f conftest conftest$ac_cv_exeext { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_exeext" >&5 $as_echo "$ac_cv_exeext" >&6; } rm -f conftest.$ac_ext EXEEXT=$ac_cv_exeext ac_exeext=$EXEEXT cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ #include int main () { FILE *f = fopen ("conftest.out", "w"); return ferror (f) || fclose (f) != 0; ; return 0; } _ACEOF ac_clean_files="$ac_clean_files conftest.out" # Check that the compiler produces executables we can run. If not, either # the compiler is broken, or we cross compile. { $as_echo "$as_me:${as_lineno-$LINENO}: checking whether we are cross compiling" >&5 $as_echo_n "checking whether we are cross compiling... " >&6; } if test "$cross_compiling" != yes; then { { ac_try="$ac_link" case "(($ac_try" in *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac eval ac_try_echo="\"\$as_me:${as_lineno-$LINENO}: $ac_try_echo\"" $as_echo "$ac_try_echo"; } >&5 (eval "$ac_link") 2>&5 ac_status=$? $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 test $ac_status = 0; } if { ac_try='./conftest$ac_cv_exeext' { { case "(($ac_try" in *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac eval ac_try_echo="\"\$as_me:${as_lineno-$LINENO}: $ac_try_echo\"" $as_echo "$ac_try_echo"; } >&5 (eval "$ac_try") 2>&5 ac_status=$? $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 test $ac_status = 0; }; }; then cross_compiling=no else if test "$cross_compiling" = maybe; then cross_compiling=yes else { { $as_echo "$as_me:${as_lineno-$LINENO}: error: in \`$ac_pwd':" >&5 $as_echo "$as_me: error: in \`$ac_pwd':" >&2;} as_fn_error $? "cannot run C compiled programs. If you meant to cross compile, use \`--host'. See \`config.log' for more details" "$LINENO" 5; } fi fi fi { $as_echo "$as_me:${as_lineno-$LINENO}: result: $cross_compiling" >&5 $as_echo "$cross_compiling" >&6; } rm -f conftest.$ac_ext conftest$ac_cv_exeext conftest.out ac_clean_files=$ac_clean_files_save { $as_echo "$as_me:${as_lineno-$LINENO}: checking for suffix of object files" >&5 $as_echo_n "checking for suffix of object files... " >&6; } if ${ac_cv_objext+:} false; then : $as_echo_n "(cached) " >&6 else cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ int main () { ; return 0; } _ACEOF rm -f conftest.o conftest.obj if { { ac_try="$ac_compile" case "(($ac_try" in *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac eval ac_try_echo="\"\$as_me:${as_lineno-$LINENO}: $ac_try_echo\"" $as_echo "$ac_try_echo"; } >&5 (eval "$ac_compile") 2>&5 ac_status=$? $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 test $ac_status = 0; }; then : for ac_file in conftest.o conftest.obj conftest.*; do test -f "$ac_file" || continue; case $ac_file in *.$ac_ext | *.xcoff | *.tds | *.d | *.pdb | *.xSYM | *.bb | *.bbg | *.map | *.inf | *.dSYM ) ;; *) ac_cv_objext=`expr "$ac_file" : '.*\.\(.*\)'` break;; esac done else $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 { { $as_echo "$as_me:${as_lineno-$LINENO}: error: in \`$ac_pwd':" >&5 $as_echo "$as_me: error: in \`$ac_pwd':" >&2;} as_fn_error $? "cannot compute suffix of object files: cannot compile See \`config.log' for more details" "$LINENO" 5; } fi rm -f conftest.$ac_cv_objext conftest.$ac_ext fi { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_objext" >&5 $as_echo "$ac_cv_objext" >&6; } OBJEXT=$ac_cv_objext ac_objext=$OBJEXT { $as_echo "$as_me:${as_lineno-$LINENO}: checking whether we are using the GNU C compiler" >&5 $as_echo_n "checking whether we are using the GNU C compiler... " >&6; } if ${ac_cv_c_compiler_gnu+:} false; then : $as_echo_n "(cached) " >&6 else cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ int main () { #ifndef __GNUC__ choke me #endif ; return 0; } _ACEOF if ac_fn_c_try_compile "$LINENO"; then : ac_compiler_gnu=yes else ac_compiler_gnu=no fi rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext ac_cv_c_compiler_gnu=$ac_compiler_gnu fi { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_c_compiler_gnu" >&5 $as_echo "$ac_cv_c_compiler_gnu" >&6; } if test $ac_compiler_gnu = yes; then GCC=yes else GCC= fi ac_test_CFLAGS=${CFLAGS+set} ac_save_CFLAGS=$CFLAGS { $as_echo "$as_me:${as_lineno-$LINENO}: checking whether $CC accepts -g" >&5 $as_echo_n "checking whether $CC accepts -g... " >&6; } if ${ac_cv_prog_cc_g+:} false; then : $as_echo_n "(cached) " >&6 else ac_save_c_werror_flag=$ac_c_werror_flag ac_c_werror_flag=yes ac_cv_prog_cc_g=no CFLAGS="-g" cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ int main () { ; return 0; } _ACEOF if ac_fn_c_try_compile "$LINENO"; then : ac_cv_prog_cc_g=yes else CFLAGS="" cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ int main () { ; return 0; } _ACEOF if ac_fn_c_try_compile "$LINENO"; then : else ac_c_werror_flag=$ac_save_c_werror_flag CFLAGS="-g" cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ int main () { ; return 0; } _ACEOF if ac_fn_c_try_compile "$LINENO"; then : ac_cv_prog_cc_g=yes fi rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext fi rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext fi rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext ac_c_werror_flag=$ac_save_c_werror_flag fi { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_prog_cc_g" >&5 $as_echo "$ac_cv_prog_cc_g" >&6; } if test "$ac_test_CFLAGS" = set; then CFLAGS=$ac_save_CFLAGS elif test $ac_cv_prog_cc_g = yes; then if test "$GCC" = yes; then CFLAGS="-g -O2" else CFLAGS="-g" fi else if test "$GCC" = yes; then CFLAGS="-O2" else CFLAGS= fi fi { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $CC option to accept ISO C89" >&5 $as_echo_n "checking for $CC option to accept ISO C89... " >&6; } if ${ac_cv_prog_cc_c89+:} false; then : $as_echo_n "(cached) " >&6 else ac_cv_prog_cc_c89=no ac_save_CC=$CC cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ #include #include struct stat; /* Most of the following tests are stolen from RCS 5.7's src/conf.sh. */ struct buf { int x; }; FILE * (*rcsopen) (struct buf *, struct stat *, int); static char *e (p, i) char **p; int i; { return p[i]; } static char *f (char * (*g) (char **, int), char **p, ...) { char *s; va_list v; va_start (v,p); s = g (p, va_arg (v,int)); va_end (v); return s; } /* OSF 4.0 Compaq cc is some sort of almost-ANSI by default. It has function prototypes and stuff, but not '\xHH' hex character constants. These don't provoke an error unfortunately, instead are silently treated as 'x'. The following induces an error, until -std is added to get proper ANSI mode. Curiously '\x00'!='x' always comes out true, for an array size at least. It's necessary to write '\x00'==0 to get something that's true only with -std. */ int osf4_cc_array ['\x00' == 0 ? 1 : -1]; /* IBM C 6 for AIX is almost-ANSI by default, but it replaces macro parameters inside strings and character constants. */ #define FOO(x) 'x' int xlc6_cc_array[FOO(a) == 'x' ? 1 : -1]; int test (int i, double x); struct s1 {int (*f) (int a);}; struct s2 {int (*f) (double a);}; int pairnames (int, char **, FILE *(*)(struct buf *, struct stat *, int), int, int); int argc; char **argv; int main () { return f (e, argv, 0) != argv[0] || f (e, argv, 1) != argv[1]; ; return 0; } _ACEOF for ac_arg in '' -qlanglvl=extc89 -qlanglvl=ansi -std \ -Ae "-Aa -D_HPUX_SOURCE" "-Xc -D__EXTENSIONS__" do CC="$ac_save_CC $ac_arg" if ac_fn_c_try_compile "$LINENO"; then : ac_cv_prog_cc_c89=$ac_arg fi rm -f core conftest.err conftest.$ac_objext test "x$ac_cv_prog_cc_c89" != "xno" && break done rm -f conftest.$ac_ext CC=$ac_save_CC fi # AC_CACHE_VAL case "x$ac_cv_prog_cc_c89" in x) { $as_echo "$as_me:${as_lineno-$LINENO}: result: none needed" >&5 $as_echo "none needed" >&6; } ;; xno) { $as_echo "$as_me:${as_lineno-$LINENO}: result: unsupported" >&5 $as_echo "unsupported" >&6; } ;; *) CC="$CC $ac_cv_prog_cc_c89" { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_prog_cc_c89" >&5 $as_echo "$ac_cv_prog_cc_c89" >&6; } ;; esac if test "x$ac_cv_prog_cc_c89" != xno; then : fi ac_ext=c ac_cpp='$CPP $CPPFLAGS' ac_compile='$CC -c $CFLAGS $CPPFLAGS conftest.$ac_ext >&5' ac_link='$CC -o conftest$ac_exeext $CFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5' ac_compiler_gnu=$ac_cv_c_compiler_gnu depcc="$CC" am_compiler_list= { $as_echo "$as_me:${as_lineno-$LINENO}: checking dependency style of $depcc" >&5 $as_echo_n "checking dependency style of $depcc... " >&6; } if ${am_cv_CC_dependencies_compiler_type+:} false; then : $as_echo_n "(cached) " >&6 else if test -z "$AMDEP_TRUE" && test -f "$am_depcomp"; then # We make a subdir and do the tests there. Otherwise we can end up # making bogus files that we don't know about and never remove. For # instance it was reported that on HP-UX the gcc test will end up # making a dummy file named `D' -- because `-MD' means `put the output # in D'. rm -rf conftest.dir mkdir conftest.dir # Copy depcomp to subdir because otherwise we won't find it if we're # using a relative directory. cp "$am_depcomp" conftest.dir cd conftest.dir # We will build objects and dependencies in a subdirectory because # it helps to detect inapplicable dependency modes. For instance # both Tru64's cc and ICC support -MD to output dependencies as a # side effect of compilation, but ICC will put the dependencies in # the current directory while Tru64 will put them in the object # directory. mkdir sub am_cv_CC_dependencies_compiler_type=none if test "$am_compiler_list" = ""; then am_compiler_list=`sed -n 's/^#*\([a-zA-Z0-9]*\))$/\1/p' < ./depcomp` fi am__universal=false case " $depcc " in #( *\ -arch\ *\ -arch\ *) am__universal=true ;; esac for depmode in $am_compiler_list; do # Setup a source with many dependencies, because some compilers # like to wrap large dependency lists on column 80 (with \), and # we should not choose a depcomp mode which is confused by this. # # We need to recreate these files for each test, as the compiler may # overwrite some of them when testing with obscure command lines. # This happens at least with the AIX C compiler. : > sub/conftest.c for i in 1 2 3 4 5 6; do echo '#include "conftst'$i'.h"' >> sub/conftest.c # Using `: > sub/conftst$i.h' creates only sub/conftst1.h with # Solaris 8's {/usr,}/bin/sh. touch sub/conftst$i.h done echo "${am__include} ${am__quote}sub/conftest.Po${am__quote}" > confmf # We check with `-c' and `-o' for the sake of the "dashmstdout" # mode. It turns out that the SunPro C++ compiler does not properly # handle `-M -o', and we need to detect this. Also, some Intel # versions had trouble with output in subdirs am__obj=sub/conftest.${OBJEXT-o} am__minus_obj="-o $am__obj" case $depmode in gcc) # This depmode causes a compiler race in universal mode. test "$am__universal" = false || continue ;; nosideeffect) # after this tag, mechanisms are not by side-effect, so they'll # only be used when explicitly requested if test "x$enable_dependency_tracking" = xyes; then continue else break fi ;; msvc7 | msvc7msys | msvisualcpp | msvcmsys) # This compiler won't grok `-c -o', but also, the minuso test has # not run yet. These depmodes are late enough in the game, and # so weak that their functioning should not be impacted. am__obj=conftest.${OBJEXT-o} am__minus_obj= ;; none) break ;; esac if depmode=$depmode \ source=sub/conftest.c object=$am__obj \ depfile=sub/conftest.Po tmpdepfile=sub/conftest.TPo \ $SHELL ./depcomp $depcc -c $am__minus_obj sub/conftest.c \ >/dev/null 2>conftest.err && grep sub/conftst1.h sub/conftest.Po > /dev/null 2>&1 && grep sub/conftst6.h sub/conftest.Po > /dev/null 2>&1 && grep $am__obj sub/conftest.Po > /dev/null 2>&1 && ${MAKE-make} -s -f confmf > /dev/null 2>&1; then # icc doesn't choke on unknown options, it will just issue warnings # or remarks (even with -Werror). So we grep stderr for any message # that says an option was ignored or not supported. # When given -MP, icc 7.0 and 7.1 complain thusly: # icc: Command line warning: ignoring option '-M'; no argument required # The diagnosis changed in icc 8.0: # icc: Command line remark: option '-MP' not supported if (grep 'ignoring option' conftest.err || grep 'not supported' conftest.err) >/dev/null 2>&1; then :; else am_cv_CC_dependencies_compiler_type=$depmode break fi fi done cd .. rm -rf conftest.dir else am_cv_CC_dependencies_compiler_type=none fi fi { $as_echo "$as_me:${as_lineno-$LINENO}: result: $am_cv_CC_dependencies_compiler_type" >&5 $as_echo "$am_cv_CC_dependencies_compiler_type" >&6; } CCDEPMODE=depmode=$am_cv_CC_dependencies_compiler_type if test "x$enable_dependency_tracking" != xno \ && test "$am_cv_CC_dependencies_compiler_type" = gcc3; then am__fastdepCC_TRUE= am__fastdepCC_FALSE='#' else am__fastdepCC_TRUE='#' am__fastdepCC_FALSE= fi ac_ext=c ac_cpp='$CPP $CPPFLAGS' ac_compile='$CC -c $CFLAGS $CPPFLAGS conftest.$ac_ext >&5' ac_link='$CC -o conftest$ac_exeext $CFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5' ac_compiler_gnu=$ac_cv_c_compiler_gnu { $as_echo "$as_me:${as_lineno-$LINENO}: checking how to run the C preprocessor" >&5 $as_echo_n "checking how to run the C preprocessor... " >&6; } # On Suns, sometimes $CPP names a directory. if test -n "$CPP" && test -d "$CPP"; then CPP= fi if test -z "$CPP"; then if ${ac_cv_prog_CPP+:} false; then : $as_echo_n "(cached) " >&6 else # Double quotes because CPP needs to be expanded for CPP in "$CC -E" "$CC -E -traditional-cpp" "/lib/cpp" do ac_preproc_ok=false for ac_c_preproc_warn_flag in '' yes do # Use a header file that comes with gcc, so configuring glibc # with a fresh cross-compiler works. # Prefer to if __STDC__ is defined, since # exists even on freestanding compilers. # On the NeXT, cc -E runs the code through the compiler's parser, # not just through cpp. "Syntax error" is here to catch this case. cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ #ifdef __STDC__ # include #else # include #endif Syntax error _ACEOF if ac_fn_c_try_cpp "$LINENO"; then : else # Broken: fails on valid input. continue fi rm -f conftest.err conftest.i conftest.$ac_ext # OK, works on sane cases. Now check whether nonexistent headers # can be detected and how. cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ #include _ACEOF if ac_fn_c_try_cpp "$LINENO"; then : # Broken: success on invalid input. continue else # Passes both tests. ac_preproc_ok=: break fi rm -f conftest.err conftest.i conftest.$ac_ext done # Because of `break', _AC_PREPROC_IFELSE's cleaning code was skipped. rm -f conftest.i conftest.err conftest.$ac_ext if $ac_preproc_ok; then : break fi done ac_cv_prog_CPP=$CPP fi CPP=$ac_cv_prog_CPP else ac_cv_prog_CPP=$CPP fi { $as_echo "$as_me:${as_lineno-$LINENO}: result: $CPP" >&5 $as_echo "$CPP" >&6; } ac_preproc_ok=false for ac_c_preproc_warn_flag in '' yes do # Use a header file that comes with gcc, so configuring glibc # with a fresh cross-compiler works. # Prefer to if __STDC__ is defined, since # exists even on freestanding compilers. # On the NeXT, cc -E runs the code through the compiler's parser, # not just through cpp. "Syntax error" is here to catch this case. cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ #ifdef __STDC__ # include #else # include #endif Syntax error _ACEOF if ac_fn_c_try_cpp "$LINENO"; then : else # Broken: fails on valid input. continue fi rm -f conftest.err conftest.i conftest.$ac_ext # OK, works on sane cases. Now check whether nonexistent headers # can be detected and how. cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ #include _ACEOF if ac_fn_c_try_cpp "$LINENO"; then : # Broken: success on invalid input. continue else # Passes both tests. ac_preproc_ok=: break fi rm -f conftest.err conftest.i conftest.$ac_ext done # Because of `break', _AC_PREPROC_IFELSE's cleaning code was skipped. rm -f conftest.i conftest.err conftest.$ac_ext if $ac_preproc_ok; then : else { { $as_echo "$as_me:${as_lineno-$LINENO}: error: in \`$ac_pwd':" >&5 $as_echo "$as_me: error: in \`$ac_pwd':" >&2;} as_fn_error $? "C preprocessor \"$CPP\" fails sanity check See \`config.log' for more details" "$LINENO" 5; } fi ac_ext=c ac_cpp='$CPP $CPPFLAGS' ac_compile='$CC -c $CFLAGS $CPPFLAGS conftest.$ac_ext >&5' ac_link='$CC -o conftest$ac_exeext $CFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5' ac_compiler_gnu=$ac_cv_c_compiler_gnu { $as_echo "$as_me:${as_lineno-$LINENO}: checking for grep that handles long lines and -e" >&5 $as_echo_n "checking for grep that handles long lines and -e... " >&6; } if ${ac_cv_path_GREP+:} false; then : $as_echo_n "(cached) " >&6 else if test -z "$GREP"; then ac_path_GREP_found=false # Loop through the user's path and test for each of PROGNAME-LIST as_save_IFS=$IFS; IFS=$PATH_SEPARATOR for as_dir in $PATH$PATH_SEPARATOR/usr/xpg4/bin do IFS=$as_save_IFS test -z "$as_dir" && as_dir=. for ac_prog in grep ggrep; do for ac_exec_ext in '' $ac_executable_extensions; do ac_path_GREP="$as_dir/$ac_prog$ac_exec_ext" as_fn_executable_p "$ac_path_GREP" || continue # Check for GNU ac_path_GREP and select it if it is found. # Check for GNU $ac_path_GREP case `"$ac_path_GREP" --version 2>&1` in *GNU*) ac_cv_path_GREP="$ac_path_GREP" ac_path_GREP_found=:;; *) ac_count=0 $as_echo_n 0123456789 >"conftest.in" while : do cat "conftest.in" "conftest.in" >"conftest.tmp" mv "conftest.tmp" "conftest.in" cp "conftest.in" "conftest.nl" $as_echo 'GREP' >> "conftest.nl" "$ac_path_GREP" -e 'GREP$' -e '-(cannot match)-' < "conftest.nl" >"conftest.out" 2>/dev/null || break diff "conftest.out" "conftest.nl" >/dev/null 2>&1 || break as_fn_arith $ac_count + 1 && ac_count=$as_val if test $ac_count -gt ${ac_path_GREP_max-0}; then # Best one so far, save it but keep looking for a better one ac_cv_path_GREP="$ac_path_GREP" ac_path_GREP_max=$ac_count fi # 10*(2^10) chars as input seems more than enough test $ac_count -gt 10 && break done rm -f conftest.in conftest.tmp conftest.nl conftest.out;; esac $ac_path_GREP_found && break 3 done done done IFS=$as_save_IFS if test -z "$ac_cv_path_GREP"; then as_fn_error $? "no acceptable grep could be found in $PATH$PATH_SEPARATOR/usr/xpg4/bin" "$LINENO" 5 fi else ac_cv_path_GREP=$GREP fi fi { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_path_GREP" >&5 $as_echo "$ac_cv_path_GREP" >&6; } GREP="$ac_cv_path_GREP" { $as_echo "$as_me:${as_lineno-$LINENO}: checking for egrep" >&5 $as_echo_n "checking for egrep... " >&6; } if ${ac_cv_path_EGREP+:} false; then : $as_echo_n "(cached) " >&6 else if echo a | $GREP -E '(a|b)' >/dev/null 2>&1 then ac_cv_path_EGREP="$GREP -E" else if test -z "$EGREP"; then ac_path_EGREP_found=false # Loop through the user's path and test for each of PROGNAME-LIST as_save_IFS=$IFS; IFS=$PATH_SEPARATOR for as_dir in $PATH$PATH_SEPARATOR/usr/xpg4/bin do IFS=$as_save_IFS test -z "$as_dir" && as_dir=. for ac_prog in egrep; do for ac_exec_ext in '' $ac_executable_extensions; do ac_path_EGREP="$as_dir/$ac_prog$ac_exec_ext" as_fn_executable_p "$ac_path_EGREP" || continue # Check for GNU ac_path_EGREP and select it if it is found. # Check for GNU $ac_path_EGREP case `"$ac_path_EGREP" --version 2>&1` in *GNU*) ac_cv_path_EGREP="$ac_path_EGREP" ac_path_EGREP_found=:;; *) ac_count=0 $as_echo_n 0123456789 >"conftest.in" while : do cat "conftest.in" "conftest.in" >"conftest.tmp" mv "conftest.tmp" "conftest.in" cp "conftest.in" "conftest.nl" $as_echo 'EGREP' >> "conftest.nl" "$ac_path_EGREP" 'EGREP$' < "conftest.nl" >"conftest.out" 2>/dev/null || break diff "conftest.out" "conftest.nl" >/dev/null 2>&1 || break as_fn_arith $ac_count + 1 && ac_count=$as_val if test $ac_count -gt ${ac_path_EGREP_max-0}; then # Best one so far, save it but keep looking for a better one ac_cv_path_EGREP="$ac_path_EGREP" ac_path_EGREP_max=$ac_count fi # 10*(2^10) chars as input seems more than enough test $ac_count -gt 10 && break done rm -f conftest.in conftest.tmp conftest.nl conftest.out;; esac $ac_path_EGREP_found && break 3 done done done IFS=$as_save_IFS if test -z "$ac_cv_path_EGREP"; then as_fn_error $? "no acceptable egrep could be found in $PATH$PATH_SEPARATOR/usr/xpg4/bin" "$LINENO" 5 fi else ac_cv_path_EGREP=$EGREP fi fi fi { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_path_EGREP" >&5 $as_echo "$ac_cv_path_EGREP" >&6; } EGREP="$ac_cv_path_EGREP" { $as_echo "$as_me:${as_lineno-$LINENO}: checking for ANSI C header files" >&5 $as_echo_n "checking for ANSI C header files... " >&6; } if ${ac_cv_header_stdc+:} false; then : $as_echo_n "(cached) " >&6 else cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ #include #include #include #include int main () { ; return 0; } _ACEOF if ac_fn_c_try_compile "$LINENO"; then : ac_cv_header_stdc=yes else ac_cv_header_stdc=no fi rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext if test $ac_cv_header_stdc = yes; then # SunOS 4.x string.h does not declare mem*, contrary to ANSI. cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ #include _ACEOF if (eval "$ac_cpp conftest.$ac_ext") 2>&5 | $EGREP "memchr" >/dev/null 2>&1; then : else ac_cv_header_stdc=no fi rm -f conftest* fi if test $ac_cv_header_stdc = yes; then # ISC 2.0.2 stdlib.h does not declare free, contrary to ANSI. cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ #include _ACEOF if (eval "$ac_cpp conftest.$ac_ext") 2>&5 | $EGREP "free" >/dev/null 2>&1; then : else ac_cv_header_stdc=no fi rm -f conftest* fi if test $ac_cv_header_stdc = yes; then # /bin/cc in Irix-4.0.5 gets non-ANSI ctype macros unless using -ansi. if test "$cross_compiling" = yes; then : : else cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ #include #include #if ((' ' & 0x0FF) == 0x020) # define ISLOWER(c) ('a' <= (c) && (c) <= 'z') # define TOUPPER(c) (ISLOWER(c) ? 'A' + ((c) - 'a') : (c)) #else # define ISLOWER(c) \ (('a' <= (c) && (c) <= 'i') \ || ('j' <= (c) && (c) <= 'r') \ || ('s' <= (c) && (c) <= 'z')) # define TOUPPER(c) (ISLOWER(c) ? ((c) | 0x40) : (c)) #endif #define XOR(e, f) (((e) && !(f)) || (!(e) && (f))) int main () { int i; for (i = 0; i < 256; i++) if (XOR (islower (i), ISLOWER (i)) || toupper (i) != TOUPPER (i)) return 2; return 0; } _ACEOF if ac_fn_c_try_run "$LINENO"; then : else ac_cv_header_stdc=no fi rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext \ conftest.$ac_objext conftest.beam conftest.$ac_ext fi fi fi { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_header_stdc" >&5 $as_echo "$ac_cv_header_stdc" >&6; } if test $ac_cv_header_stdc = yes; then $as_echo "#define STDC_HEADERS 1" >>confdefs.h fi # On IRIX 5.3, sys/types and inttypes.h are conflicting. for ac_header in sys/types.h sys/stat.h stdlib.h string.h memory.h strings.h \ inttypes.h stdint.h unistd.h do : as_ac_Header=`$as_echo "ac_cv_header_$ac_header" | $as_tr_sh` ac_fn_c_check_header_compile "$LINENO" "$ac_header" "$as_ac_Header" "$ac_includes_default " if eval test \"x\$"$as_ac_Header"\" = x"yes"; then : cat >>confdefs.h <<_ACEOF #define `$as_echo "HAVE_$ac_header" | $as_tr_cpp` 1 _ACEOF fi done ac_fn_c_check_header_mongrel "$LINENO" "minix/config.h" "ac_cv_header_minix_config_h" "$ac_includes_default" if test "x$ac_cv_header_minix_config_h" = xyes; then : MINIX=yes else MINIX= fi if test "$MINIX" = yes; then $as_echo "#define _POSIX_SOURCE 1" >>confdefs.h $as_echo "#define _POSIX_1_SOURCE 2" >>confdefs.h $as_echo "#define _MINIX 1" >>confdefs.h fi { $as_echo "$as_me:${as_lineno-$LINENO}: checking whether it is safe to define __EXTENSIONS__" >&5 $as_echo_n "checking whether it is safe to define __EXTENSIONS__... " >&6; } if ${ac_cv_safe_to_define___extensions__+:} false; then : $as_echo_n "(cached) " >&6 else cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ # define __EXTENSIONS__ 1 $ac_includes_default int main () { ; return 0; } _ACEOF if ac_fn_c_try_compile "$LINENO"; then : ac_cv_safe_to_define___extensions__=yes else ac_cv_safe_to_define___extensions__=no fi rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext fi { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_safe_to_define___extensions__" >&5 $as_echo "$ac_cv_safe_to_define___extensions__" >&6; } test $ac_cv_safe_to_define___extensions__ = yes && $as_echo "#define __EXTENSIONS__ 1" >>confdefs.h $as_echo "#define _ALL_SOURCE 1" >>confdefs.h $as_echo "#define _GNU_SOURCE 1" >>confdefs.h $as_echo "#define _POSIX_PTHREAD_SEMANTICS 1" >>confdefs.h $as_echo "#define _TANDEM_SOURCE 1" >>confdefs.h # Check whether --enable-shared was given. if test "${enable_shared+set}" = set; then : enableval=$enable_shared; p=${PACKAGE-default} case $enableval in yes) enable_shared=yes ;; no) enable_shared=no ;; *) enable_shared=no # Look at the argument we got. We use all the common list separators. lt_save_ifs="$IFS"; IFS="${IFS}$PATH_SEPARATOR," for pkg in $enableval; do IFS="$lt_save_ifs" if test "X$pkg" = "X$p"; then enable_shared=yes fi done IFS="$lt_save_ifs" ;; esac else enable_shared=yes fi # Check whether --enable-static was given. if test "${enable_static+set}" = set; then : enableval=$enable_static; p=${PACKAGE-default} case $enableval in yes) enable_static=yes ;; no) enable_static=no ;; *) enable_static=no # Look at the argument we got. We use all the common list separators. lt_save_ifs="$IFS"; IFS="${IFS}$PATH_SEPARATOR," for pkg in $enableval; do IFS="$lt_save_ifs" if test "X$pkg" = "X$p"; then enable_static=yes fi done IFS="$lt_save_ifs" ;; esac else enable_static=no fi ac_ext=c ac_cpp='$CPP $CPPFLAGS' ac_compile='$CC -c $CFLAGS $CPPFLAGS conftest.$ac_ext >&5' ac_link='$CC -o conftest$ac_exeext $CFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5' ac_compiler_gnu=$ac_cv_c_compiler_gnu if test -n "$ac_tool_prefix"; then # Extract the first word of "${ac_tool_prefix}gcc", so it can be a program name with args. set dummy ${ac_tool_prefix}gcc; ac_word=$2 { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 $as_echo_n "checking for $ac_word... " >&6; } if ${ac_cv_prog_CC+:} false; then : $as_echo_n "(cached) " >&6 else if test -n "$CC"; then ac_cv_prog_CC="$CC" # Let the user override the test. else as_save_IFS=$IFS; IFS=$PATH_SEPARATOR for as_dir in $PATH do IFS=$as_save_IFS test -z "$as_dir" && as_dir=. for ac_exec_ext in '' $ac_executable_extensions; do if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then ac_cv_prog_CC="${ac_tool_prefix}gcc" $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5 break 2 fi done done IFS=$as_save_IFS fi fi CC=$ac_cv_prog_CC if test -n "$CC"; then { $as_echo "$as_me:${as_lineno-$LINENO}: result: $CC" >&5 $as_echo "$CC" >&6; } else { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 $as_echo "no" >&6; } fi fi if test -z "$ac_cv_prog_CC"; then ac_ct_CC=$CC # Extract the first word of "gcc", so it can be a program name with args. set dummy gcc; ac_word=$2 { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 $as_echo_n "checking for $ac_word... " >&6; } if ${ac_cv_prog_ac_ct_CC+:} false; then : $as_echo_n "(cached) " >&6 else if test -n "$ac_ct_CC"; then ac_cv_prog_ac_ct_CC="$ac_ct_CC" # Let the user override the test. else as_save_IFS=$IFS; IFS=$PATH_SEPARATOR for as_dir in $PATH do IFS=$as_save_IFS test -z "$as_dir" && as_dir=. for ac_exec_ext in '' $ac_executable_extensions; do if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then ac_cv_prog_ac_ct_CC="gcc" $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5 break 2 fi done done IFS=$as_save_IFS fi fi ac_ct_CC=$ac_cv_prog_ac_ct_CC if test -n "$ac_ct_CC"; then { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_ct_CC" >&5 $as_echo "$ac_ct_CC" >&6; } else { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 $as_echo "no" >&6; } fi if test "x$ac_ct_CC" = x; then CC="" else case $cross_compiling:$ac_tool_warned in yes:) { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: using cross tools not prefixed with host triplet" >&5 $as_echo "$as_me: WARNING: using cross tools not prefixed with host triplet" >&2;} ac_tool_warned=yes ;; esac CC=$ac_ct_CC fi else CC="$ac_cv_prog_CC" fi if test -z "$CC"; then if test -n "$ac_tool_prefix"; then # Extract the first word of "${ac_tool_prefix}cc", so it can be a program name with args. set dummy ${ac_tool_prefix}cc; ac_word=$2 { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 $as_echo_n "checking for $ac_word... " >&6; } if ${ac_cv_prog_CC+:} false; then : $as_echo_n "(cached) " >&6 else if test -n "$CC"; then ac_cv_prog_CC="$CC" # Let the user override the test. else as_save_IFS=$IFS; IFS=$PATH_SEPARATOR for as_dir in $PATH do IFS=$as_save_IFS test -z "$as_dir" && as_dir=. for ac_exec_ext in '' $ac_executable_extensions; do if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then ac_cv_prog_CC="${ac_tool_prefix}cc" $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5 break 2 fi done done IFS=$as_save_IFS fi fi CC=$ac_cv_prog_CC if test -n "$CC"; then { $as_echo "$as_me:${as_lineno-$LINENO}: result: $CC" >&5 $as_echo "$CC" >&6; } else { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 $as_echo "no" >&6; } fi fi fi if test -z "$CC"; then # Extract the first word of "cc", so it can be a program name with args. set dummy cc; ac_word=$2 { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 $as_echo_n "checking for $ac_word... " >&6; } if ${ac_cv_prog_CC+:} false; then : $as_echo_n "(cached) " >&6 else if test -n "$CC"; then ac_cv_prog_CC="$CC" # Let the user override the test. else ac_prog_rejected=no as_save_IFS=$IFS; IFS=$PATH_SEPARATOR for as_dir in $PATH do IFS=$as_save_IFS test -z "$as_dir" && as_dir=. for ac_exec_ext in '' $ac_executable_extensions; do if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then if test "$as_dir/$ac_word$ac_exec_ext" = "/usr/ucb/cc"; then ac_prog_rejected=yes continue fi ac_cv_prog_CC="cc" $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5 break 2 fi done done IFS=$as_save_IFS if test $ac_prog_rejected = yes; then # We found a bogon in the path, so make sure we never use it. set dummy $ac_cv_prog_CC shift if test $# != 0; then # We chose a different compiler from the bogus one. # However, it has the same basename, so the bogon will be chosen # first if we set CC to just the basename; use the full file name. shift ac_cv_prog_CC="$as_dir/$ac_word${1+' '}$@" fi fi fi fi CC=$ac_cv_prog_CC if test -n "$CC"; then { $as_echo "$as_me:${as_lineno-$LINENO}: result: $CC" >&5 $as_echo "$CC" >&6; } else { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 $as_echo "no" >&6; } fi fi if test -z "$CC"; then if test -n "$ac_tool_prefix"; then for ac_prog in cl.exe do # Extract the first word of "$ac_tool_prefix$ac_prog", so it can be a program name with args. set dummy $ac_tool_prefix$ac_prog; ac_word=$2 { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 $as_echo_n "checking for $ac_word... " >&6; } if ${ac_cv_prog_CC+:} false; then : $as_echo_n "(cached) " >&6 else if test -n "$CC"; then ac_cv_prog_CC="$CC" # Let the user override the test. else as_save_IFS=$IFS; IFS=$PATH_SEPARATOR for as_dir in $PATH do IFS=$as_save_IFS test -z "$as_dir" && as_dir=. for ac_exec_ext in '' $ac_executable_extensions; do if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then ac_cv_prog_CC="$ac_tool_prefix$ac_prog" $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5 break 2 fi done done IFS=$as_save_IFS fi fi CC=$ac_cv_prog_CC if test -n "$CC"; then { $as_echo "$as_me:${as_lineno-$LINENO}: result: $CC" >&5 $as_echo "$CC" >&6; } else { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 $as_echo "no" >&6; } fi test -n "$CC" && break done fi if test -z "$CC"; then ac_ct_CC=$CC for ac_prog in cl.exe do # Extract the first word of "$ac_prog", so it can be a program name with args. set dummy $ac_prog; ac_word=$2 { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 $as_echo_n "checking for $ac_word... " >&6; } if ${ac_cv_prog_ac_ct_CC+:} false; then : $as_echo_n "(cached) " >&6 else if test -n "$ac_ct_CC"; then ac_cv_prog_ac_ct_CC="$ac_ct_CC" # Let the user override the test. else as_save_IFS=$IFS; IFS=$PATH_SEPARATOR for as_dir in $PATH do IFS=$as_save_IFS test -z "$as_dir" && as_dir=. for ac_exec_ext in '' $ac_executable_extensions; do if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then ac_cv_prog_ac_ct_CC="$ac_prog" $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5 break 2 fi done done IFS=$as_save_IFS fi fi ac_ct_CC=$ac_cv_prog_ac_ct_CC if test -n "$ac_ct_CC"; then { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_ct_CC" >&5 $as_echo "$ac_ct_CC" >&6; } else { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 $as_echo "no" >&6; } fi test -n "$ac_ct_CC" && break done if test "x$ac_ct_CC" = x; then CC="" else case $cross_compiling:$ac_tool_warned in yes:) { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: using cross tools not prefixed with host triplet" >&5 $as_echo "$as_me: WARNING: using cross tools not prefixed with host triplet" >&2;} ac_tool_warned=yes ;; esac CC=$ac_ct_CC fi fi fi test -z "$CC" && { { $as_echo "$as_me:${as_lineno-$LINENO}: error: in \`$ac_pwd':" >&5 $as_echo "$as_me: error: in \`$ac_pwd':" >&2;} as_fn_error $? "no acceptable C compiler found in \$PATH See \`config.log' for more details" "$LINENO" 5; } # Provide some information about the compiler. $as_echo "$as_me:${as_lineno-$LINENO}: checking for C compiler version" >&5 set X $ac_compile ac_compiler=$2 for ac_option in --version -v -V -qversion; do { { ac_try="$ac_compiler $ac_option >&5" case "(($ac_try" in *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac eval ac_try_echo="\"\$as_me:${as_lineno-$LINENO}: $ac_try_echo\"" $as_echo "$ac_try_echo"; } >&5 (eval "$ac_compiler $ac_option >&5") 2>conftest.err ac_status=$? if test -s conftest.err; then sed '10a\ ... rest of stderr output deleted ... 10q' conftest.err >conftest.er1 cat conftest.er1 >&5 fi rm -f conftest.er1 conftest.err $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 test $ac_status = 0; } done { $as_echo "$as_me:${as_lineno-$LINENO}: checking whether we are using the GNU C compiler" >&5 $as_echo_n "checking whether we are using the GNU C compiler... " >&6; } if ${ac_cv_c_compiler_gnu+:} false; then : $as_echo_n "(cached) " >&6 else cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ int main () { #ifndef __GNUC__ choke me #endif ; return 0; } _ACEOF if ac_fn_c_try_compile "$LINENO"; then : ac_compiler_gnu=yes else ac_compiler_gnu=no fi rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext ac_cv_c_compiler_gnu=$ac_compiler_gnu fi { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_c_compiler_gnu" >&5 $as_echo "$ac_cv_c_compiler_gnu" >&6; } if test $ac_compiler_gnu = yes; then GCC=yes else GCC= fi ac_test_CFLAGS=${CFLAGS+set} ac_save_CFLAGS=$CFLAGS { $as_echo "$as_me:${as_lineno-$LINENO}: checking whether $CC accepts -g" >&5 $as_echo_n "checking whether $CC accepts -g... " >&6; } if ${ac_cv_prog_cc_g+:} false; then : $as_echo_n "(cached) " >&6 else ac_save_c_werror_flag=$ac_c_werror_flag ac_c_werror_flag=yes ac_cv_prog_cc_g=no CFLAGS="-g" cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ int main () { ; return 0; } _ACEOF if ac_fn_c_try_compile "$LINENO"; then : ac_cv_prog_cc_g=yes else CFLAGS="" cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ int main () { ; return 0; } _ACEOF if ac_fn_c_try_compile "$LINENO"; then : else ac_c_werror_flag=$ac_save_c_werror_flag CFLAGS="-g" cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ int main () { ; return 0; } _ACEOF if ac_fn_c_try_compile "$LINENO"; then : ac_cv_prog_cc_g=yes fi rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext fi rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext fi rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext ac_c_werror_flag=$ac_save_c_werror_flag fi { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_prog_cc_g" >&5 $as_echo "$ac_cv_prog_cc_g" >&6; } if test "$ac_test_CFLAGS" = set; then CFLAGS=$ac_save_CFLAGS elif test $ac_cv_prog_cc_g = yes; then if test "$GCC" = yes; then CFLAGS="-g -O2" else CFLAGS="-g" fi else if test "$GCC" = yes; then CFLAGS="-O2" else CFLAGS= fi fi { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $CC option to accept ISO C89" >&5 $as_echo_n "checking for $CC option to accept ISO C89... " >&6; } if ${ac_cv_prog_cc_c89+:} false; then : $as_echo_n "(cached) " >&6 else ac_cv_prog_cc_c89=no ac_save_CC=$CC cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ #include #include struct stat; /* Most of the following tests are stolen from RCS 5.7's src/conf.sh. */ struct buf { int x; }; FILE * (*rcsopen) (struct buf *, struct stat *, int); static char *e (p, i) char **p; int i; { return p[i]; } static char *f (char * (*g) (char **, int), char **p, ...) { char *s; va_list v; va_start (v,p); s = g (p, va_arg (v,int)); va_end (v); return s; } /* OSF 4.0 Compaq cc is some sort of almost-ANSI by default. It has function prototypes and stuff, but not '\xHH' hex character constants. These don't provoke an error unfortunately, instead are silently treated as 'x'. The following induces an error, until -std is added to get proper ANSI mode. Curiously '\x00'!='x' always comes out true, for an array size at least. It's necessary to write '\x00'==0 to get something that's true only with -std. */ int osf4_cc_array ['\x00' == 0 ? 1 : -1]; /* IBM C 6 for AIX is almost-ANSI by default, but it replaces macro parameters inside strings and character constants. */ #define FOO(x) 'x' int xlc6_cc_array[FOO(a) == 'x' ? 1 : -1]; int test (int i, double x); struct s1 {int (*f) (int a);}; struct s2 {int (*f) (double a);}; int pairnames (int, char **, FILE *(*)(struct buf *, struct stat *, int), int, int); int argc; char **argv; int main () { return f (e, argv, 0) != argv[0] || f (e, argv, 1) != argv[1]; ; return 0; } _ACEOF for ac_arg in '' -qlanglvl=extc89 -qlanglvl=ansi -std \ -Ae "-Aa -D_HPUX_SOURCE" "-Xc -D__EXTENSIONS__" do CC="$ac_save_CC $ac_arg" if ac_fn_c_try_compile "$LINENO"; then : ac_cv_prog_cc_c89=$ac_arg fi rm -f core conftest.err conftest.$ac_objext test "x$ac_cv_prog_cc_c89" != "xno" && break done rm -f conftest.$ac_ext CC=$ac_save_CC fi # AC_CACHE_VAL case "x$ac_cv_prog_cc_c89" in x) { $as_echo "$as_me:${as_lineno-$LINENO}: result: none needed" >&5 $as_echo "none needed" >&6; } ;; xno) { $as_echo "$as_me:${as_lineno-$LINENO}: result: unsupported" >&5 $as_echo "unsupported" >&6; } ;; *) CC="$CC $ac_cv_prog_cc_c89" { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_prog_cc_c89" >&5 $as_echo "$ac_cv_prog_cc_c89" >&6; } ;; esac if test "x$ac_cv_prog_cc_c89" != xno; then : fi ac_ext=c ac_cpp='$CPP $CPPFLAGS' ac_compile='$CC -c $CFLAGS $CPPFLAGS conftest.$ac_ext >&5' ac_link='$CC -o conftest$ac_exeext $CFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5' ac_compiler_gnu=$ac_cv_c_compiler_gnu depcc="$CC" am_compiler_list= { $as_echo "$as_me:${as_lineno-$LINENO}: checking dependency style of $depcc" >&5 $as_echo_n "checking dependency style of $depcc... " >&6; } if ${am_cv_CC_dependencies_compiler_type+:} false; then : $as_echo_n "(cached) " >&6 else if test -z "$AMDEP_TRUE" && test -f "$am_depcomp"; then # We make a subdir and do the tests there. Otherwise we can end up # making bogus files that we don't know about and never remove. For # instance it was reported that on HP-UX the gcc test will end up # making a dummy file named `D' -- because `-MD' means `put the output # in D'. rm -rf conftest.dir mkdir conftest.dir # Copy depcomp to subdir because otherwise we won't find it if we're # using a relative directory. cp "$am_depcomp" conftest.dir cd conftest.dir # We will build objects and dependencies in a subdirectory because # it helps to detect inapplicable dependency modes. For instance # both Tru64's cc and ICC support -MD to output dependencies as a # side effect of compilation, but ICC will put the dependencies in # the current directory while Tru64 will put them in the object # directory. mkdir sub am_cv_CC_dependencies_compiler_type=none if test "$am_compiler_list" = ""; then am_compiler_list=`sed -n 's/^#*\([a-zA-Z0-9]*\))$/\1/p' < ./depcomp` fi am__universal=false case " $depcc " in #( *\ -arch\ *\ -arch\ *) am__universal=true ;; esac for depmode in $am_compiler_list; do # Setup a source with many dependencies, because some compilers # like to wrap large dependency lists on column 80 (with \), and # we should not choose a depcomp mode which is confused by this. # # We need to recreate these files for each test, as the compiler may # overwrite some of them when testing with obscure command lines. # This happens at least with the AIX C compiler. : > sub/conftest.c for i in 1 2 3 4 5 6; do echo '#include "conftst'$i'.h"' >> sub/conftest.c # Using `: > sub/conftst$i.h' creates only sub/conftst1.h with # Solaris 8's {/usr,}/bin/sh. touch sub/conftst$i.h done echo "${am__include} ${am__quote}sub/conftest.Po${am__quote}" > confmf # We check with `-c' and `-o' for the sake of the "dashmstdout" # mode. It turns out that the SunPro C++ compiler does not properly # handle `-M -o', and we need to detect this. Also, some Intel # versions had trouble with output in subdirs am__obj=sub/conftest.${OBJEXT-o} am__minus_obj="-o $am__obj" case $depmode in gcc) # This depmode causes a compiler race in universal mode. test "$am__universal" = false || continue ;; nosideeffect) # after this tag, mechanisms are not by side-effect, so they'll # only be used when explicitly requested if test "x$enable_dependency_tracking" = xyes; then continue else break fi ;; msvc7 | msvc7msys | msvisualcpp | msvcmsys) # This compiler won't grok `-c -o', but also, the minuso test has # not run yet. These depmodes are late enough in the game, and # so weak that their functioning should not be impacted. am__obj=conftest.${OBJEXT-o} am__minus_obj= ;; none) break ;; esac if depmode=$depmode \ source=sub/conftest.c object=$am__obj \ depfile=sub/conftest.Po tmpdepfile=sub/conftest.TPo \ $SHELL ./depcomp $depcc -c $am__minus_obj sub/conftest.c \ >/dev/null 2>conftest.err && grep sub/conftst1.h sub/conftest.Po > /dev/null 2>&1 && grep sub/conftst6.h sub/conftest.Po > /dev/null 2>&1 && grep $am__obj sub/conftest.Po > /dev/null 2>&1 && ${MAKE-make} -s -f confmf > /dev/null 2>&1; then # icc doesn't choke on unknown options, it will just issue warnings # or remarks (even with -Werror). So we grep stderr for any message # that says an option was ignored or not supported. # When given -MP, icc 7.0 and 7.1 complain thusly: # icc: Command line warning: ignoring option '-M'; no argument required # The diagnosis changed in icc 8.0: # icc: Command line remark: option '-MP' not supported if (grep 'ignoring option' conftest.err || grep 'not supported' conftest.err) >/dev/null 2>&1; then :; else am_cv_CC_dependencies_compiler_type=$depmode break fi fi done cd .. rm -rf conftest.dir else am_cv_CC_dependencies_compiler_type=none fi fi { $as_echo "$as_me:${as_lineno-$LINENO}: result: $am_cv_CC_dependencies_compiler_type" >&5 $as_echo "$am_cv_CC_dependencies_compiler_type" >&6; } CCDEPMODE=depmode=$am_cv_CC_dependencies_compiler_type if test "x$enable_dependency_tracking" != xno \ && test "$am_cv_CC_dependencies_compiler_type" = gcc3; then am__fastdepCC_TRUE= am__fastdepCC_FALSE='#' else am__fastdepCC_TRUE='#' am__fastdepCC_FALSE= fi case `pwd` in *\ * | *\ *) { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: Libtool does not cope well with whitespace in \`pwd\`" >&5 $as_echo "$as_me: WARNING: Libtool does not cope well with whitespace in \`pwd\`" >&2;} ;; esac macro_version='2.4.2' macro_revision='1.3337' ltmain="$ac_aux_dir/ltmain.sh" # Make sure we can run config.sub. $SHELL "$ac_aux_dir/config.sub" sun4 >/dev/null 2>&1 || as_fn_error $? "cannot run $SHELL $ac_aux_dir/config.sub" "$LINENO" 5 { $as_echo "$as_me:${as_lineno-$LINENO}: checking build system type" >&5 $as_echo_n "checking build system type... " >&6; } if ${ac_cv_build+:} false; then : $as_echo_n "(cached) " >&6 else ac_build_alias=$build_alias test "x$ac_build_alias" = x && ac_build_alias=`$SHELL "$ac_aux_dir/config.guess"` test "x$ac_build_alias" = x && as_fn_error $? "cannot guess build type; you must specify one" "$LINENO" 5 ac_cv_build=`$SHELL "$ac_aux_dir/config.sub" $ac_build_alias` || as_fn_error $? "$SHELL $ac_aux_dir/config.sub $ac_build_alias failed" "$LINENO" 5 fi { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_build" >&5 $as_echo "$ac_cv_build" >&6; } case $ac_cv_build in *-*-*) ;; *) as_fn_error $? "invalid value of canonical build" "$LINENO" 5;; esac build=$ac_cv_build ac_save_IFS=$IFS; IFS='-' set x $ac_cv_build shift build_cpu=$1 build_vendor=$2 shift; shift # Remember, the first character of IFS is used to create $*, # except with old shells: build_os=$* IFS=$ac_save_IFS case $build_os in *\ *) build_os=`echo "$build_os" | sed 's/ /-/g'`;; esac { $as_echo "$as_me:${as_lineno-$LINENO}: checking host system type" >&5 $as_echo_n "checking host system type... " >&6; } if ${ac_cv_host+:} false; then : $as_echo_n "(cached) " >&6 else if test "x$host_alias" = x; then ac_cv_host=$ac_cv_build else ac_cv_host=`$SHELL "$ac_aux_dir/config.sub" $host_alias` || as_fn_error $? "$SHELL $ac_aux_dir/config.sub $host_alias failed" "$LINENO" 5 fi fi { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_host" >&5 $as_echo "$ac_cv_host" >&6; } case $ac_cv_host in *-*-*) ;; *) as_fn_error $? "invalid value of canonical host" "$LINENO" 5;; esac host=$ac_cv_host ac_save_IFS=$IFS; IFS='-' set x $ac_cv_host shift host_cpu=$1 host_vendor=$2 shift; shift # Remember, the first character of IFS is used to create $*, # except with old shells: host_os=$* IFS=$ac_save_IFS case $host_os in *\ *) host_os=`echo "$host_os" | sed 's/ /-/g'`;; esac # Backslashify metacharacters that are still active within # double-quoted strings. sed_quote_subst='s/\(["`$\\]\)/\\\1/g' # Same as above, but do not quote variable references. double_quote_subst='s/\(["`\\]\)/\\\1/g' # Sed substitution to delay expansion of an escaped shell variable in a # double_quote_subst'ed string. delay_variable_subst='s/\\\\\\\\\\\$/\\\\\\$/g' # Sed substitution to delay expansion of an escaped single quote. delay_single_quote_subst='s/'\''/'\'\\\\\\\'\''/g' # Sed substitution to avoid accidental globbing in evaled expressions no_glob_subst='s/\*/\\\*/g' ECHO='\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\' ECHO=$ECHO$ECHO$ECHO$ECHO$ECHO ECHO=$ECHO$ECHO$ECHO$ECHO$ECHO$ECHO { $as_echo "$as_me:${as_lineno-$LINENO}: checking how to print strings" >&5 $as_echo_n "checking how to print strings... " >&6; } # Test print first, because it will be a builtin if present. if test "X`( print -r -- -n ) 2>/dev/null`" = X-n && \ test "X`print -r -- $ECHO 2>/dev/null`" = "X$ECHO"; then ECHO='print -r --' elif test "X`printf %s $ECHO 2>/dev/null`" = "X$ECHO"; then ECHO='printf %s\n' else # Use this function as a fallback that always works. func_fallback_echo () { eval 'cat <<_LTECHO_EOF $1 _LTECHO_EOF' } ECHO='func_fallback_echo' fi # func_echo_all arg... # Invoke $ECHO with all args, space-separated. func_echo_all () { $ECHO "" } case "$ECHO" in printf*) { $as_echo "$as_me:${as_lineno-$LINENO}: result: printf" >&5 $as_echo "printf" >&6; } ;; print*) { $as_echo "$as_me:${as_lineno-$LINENO}: result: print -r" >&5 $as_echo "print -r" >&6; } ;; *) { $as_echo "$as_me:${as_lineno-$LINENO}: result: cat" >&5 $as_echo "cat" >&6; } ;; esac { $as_echo "$as_me:${as_lineno-$LINENO}: checking for a sed that does not truncate output" >&5 $as_echo_n "checking for a sed that does not truncate output... " >&6; } if ${ac_cv_path_SED+:} false; then : $as_echo_n "(cached) " >&6 else ac_script=s/aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb/ for ac_i in 1 2 3 4 5 6 7; do ac_script="$ac_script$as_nl$ac_script" done echo "$ac_script" 2>/dev/null | sed 99q >conftest.sed { ac_script=; unset ac_script;} if test -z "$SED"; then ac_path_SED_found=false # Loop through the user's path and test for each of PROGNAME-LIST as_save_IFS=$IFS; IFS=$PATH_SEPARATOR for as_dir in $PATH do IFS=$as_save_IFS test -z "$as_dir" && as_dir=. for ac_prog in sed gsed; do for ac_exec_ext in '' $ac_executable_extensions; do ac_path_SED="$as_dir/$ac_prog$ac_exec_ext" as_fn_executable_p "$ac_path_SED" || continue # Check for GNU ac_path_SED and select it if it is found. # Check for GNU $ac_path_SED case `"$ac_path_SED" --version 2>&1` in *GNU*) ac_cv_path_SED="$ac_path_SED" ac_path_SED_found=:;; *) ac_count=0 $as_echo_n 0123456789 >"conftest.in" while : do cat "conftest.in" "conftest.in" >"conftest.tmp" mv "conftest.tmp" "conftest.in" cp "conftest.in" "conftest.nl" $as_echo '' >> "conftest.nl" "$ac_path_SED" -f conftest.sed < "conftest.nl" >"conftest.out" 2>/dev/null || break diff "conftest.out" "conftest.nl" >/dev/null 2>&1 || break as_fn_arith $ac_count + 1 && ac_count=$as_val if test $ac_count -gt ${ac_path_SED_max-0}; then # Best one so far, save it but keep looking for a better one ac_cv_path_SED="$ac_path_SED" ac_path_SED_max=$ac_count fi # 10*(2^10) chars as input seems more than enough test $ac_count -gt 10 && break done rm -f conftest.in conftest.tmp conftest.nl conftest.out;; esac $ac_path_SED_found && break 3 done done done IFS=$as_save_IFS if test -z "$ac_cv_path_SED"; then as_fn_error $? "no acceptable sed could be found in \$PATH" "$LINENO" 5 fi else ac_cv_path_SED=$SED fi fi { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_path_SED" >&5 $as_echo "$ac_cv_path_SED" >&6; } SED="$ac_cv_path_SED" rm -f conftest.sed test -z "$SED" && SED=sed Xsed="$SED -e 1s/^X//" { $as_echo "$as_me:${as_lineno-$LINENO}: checking for fgrep" >&5 $as_echo_n "checking for fgrep... " >&6; } if ${ac_cv_path_FGREP+:} false; then : $as_echo_n "(cached) " >&6 else if echo 'ab*c' | $GREP -F 'ab*c' >/dev/null 2>&1 then ac_cv_path_FGREP="$GREP -F" else if test -z "$FGREP"; then ac_path_FGREP_found=false # Loop through the user's path and test for each of PROGNAME-LIST as_save_IFS=$IFS; IFS=$PATH_SEPARATOR for as_dir in $PATH$PATH_SEPARATOR/usr/xpg4/bin do IFS=$as_save_IFS test -z "$as_dir" && as_dir=. for ac_prog in fgrep; do for ac_exec_ext in '' $ac_executable_extensions; do ac_path_FGREP="$as_dir/$ac_prog$ac_exec_ext" as_fn_executable_p "$ac_path_FGREP" || continue # Check for GNU ac_path_FGREP and select it if it is found. # Check for GNU $ac_path_FGREP case `"$ac_path_FGREP" --version 2>&1` in *GNU*) ac_cv_path_FGREP="$ac_path_FGREP" ac_path_FGREP_found=:;; *) ac_count=0 $as_echo_n 0123456789 >"conftest.in" while : do cat "conftest.in" "conftest.in" >"conftest.tmp" mv "conftest.tmp" "conftest.in" cp "conftest.in" "conftest.nl" $as_echo 'FGREP' >> "conftest.nl" "$ac_path_FGREP" FGREP < "conftest.nl" >"conftest.out" 2>/dev/null || break diff "conftest.out" "conftest.nl" >/dev/null 2>&1 || break as_fn_arith $ac_count + 1 && ac_count=$as_val if test $ac_count -gt ${ac_path_FGREP_max-0}; then # Best one so far, save it but keep looking for a better one ac_cv_path_FGREP="$ac_path_FGREP" ac_path_FGREP_max=$ac_count fi # 10*(2^10) chars as input seems more than enough test $ac_count -gt 10 && break done rm -f conftest.in conftest.tmp conftest.nl conftest.out;; esac $ac_path_FGREP_found && break 3 done done done IFS=$as_save_IFS if test -z "$ac_cv_path_FGREP"; then as_fn_error $? "no acceptable fgrep could be found in $PATH$PATH_SEPARATOR/usr/xpg4/bin" "$LINENO" 5 fi else ac_cv_path_FGREP=$FGREP fi fi fi { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_path_FGREP" >&5 $as_echo "$ac_cv_path_FGREP" >&6; } FGREP="$ac_cv_path_FGREP" test -z "$GREP" && GREP=grep # Check whether --with-gnu-ld was given. if test "${with_gnu_ld+set}" = set; then : withval=$with_gnu_ld; test "$withval" = no || with_gnu_ld=yes else with_gnu_ld=no fi ac_prog=ld if test "$GCC" = yes; then # Check if gcc -print-prog-name=ld gives a path. { $as_echo "$as_me:${as_lineno-$LINENO}: checking for ld used by $CC" >&5 $as_echo_n "checking for ld used by $CC... " >&6; } case $host in *-*-mingw*) # gcc leaves a trailing carriage return which upsets mingw ac_prog=`($CC -print-prog-name=ld) 2>&5 | tr -d '\015'` ;; *) ac_prog=`($CC -print-prog-name=ld) 2>&5` ;; esac case $ac_prog in # Accept absolute paths. [\\/]* | ?:[\\/]*) re_direlt='/[^/][^/]*/\.\./' # Canonicalize the pathname of ld ac_prog=`$ECHO "$ac_prog"| $SED 's%\\\\%/%g'` while $ECHO "$ac_prog" | $GREP "$re_direlt" > /dev/null 2>&1; do ac_prog=`$ECHO $ac_prog| $SED "s%$re_direlt%/%"` done test -z "$LD" && LD="$ac_prog" ;; "") # If it fails, then pretend we aren't using GCC. ac_prog=ld ;; *) # If it is relative, then search for the first ld in PATH. with_gnu_ld=unknown ;; esac elif test "$with_gnu_ld" = yes; then { $as_echo "$as_me:${as_lineno-$LINENO}: checking for GNU ld" >&5 $as_echo_n "checking for GNU ld... " >&6; } else { $as_echo "$as_me:${as_lineno-$LINENO}: checking for non-GNU ld" >&5 $as_echo_n "checking for non-GNU ld... " >&6; } fi if ${lt_cv_path_LD+:} false; then : $as_echo_n "(cached) " >&6 else if test -z "$LD"; then lt_save_ifs="$IFS"; IFS=$PATH_SEPARATOR for ac_dir in $PATH; do IFS="$lt_save_ifs" test -z "$ac_dir" && ac_dir=. if test -f "$ac_dir/$ac_prog" || test -f "$ac_dir/$ac_prog$ac_exeext"; then lt_cv_path_LD="$ac_dir/$ac_prog" # Check to see if the program is GNU ld. I'd rather use --version, # but apparently some variants of GNU ld only accept -v. # Break only if it was the GNU/non-GNU ld that we prefer. case `"$lt_cv_path_LD" -v 2>&1 &5 $as_echo "$LD" >&6; } else { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 $as_echo "no" >&6; } fi test -z "$LD" && as_fn_error $? "no acceptable ld found in \$PATH" "$LINENO" 5 { $as_echo "$as_me:${as_lineno-$LINENO}: checking if the linker ($LD) is GNU ld" >&5 $as_echo_n "checking if the linker ($LD) is GNU ld... " >&6; } if ${lt_cv_prog_gnu_ld+:} false; then : $as_echo_n "(cached) " >&6 else # I'd rather use --version here, but apparently some GNU lds only accept -v. case `$LD -v 2>&1 &5 $as_echo "$lt_cv_prog_gnu_ld" >&6; } with_gnu_ld=$lt_cv_prog_gnu_ld { $as_echo "$as_me:${as_lineno-$LINENO}: checking for BSD- or MS-compatible name lister (nm)" >&5 $as_echo_n "checking for BSD- or MS-compatible name lister (nm)... " >&6; } if ${lt_cv_path_NM+:} false; then : $as_echo_n "(cached) " >&6 else if test -n "$NM"; then # Let the user override the test. lt_cv_path_NM="$NM" else lt_nm_to_check="${ac_tool_prefix}nm" if test -n "$ac_tool_prefix" && test "$build" = "$host"; then lt_nm_to_check="$lt_nm_to_check nm" fi for lt_tmp_nm in $lt_nm_to_check; do lt_save_ifs="$IFS"; IFS=$PATH_SEPARATOR for ac_dir in $PATH /usr/ccs/bin/elf /usr/ccs/bin /usr/ucb /bin; do IFS="$lt_save_ifs" test -z "$ac_dir" && ac_dir=. tmp_nm="$ac_dir/$lt_tmp_nm" if test -f "$tmp_nm" || test -f "$tmp_nm$ac_exeext" ; then # Check to see if the nm accepts a BSD-compat flag. # Adding the `sed 1q' prevents false positives on HP-UX, which says: # nm: unknown option "B" ignored # Tru64's nm complains that /dev/null is an invalid object file case `"$tmp_nm" -B /dev/null 2>&1 | sed '1q'` in */dev/null* | *'Invalid file or object type'*) lt_cv_path_NM="$tmp_nm -B" break ;; *) case `"$tmp_nm" -p /dev/null 2>&1 | sed '1q'` in */dev/null*) lt_cv_path_NM="$tmp_nm -p" break ;; *) lt_cv_path_NM=${lt_cv_path_NM="$tmp_nm"} # keep the first match, but continue # so that we can try to find one that supports BSD flags ;; esac ;; esac fi done IFS="$lt_save_ifs" done : ${lt_cv_path_NM=no} fi fi { $as_echo "$as_me:${as_lineno-$LINENO}: result: $lt_cv_path_NM" >&5 $as_echo "$lt_cv_path_NM" >&6; } if test "$lt_cv_path_NM" != "no"; then NM="$lt_cv_path_NM" else # Didn't find any BSD compatible name lister, look for dumpbin. if test -n "$DUMPBIN"; then : # Let the user override the test. else if test -n "$ac_tool_prefix"; then for ac_prog in dumpbin "link -dump" do # Extract the first word of "$ac_tool_prefix$ac_prog", so it can be a program name with args. set dummy $ac_tool_prefix$ac_prog; ac_word=$2 { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 $as_echo_n "checking for $ac_word... " >&6; } if ${ac_cv_prog_DUMPBIN+:} false; then : $as_echo_n "(cached) " >&6 else if test -n "$DUMPBIN"; then ac_cv_prog_DUMPBIN="$DUMPBIN" # Let the user override the test. else as_save_IFS=$IFS; IFS=$PATH_SEPARATOR for as_dir in $PATH do IFS=$as_save_IFS test -z "$as_dir" && as_dir=. for ac_exec_ext in '' $ac_executable_extensions; do if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then ac_cv_prog_DUMPBIN="$ac_tool_prefix$ac_prog" $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5 break 2 fi done done IFS=$as_save_IFS fi fi DUMPBIN=$ac_cv_prog_DUMPBIN if test -n "$DUMPBIN"; then { $as_echo "$as_me:${as_lineno-$LINENO}: result: $DUMPBIN" >&5 $as_echo "$DUMPBIN" >&6; } else { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 $as_echo "no" >&6; } fi test -n "$DUMPBIN" && break done fi if test -z "$DUMPBIN"; then ac_ct_DUMPBIN=$DUMPBIN for ac_prog in dumpbin "link -dump" do # Extract the first word of "$ac_prog", so it can be a program name with args. set dummy $ac_prog; ac_word=$2 { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 $as_echo_n "checking for $ac_word... " >&6; } if ${ac_cv_prog_ac_ct_DUMPBIN+:} false; then : $as_echo_n "(cached) " >&6 else if test -n "$ac_ct_DUMPBIN"; then ac_cv_prog_ac_ct_DUMPBIN="$ac_ct_DUMPBIN" # Let the user override the test. else as_save_IFS=$IFS; IFS=$PATH_SEPARATOR for as_dir in $PATH do IFS=$as_save_IFS test -z "$as_dir" && as_dir=. for ac_exec_ext in '' $ac_executable_extensions; do if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then ac_cv_prog_ac_ct_DUMPBIN="$ac_prog" $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5 break 2 fi done done IFS=$as_save_IFS fi fi ac_ct_DUMPBIN=$ac_cv_prog_ac_ct_DUMPBIN if test -n "$ac_ct_DUMPBIN"; then { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_ct_DUMPBIN" >&5 $as_echo "$ac_ct_DUMPBIN" >&6; } else { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 $as_echo "no" >&6; } fi test -n "$ac_ct_DUMPBIN" && break done if test "x$ac_ct_DUMPBIN" = x; then DUMPBIN=":" else case $cross_compiling:$ac_tool_warned in yes:) { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: using cross tools not prefixed with host triplet" >&5 $as_echo "$as_me: WARNING: using cross tools not prefixed with host triplet" >&2;} ac_tool_warned=yes ;; esac DUMPBIN=$ac_ct_DUMPBIN fi fi case `$DUMPBIN -symbols /dev/null 2>&1 | sed '1q'` in *COFF*) DUMPBIN="$DUMPBIN -symbols" ;; *) DUMPBIN=: ;; esac fi if test "$DUMPBIN" != ":"; then NM="$DUMPBIN" fi fi test -z "$NM" && NM=nm { $as_echo "$as_me:${as_lineno-$LINENO}: checking the name lister ($NM) interface" >&5 $as_echo_n "checking the name lister ($NM) interface... " >&6; } if ${lt_cv_nm_interface+:} false; then : $as_echo_n "(cached) " >&6 else lt_cv_nm_interface="BSD nm" echo "int some_variable = 0;" > conftest.$ac_ext (eval echo "\"\$as_me:$LINENO: $ac_compile\"" >&5) (eval "$ac_compile" 2>conftest.err) cat conftest.err >&5 (eval echo "\"\$as_me:$LINENO: $NM \\\"conftest.$ac_objext\\\"\"" >&5) (eval "$NM \"conftest.$ac_objext\"" 2>conftest.err > conftest.out) cat conftest.err >&5 (eval echo "\"\$as_me:$LINENO: output\"" >&5) cat conftest.out >&5 if $GREP 'External.*some_variable' conftest.out > /dev/null; then lt_cv_nm_interface="MS dumpbin" fi rm -f conftest* fi { $as_echo "$as_me:${as_lineno-$LINENO}: result: $lt_cv_nm_interface" >&5 $as_echo "$lt_cv_nm_interface" >&6; } { $as_echo "$as_me:${as_lineno-$LINENO}: checking whether ln -s works" >&5 $as_echo_n "checking whether ln -s works... " >&6; } LN_S=$as_ln_s if test "$LN_S" = "ln -s"; then { $as_echo "$as_me:${as_lineno-$LINENO}: result: yes" >&5 $as_echo "yes" >&6; } else { $as_echo "$as_me:${as_lineno-$LINENO}: result: no, using $LN_S" >&5 $as_echo "no, using $LN_S" >&6; } fi # find the maximum length of command line arguments { $as_echo "$as_me:${as_lineno-$LINENO}: checking the maximum length of command line arguments" >&5 $as_echo_n "checking the maximum length of command line arguments... " >&6; } if ${lt_cv_sys_max_cmd_len+:} false; then : $as_echo_n "(cached) " >&6 else i=0 teststring="ABCD" case $build_os in msdosdjgpp*) # On DJGPP, this test can blow up pretty badly due to problems in libc # (any single argument exceeding 2000 bytes causes a buffer overrun # during glob expansion). Even if it were fixed, the result of this # check would be larger than it should be. lt_cv_sys_max_cmd_len=12288; # 12K is about right ;; gnu*) # Under GNU Hurd, this test is not required because there is # no limit to the length of command line arguments. # Libtool will interpret -1 as no limit whatsoever lt_cv_sys_max_cmd_len=-1; ;; cygwin* | mingw* | cegcc*) # On Win9x/ME, this test blows up -- it succeeds, but takes # about 5 minutes as the teststring grows exponentially. # Worse, since 9x/ME are not pre-emptively multitasking, # you end up with a "frozen" computer, even though with patience # the test eventually succeeds (with a max line length of 256k). # Instead, let's just punt: use the minimum linelength reported by # all of the supported platforms: 8192 (on NT/2K/XP). lt_cv_sys_max_cmd_len=8192; ;; mint*) # On MiNT this can take a long time and run out of memory. lt_cv_sys_max_cmd_len=8192; ;; amigaos*) # On AmigaOS with pdksh, this test takes hours, literally. # So we just punt and use a minimum line length of 8192. lt_cv_sys_max_cmd_len=8192; ;; netbsd* | freebsd* | openbsd* | darwin* | dragonfly*) # This has been around since 386BSD, at least. Likely further. if test -x /sbin/sysctl; then lt_cv_sys_max_cmd_len=`/sbin/sysctl -n kern.argmax` elif test -x /usr/sbin/sysctl; then lt_cv_sys_max_cmd_len=`/usr/sbin/sysctl -n kern.argmax` else lt_cv_sys_max_cmd_len=65536 # usable default for all BSDs fi # And add a safety zone lt_cv_sys_max_cmd_len=`expr $lt_cv_sys_max_cmd_len \/ 4` lt_cv_sys_max_cmd_len=`expr $lt_cv_sys_max_cmd_len \* 3` ;; interix*) # We know the value 262144 and hardcode it with a safety zone (like BSD) lt_cv_sys_max_cmd_len=196608 ;; os2*) # The test takes a long time on OS/2. lt_cv_sys_max_cmd_len=8192 ;; osf*) # Dr. Hans Ekkehard Plesser reports seeing a kernel panic running configure # due to this test when exec_disable_arg_limit is 1 on Tru64. It is not # nice to cause kernel panics so lets avoid the loop below. # First set a reasonable default. lt_cv_sys_max_cmd_len=16384 # if test -x /sbin/sysconfig; then case `/sbin/sysconfig -q proc exec_disable_arg_limit` in *1*) lt_cv_sys_max_cmd_len=-1 ;; esac fi ;; sco3.2v5*) lt_cv_sys_max_cmd_len=102400 ;; sysv5* | sco5v6* | sysv4.2uw2*) kargmax=`grep ARG_MAX /etc/conf/cf.d/stune 2>/dev/null` if test -n "$kargmax"; then lt_cv_sys_max_cmd_len=`echo $kargmax | sed 's/.*[ ]//'` else lt_cv_sys_max_cmd_len=32768 fi ;; *) lt_cv_sys_max_cmd_len=`(getconf ARG_MAX) 2> /dev/null` if test -n "$lt_cv_sys_max_cmd_len"; then lt_cv_sys_max_cmd_len=`expr $lt_cv_sys_max_cmd_len \/ 4` lt_cv_sys_max_cmd_len=`expr $lt_cv_sys_max_cmd_len \* 3` else # Make teststring a little bigger before we do anything with it. # a 1K string should be a reasonable start. for i in 1 2 3 4 5 6 7 8 ; do teststring=$teststring$teststring done SHELL=${SHELL-${CONFIG_SHELL-/bin/sh}} # If test is not a shell built-in, we'll probably end up computing a # maximum length that is only half of the actual maximum length, but # we can't tell. while { test "X"`env echo "$teststring$teststring" 2>/dev/null` \ = "X$teststring$teststring"; } >/dev/null 2>&1 && test $i != 17 # 1/2 MB should be enough do i=`expr $i + 1` teststring=$teststring$teststring done # Only check the string length outside the loop. lt_cv_sys_max_cmd_len=`expr "X$teststring" : ".*" 2>&1` teststring= # Add a significant safety factor because C++ compilers can tack on # massive amounts of additional arguments before passing them to the # linker. It appears as though 1/2 is a usable value. lt_cv_sys_max_cmd_len=`expr $lt_cv_sys_max_cmd_len \/ 2` fi ;; esac fi if test -n $lt_cv_sys_max_cmd_len ; then { $as_echo "$as_me:${as_lineno-$LINENO}: result: $lt_cv_sys_max_cmd_len" >&5 $as_echo "$lt_cv_sys_max_cmd_len" >&6; } else { $as_echo "$as_me:${as_lineno-$LINENO}: result: none" >&5 $as_echo "none" >&6; } fi max_cmd_len=$lt_cv_sys_max_cmd_len : ${CP="cp -f"} : ${MV="mv -f"} : ${RM="rm -f"} { $as_echo "$as_me:${as_lineno-$LINENO}: checking whether the shell understands some XSI constructs" >&5 $as_echo_n "checking whether the shell understands some XSI constructs... " >&6; } # Try some XSI features xsi_shell=no ( _lt_dummy="a/b/c" test "${_lt_dummy##*/},${_lt_dummy%/*},${_lt_dummy#??}"${_lt_dummy%"$_lt_dummy"}, \ = c,a/b,b/c, \ && eval 'test $(( 1 + 1 )) -eq 2 \ && test "${#_lt_dummy}" -eq 5' ) >/dev/null 2>&1 \ && xsi_shell=yes { $as_echo "$as_me:${as_lineno-$LINENO}: result: $xsi_shell" >&5 $as_echo "$xsi_shell" >&6; } { $as_echo "$as_me:${as_lineno-$LINENO}: checking whether the shell understands \"+=\"" >&5 $as_echo_n "checking whether the shell understands \"+=\"... " >&6; } lt_shell_append=no ( foo=bar; set foo baz; eval "$1+=\$2" && test "$foo" = barbaz ) \ >/dev/null 2>&1 \ && lt_shell_append=yes { $as_echo "$as_me:${as_lineno-$LINENO}: result: $lt_shell_append" >&5 $as_echo "$lt_shell_append" >&6; } if ( (MAIL=60; unset MAIL) || exit) >/dev/null 2>&1; then lt_unset=unset else lt_unset=false fi # test EBCDIC or ASCII case `echo X|tr X '\101'` in A) # ASCII based system # \n is not interpreted correctly by Solaris 8 /usr/ucb/tr lt_SP2NL='tr \040 \012' lt_NL2SP='tr \015\012 \040\040' ;; *) # EBCDIC based system lt_SP2NL='tr \100 \n' lt_NL2SP='tr \r\n \100\100' ;; esac { $as_echo "$as_me:${as_lineno-$LINENO}: checking how to convert $build file names to $host format" >&5 $as_echo_n "checking how to convert $build file names to $host format... " >&6; } if ${lt_cv_to_host_file_cmd+:} false; then : $as_echo_n "(cached) " >&6 else case $host in *-*-mingw* ) case $build in *-*-mingw* ) # actually msys lt_cv_to_host_file_cmd=func_convert_file_msys_to_w32 ;; *-*-cygwin* ) lt_cv_to_host_file_cmd=func_convert_file_cygwin_to_w32 ;; * ) # otherwise, assume *nix lt_cv_to_host_file_cmd=func_convert_file_nix_to_w32 ;; esac ;; *-*-cygwin* ) case $build in *-*-mingw* ) # actually msys lt_cv_to_host_file_cmd=func_convert_file_msys_to_cygwin ;; *-*-cygwin* ) lt_cv_to_host_file_cmd=func_convert_file_noop ;; * ) # otherwise, assume *nix lt_cv_to_host_file_cmd=func_convert_file_nix_to_cygwin ;; esac ;; * ) # unhandled hosts (and "normal" native builds) lt_cv_to_host_file_cmd=func_convert_file_noop ;; esac fi to_host_file_cmd=$lt_cv_to_host_file_cmd { $as_echo "$as_me:${as_lineno-$LINENO}: result: $lt_cv_to_host_file_cmd" >&5 $as_echo "$lt_cv_to_host_file_cmd" >&6; } { $as_echo "$as_me:${as_lineno-$LINENO}: checking how to convert $build file names to toolchain format" >&5 $as_echo_n "checking how to convert $build file names to toolchain format... " >&6; } if ${lt_cv_to_tool_file_cmd+:} false; then : $as_echo_n "(cached) " >&6 else #assume ordinary cross tools, or native build. lt_cv_to_tool_file_cmd=func_convert_file_noop case $host in *-*-mingw* ) case $build in *-*-mingw* ) # actually msys lt_cv_to_tool_file_cmd=func_convert_file_msys_to_w32 ;; esac ;; esac fi to_tool_file_cmd=$lt_cv_to_tool_file_cmd { $as_echo "$as_me:${as_lineno-$LINENO}: result: $lt_cv_to_tool_file_cmd" >&5 $as_echo "$lt_cv_to_tool_file_cmd" >&6; } { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $LD option to reload object files" >&5 $as_echo_n "checking for $LD option to reload object files... " >&6; } if ${lt_cv_ld_reload_flag+:} false; then : $as_echo_n "(cached) " >&6 else lt_cv_ld_reload_flag='-r' fi { $as_echo "$as_me:${as_lineno-$LINENO}: result: $lt_cv_ld_reload_flag" >&5 $as_echo "$lt_cv_ld_reload_flag" >&6; } reload_flag=$lt_cv_ld_reload_flag case $reload_flag in "" | " "*) ;; *) reload_flag=" $reload_flag" ;; esac reload_cmds='$LD$reload_flag -o $output$reload_objs' case $host_os in cygwin* | mingw* | pw32* | cegcc*) if test "$GCC" != yes; then reload_cmds=false fi ;; darwin*) if test "$GCC" = yes; then reload_cmds='$LTCC $LTCFLAGS -nostdlib ${wl}-r -o $output$reload_objs' else reload_cmds='$LD$reload_flag -o $output$reload_objs' fi ;; esac if test -n "$ac_tool_prefix"; then # Extract the first word of "${ac_tool_prefix}objdump", so it can be a program name with args. set dummy ${ac_tool_prefix}objdump; ac_word=$2 { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 $as_echo_n "checking for $ac_word... " >&6; } if ${ac_cv_prog_OBJDUMP+:} false; then : $as_echo_n "(cached) " >&6 else if test -n "$OBJDUMP"; then ac_cv_prog_OBJDUMP="$OBJDUMP" # Let the user override the test. else as_save_IFS=$IFS; IFS=$PATH_SEPARATOR for as_dir in $PATH do IFS=$as_save_IFS test -z "$as_dir" && as_dir=. for ac_exec_ext in '' $ac_executable_extensions; do if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then ac_cv_prog_OBJDUMP="${ac_tool_prefix}objdump" $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5 break 2 fi done done IFS=$as_save_IFS fi fi OBJDUMP=$ac_cv_prog_OBJDUMP if test -n "$OBJDUMP"; then { $as_echo "$as_me:${as_lineno-$LINENO}: result: $OBJDUMP" >&5 $as_echo "$OBJDUMP" >&6; } else { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 $as_echo "no" >&6; } fi fi if test -z "$ac_cv_prog_OBJDUMP"; then ac_ct_OBJDUMP=$OBJDUMP # Extract the first word of "objdump", so it can be a program name with args. set dummy objdump; ac_word=$2 { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 $as_echo_n "checking for $ac_word... " >&6; } if ${ac_cv_prog_ac_ct_OBJDUMP+:} false; then : $as_echo_n "(cached) " >&6 else if test -n "$ac_ct_OBJDUMP"; then ac_cv_prog_ac_ct_OBJDUMP="$ac_ct_OBJDUMP" # Let the user override the test. else as_save_IFS=$IFS; IFS=$PATH_SEPARATOR for as_dir in $PATH do IFS=$as_save_IFS test -z "$as_dir" && as_dir=. for ac_exec_ext in '' $ac_executable_extensions; do if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then ac_cv_prog_ac_ct_OBJDUMP="objdump" $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5 break 2 fi done done IFS=$as_save_IFS fi fi ac_ct_OBJDUMP=$ac_cv_prog_ac_ct_OBJDUMP if test -n "$ac_ct_OBJDUMP"; then { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_ct_OBJDUMP" >&5 $as_echo "$ac_ct_OBJDUMP" >&6; } else { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 $as_echo "no" >&6; } fi if test "x$ac_ct_OBJDUMP" = x; then OBJDUMP="false" else case $cross_compiling:$ac_tool_warned in yes:) { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: using cross tools not prefixed with host triplet" >&5 $as_echo "$as_me: WARNING: using cross tools not prefixed with host triplet" >&2;} ac_tool_warned=yes ;; esac OBJDUMP=$ac_ct_OBJDUMP fi else OBJDUMP="$ac_cv_prog_OBJDUMP" fi test -z "$OBJDUMP" && OBJDUMP=objdump { $as_echo "$as_me:${as_lineno-$LINENO}: checking how to recognize dependent libraries" >&5 $as_echo_n "checking how to recognize dependent libraries... " >&6; } if ${lt_cv_deplibs_check_method+:} false; then : $as_echo_n "(cached) " >&6 else lt_cv_file_magic_cmd='$MAGIC_CMD' lt_cv_file_magic_test_file= lt_cv_deplibs_check_method='unknown' # Need to set the preceding variable on all platforms that support # interlibrary dependencies. # 'none' -- dependencies not supported. # `unknown' -- same as none, but documents that we really don't know. # 'pass_all' -- all dependencies passed with no checks. # 'test_compile' -- check by making test program. # 'file_magic [[regex]]' -- check by looking for files in library path # which responds to the $file_magic_cmd with a given extended regex. # If you have `file' or equivalent on your system and you're not sure # whether `pass_all' will *always* work, you probably want this one. case $host_os in aix[4-9]*) lt_cv_deplibs_check_method=pass_all ;; beos*) lt_cv_deplibs_check_method=pass_all ;; bsdi[45]*) lt_cv_deplibs_check_method='file_magic ELF [0-9][0-9]*-bit [ML]SB (shared object|dynamic lib)' lt_cv_file_magic_cmd='/usr/bin/file -L' lt_cv_file_magic_test_file=/shlib/libc.so ;; cygwin*) # func_win32_libid is a shell function defined in ltmain.sh lt_cv_deplibs_check_method='file_magic ^x86 archive import|^x86 DLL' lt_cv_file_magic_cmd='func_win32_libid' ;; mingw* | pw32*) # Base MSYS/MinGW do not provide the 'file' command needed by # func_win32_libid shell function, so use a weaker test based on 'objdump', # unless we find 'file', for example because we are cross-compiling. # func_win32_libid assumes BSD nm, so disallow it if using MS dumpbin. if ( test "$lt_cv_nm_interface" = "BSD nm" && file / ) >/dev/null 2>&1; then lt_cv_deplibs_check_method='file_magic ^x86 archive import|^x86 DLL' lt_cv_file_magic_cmd='func_win32_libid' else # Keep this pattern in sync with the one in func_win32_libid. lt_cv_deplibs_check_method='file_magic file format (pei*-i386(.*architecture: i386)?|pe-arm-wince|pe-x86-64)' lt_cv_file_magic_cmd='$OBJDUMP -f' fi ;; cegcc*) # use the weaker test based on 'objdump'. See mingw*. lt_cv_deplibs_check_method='file_magic file format pe-arm-.*little(.*architecture: arm)?' lt_cv_file_magic_cmd='$OBJDUMP -f' ;; darwin* | rhapsody*) lt_cv_deplibs_check_method=pass_all ;; freebsd* | dragonfly*) if echo __ELF__ | $CC -E - | $GREP __ELF__ > /dev/null; then case $host_cpu in i*86 ) # Not sure whether the presence of OpenBSD here was a mistake. # Let's accept both of them until this is cleared up. lt_cv_deplibs_check_method='file_magic (FreeBSD|OpenBSD|DragonFly)/i[3-9]86 (compact )?demand paged shared library' lt_cv_file_magic_cmd=/usr/bin/file lt_cv_file_magic_test_file=`echo /usr/lib/libc.so.*` ;; esac else lt_cv_deplibs_check_method=pass_all fi ;; gnu*) lt_cv_deplibs_check_method=pass_all ;; haiku*) lt_cv_deplibs_check_method=pass_all ;; hpux10.20* | hpux11*) lt_cv_file_magic_cmd=/usr/bin/file case $host_cpu in ia64*) lt_cv_deplibs_check_method='file_magic (s[0-9][0-9][0-9]|ELF-[0-9][0-9]) shared object file - IA64' lt_cv_file_magic_test_file=/usr/lib/hpux32/libc.so ;; hppa*64*) lt_cv_deplibs_check_method='file_magic (s[0-9][0-9][0-9]|ELF[ -][0-9][0-9])(-bit)?( [LM]SB)? shared object( file)?[, -]* PA-RISC [0-9]\.[0-9]' lt_cv_file_magic_test_file=/usr/lib/pa20_64/libc.sl ;; *) lt_cv_deplibs_check_method='file_magic (s[0-9][0-9][0-9]|PA-RISC[0-9]\.[0-9]) shared library' lt_cv_file_magic_test_file=/usr/lib/libc.sl ;; esac ;; interix[3-9]*) # PIC code is broken on Interix 3.x, that's why |\.a not |_pic\.a here lt_cv_deplibs_check_method='match_pattern /lib[^/]+(\.so|\.a)$' ;; irix5* | irix6* | nonstopux*) case $LD in *-32|*"-32 ") libmagic=32-bit;; *-n32|*"-n32 ") libmagic=N32;; *-64|*"-64 ") libmagic=64-bit;; *) libmagic=never-match;; esac lt_cv_deplibs_check_method=pass_all ;; # This must be glibc/ELF. linux* | k*bsd*-gnu | kopensolaris*-gnu) lt_cv_deplibs_check_method=pass_all ;; netbsd*) if echo __ELF__ | $CC -E - | $GREP __ELF__ > /dev/null; then lt_cv_deplibs_check_method='match_pattern /lib[^/]+(\.so\.[0-9]+\.[0-9]+|_pic\.a)$' else lt_cv_deplibs_check_method='match_pattern /lib[^/]+(\.so|_pic\.a)$' fi ;; newos6*) lt_cv_deplibs_check_method='file_magic ELF [0-9][0-9]*-bit [ML]SB (executable|dynamic lib)' lt_cv_file_magic_cmd=/usr/bin/file lt_cv_file_magic_test_file=/usr/lib/libnls.so ;; *nto* | *qnx*) lt_cv_deplibs_check_method=pass_all ;; openbsd*) if test -z "`echo __ELF__ | $CC -E - | $GREP __ELF__`" || test "$host_os-$host_cpu" = "openbsd2.8-powerpc"; then lt_cv_deplibs_check_method='match_pattern /lib[^/]+(\.so\.[0-9]+\.[0-9]+|\.so|_pic\.a)$' else lt_cv_deplibs_check_method='match_pattern /lib[^/]+(\.so\.[0-9]+\.[0-9]+|_pic\.a)$' fi ;; osf3* | osf4* | osf5*) lt_cv_deplibs_check_method=pass_all ;; rdos*) lt_cv_deplibs_check_method=pass_all ;; solaris*) lt_cv_deplibs_check_method=pass_all ;; sysv5* | sco3.2v5* | sco5v6* | unixware* | OpenUNIX* | sysv4*uw2*) lt_cv_deplibs_check_method=pass_all ;; sysv4 | sysv4.3*) case $host_vendor in motorola) lt_cv_deplibs_check_method='file_magic ELF [0-9][0-9]*-bit [ML]SB (shared object|dynamic lib) M[0-9][0-9]* Version [0-9]' lt_cv_file_magic_test_file=`echo /usr/lib/libc.so*` ;; ncr) lt_cv_deplibs_check_method=pass_all ;; sequent) lt_cv_file_magic_cmd='/bin/file' lt_cv_deplibs_check_method='file_magic ELF [0-9][0-9]*-bit [LM]SB (shared object|dynamic lib )' ;; sni) lt_cv_file_magic_cmd='/bin/file' lt_cv_deplibs_check_method="file_magic ELF [0-9][0-9]*-bit [LM]SB dynamic lib" lt_cv_file_magic_test_file=/lib/libc.so ;; siemens) lt_cv_deplibs_check_method=pass_all ;; pc) lt_cv_deplibs_check_method=pass_all ;; esac ;; tpf*) lt_cv_deplibs_check_method=pass_all ;; esac fi { $as_echo "$as_me:${as_lineno-$LINENO}: result: $lt_cv_deplibs_check_method" >&5 $as_echo "$lt_cv_deplibs_check_method" >&6; } file_magic_glob= want_nocaseglob=no if test "$build" = "$host"; then case $host_os in mingw* | pw32*) if ( shopt | grep nocaseglob ) >/dev/null 2>&1; then want_nocaseglob=yes else file_magic_glob=`echo aAbBcCdDeEfFgGhHiIjJkKlLmMnNoOpPqQrRsStTuUvVwWxXyYzZ | $SED -e "s/\(..\)/s\/[\1]\/[\1]\/g;/g"` fi ;; esac fi file_magic_cmd=$lt_cv_file_magic_cmd deplibs_check_method=$lt_cv_deplibs_check_method test -z "$deplibs_check_method" && deplibs_check_method=unknown if test -n "$ac_tool_prefix"; then # Extract the first word of "${ac_tool_prefix}dlltool", so it can be a program name with args. set dummy ${ac_tool_prefix}dlltool; ac_word=$2 { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 $as_echo_n "checking for $ac_word... " >&6; } if ${ac_cv_prog_DLLTOOL+:} false; then : $as_echo_n "(cached) " >&6 else if test -n "$DLLTOOL"; then ac_cv_prog_DLLTOOL="$DLLTOOL" # Let the user override the test. else as_save_IFS=$IFS; IFS=$PATH_SEPARATOR for as_dir in $PATH do IFS=$as_save_IFS test -z "$as_dir" && as_dir=. for ac_exec_ext in '' $ac_executable_extensions; do if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then ac_cv_prog_DLLTOOL="${ac_tool_prefix}dlltool" $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5 break 2 fi done done IFS=$as_save_IFS fi fi DLLTOOL=$ac_cv_prog_DLLTOOL if test -n "$DLLTOOL"; then { $as_echo "$as_me:${as_lineno-$LINENO}: result: $DLLTOOL" >&5 $as_echo "$DLLTOOL" >&6; } else { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 $as_echo "no" >&6; } fi fi if test -z "$ac_cv_prog_DLLTOOL"; then ac_ct_DLLTOOL=$DLLTOOL # Extract the first word of "dlltool", so it can be a program name with args. set dummy dlltool; ac_word=$2 { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 $as_echo_n "checking for $ac_word... " >&6; } if ${ac_cv_prog_ac_ct_DLLTOOL+:} false; then : $as_echo_n "(cached) " >&6 else if test -n "$ac_ct_DLLTOOL"; then ac_cv_prog_ac_ct_DLLTOOL="$ac_ct_DLLTOOL" # Let the user override the test. else as_save_IFS=$IFS; IFS=$PATH_SEPARATOR for as_dir in $PATH do IFS=$as_save_IFS test -z "$as_dir" && as_dir=. for ac_exec_ext in '' $ac_executable_extensions; do if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then ac_cv_prog_ac_ct_DLLTOOL="dlltool" $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5 break 2 fi done done IFS=$as_save_IFS fi fi ac_ct_DLLTOOL=$ac_cv_prog_ac_ct_DLLTOOL if test -n "$ac_ct_DLLTOOL"; then { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_ct_DLLTOOL" >&5 $as_echo "$ac_ct_DLLTOOL" >&6; } else { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 $as_echo "no" >&6; } fi if test "x$ac_ct_DLLTOOL" = x; then DLLTOOL="false" else case $cross_compiling:$ac_tool_warned in yes:) { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: using cross tools not prefixed with host triplet" >&5 $as_echo "$as_me: WARNING: using cross tools not prefixed with host triplet" >&2;} ac_tool_warned=yes ;; esac DLLTOOL=$ac_ct_DLLTOOL fi else DLLTOOL="$ac_cv_prog_DLLTOOL" fi test -z "$DLLTOOL" && DLLTOOL=dlltool { $as_echo "$as_me:${as_lineno-$LINENO}: checking how to associate runtime and link libraries" >&5 $as_echo_n "checking how to associate runtime and link libraries... " >&6; } if ${lt_cv_sharedlib_from_linklib_cmd+:} false; then : $as_echo_n "(cached) " >&6 else lt_cv_sharedlib_from_linklib_cmd='unknown' case $host_os in cygwin* | mingw* | pw32* | cegcc*) # two different shell functions defined in ltmain.sh # decide which to use based on capabilities of $DLLTOOL case `$DLLTOOL --help 2>&1` in *--identify-strict*) lt_cv_sharedlib_from_linklib_cmd=func_cygming_dll_for_implib ;; *) lt_cv_sharedlib_from_linklib_cmd=func_cygming_dll_for_implib_fallback ;; esac ;; *) # fallback: assume linklib IS sharedlib lt_cv_sharedlib_from_linklib_cmd="$ECHO" ;; esac fi { $as_echo "$as_me:${as_lineno-$LINENO}: result: $lt_cv_sharedlib_from_linklib_cmd" >&5 $as_echo "$lt_cv_sharedlib_from_linklib_cmd" >&6; } sharedlib_from_linklib_cmd=$lt_cv_sharedlib_from_linklib_cmd test -z "$sharedlib_from_linklib_cmd" && sharedlib_from_linklib_cmd=$ECHO if test -n "$ac_tool_prefix"; then for ac_prog in ar do # Extract the first word of "$ac_tool_prefix$ac_prog", so it can be a program name with args. set dummy $ac_tool_prefix$ac_prog; ac_word=$2 { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 $as_echo_n "checking for $ac_word... " >&6; } if ${ac_cv_prog_AR+:} false; then : $as_echo_n "(cached) " >&6 else if test -n "$AR"; then ac_cv_prog_AR="$AR" # Let the user override the test. else as_save_IFS=$IFS; IFS=$PATH_SEPARATOR for as_dir in $PATH do IFS=$as_save_IFS test -z "$as_dir" && as_dir=. for ac_exec_ext in '' $ac_executable_extensions; do if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then ac_cv_prog_AR="$ac_tool_prefix$ac_prog" $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5 break 2 fi done done IFS=$as_save_IFS fi fi AR=$ac_cv_prog_AR if test -n "$AR"; then { $as_echo "$as_me:${as_lineno-$LINENO}: result: $AR" >&5 $as_echo "$AR" >&6; } else { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 $as_echo "no" >&6; } fi test -n "$AR" && break done fi if test -z "$AR"; then ac_ct_AR=$AR for ac_prog in ar do # Extract the first word of "$ac_prog", so it can be a program name with args. set dummy $ac_prog; ac_word=$2 { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 $as_echo_n "checking for $ac_word... " >&6; } if ${ac_cv_prog_ac_ct_AR+:} false; then : $as_echo_n "(cached) " >&6 else if test -n "$ac_ct_AR"; then ac_cv_prog_ac_ct_AR="$ac_ct_AR" # Let the user override the test. else as_save_IFS=$IFS; IFS=$PATH_SEPARATOR for as_dir in $PATH do IFS=$as_save_IFS test -z "$as_dir" && as_dir=. for ac_exec_ext in '' $ac_executable_extensions; do if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then ac_cv_prog_ac_ct_AR="$ac_prog" $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5 break 2 fi done done IFS=$as_save_IFS fi fi ac_ct_AR=$ac_cv_prog_ac_ct_AR if test -n "$ac_ct_AR"; then { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_ct_AR" >&5 $as_echo "$ac_ct_AR" >&6; } else { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 $as_echo "no" >&6; } fi test -n "$ac_ct_AR" && break done if test "x$ac_ct_AR" = x; then AR="false" else case $cross_compiling:$ac_tool_warned in yes:) { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: using cross tools not prefixed with host triplet" >&5 $as_echo "$as_me: WARNING: using cross tools not prefixed with host triplet" >&2;} ac_tool_warned=yes ;; esac AR=$ac_ct_AR fi fi : ${AR=ar} : ${AR_FLAGS=cru} { $as_echo "$as_me:${as_lineno-$LINENO}: checking for archiver @FILE support" >&5 $as_echo_n "checking for archiver @FILE support... " >&6; } if ${lt_cv_ar_at_file+:} false; then : $as_echo_n "(cached) " >&6 else lt_cv_ar_at_file=no cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ int main () { ; return 0; } _ACEOF if ac_fn_c_try_compile "$LINENO"; then : echo conftest.$ac_objext > conftest.lst lt_ar_try='$AR $AR_FLAGS libconftest.a @conftest.lst >&5' { { eval echo "\"\$as_me\":${as_lineno-$LINENO}: \"$lt_ar_try\""; } >&5 (eval $lt_ar_try) 2>&5 ac_status=$? $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 test $ac_status = 0; } if test "$ac_status" -eq 0; then # Ensure the archiver fails upon bogus file names. rm -f conftest.$ac_objext libconftest.a { { eval echo "\"\$as_me\":${as_lineno-$LINENO}: \"$lt_ar_try\""; } >&5 (eval $lt_ar_try) 2>&5 ac_status=$? $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 test $ac_status = 0; } if test "$ac_status" -ne 0; then lt_cv_ar_at_file=@ fi fi rm -f conftest.* libconftest.a fi rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext fi { $as_echo "$as_me:${as_lineno-$LINENO}: result: $lt_cv_ar_at_file" >&5 $as_echo "$lt_cv_ar_at_file" >&6; } if test "x$lt_cv_ar_at_file" = xno; then archiver_list_spec= else archiver_list_spec=$lt_cv_ar_at_file fi if test -n "$ac_tool_prefix"; then # Extract the first word of "${ac_tool_prefix}strip", so it can be a program name with args. set dummy ${ac_tool_prefix}strip; ac_word=$2 { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 $as_echo_n "checking for $ac_word... " >&6; } if ${ac_cv_prog_STRIP+:} false; then : $as_echo_n "(cached) " >&6 else if test -n "$STRIP"; then ac_cv_prog_STRIP="$STRIP" # Let the user override the test. else as_save_IFS=$IFS; IFS=$PATH_SEPARATOR for as_dir in $PATH do IFS=$as_save_IFS test -z "$as_dir" && as_dir=. for ac_exec_ext in '' $ac_executable_extensions; do if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then ac_cv_prog_STRIP="${ac_tool_prefix}strip" $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5 break 2 fi done done IFS=$as_save_IFS fi fi STRIP=$ac_cv_prog_STRIP if test -n "$STRIP"; then { $as_echo "$as_me:${as_lineno-$LINENO}: result: $STRIP" >&5 $as_echo "$STRIP" >&6; } else { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 $as_echo "no" >&6; } fi fi if test -z "$ac_cv_prog_STRIP"; then ac_ct_STRIP=$STRIP # Extract the first word of "strip", so it can be a program name with args. set dummy strip; ac_word=$2 { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 $as_echo_n "checking for $ac_word... " >&6; } if ${ac_cv_prog_ac_ct_STRIP+:} false; then : $as_echo_n "(cached) " >&6 else if test -n "$ac_ct_STRIP"; then ac_cv_prog_ac_ct_STRIP="$ac_ct_STRIP" # Let the user override the test. else as_save_IFS=$IFS; IFS=$PATH_SEPARATOR for as_dir in $PATH do IFS=$as_save_IFS test -z "$as_dir" && as_dir=. for ac_exec_ext in '' $ac_executable_extensions; do if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then ac_cv_prog_ac_ct_STRIP="strip" $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5 break 2 fi done done IFS=$as_save_IFS fi fi ac_ct_STRIP=$ac_cv_prog_ac_ct_STRIP if test -n "$ac_ct_STRIP"; then { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_ct_STRIP" >&5 $as_echo "$ac_ct_STRIP" >&6; } else { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 $as_echo "no" >&6; } fi if test "x$ac_ct_STRIP" = x; then STRIP=":" else case $cross_compiling:$ac_tool_warned in yes:) { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: using cross tools not prefixed with host triplet" >&5 $as_echo "$as_me: WARNING: using cross tools not prefixed with host triplet" >&2;} ac_tool_warned=yes ;; esac STRIP=$ac_ct_STRIP fi else STRIP="$ac_cv_prog_STRIP" fi test -z "$STRIP" && STRIP=: if test -n "$ac_tool_prefix"; then # Extract the first word of "${ac_tool_prefix}ranlib", so it can be a program name with args. set dummy ${ac_tool_prefix}ranlib; ac_word=$2 { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 $as_echo_n "checking for $ac_word... " >&6; } if ${ac_cv_prog_RANLIB+:} false; then : $as_echo_n "(cached) " >&6 else if test -n "$RANLIB"; then ac_cv_prog_RANLIB="$RANLIB" # Let the user override the test. else as_save_IFS=$IFS; IFS=$PATH_SEPARATOR for as_dir in $PATH do IFS=$as_save_IFS test -z "$as_dir" && as_dir=. for ac_exec_ext in '' $ac_executable_extensions; do if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then ac_cv_prog_RANLIB="${ac_tool_prefix}ranlib" $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5 break 2 fi done done IFS=$as_save_IFS fi fi RANLIB=$ac_cv_prog_RANLIB if test -n "$RANLIB"; then { $as_echo "$as_me:${as_lineno-$LINENO}: result: $RANLIB" >&5 $as_echo "$RANLIB" >&6; } else { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 $as_echo "no" >&6; } fi fi if test -z "$ac_cv_prog_RANLIB"; then ac_ct_RANLIB=$RANLIB # Extract the first word of "ranlib", so it can be a program name with args. set dummy ranlib; ac_word=$2 { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 $as_echo_n "checking for $ac_word... " >&6; } if ${ac_cv_prog_ac_ct_RANLIB+:} false; then : $as_echo_n "(cached) " >&6 else if test -n "$ac_ct_RANLIB"; then ac_cv_prog_ac_ct_RANLIB="$ac_ct_RANLIB" # Let the user override the test. else as_save_IFS=$IFS; IFS=$PATH_SEPARATOR for as_dir in $PATH do IFS=$as_save_IFS test -z "$as_dir" && as_dir=. for ac_exec_ext in '' $ac_executable_extensions; do if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then ac_cv_prog_ac_ct_RANLIB="ranlib" $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5 break 2 fi done done IFS=$as_save_IFS fi fi ac_ct_RANLIB=$ac_cv_prog_ac_ct_RANLIB if test -n "$ac_ct_RANLIB"; then { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_ct_RANLIB" >&5 $as_echo "$ac_ct_RANLIB" >&6; } else { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 $as_echo "no" >&6; } fi if test "x$ac_ct_RANLIB" = x; then RANLIB=":" else case $cross_compiling:$ac_tool_warned in yes:) { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: using cross tools not prefixed with host triplet" >&5 $as_echo "$as_me: WARNING: using cross tools not prefixed with host triplet" >&2;} ac_tool_warned=yes ;; esac RANLIB=$ac_ct_RANLIB fi else RANLIB="$ac_cv_prog_RANLIB" fi test -z "$RANLIB" && RANLIB=: # Determine commands to create old-style static archives. old_archive_cmds='$AR $AR_FLAGS $oldlib$oldobjs' old_postinstall_cmds='chmod 644 $oldlib' old_postuninstall_cmds= if test -n "$RANLIB"; then case $host_os in openbsd*) old_postinstall_cmds="$old_postinstall_cmds~\$RANLIB -t \$tool_oldlib" ;; *) old_postinstall_cmds="$old_postinstall_cmds~\$RANLIB \$tool_oldlib" ;; esac old_archive_cmds="$old_archive_cmds~\$RANLIB \$tool_oldlib" fi case $host_os in darwin*) lock_old_archive_extraction=yes ;; *) lock_old_archive_extraction=no ;; esac # If no C compiler was specified, use CC. LTCC=${LTCC-"$CC"} # If no C compiler flags were specified, use CFLAGS. LTCFLAGS=${LTCFLAGS-"$CFLAGS"} # Allow CC to be a program name with arguments. compiler=$CC # Check for command to grab the raw symbol name followed by C symbol from nm. { $as_echo "$as_me:${as_lineno-$LINENO}: checking command to parse $NM output from $compiler object" >&5 $as_echo_n "checking command to parse $NM output from $compiler object... " >&6; } if ${lt_cv_sys_global_symbol_pipe+:} false; then : $as_echo_n "(cached) " >&6 else # These are sane defaults that work on at least a few old systems. # [They come from Ultrix. What could be older than Ultrix?!! ;)] # Character class describing NM global symbol codes. symcode='[BCDEGRST]' # Regexp to match symbols that can be accessed directly from C. sympat='\([_A-Za-z][_A-Za-z0-9]*\)' # Define system-specific variables. case $host_os in aix*) symcode='[BCDT]' ;; cygwin* | mingw* | pw32* | cegcc*) symcode='[ABCDGISTW]' ;; hpux*) if test "$host_cpu" = ia64; then symcode='[ABCDEGRST]' fi ;; irix* | nonstopux*) symcode='[BCDEGRST]' ;; osf*) symcode='[BCDEGQRST]' ;; solaris*) symcode='[BDRT]' ;; sco3.2v5*) symcode='[DT]' ;; sysv4.2uw2*) symcode='[DT]' ;; sysv5* | sco5v6* | unixware* | OpenUNIX*) symcode='[ABDT]' ;; sysv4) symcode='[DFNSTU]' ;; esac # If we're using GNU nm, then use its standard symbol codes. case `$NM -V 2>&1` in *GNU* | *'with BFD'*) symcode='[ABCDGIRSTW]' ;; esac # Transform an extracted symbol line into a proper C declaration. # Some systems (esp. on ia64) link data and code symbols differently, # so use this general approach. lt_cv_sys_global_symbol_to_cdecl="sed -n -e 's/^T .* \(.*\)$/extern int \1();/p' -e 's/^$symcode* .* \(.*\)$/extern char \1;/p'" # Transform an extracted symbol line into symbol name and symbol address lt_cv_sys_global_symbol_to_c_name_address="sed -n -e 's/^: \([^ ]*\)[ ]*$/ {\\\"\1\\\", (void *) 0},/p' -e 's/^$symcode* \([^ ]*\) \([^ ]*\)$/ {\"\2\", (void *) \&\2},/p'" lt_cv_sys_global_symbol_to_c_name_address_lib_prefix="sed -n -e 's/^: \([^ ]*\)[ ]*$/ {\\\"\1\\\", (void *) 0},/p' -e 's/^$symcode* \([^ ]*\) \(lib[^ ]*\)$/ {\"\2\", (void *) \&\2},/p' -e 's/^$symcode* \([^ ]*\) \([^ ]*\)$/ {\"lib\2\", (void *) \&\2},/p'" # Handle CRLF in mingw tool chain opt_cr= case $build_os in mingw*) opt_cr=`$ECHO 'x\{0,1\}' | tr x '\015'` # option cr in regexp ;; esac # Try without a prefix underscore, then with it. for ac_symprfx in "" "_"; do # Transform symcode, sympat, and symprfx into a raw symbol and a C symbol. symxfrm="\\1 $ac_symprfx\\2 \\2" # Write the raw and C identifiers. if test "$lt_cv_nm_interface" = "MS dumpbin"; then # Fake it for dumpbin and say T for any non-static function # and D for any global variable. # Also find C++ and __fastcall symbols from MSVC++, # which start with @ or ?. lt_cv_sys_global_symbol_pipe="$AWK '"\ " {last_section=section; section=\$ 3};"\ " /^COFF SYMBOL TABLE/{for(i in hide) delete hide[i]};"\ " /Section length .*#relocs.*(pick any)/{hide[last_section]=1};"\ " \$ 0!~/External *\|/{next};"\ " / 0+ UNDEF /{next}; / UNDEF \([^|]\)*()/{next};"\ " {if(hide[section]) next};"\ " {f=0}; \$ 0~/\(\).*\|/{f=1}; {printf f ? \"T \" : \"D \"};"\ " {split(\$ 0, a, /\||\r/); split(a[2], s)};"\ " s[1]~/^[@?]/{print s[1], s[1]; next};"\ " s[1]~prfx {split(s[1],t,\"@\"); print t[1], substr(t[1],length(prfx))}"\ " ' prfx=^$ac_symprfx" else lt_cv_sys_global_symbol_pipe="sed -n -e 's/^.*[ ]\($symcode$symcode*\)[ ][ ]*$ac_symprfx$sympat$opt_cr$/$symxfrm/p'" fi lt_cv_sys_global_symbol_pipe="$lt_cv_sys_global_symbol_pipe | sed '/ __gnu_lto/d'" # Check to see that the pipe works correctly. pipe_works=no rm -f conftest* cat > conftest.$ac_ext <<_LT_EOF #ifdef __cplusplus extern "C" { #endif char nm_test_var; void nm_test_func(void); void nm_test_func(void){} #ifdef __cplusplus } #endif int main(){nm_test_var='a';nm_test_func();return(0);} _LT_EOF if { { eval echo "\"\$as_me\":${as_lineno-$LINENO}: \"$ac_compile\""; } >&5 (eval $ac_compile) 2>&5 ac_status=$? $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 test $ac_status = 0; }; then # Now try to grab the symbols. nlist=conftest.nm if { { eval echo "\"\$as_me\":${as_lineno-$LINENO}: \"$NM conftest.$ac_objext \| "$lt_cv_sys_global_symbol_pipe" \> $nlist\""; } >&5 (eval $NM conftest.$ac_objext \| "$lt_cv_sys_global_symbol_pipe" \> $nlist) 2>&5 ac_status=$? $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 test $ac_status = 0; } && test -s "$nlist"; then # Try sorting and uniquifying the output. if sort "$nlist" | uniq > "$nlist"T; then mv -f "$nlist"T "$nlist" else rm -f "$nlist"T fi # Make sure that we snagged all the symbols we need. if $GREP ' nm_test_var$' "$nlist" >/dev/null; then if $GREP ' nm_test_func$' "$nlist" >/dev/null; then cat <<_LT_EOF > conftest.$ac_ext /* Keep this code in sync between libtool.m4, ltmain, lt_system.h, and tests. */ #if defined(_WIN32) || defined(__CYGWIN__) || defined(_WIN32_WCE) /* DATA imports from DLLs on WIN32 con't be const, because runtime relocations are performed -- see ld's documentation on pseudo-relocs. */ # define LT_DLSYM_CONST #elif defined(__osf__) /* This system does not cope well with relocations in const data. */ # define LT_DLSYM_CONST #else # define LT_DLSYM_CONST const #endif #ifdef __cplusplus extern "C" { #endif _LT_EOF # Now generate the symbol file. eval "$lt_cv_sys_global_symbol_to_cdecl"' < "$nlist" | $GREP -v main >> conftest.$ac_ext' cat <<_LT_EOF >> conftest.$ac_ext /* The mapping between symbol names and symbols. */ LT_DLSYM_CONST struct { const char *name; void *address; } lt__PROGRAM__LTX_preloaded_symbols[] = { { "@PROGRAM@", (void *) 0 }, _LT_EOF $SED "s/^$symcode$symcode* \(.*\) \(.*\)$/ {\"\2\", (void *) \&\2},/" < "$nlist" | $GREP -v main >> conftest.$ac_ext cat <<\_LT_EOF >> conftest.$ac_ext {0, (void *) 0} }; /* This works around a problem in FreeBSD linker */ #ifdef FREEBSD_WORKAROUND static const void *lt_preloaded_setup() { return lt__PROGRAM__LTX_preloaded_symbols; } #endif #ifdef __cplusplus } #endif _LT_EOF # Now try linking the two files. mv conftest.$ac_objext conftstm.$ac_objext lt_globsym_save_LIBS=$LIBS lt_globsym_save_CFLAGS=$CFLAGS LIBS="conftstm.$ac_objext" CFLAGS="$CFLAGS$lt_prog_compiler_no_builtin_flag" if { { eval echo "\"\$as_me\":${as_lineno-$LINENO}: \"$ac_link\""; } >&5 (eval $ac_link) 2>&5 ac_status=$? $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 test $ac_status = 0; } && test -s conftest${ac_exeext}; then pipe_works=yes fi LIBS=$lt_globsym_save_LIBS CFLAGS=$lt_globsym_save_CFLAGS else echo "cannot find nm_test_func in $nlist" >&5 fi else echo "cannot find nm_test_var in $nlist" >&5 fi else echo "cannot run $lt_cv_sys_global_symbol_pipe" >&5 fi else echo "$progname: failed program was:" >&5 cat conftest.$ac_ext >&5 fi rm -rf conftest* conftst* # Do not use the global_symbol_pipe unless it works. if test "$pipe_works" = yes; then break else lt_cv_sys_global_symbol_pipe= fi done fi if test -z "$lt_cv_sys_global_symbol_pipe"; then lt_cv_sys_global_symbol_to_cdecl= fi if test -z "$lt_cv_sys_global_symbol_pipe$lt_cv_sys_global_symbol_to_cdecl"; then { $as_echo "$as_me:${as_lineno-$LINENO}: result: failed" >&5 $as_echo "failed" >&6; } else { $as_echo "$as_me:${as_lineno-$LINENO}: result: ok" >&5 $as_echo "ok" >&6; } fi # Response file support. if test "$lt_cv_nm_interface" = "MS dumpbin"; then nm_file_list_spec='@' elif $NM --help 2>/dev/null | grep '[@]FILE' >/dev/null; then nm_file_list_spec='@' fi { $as_echo "$as_me:${as_lineno-$LINENO}: checking for sysroot" >&5 $as_echo_n "checking for sysroot... " >&6; } # Check whether --with-sysroot was given. if test "${with_sysroot+set}" = set; then : withval=$with_sysroot; else with_sysroot=no fi lt_sysroot= case ${with_sysroot} in #( yes) if test "$GCC" = yes; then lt_sysroot=`$CC --print-sysroot 2>/dev/null` fi ;; #( /*) lt_sysroot=`echo "$with_sysroot" | sed -e "$sed_quote_subst"` ;; #( no|'') ;; #( *) { $as_echo "$as_me:${as_lineno-$LINENO}: result: ${with_sysroot}" >&5 $as_echo "${with_sysroot}" >&6; } as_fn_error $? "The sysroot must be an absolute path." "$LINENO" 5 ;; esac { $as_echo "$as_me:${as_lineno-$LINENO}: result: ${lt_sysroot:-no}" >&5 $as_echo "${lt_sysroot:-no}" >&6; } # Check whether --enable-libtool-lock was given. if test "${enable_libtool_lock+set}" = set; then : enableval=$enable_libtool_lock; fi test "x$enable_libtool_lock" != xno && enable_libtool_lock=yes # Some flags need to be propagated to the compiler or linker for good # libtool support. case $host in ia64-*-hpux*) # Find out which ABI we are using. echo 'int i;' > conftest.$ac_ext if { { eval echo "\"\$as_me\":${as_lineno-$LINENO}: \"$ac_compile\""; } >&5 (eval $ac_compile) 2>&5 ac_status=$? $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 test $ac_status = 0; }; then case `/usr/bin/file conftest.$ac_objext` in *ELF-32*) HPUX_IA64_MODE="32" ;; *ELF-64*) HPUX_IA64_MODE="64" ;; esac fi rm -rf conftest* ;; *-*-irix6*) # Find out which ABI we are using. echo '#line '$LINENO' "configure"' > conftest.$ac_ext if { { eval echo "\"\$as_me\":${as_lineno-$LINENO}: \"$ac_compile\""; } >&5 (eval $ac_compile) 2>&5 ac_status=$? $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 test $ac_status = 0; }; then if test "$lt_cv_prog_gnu_ld" = yes; then case `/usr/bin/file conftest.$ac_objext` in *32-bit*) LD="${LD-ld} -melf32bsmip" ;; *N32*) LD="${LD-ld} -melf32bmipn32" ;; *64-bit*) LD="${LD-ld} -melf64bmip" ;; esac else case `/usr/bin/file conftest.$ac_objext` in *32-bit*) LD="${LD-ld} -32" ;; *N32*) LD="${LD-ld} -n32" ;; *64-bit*) LD="${LD-ld} -64" ;; esac fi fi rm -rf conftest* ;; x86_64-*kfreebsd*-gnu|x86_64-*linux*|ppc*-*linux*|powerpc*-*linux*| \ s390*-*linux*|s390*-*tpf*|sparc*-*linux*) # Find out which ABI we are using. echo 'int i;' > conftest.$ac_ext if { { eval echo "\"\$as_me\":${as_lineno-$LINENO}: \"$ac_compile\""; } >&5 (eval $ac_compile) 2>&5 ac_status=$? $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 test $ac_status = 0; }; then case `/usr/bin/file conftest.o` in *32-bit*) case $host in x86_64-*kfreebsd*-gnu) LD="${LD-ld} -m elf_i386_fbsd" ;; x86_64-*linux*) LD="${LD-ld} -m elf_i386" ;; ppc64-*linux*|powerpc64-*linux*) LD="${LD-ld} -m elf32ppclinux" ;; s390x-*linux*) LD="${LD-ld} -m elf_s390" ;; sparc64-*linux*) LD="${LD-ld} -m elf32_sparc" ;; esac ;; *64-bit*) case $host in x86_64-*kfreebsd*-gnu) LD="${LD-ld} -m elf_x86_64_fbsd" ;; x86_64-*linux*) LD="${LD-ld} -m elf_x86_64" ;; ppc*-*linux*|powerpc*-*linux*) LD="${LD-ld} -m elf64ppc" ;; s390*-*linux*|s390*-*tpf*) LD="${LD-ld} -m elf64_s390" ;; sparc*-*linux*) LD="${LD-ld} -m elf64_sparc" ;; esac ;; esac fi rm -rf conftest* ;; *-*-sco3.2v5*) # On SCO OpenServer 5, we need -belf to get full-featured binaries. SAVE_CFLAGS="$CFLAGS" CFLAGS="$CFLAGS -belf" { $as_echo "$as_me:${as_lineno-$LINENO}: checking whether the C compiler needs -belf" >&5 $as_echo_n "checking whether the C compiler needs -belf... " >&6; } if ${lt_cv_cc_needs_belf+:} false; then : $as_echo_n "(cached) " >&6 else ac_ext=c ac_cpp='$CPP $CPPFLAGS' ac_compile='$CC -c $CFLAGS $CPPFLAGS conftest.$ac_ext >&5' ac_link='$CC -o conftest$ac_exeext $CFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5' ac_compiler_gnu=$ac_cv_c_compiler_gnu cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ int main () { ; return 0; } _ACEOF if ac_fn_c_try_link "$LINENO"; then : lt_cv_cc_needs_belf=yes else lt_cv_cc_needs_belf=no fi rm -f core conftest.err conftest.$ac_objext \ conftest$ac_exeext conftest.$ac_ext ac_ext=c ac_cpp='$CPP $CPPFLAGS' ac_compile='$CC -c $CFLAGS $CPPFLAGS conftest.$ac_ext >&5' ac_link='$CC -o conftest$ac_exeext $CFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5' ac_compiler_gnu=$ac_cv_c_compiler_gnu fi { $as_echo "$as_me:${as_lineno-$LINENO}: result: $lt_cv_cc_needs_belf" >&5 $as_echo "$lt_cv_cc_needs_belf" >&6; } if test x"$lt_cv_cc_needs_belf" != x"yes"; then # this is probably gcc 2.8.0, egcs 1.0 or newer; no need for -belf CFLAGS="$SAVE_CFLAGS" fi ;; *-*solaris*) # Find out which ABI we are using. echo 'int i;' > conftest.$ac_ext if { { eval echo "\"\$as_me\":${as_lineno-$LINENO}: \"$ac_compile\""; } >&5 (eval $ac_compile) 2>&5 ac_status=$? $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 test $ac_status = 0; }; then case `/usr/bin/file conftest.o` in *64-bit*) case $lt_cv_prog_gnu_ld in yes*) case $host in i?86-*-solaris*) LD="${LD-ld} -m elf_x86_64" ;; sparc*-*-solaris*) LD="${LD-ld} -m elf64_sparc" ;; esac # GNU ld 2.21 introduced _sol2 emulations. Use them if available. if ${LD-ld} -V | grep _sol2 >/dev/null 2>&1; then LD="${LD-ld}_sol2" fi ;; *) if ${LD-ld} -64 -r -o conftest2.o conftest.o >/dev/null 2>&1; then LD="${LD-ld} -64" fi ;; esac ;; esac fi rm -rf conftest* ;; esac need_locks="$enable_libtool_lock" if test -n "$ac_tool_prefix"; then # Extract the first word of "${ac_tool_prefix}mt", so it can be a program name with args. set dummy ${ac_tool_prefix}mt; ac_word=$2 { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 $as_echo_n "checking for $ac_word... " >&6; } if ${ac_cv_prog_MANIFEST_TOOL+:} false; then : $as_echo_n "(cached) " >&6 else if test -n "$MANIFEST_TOOL"; then ac_cv_prog_MANIFEST_TOOL="$MANIFEST_TOOL" # Let the user override the test. else as_save_IFS=$IFS; IFS=$PATH_SEPARATOR for as_dir in $PATH do IFS=$as_save_IFS test -z "$as_dir" && as_dir=. for ac_exec_ext in '' $ac_executable_extensions; do if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then ac_cv_prog_MANIFEST_TOOL="${ac_tool_prefix}mt" $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5 break 2 fi done done IFS=$as_save_IFS fi fi MANIFEST_TOOL=$ac_cv_prog_MANIFEST_TOOL if test -n "$MANIFEST_TOOL"; then { $as_echo "$as_me:${as_lineno-$LINENO}: result: $MANIFEST_TOOL" >&5 $as_echo "$MANIFEST_TOOL" >&6; } else { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 $as_echo "no" >&6; } fi fi if test -z "$ac_cv_prog_MANIFEST_TOOL"; then ac_ct_MANIFEST_TOOL=$MANIFEST_TOOL # Extract the first word of "mt", so it can be a program name with args. set dummy mt; ac_word=$2 { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 $as_echo_n "checking for $ac_word... " >&6; } if ${ac_cv_prog_ac_ct_MANIFEST_TOOL+:} false; then : $as_echo_n "(cached) " >&6 else if test -n "$ac_ct_MANIFEST_TOOL"; then ac_cv_prog_ac_ct_MANIFEST_TOOL="$ac_ct_MANIFEST_TOOL" # Let the user override the test. else as_save_IFS=$IFS; IFS=$PATH_SEPARATOR for as_dir in $PATH do IFS=$as_save_IFS test -z "$as_dir" && as_dir=. for ac_exec_ext in '' $ac_executable_extensions; do if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then ac_cv_prog_ac_ct_MANIFEST_TOOL="mt" $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5 break 2 fi done done IFS=$as_save_IFS fi fi ac_ct_MANIFEST_TOOL=$ac_cv_prog_ac_ct_MANIFEST_TOOL if test -n "$ac_ct_MANIFEST_TOOL"; then { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_ct_MANIFEST_TOOL" >&5 $as_echo "$ac_ct_MANIFEST_TOOL" >&6; } else { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 $as_echo "no" >&6; } fi if test "x$ac_ct_MANIFEST_TOOL" = x; then MANIFEST_TOOL=":" else case $cross_compiling:$ac_tool_warned in yes:) { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: using cross tools not prefixed with host triplet" >&5 $as_echo "$as_me: WARNING: using cross tools not prefixed with host triplet" >&2;} ac_tool_warned=yes ;; esac MANIFEST_TOOL=$ac_ct_MANIFEST_TOOL fi else MANIFEST_TOOL="$ac_cv_prog_MANIFEST_TOOL" fi test -z "$MANIFEST_TOOL" && MANIFEST_TOOL=mt { $as_echo "$as_me:${as_lineno-$LINENO}: checking if $MANIFEST_TOOL is a manifest tool" >&5 $as_echo_n "checking if $MANIFEST_TOOL is a manifest tool... " >&6; } if ${lt_cv_path_mainfest_tool+:} false; then : $as_echo_n "(cached) " >&6 else lt_cv_path_mainfest_tool=no echo "$as_me:$LINENO: $MANIFEST_TOOL '-?'" >&5 $MANIFEST_TOOL '-?' 2>conftest.err > conftest.out cat conftest.err >&5 if $GREP 'Manifest Tool' conftest.out > /dev/null; then lt_cv_path_mainfest_tool=yes fi rm -f conftest* fi { $as_echo "$as_me:${as_lineno-$LINENO}: result: $lt_cv_path_mainfest_tool" >&5 $as_echo "$lt_cv_path_mainfest_tool" >&6; } if test "x$lt_cv_path_mainfest_tool" != xyes; then MANIFEST_TOOL=: fi case $host_os in rhapsody* | darwin*) if test -n "$ac_tool_prefix"; then # Extract the first word of "${ac_tool_prefix}dsymutil", so it can be a program name with args. set dummy ${ac_tool_prefix}dsymutil; ac_word=$2 { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 $as_echo_n "checking for $ac_word... " >&6; } if ${ac_cv_prog_DSYMUTIL+:} false; then : $as_echo_n "(cached) " >&6 else if test -n "$DSYMUTIL"; then ac_cv_prog_DSYMUTIL="$DSYMUTIL" # Let the user override the test. else as_save_IFS=$IFS; IFS=$PATH_SEPARATOR for as_dir in $PATH do IFS=$as_save_IFS test -z "$as_dir" && as_dir=. for ac_exec_ext in '' $ac_executable_extensions; do if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then ac_cv_prog_DSYMUTIL="${ac_tool_prefix}dsymutil" $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5 break 2 fi done done IFS=$as_save_IFS fi fi DSYMUTIL=$ac_cv_prog_DSYMUTIL if test -n "$DSYMUTIL"; then { $as_echo "$as_me:${as_lineno-$LINENO}: result: $DSYMUTIL" >&5 $as_echo "$DSYMUTIL" >&6; } else { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 $as_echo "no" >&6; } fi fi if test -z "$ac_cv_prog_DSYMUTIL"; then ac_ct_DSYMUTIL=$DSYMUTIL # Extract the first word of "dsymutil", so it can be a program name with args. set dummy dsymutil; ac_word=$2 { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 $as_echo_n "checking for $ac_word... " >&6; } if ${ac_cv_prog_ac_ct_DSYMUTIL+:} false; then : $as_echo_n "(cached) " >&6 else if test -n "$ac_ct_DSYMUTIL"; then ac_cv_prog_ac_ct_DSYMUTIL="$ac_ct_DSYMUTIL" # Let the user override the test. else as_save_IFS=$IFS; IFS=$PATH_SEPARATOR for as_dir in $PATH do IFS=$as_save_IFS test -z "$as_dir" && as_dir=. for ac_exec_ext in '' $ac_executable_extensions; do if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then ac_cv_prog_ac_ct_DSYMUTIL="dsymutil" $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5 break 2 fi done done IFS=$as_save_IFS fi fi ac_ct_DSYMUTIL=$ac_cv_prog_ac_ct_DSYMUTIL if test -n "$ac_ct_DSYMUTIL"; then { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_ct_DSYMUTIL" >&5 $as_echo "$ac_ct_DSYMUTIL" >&6; } else { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 $as_echo "no" >&6; } fi if test "x$ac_ct_DSYMUTIL" = x; then DSYMUTIL=":" else case $cross_compiling:$ac_tool_warned in yes:) { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: using cross tools not prefixed with host triplet" >&5 $as_echo "$as_me: WARNING: using cross tools not prefixed with host triplet" >&2;} ac_tool_warned=yes ;; esac DSYMUTIL=$ac_ct_DSYMUTIL fi else DSYMUTIL="$ac_cv_prog_DSYMUTIL" fi if test -n "$ac_tool_prefix"; then # Extract the first word of "${ac_tool_prefix}nmedit", so it can be a program name with args. set dummy ${ac_tool_prefix}nmedit; ac_word=$2 { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 $as_echo_n "checking for $ac_word... " >&6; } if ${ac_cv_prog_NMEDIT+:} false; then : $as_echo_n "(cached) " >&6 else if test -n "$NMEDIT"; then ac_cv_prog_NMEDIT="$NMEDIT" # Let the user override the test. else as_save_IFS=$IFS; IFS=$PATH_SEPARATOR for as_dir in $PATH do IFS=$as_save_IFS test -z "$as_dir" && as_dir=. for ac_exec_ext in '' $ac_executable_extensions; do if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then ac_cv_prog_NMEDIT="${ac_tool_prefix}nmedit" $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5 break 2 fi done done IFS=$as_save_IFS fi fi NMEDIT=$ac_cv_prog_NMEDIT if test -n "$NMEDIT"; then { $as_echo "$as_me:${as_lineno-$LINENO}: result: $NMEDIT" >&5 $as_echo "$NMEDIT" >&6; } else { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 $as_echo "no" >&6; } fi fi if test -z "$ac_cv_prog_NMEDIT"; then ac_ct_NMEDIT=$NMEDIT # Extract the first word of "nmedit", so it can be a program name with args. set dummy nmedit; ac_word=$2 { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 $as_echo_n "checking for $ac_word... " >&6; } if ${ac_cv_prog_ac_ct_NMEDIT+:} false; then : $as_echo_n "(cached) " >&6 else if test -n "$ac_ct_NMEDIT"; then ac_cv_prog_ac_ct_NMEDIT="$ac_ct_NMEDIT" # Let the user override the test. else as_save_IFS=$IFS; IFS=$PATH_SEPARATOR for as_dir in $PATH do IFS=$as_save_IFS test -z "$as_dir" && as_dir=. for ac_exec_ext in '' $ac_executable_extensions; do if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then ac_cv_prog_ac_ct_NMEDIT="nmedit" $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5 break 2 fi done done IFS=$as_save_IFS fi fi ac_ct_NMEDIT=$ac_cv_prog_ac_ct_NMEDIT if test -n "$ac_ct_NMEDIT"; then { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_ct_NMEDIT" >&5 $as_echo "$ac_ct_NMEDIT" >&6; } else { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 $as_echo "no" >&6; } fi if test "x$ac_ct_NMEDIT" = x; then NMEDIT=":" else case $cross_compiling:$ac_tool_warned in yes:) { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: using cross tools not prefixed with host triplet" >&5 $as_echo "$as_me: WARNING: using cross tools not prefixed with host triplet" >&2;} ac_tool_warned=yes ;; esac NMEDIT=$ac_ct_NMEDIT fi else NMEDIT="$ac_cv_prog_NMEDIT" fi if test -n "$ac_tool_prefix"; then # Extract the first word of "${ac_tool_prefix}lipo", so it can be a program name with args. set dummy ${ac_tool_prefix}lipo; ac_word=$2 { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 $as_echo_n "checking for $ac_word... " >&6; } if ${ac_cv_prog_LIPO+:} false; then : $as_echo_n "(cached) " >&6 else if test -n "$LIPO"; then ac_cv_prog_LIPO="$LIPO" # Let the user override the test. else as_save_IFS=$IFS; IFS=$PATH_SEPARATOR for as_dir in $PATH do IFS=$as_save_IFS test -z "$as_dir" && as_dir=. for ac_exec_ext in '' $ac_executable_extensions; do if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then ac_cv_prog_LIPO="${ac_tool_prefix}lipo" $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5 break 2 fi done done IFS=$as_save_IFS fi fi LIPO=$ac_cv_prog_LIPO if test -n "$LIPO"; then { $as_echo "$as_me:${as_lineno-$LINENO}: result: $LIPO" >&5 $as_echo "$LIPO" >&6; } else { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 $as_echo "no" >&6; } fi fi if test -z "$ac_cv_prog_LIPO"; then ac_ct_LIPO=$LIPO # Extract the first word of "lipo", so it can be a program name with args. set dummy lipo; ac_word=$2 { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 $as_echo_n "checking for $ac_word... " >&6; } if ${ac_cv_prog_ac_ct_LIPO+:} false; then : $as_echo_n "(cached) " >&6 else if test -n "$ac_ct_LIPO"; then ac_cv_prog_ac_ct_LIPO="$ac_ct_LIPO" # Let the user override the test. else as_save_IFS=$IFS; IFS=$PATH_SEPARATOR for as_dir in $PATH do IFS=$as_save_IFS test -z "$as_dir" && as_dir=. for ac_exec_ext in '' $ac_executable_extensions; do if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then ac_cv_prog_ac_ct_LIPO="lipo" $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5 break 2 fi done done IFS=$as_save_IFS fi fi ac_ct_LIPO=$ac_cv_prog_ac_ct_LIPO if test -n "$ac_ct_LIPO"; then { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_ct_LIPO" >&5 $as_echo "$ac_ct_LIPO" >&6; } else { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 $as_echo "no" >&6; } fi if test "x$ac_ct_LIPO" = x; then LIPO=":" else case $cross_compiling:$ac_tool_warned in yes:) { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: using cross tools not prefixed with host triplet" >&5 $as_echo "$as_me: WARNING: using cross tools not prefixed with host triplet" >&2;} ac_tool_warned=yes ;; esac LIPO=$ac_ct_LIPO fi else LIPO="$ac_cv_prog_LIPO" fi if test -n "$ac_tool_prefix"; then # Extract the first word of "${ac_tool_prefix}otool", so it can be a program name with args. set dummy ${ac_tool_prefix}otool; ac_word=$2 { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 $as_echo_n "checking for $ac_word... " >&6; } if ${ac_cv_prog_OTOOL+:} false; then : $as_echo_n "(cached) " >&6 else if test -n "$OTOOL"; then ac_cv_prog_OTOOL="$OTOOL" # Let the user override the test. else as_save_IFS=$IFS; IFS=$PATH_SEPARATOR for as_dir in $PATH do IFS=$as_save_IFS test -z "$as_dir" && as_dir=. for ac_exec_ext in '' $ac_executable_extensions; do if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then ac_cv_prog_OTOOL="${ac_tool_prefix}otool" $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5 break 2 fi done done IFS=$as_save_IFS fi fi OTOOL=$ac_cv_prog_OTOOL if test -n "$OTOOL"; then { $as_echo "$as_me:${as_lineno-$LINENO}: result: $OTOOL" >&5 $as_echo "$OTOOL" >&6; } else { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 $as_echo "no" >&6; } fi fi if test -z "$ac_cv_prog_OTOOL"; then ac_ct_OTOOL=$OTOOL # Extract the first word of "otool", so it can be a program name with args. set dummy otool; ac_word=$2 { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 $as_echo_n "checking for $ac_word... " >&6; } if ${ac_cv_prog_ac_ct_OTOOL+:} false; then : $as_echo_n "(cached) " >&6 else if test -n "$ac_ct_OTOOL"; then ac_cv_prog_ac_ct_OTOOL="$ac_ct_OTOOL" # Let the user override the test. else as_save_IFS=$IFS; IFS=$PATH_SEPARATOR for as_dir in $PATH do IFS=$as_save_IFS test -z "$as_dir" && as_dir=. for ac_exec_ext in '' $ac_executable_extensions; do if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then ac_cv_prog_ac_ct_OTOOL="otool" $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5 break 2 fi done done IFS=$as_save_IFS fi fi ac_ct_OTOOL=$ac_cv_prog_ac_ct_OTOOL if test -n "$ac_ct_OTOOL"; then { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_ct_OTOOL" >&5 $as_echo "$ac_ct_OTOOL" >&6; } else { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 $as_echo "no" >&6; } fi if test "x$ac_ct_OTOOL" = x; then OTOOL=":" else case $cross_compiling:$ac_tool_warned in yes:) { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: using cross tools not prefixed with host triplet" >&5 $as_echo "$as_me: WARNING: using cross tools not prefixed with host triplet" >&2;} ac_tool_warned=yes ;; esac OTOOL=$ac_ct_OTOOL fi else OTOOL="$ac_cv_prog_OTOOL" fi if test -n "$ac_tool_prefix"; then # Extract the first word of "${ac_tool_prefix}otool64", so it can be a program name with args. set dummy ${ac_tool_prefix}otool64; ac_word=$2 { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 $as_echo_n "checking for $ac_word... " >&6; } if ${ac_cv_prog_OTOOL64+:} false; then : $as_echo_n "(cached) " >&6 else if test -n "$OTOOL64"; then ac_cv_prog_OTOOL64="$OTOOL64" # Let the user override the test. else as_save_IFS=$IFS; IFS=$PATH_SEPARATOR for as_dir in $PATH do IFS=$as_save_IFS test -z "$as_dir" && as_dir=. for ac_exec_ext in '' $ac_executable_extensions; do if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then ac_cv_prog_OTOOL64="${ac_tool_prefix}otool64" $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5 break 2 fi done done IFS=$as_save_IFS fi fi OTOOL64=$ac_cv_prog_OTOOL64 if test -n "$OTOOL64"; then { $as_echo "$as_me:${as_lineno-$LINENO}: result: $OTOOL64" >&5 $as_echo "$OTOOL64" >&6; } else { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 $as_echo "no" >&6; } fi fi if test -z "$ac_cv_prog_OTOOL64"; then ac_ct_OTOOL64=$OTOOL64 # Extract the first word of "otool64", so it can be a program name with args. set dummy otool64; ac_word=$2 { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 $as_echo_n "checking for $ac_word... " >&6; } if ${ac_cv_prog_ac_ct_OTOOL64+:} false; then : $as_echo_n "(cached) " >&6 else if test -n "$ac_ct_OTOOL64"; then ac_cv_prog_ac_ct_OTOOL64="$ac_ct_OTOOL64" # Let the user override the test. else as_save_IFS=$IFS; IFS=$PATH_SEPARATOR for as_dir in $PATH do IFS=$as_save_IFS test -z "$as_dir" && as_dir=. for ac_exec_ext in '' $ac_executable_extensions; do if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then ac_cv_prog_ac_ct_OTOOL64="otool64" $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5 break 2 fi done done IFS=$as_save_IFS fi fi ac_ct_OTOOL64=$ac_cv_prog_ac_ct_OTOOL64 if test -n "$ac_ct_OTOOL64"; then { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_ct_OTOOL64" >&5 $as_echo "$ac_ct_OTOOL64" >&6; } else { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 $as_echo "no" >&6; } fi if test "x$ac_ct_OTOOL64" = x; then OTOOL64=":" else case $cross_compiling:$ac_tool_warned in yes:) { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: using cross tools not prefixed with host triplet" >&5 $as_echo "$as_me: WARNING: using cross tools not prefixed with host triplet" >&2;} ac_tool_warned=yes ;; esac OTOOL64=$ac_ct_OTOOL64 fi else OTOOL64="$ac_cv_prog_OTOOL64" fi { $as_echo "$as_me:${as_lineno-$LINENO}: checking for -single_module linker flag" >&5 $as_echo_n "checking for -single_module linker flag... " >&6; } if ${lt_cv_apple_cc_single_mod+:} false; then : $as_echo_n "(cached) " >&6 else lt_cv_apple_cc_single_mod=no if test -z "${LT_MULTI_MODULE}"; then # By default we will add the -single_module flag. You can override # by either setting the environment variable LT_MULTI_MODULE # non-empty at configure time, or by adding -multi_module to the # link flags. rm -rf libconftest.dylib* echo "int foo(void){return 1;}" > conftest.c echo "$LTCC $LTCFLAGS $LDFLAGS -o libconftest.dylib \ -dynamiclib -Wl,-single_module conftest.c" >&5 $LTCC $LTCFLAGS $LDFLAGS -o libconftest.dylib \ -dynamiclib -Wl,-single_module conftest.c 2>conftest.err _lt_result=$? # If there is a non-empty error log, and "single_module" # appears in it, assume the flag caused a linker warning if test -s conftest.err && $GREP single_module conftest.err; then cat conftest.err >&5 # Otherwise, if the output was created with a 0 exit code from # the compiler, it worked. elif test -f libconftest.dylib && test $_lt_result -eq 0; then lt_cv_apple_cc_single_mod=yes else cat conftest.err >&5 fi rm -rf libconftest.dylib* rm -f conftest.* fi fi { $as_echo "$as_me:${as_lineno-$LINENO}: result: $lt_cv_apple_cc_single_mod" >&5 $as_echo "$lt_cv_apple_cc_single_mod" >&6; } { $as_echo "$as_me:${as_lineno-$LINENO}: checking for -exported_symbols_list linker flag" >&5 $as_echo_n "checking for -exported_symbols_list linker flag... " >&6; } if ${lt_cv_ld_exported_symbols_list+:} false; then : $as_echo_n "(cached) " >&6 else lt_cv_ld_exported_symbols_list=no save_LDFLAGS=$LDFLAGS echo "_main" > conftest.sym LDFLAGS="$LDFLAGS -Wl,-exported_symbols_list,conftest.sym" cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ int main () { ; return 0; } _ACEOF if ac_fn_c_try_link "$LINENO"; then : lt_cv_ld_exported_symbols_list=yes else lt_cv_ld_exported_symbols_list=no fi rm -f core conftest.err conftest.$ac_objext \ conftest$ac_exeext conftest.$ac_ext LDFLAGS="$save_LDFLAGS" fi { $as_echo "$as_me:${as_lineno-$LINENO}: result: $lt_cv_ld_exported_symbols_list" >&5 $as_echo "$lt_cv_ld_exported_symbols_list" >&6; } { $as_echo "$as_me:${as_lineno-$LINENO}: checking for -force_load linker flag" >&5 $as_echo_n "checking for -force_load linker flag... " >&6; } if ${lt_cv_ld_force_load+:} false; then : $as_echo_n "(cached) " >&6 else lt_cv_ld_force_load=no cat > conftest.c << _LT_EOF int forced_loaded() { return 2;} _LT_EOF echo "$LTCC $LTCFLAGS -c -o conftest.o conftest.c" >&5 $LTCC $LTCFLAGS -c -o conftest.o conftest.c 2>&5 echo "$AR cru libconftest.a conftest.o" >&5 $AR cru libconftest.a conftest.o 2>&5 echo "$RANLIB libconftest.a" >&5 $RANLIB libconftest.a 2>&5 cat > conftest.c << _LT_EOF int main() { return 0;} _LT_EOF echo "$LTCC $LTCFLAGS $LDFLAGS -o conftest conftest.c -Wl,-force_load,./libconftest.a" >&5 $LTCC $LTCFLAGS $LDFLAGS -o conftest conftest.c -Wl,-force_load,./libconftest.a 2>conftest.err _lt_result=$? if test -s conftest.err && $GREP force_load conftest.err; then cat conftest.err >&5 elif test -f conftest && test $_lt_result -eq 0 && $GREP forced_load conftest >/dev/null 2>&1 ; then lt_cv_ld_force_load=yes else cat conftest.err >&5 fi rm -f conftest.err libconftest.a conftest conftest.c rm -rf conftest.dSYM fi { $as_echo "$as_me:${as_lineno-$LINENO}: result: $lt_cv_ld_force_load" >&5 $as_echo "$lt_cv_ld_force_load" >&6; } case $host_os in rhapsody* | darwin1.[012]) _lt_dar_allow_undefined='${wl}-undefined ${wl}suppress' ;; darwin1.*) _lt_dar_allow_undefined='${wl}-flat_namespace ${wl}-undefined ${wl}suppress' ;; darwin*) # darwin 5.x on # if running on 10.5 or later, the deployment target defaults # to the OS version, if on x86, and 10.4, the deployment # target defaults to 10.4. Don't you love it? case ${MACOSX_DEPLOYMENT_TARGET-10.0},$host in 10.0,*86*-darwin8*|10.0,*-darwin[91]*) _lt_dar_allow_undefined='${wl}-undefined ${wl}dynamic_lookup' ;; 10.[012]*) _lt_dar_allow_undefined='${wl}-flat_namespace ${wl}-undefined ${wl}suppress' ;; 10.*) _lt_dar_allow_undefined='${wl}-undefined ${wl}dynamic_lookup' ;; esac ;; esac if test "$lt_cv_apple_cc_single_mod" = "yes"; then _lt_dar_single_mod='$single_module' fi if test "$lt_cv_ld_exported_symbols_list" = "yes"; then _lt_dar_export_syms=' ${wl}-exported_symbols_list,$output_objdir/${libname}-symbols.expsym' else _lt_dar_export_syms='~$NMEDIT -s $output_objdir/${libname}-symbols.expsym ${lib}' fi if test "$DSYMUTIL" != ":" && test "$lt_cv_ld_force_load" = "no"; then _lt_dsymutil='~$DSYMUTIL $lib || :' else _lt_dsymutil= fi ;; esac for ac_header in dlfcn.h do : ac_fn_c_check_header_compile "$LINENO" "dlfcn.h" "ac_cv_header_dlfcn_h" "$ac_includes_default " if test "x$ac_cv_header_dlfcn_h" = xyes; then : cat >>confdefs.h <<_ACEOF #define HAVE_DLFCN_H 1 _ACEOF fi done # Set options enable_win32_dll=yes case $host in *-*-cygwin* | *-*-mingw* | *-*-pw32* | *-*-cegcc*) if test -n "$ac_tool_prefix"; then # Extract the first word of "${ac_tool_prefix}as", so it can be a program name with args. set dummy ${ac_tool_prefix}as; ac_word=$2 { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 $as_echo_n "checking for $ac_word... " >&6; } if ${ac_cv_prog_AS+:} false; then : $as_echo_n "(cached) " >&6 else if test -n "$AS"; then ac_cv_prog_AS="$AS" # Let the user override the test. else as_save_IFS=$IFS; IFS=$PATH_SEPARATOR for as_dir in $PATH do IFS=$as_save_IFS test -z "$as_dir" && as_dir=. for ac_exec_ext in '' $ac_executable_extensions; do if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then ac_cv_prog_AS="${ac_tool_prefix}as" $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5 break 2 fi done done IFS=$as_save_IFS fi fi AS=$ac_cv_prog_AS if test -n "$AS"; then { $as_echo "$as_me:${as_lineno-$LINENO}: result: $AS" >&5 $as_echo "$AS" >&6; } else { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 $as_echo "no" >&6; } fi fi if test -z "$ac_cv_prog_AS"; then ac_ct_AS=$AS # Extract the first word of "as", so it can be a program name with args. set dummy as; ac_word=$2 { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 $as_echo_n "checking for $ac_word... " >&6; } if ${ac_cv_prog_ac_ct_AS+:} false; then : $as_echo_n "(cached) " >&6 else if test -n "$ac_ct_AS"; then ac_cv_prog_ac_ct_AS="$ac_ct_AS" # Let the user override the test. else as_save_IFS=$IFS; IFS=$PATH_SEPARATOR for as_dir in $PATH do IFS=$as_save_IFS test -z "$as_dir" && as_dir=. for ac_exec_ext in '' $ac_executable_extensions; do if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then ac_cv_prog_ac_ct_AS="as" $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5 break 2 fi done done IFS=$as_save_IFS fi fi ac_ct_AS=$ac_cv_prog_ac_ct_AS if test -n "$ac_ct_AS"; then { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_ct_AS" >&5 $as_echo "$ac_ct_AS" >&6; } else { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 $as_echo "no" >&6; } fi if test "x$ac_ct_AS" = x; then AS="false" else case $cross_compiling:$ac_tool_warned in yes:) { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: using cross tools not prefixed with host triplet" >&5 $as_echo "$as_me: WARNING: using cross tools not prefixed with host triplet" >&2;} ac_tool_warned=yes ;; esac AS=$ac_ct_AS fi else AS="$ac_cv_prog_AS" fi if test -n "$ac_tool_prefix"; then # Extract the first word of "${ac_tool_prefix}dlltool", so it can be a program name with args. set dummy ${ac_tool_prefix}dlltool; ac_word=$2 { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 $as_echo_n "checking for $ac_word... " >&6; } if ${ac_cv_prog_DLLTOOL+:} false; then : $as_echo_n "(cached) " >&6 else if test -n "$DLLTOOL"; then ac_cv_prog_DLLTOOL="$DLLTOOL" # Let the user override the test. else as_save_IFS=$IFS; IFS=$PATH_SEPARATOR for as_dir in $PATH do IFS=$as_save_IFS test -z "$as_dir" && as_dir=. for ac_exec_ext in '' $ac_executable_extensions; do if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then ac_cv_prog_DLLTOOL="${ac_tool_prefix}dlltool" $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5 break 2 fi done done IFS=$as_save_IFS fi fi DLLTOOL=$ac_cv_prog_DLLTOOL if test -n "$DLLTOOL"; then { $as_echo "$as_me:${as_lineno-$LINENO}: result: $DLLTOOL" >&5 $as_echo "$DLLTOOL" >&6; } else { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 $as_echo "no" >&6; } fi fi if test -z "$ac_cv_prog_DLLTOOL"; then ac_ct_DLLTOOL=$DLLTOOL # Extract the first word of "dlltool", so it can be a program name with args. set dummy dlltool; ac_word=$2 { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 $as_echo_n "checking for $ac_word... " >&6; } if ${ac_cv_prog_ac_ct_DLLTOOL+:} false; then : $as_echo_n "(cached) " >&6 else if test -n "$ac_ct_DLLTOOL"; then ac_cv_prog_ac_ct_DLLTOOL="$ac_ct_DLLTOOL" # Let the user override the test. else as_save_IFS=$IFS; IFS=$PATH_SEPARATOR for as_dir in $PATH do IFS=$as_save_IFS test -z "$as_dir" && as_dir=. for ac_exec_ext in '' $ac_executable_extensions; do if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then ac_cv_prog_ac_ct_DLLTOOL="dlltool" $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5 break 2 fi done done IFS=$as_save_IFS fi fi ac_ct_DLLTOOL=$ac_cv_prog_ac_ct_DLLTOOL if test -n "$ac_ct_DLLTOOL"; then { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_ct_DLLTOOL" >&5 $as_echo "$ac_ct_DLLTOOL" >&6; } else { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 $as_echo "no" >&6; } fi if test "x$ac_ct_DLLTOOL" = x; then DLLTOOL="false" else case $cross_compiling:$ac_tool_warned in yes:) { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: using cross tools not prefixed with host triplet" >&5 $as_echo "$as_me: WARNING: using cross tools not prefixed with host triplet" >&2;} ac_tool_warned=yes ;; esac DLLTOOL=$ac_ct_DLLTOOL fi else DLLTOOL="$ac_cv_prog_DLLTOOL" fi if test -n "$ac_tool_prefix"; then # Extract the first word of "${ac_tool_prefix}objdump", so it can be a program name with args. set dummy ${ac_tool_prefix}objdump; ac_word=$2 { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 $as_echo_n "checking for $ac_word... " >&6; } if ${ac_cv_prog_OBJDUMP+:} false; then : $as_echo_n "(cached) " >&6 else if test -n "$OBJDUMP"; then ac_cv_prog_OBJDUMP="$OBJDUMP" # Let the user override the test. else as_save_IFS=$IFS; IFS=$PATH_SEPARATOR for as_dir in $PATH do IFS=$as_save_IFS test -z "$as_dir" && as_dir=. for ac_exec_ext in '' $ac_executable_extensions; do if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then ac_cv_prog_OBJDUMP="${ac_tool_prefix}objdump" $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5 break 2 fi done done IFS=$as_save_IFS fi fi OBJDUMP=$ac_cv_prog_OBJDUMP if test -n "$OBJDUMP"; then { $as_echo "$as_me:${as_lineno-$LINENO}: result: $OBJDUMP" >&5 $as_echo "$OBJDUMP" >&6; } else { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 $as_echo "no" >&6; } fi fi if test -z "$ac_cv_prog_OBJDUMP"; then ac_ct_OBJDUMP=$OBJDUMP # Extract the first word of "objdump", so it can be a program name with args. set dummy objdump; ac_word=$2 { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 $as_echo_n "checking for $ac_word... " >&6; } if ${ac_cv_prog_ac_ct_OBJDUMP+:} false; then : $as_echo_n "(cached) " >&6 else if test -n "$ac_ct_OBJDUMP"; then ac_cv_prog_ac_ct_OBJDUMP="$ac_ct_OBJDUMP" # Let the user override the test. else as_save_IFS=$IFS; IFS=$PATH_SEPARATOR for as_dir in $PATH do IFS=$as_save_IFS test -z "$as_dir" && as_dir=. for ac_exec_ext in '' $ac_executable_extensions; do if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then ac_cv_prog_ac_ct_OBJDUMP="objdump" $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5 break 2 fi done done IFS=$as_save_IFS fi fi ac_ct_OBJDUMP=$ac_cv_prog_ac_ct_OBJDUMP if test -n "$ac_ct_OBJDUMP"; then { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_ct_OBJDUMP" >&5 $as_echo "$ac_ct_OBJDUMP" >&6; } else { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 $as_echo "no" >&6; } fi if test "x$ac_ct_OBJDUMP" = x; then OBJDUMP="false" else case $cross_compiling:$ac_tool_warned in yes:) { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: using cross tools not prefixed with host triplet" >&5 $as_echo "$as_me: WARNING: using cross tools not prefixed with host triplet" >&2;} ac_tool_warned=yes ;; esac OBJDUMP=$ac_ct_OBJDUMP fi else OBJDUMP="$ac_cv_prog_OBJDUMP" fi ;; esac test -z "$AS" && AS=as test -z "$DLLTOOL" && DLLTOOL=dlltool test -z "$OBJDUMP" && OBJDUMP=objdump enable_dlopen=no # Check whether --with-pic was given. if test "${with_pic+set}" = set; then : withval=$with_pic; lt_p=${PACKAGE-default} case $withval in yes|no) pic_mode=$withval ;; *) pic_mode=default # Look at the argument we got. We use all the common list separators. lt_save_ifs="$IFS"; IFS="${IFS}$PATH_SEPARATOR," for lt_pkg in $withval; do IFS="$lt_save_ifs" if test "X$lt_pkg" = "X$lt_p"; then pic_mode=yes fi done IFS="$lt_save_ifs" ;; esac else pic_mode=default fi test -z "$pic_mode" && pic_mode=default # Check whether --enable-fast-install was given. if test "${enable_fast_install+set}" = set; then : enableval=$enable_fast_install; p=${PACKAGE-default} case $enableval in yes) enable_fast_install=yes ;; no) enable_fast_install=no ;; *) enable_fast_install=no # Look at the argument we got. We use all the common list separators. lt_save_ifs="$IFS"; IFS="${IFS}$PATH_SEPARATOR," for pkg in $enableval; do IFS="$lt_save_ifs" if test "X$pkg" = "X$p"; then enable_fast_install=yes fi done IFS="$lt_save_ifs" ;; esac else enable_fast_install=yes fi # This can be used to rebuild libtool when needed LIBTOOL_DEPS="$ltmain" # Always use our own libtool. LIBTOOL='$(SHELL) $(top_builddir)/libtool' test -z "$LN_S" && LN_S="ln -s" if test -n "${ZSH_VERSION+set}" ; then setopt NO_GLOB_SUBST fi { $as_echo "$as_me:${as_lineno-$LINENO}: checking for objdir" >&5 $as_echo_n "checking for objdir... " >&6; } if ${lt_cv_objdir+:} false; then : $as_echo_n "(cached) " >&6 else rm -f .libs 2>/dev/null mkdir .libs 2>/dev/null if test -d .libs; then lt_cv_objdir=.libs else # MS-DOS does not allow filenames that begin with a dot. lt_cv_objdir=_libs fi rmdir .libs 2>/dev/null fi { $as_echo "$as_me:${as_lineno-$LINENO}: result: $lt_cv_objdir" >&5 $as_echo "$lt_cv_objdir" >&6; } objdir=$lt_cv_objdir cat >>confdefs.h <<_ACEOF #define LT_OBJDIR "$lt_cv_objdir/" _ACEOF case $host_os in aix3*) # AIX sometimes has problems with the GCC collect2 program. For some # reason, if we set the COLLECT_NAMES environment variable, the problems # vanish in a puff of smoke. if test "X${COLLECT_NAMES+set}" != Xset; then COLLECT_NAMES= export COLLECT_NAMES fi ;; esac # Global variables: ofile=libtool can_build_shared=yes # All known linkers require a `.a' archive for static linking (except MSVC, # which needs '.lib'). libext=a with_gnu_ld="$lt_cv_prog_gnu_ld" old_CC="$CC" old_CFLAGS="$CFLAGS" # Set sane defaults for various variables test -z "$CC" && CC=cc test -z "$LTCC" && LTCC=$CC test -z "$LTCFLAGS" && LTCFLAGS=$CFLAGS test -z "$LD" && LD=ld test -z "$ac_objext" && ac_objext=o for cc_temp in $compiler""; do case $cc_temp in compile | *[\\/]compile | ccache | *[\\/]ccache ) ;; distcc | *[\\/]distcc | purify | *[\\/]purify ) ;; \-*) ;; *) break;; esac done cc_basename=`$ECHO "$cc_temp" | $SED "s%.*/%%; s%^$host_alias-%%"` # Only perform the check for file, if the check method requires it test -z "$MAGIC_CMD" && MAGIC_CMD=file case $deplibs_check_method in file_magic*) if test "$file_magic_cmd" = '$MAGIC_CMD'; then { $as_echo "$as_me:${as_lineno-$LINENO}: checking for ${ac_tool_prefix}file" >&5 $as_echo_n "checking for ${ac_tool_prefix}file... " >&6; } if ${lt_cv_path_MAGIC_CMD+:} false; then : $as_echo_n "(cached) " >&6 else case $MAGIC_CMD in [\\/*] | ?:[\\/]*) lt_cv_path_MAGIC_CMD="$MAGIC_CMD" # Let the user override the test with a path. ;; *) lt_save_MAGIC_CMD="$MAGIC_CMD" lt_save_ifs="$IFS"; IFS=$PATH_SEPARATOR ac_dummy="/usr/bin$PATH_SEPARATOR$PATH" for ac_dir in $ac_dummy; do IFS="$lt_save_ifs" test -z "$ac_dir" && ac_dir=. if test -f $ac_dir/${ac_tool_prefix}file; then lt_cv_path_MAGIC_CMD="$ac_dir/${ac_tool_prefix}file" if test -n "$file_magic_test_file"; then case $deplibs_check_method in "file_magic "*) file_magic_regex=`expr "$deplibs_check_method" : "file_magic \(.*\)"` MAGIC_CMD="$lt_cv_path_MAGIC_CMD" if eval $file_magic_cmd \$file_magic_test_file 2> /dev/null | $EGREP "$file_magic_regex" > /dev/null; then : else cat <<_LT_EOF 1>&2 *** Warning: the command libtool uses to detect shared libraries, *** $file_magic_cmd, produces output that libtool cannot recognize. *** The result is that libtool may fail to recognize shared libraries *** as such. This will affect the creation of libtool libraries that *** depend on shared libraries, but programs linked with such libtool *** libraries will work regardless of this problem. Nevertheless, you *** may want to report the problem to your system manager and/or to *** bug-libtool@gnu.org _LT_EOF fi ;; esac fi break fi done IFS="$lt_save_ifs" MAGIC_CMD="$lt_save_MAGIC_CMD" ;; esac fi MAGIC_CMD="$lt_cv_path_MAGIC_CMD" if test -n "$MAGIC_CMD"; then { $as_echo "$as_me:${as_lineno-$LINENO}: result: $MAGIC_CMD" >&5 $as_echo "$MAGIC_CMD" >&6; } else { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 $as_echo "no" >&6; } fi if test -z "$lt_cv_path_MAGIC_CMD"; then if test -n "$ac_tool_prefix"; then { $as_echo "$as_me:${as_lineno-$LINENO}: checking for file" >&5 $as_echo_n "checking for file... " >&6; } if ${lt_cv_path_MAGIC_CMD+:} false; then : $as_echo_n "(cached) " >&6 else case $MAGIC_CMD in [\\/*] | ?:[\\/]*) lt_cv_path_MAGIC_CMD="$MAGIC_CMD" # Let the user override the test with a path. ;; *) lt_save_MAGIC_CMD="$MAGIC_CMD" lt_save_ifs="$IFS"; IFS=$PATH_SEPARATOR ac_dummy="/usr/bin$PATH_SEPARATOR$PATH" for ac_dir in $ac_dummy; do IFS="$lt_save_ifs" test -z "$ac_dir" && ac_dir=. if test -f $ac_dir/file; then lt_cv_path_MAGIC_CMD="$ac_dir/file" if test -n "$file_magic_test_file"; then case $deplibs_check_method in "file_magic "*) file_magic_regex=`expr "$deplibs_check_method" : "file_magic \(.*\)"` MAGIC_CMD="$lt_cv_path_MAGIC_CMD" if eval $file_magic_cmd \$file_magic_test_file 2> /dev/null | $EGREP "$file_magic_regex" > /dev/null; then : else cat <<_LT_EOF 1>&2 *** Warning: the command libtool uses to detect shared libraries, *** $file_magic_cmd, produces output that libtool cannot recognize. *** The result is that libtool may fail to recognize shared libraries *** as such. This will affect the creation of libtool libraries that *** depend on shared libraries, but programs linked with such libtool *** libraries will work regardless of this problem. Nevertheless, you *** may want to report the problem to your system manager and/or to *** bug-libtool@gnu.org _LT_EOF fi ;; esac fi break fi done IFS="$lt_save_ifs" MAGIC_CMD="$lt_save_MAGIC_CMD" ;; esac fi MAGIC_CMD="$lt_cv_path_MAGIC_CMD" if test -n "$MAGIC_CMD"; then { $as_echo "$as_me:${as_lineno-$LINENO}: result: $MAGIC_CMD" >&5 $as_echo "$MAGIC_CMD" >&6; } else { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 $as_echo "no" >&6; } fi else MAGIC_CMD=: fi fi fi ;; esac # Use C for the default configuration in the libtool script lt_save_CC="$CC" ac_ext=c ac_cpp='$CPP $CPPFLAGS' ac_compile='$CC -c $CFLAGS $CPPFLAGS conftest.$ac_ext >&5' ac_link='$CC -o conftest$ac_exeext $CFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5' ac_compiler_gnu=$ac_cv_c_compiler_gnu # Source file extension for C test sources. ac_ext=c # Object file extension for compiled C test sources. objext=o objext=$objext # Code to be used in simple compile tests lt_simple_compile_test_code="int some_variable = 0;" # Code to be used in simple link tests lt_simple_link_test_code='int main(){return(0);}' # If no C compiler was specified, use CC. LTCC=${LTCC-"$CC"} # If no C compiler flags were specified, use CFLAGS. LTCFLAGS=${LTCFLAGS-"$CFLAGS"} # Allow CC to be a program name with arguments. compiler=$CC # Save the default compiler, since it gets overwritten when the other # tags are being tested, and _LT_TAGVAR(compiler, []) is a NOP. compiler_DEFAULT=$CC # save warnings/boilerplate of simple test code ac_outfile=conftest.$ac_objext echo "$lt_simple_compile_test_code" >conftest.$ac_ext eval "$ac_compile" 2>&1 >/dev/null | $SED '/^$/d; /^ *+/d' >conftest.err _lt_compiler_boilerplate=`cat conftest.err` $RM conftest* ac_outfile=conftest.$ac_objext echo "$lt_simple_link_test_code" >conftest.$ac_ext eval "$ac_link" 2>&1 >/dev/null | $SED '/^$/d; /^ *+/d' >conftest.err _lt_linker_boilerplate=`cat conftest.err` $RM -r conftest* ## CAVEAT EMPTOR: ## There is no encapsulation within the following macros, do not change ## the running order or otherwise move them around unless you know exactly ## what you are doing... if test -n "$compiler"; then lt_prog_compiler_no_builtin_flag= if test "$GCC" = yes; then case $cc_basename in nvcc*) lt_prog_compiler_no_builtin_flag=' -Xcompiler -fno-builtin' ;; *) lt_prog_compiler_no_builtin_flag=' -fno-builtin' ;; esac { $as_echo "$as_me:${as_lineno-$LINENO}: checking if $compiler supports -fno-rtti -fno-exceptions" >&5 $as_echo_n "checking if $compiler supports -fno-rtti -fno-exceptions... " >&6; } if ${lt_cv_prog_compiler_rtti_exceptions+:} false; then : $as_echo_n "(cached) " >&6 else lt_cv_prog_compiler_rtti_exceptions=no ac_outfile=conftest.$ac_objext echo "$lt_simple_compile_test_code" > conftest.$ac_ext lt_compiler_flag="-fno-rtti -fno-exceptions" # Insert the option either (1) after the last *FLAGS variable, or # (2) before a word containing "conftest.", or (3) at the end. # Note that $ac_compile itself does not contain backslashes and begins # with a dollar sign (not a hyphen), so the echo should work correctly. # The option is referenced via a variable to avoid confusing sed. lt_compile=`echo "$ac_compile" | $SED \ -e 's:.*FLAGS}\{0,1\} :&$lt_compiler_flag :; t' \ -e 's: [^ ]*conftest\.: $lt_compiler_flag&:; t' \ -e 's:$: $lt_compiler_flag:'` (eval echo "\"\$as_me:$LINENO: $lt_compile\"" >&5) (eval "$lt_compile" 2>conftest.err) ac_status=$? cat conftest.err >&5 echo "$as_me:$LINENO: \$? = $ac_status" >&5 if (exit $ac_status) && test -s "$ac_outfile"; then # The compiler can only warn and ignore the option if not recognized # So say no if there are warnings other than the usual output. $ECHO "$_lt_compiler_boilerplate" | $SED '/^$/d' >conftest.exp $SED '/^$/d; /^ *+/d' conftest.err >conftest.er2 if test ! -s conftest.er2 || diff conftest.exp conftest.er2 >/dev/null; then lt_cv_prog_compiler_rtti_exceptions=yes fi fi $RM conftest* fi { $as_echo "$as_me:${as_lineno-$LINENO}: result: $lt_cv_prog_compiler_rtti_exceptions" >&5 $as_echo "$lt_cv_prog_compiler_rtti_exceptions" >&6; } if test x"$lt_cv_prog_compiler_rtti_exceptions" = xyes; then lt_prog_compiler_no_builtin_flag="$lt_prog_compiler_no_builtin_flag -fno-rtti -fno-exceptions" else : fi fi lt_prog_compiler_wl= lt_prog_compiler_pic= lt_prog_compiler_static= if test "$GCC" = yes; then lt_prog_compiler_wl='-Wl,' lt_prog_compiler_static='-static' case $host_os in aix*) # All AIX code is PIC. if test "$host_cpu" = ia64; then # AIX 5 now supports IA64 processor lt_prog_compiler_static='-Bstatic' fi ;; amigaos*) case $host_cpu in powerpc) # see comment about AmigaOS4 .so support lt_prog_compiler_pic='-fPIC' ;; m68k) # FIXME: we need at least 68020 code to build shared libraries, but # adding the `-m68020' flag to GCC prevents building anything better, # like `-m68040'. lt_prog_compiler_pic='-m68020 -resident32 -malways-restore-a4' ;; esac ;; beos* | irix5* | irix6* | nonstopux* | osf3* | osf4* | osf5*) # PIC is the default for these OSes. ;; mingw* | cygwin* | pw32* | os2* | cegcc*) # This hack is so that the source file can tell whether it is being # built for inclusion in a dll (and should export symbols for example). # Although the cygwin gcc ignores -fPIC, still need this for old-style # (--disable-auto-import) libraries lt_prog_compiler_pic='-DDLL_EXPORT' ;; darwin* | rhapsody*) # PIC is the default on this platform # Common symbols not allowed in MH_DYLIB files lt_prog_compiler_pic='-fno-common' ;; haiku*) # PIC is the default for Haiku. # The "-static" flag exists, but is broken. lt_prog_compiler_static= ;; hpux*) # PIC is the default for 64-bit PA HP-UX, but not for 32-bit # PA HP-UX. On IA64 HP-UX, PIC is the default but the pic flag # sets the default TLS model and affects inlining. case $host_cpu in hppa*64*) # +Z the default ;; *) lt_prog_compiler_pic='-fPIC' ;; esac ;; interix[3-9]*) # Interix 3.x gcc -fpic/-fPIC options generate broken code. # Instead, we relocate shared libraries at runtime. ;; msdosdjgpp*) # Just because we use GCC doesn't mean we suddenly get shared libraries # on systems that don't support them. lt_prog_compiler_can_build_shared=no enable_shared=no ;; *nto* | *qnx*) # QNX uses GNU C++, but need to define -shared option too, otherwise # it will coredump. lt_prog_compiler_pic='-fPIC -shared' ;; sysv4*MP*) if test -d /usr/nec; then lt_prog_compiler_pic=-Kconform_pic fi ;; *) lt_prog_compiler_pic='-fPIC' ;; esac case $cc_basename in nvcc*) # Cuda Compiler Driver 2.2 lt_prog_compiler_wl='-Xlinker ' if test -n "$lt_prog_compiler_pic"; then lt_prog_compiler_pic="-Xcompiler $lt_prog_compiler_pic" fi ;; esac else # PORTME Check for flag to pass linker flags through the system compiler. case $host_os in aix*) lt_prog_compiler_wl='-Wl,' if test "$host_cpu" = ia64; then # AIX 5 now supports IA64 processor lt_prog_compiler_static='-Bstatic' else lt_prog_compiler_static='-bnso -bI:/lib/syscalls.exp' fi ;; mingw* | cygwin* | pw32* | os2* | cegcc*) # This hack is so that the source file can tell whether it is being # built for inclusion in a dll (and should export symbols for example). lt_prog_compiler_pic='-DDLL_EXPORT' ;; hpux9* | hpux10* | hpux11*) lt_prog_compiler_wl='-Wl,' # PIC is the default for IA64 HP-UX and 64-bit HP-UX, but # not for PA HP-UX. case $host_cpu in hppa*64*|ia64*) # +Z the default ;; *) lt_prog_compiler_pic='+Z' ;; esac # Is there a better lt_prog_compiler_static that works with the bundled CC? lt_prog_compiler_static='${wl}-a ${wl}archive' ;; irix5* | irix6* | nonstopux*) lt_prog_compiler_wl='-Wl,' # PIC (with -KPIC) is the default. lt_prog_compiler_static='-non_shared' ;; linux* | k*bsd*-gnu | kopensolaris*-gnu) case $cc_basename in # old Intel for x86_64 which still supported -KPIC. ecc*) lt_prog_compiler_wl='-Wl,' lt_prog_compiler_pic='-KPIC' lt_prog_compiler_static='-static' ;; # icc used to be incompatible with GCC. # ICC 10 doesn't accept -KPIC any more. icc* | ifort*) lt_prog_compiler_wl='-Wl,' lt_prog_compiler_pic='-fPIC' lt_prog_compiler_static='-static' ;; # Lahey Fortran 8.1. lf95*) lt_prog_compiler_wl='-Wl,' lt_prog_compiler_pic='--shared' lt_prog_compiler_static='--static' ;; nagfor*) # NAG Fortran compiler lt_prog_compiler_wl='-Wl,-Wl,,' lt_prog_compiler_pic='-PIC' lt_prog_compiler_static='-Bstatic' ;; pgcc* | pgf77* | pgf90* | pgf95* | pgfortran*) # Portland Group compilers (*not* the Pentium gcc compiler, # which looks to be a dead project) lt_prog_compiler_wl='-Wl,' lt_prog_compiler_pic='-fpic' lt_prog_compiler_static='-Bstatic' ;; ccc*) lt_prog_compiler_wl='-Wl,' # All Alpha code is PIC. lt_prog_compiler_static='-non_shared' ;; xl* | bgxl* | bgf* | mpixl*) # IBM XL C 8.0/Fortran 10.1, 11.1 on PPC and BlueGene lt_prog_compiler_wl='-Wl,' lt_prog_compiler_pic='-qpic' lt_prog_compiler_static='-qstaticlink' ;; *) case `$CC -V 2>&1 | sed 5q` in *Sun\ Ceres\ Fortran* | *Sun*Fortran*\ [1-7].* | *Sun*Fortran*\ 8.[0-3]*) # Sun Fortran 8.3 passes all unrecognized flags to the linker lt_prog_compiler_pic='-KPIC' lt_prog_compiler_static='-Bstatic' lt_prog_compiler_wl='' ;; *Sun\ F* | *Sun*Fortran*) lt_prog_compiler_pic='-KPIC' lt_prog_compiler_static='-Bstatic' lt_prog_compiler_wl='-Qoption ld ' ;; *Sun\ C*) # Sun C 5.9 lt_prog_compiler_pic='-KPIC' lt_prog_compiler_static='-Bstatic' lt_prog_compiler_wl='-Wl,' ;; *Intel*\ [CF]*Compiler*) lt_prog_compiler_wl='-Wl,' lt_prog_compiler_pic='-fPIC' lt_prog_compiler_static='-static' ;; *Portland\ Group*) lt_prog_compiler_wl='-Wl,' lt_prog_compiler_pic='-fpic' lt_prog_compiler_static='-Bstatic' ;; esac ;; esac ;; newsos6) lt_prog_compiler_pic='-KPIC' lt_prog_compiler_static='-Bstatic' ;; *nto* | *qnx*) # QNX uses GNU C++, but need to define -shared option too, otherwise # it will coredump. lt_prog_compiler_pic='-fPIC -shared' ;; osf3* | osf4* | osf5*) lt_prog_compiler_wl='-Wl,' # All OSF/1 code is PIC. lt_prog_compiler_static='-non_shared' ;; rdos*) lt_prog_compiler_static='-non_shared' ;; solaris*) lt_prog_compiler_pic='-KPIC' lt_prog_compiler_static='-Bstatic' case $cc_basename in f77* | f90* | f95* | sunf77* | sunf90* | sunf95*) lt_prog_compiler_wl='-Qoption ld ';; *) lt_prog_compiler_wl='-Wl,';; esac ;; sunos4*) lt_prog_compiler_wl='-Qoption ld ' lt_prog_compiler_pic='-PIC' lt_prog_compiler_static='-Bstatic' ;; sysv4 | sysv4.2uw2* | sysv4.3*) lt_prog_compiler_wl='-Wl,' lt_prog_compiler_pic='-KPIC' lt_prog_compiler_static='-Bstatic' ;; sysv4*MP*) if test -d /usr/nec ;then lt_prog_compiler_pic='-Kconform_pic' lt_prog_compiler_static='-Bstatic' fi ;; sysv5* | unixware* | sco3.2v5* | sco5v6* | OpenUNIX*) lt_prog_compiler_wl='-Wl,' lt_prog_compiler_pic='-KPIC' lt_prog_compiler_static='-Bstatic' ;; unicos*) lt_prog_compiler_wl='-Wl,' lt_prog_compiler_can_build_shared=no ;; uts4*) lt_prog_compiler_pic='-pic' lt_prog_compiler_static='-Bstatic' ;; *) lt_prog_compiler_can_build_shared=no ;; esac fi case $host_os in # For platforms which do not support PIC, -DPIC is meaningless: *djgpp*) lt_prog_compiler_pic= ;; *) lt_prog_compiler_pic="$lt_prog_compiler_pic -DPIC" ;; esac { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $compiler option to produce PIC" >&5 $as_echo_n "checking for $compiler option to produce PIC... " >&6; } if ${lt_cv_prog_compiler_pic+:} false; then : $as_echo_n "(cached) " >&6 else lt_cv_prog_compiler_pic=$lt_prog_compiler_pic fi { $as_echo "$as_me:${as_lineno-$LINENO}: result: $lt_cv_prog_compiler_pic" >&5 $as_echo "$lt_cv_prog_compiler_pic" >&6; } lt_prog_compiler_pic=$lt_cv_prog_compiler_pic # # Check to make sure the PIC flag actually works. # if test -n "$lt_prog_compiler_pic"; then { $as_echo "$as_me:${as_lineno-$LINENO}: checking if $compiler PIC flag $lt_prog_compiler_pic works" >&5 $as_echo_n "checking if $compiler PIC flag $lt_prog_compiler_pic works... " >&6; } if ${lt_cv_prog_compiler_pic_works+:} false; then : $as_echo_n "(cached) " >&6 else lt_cv_prog_compiler_pic_works=no ac_outfile=conftest.$ac_objext echo "$lt_simple_compile_test_code" > conftest.$ac_ext lt_compiler_flag="$lt_prog_compiler_pic -DPIC" # Insert the option either (1) after the last *FLAGS variable, or # (2) before a word containing "conftest.", or (3) at the end. # Note that $ac_compile itself does not contain backslashes and begins # with a dollar sign (not a hyphen), so the echo should work correctly. # The option is referenced via a variable to avoid confusing sed. lt_compile=`echo "$ac_compile" | $SED \ -e 's:.*FLAGS}\{0,1\} :&$lt_compiler_flag :; t' \ -e 's: [^ ]*conftest\.: $lt_compiler_flag&:; t' \ -e 's:$: $lt_compiler_flag:'` (eval echo "\"\$as_me:$LINENO: $lt_compile\"" >&5) (eval "$lt_compile" 2>conftest.err) ac_status=$? cat conftest.err >&5 echo "$as_me:$LINENO: \$? = $ac_status" >&5 if (exit $ac_status) && test -s "$ac_outfile"; then # The compiler can only warn and ignore the option if not recognized # So say no if there are warnings other than the usual output. $ECHO "$_lt_compiler_boilerplate" | $SED '/^$/d' >conftest.exp $SED '/^$/d; /^ *+/d' conftest.err >conftest.er2 if test ! -s conftest.er2 || diff conftest.exp conftest.er2 >/dev/null; then lt_cv_prog_compiler_pic_works=yes fi fi $RM conftest* fi { $as_echo "$as_me:${as_lineno-$LINENO}: result: $lt_cv_prog_compiler_pic_works" >&5 $as_echo "$lt_cv_prog_compiler_pic_works" >&6; } if test x"$lt_cv_prog_compiler_pic_works" = xyes; then case $lt_prog_compiler_pic in "" | " "*) ;; *) lt_prog_compiler_pic=" $lt_prog_compiler_pic" ;; esac else lt_prog_compiler_pic= lt_prog_compiler_can_build_shared=no fi fi # # Check to make sure the static flag actually works. # wl=$lt_prog_compiler_wl eval lt_tmp_static_flag=\"$lt_prog_compiler_static\" { $as_echo "$as_me:${as_lineno-$LINENO}: checking if $compiler static flag $lt_tmp_static_flag works" >&5 $as_echo_n "checking if $compiler static flag $lt_tmp_static_flag works... " >&6; } if ${lt_cv_prog_compiler_static_works+:} false; then : $as_echo_n "(cached) " >&6 else lt_cv_prog_compiler_static_works=no save_LDFLAGS="$LDFLAGS" LDFLAGS="$LDFLAGS $lt_tmp_static_flag" echo "$lt_simple_link_test_code" > conftest.$ac_ext if (eval $ac_link 2>conftest.err) && test -s conftest$ac_exeext; then # The linker can only warn and ignore the option if not recognized # So say no if there are warnings if test -s conftest.err; then # Append any errors to the config.log. cat conftest.err 1>&5 $ECHO "$_lt_linker_boilerplate" | $SED '/^$/d' > conftest.exp $SED '/^$/d; /^ *+/d' conftest.err >conftest.er2 if diff conftest.exp conftest.er2 >/dev/null; then lt_cv_prog_compiler_static_works=yes fi else lt_cv_prog_compiler_static_works=yes fi fi $RM -r conftest* LDFLAGS="$save_LDFLAGS" fi { $as_echo "$as_me:${as_lineno-$LINENO}: result: $lt_cv_prog_compiler_static_works" >&5 $as_echo "$lt_cv_prog_compiler_static_works" >&6; } if test x"$lt_cv_prog_compiler_static_works" = xyes; then : else lt_prog_compiler_static= fi { $as_echo "$as_me:${as_lineno-$LINENO}: checking if $compiler supports -c -o file.$ac_objext" >&5 $as_echo_n "checking if $compiler supports -c -o file.$ac_objext... " >&6; } if ${lt_cv_prog_compiler_c_o+:} false; then : $as_echo_n "(cached) " >&6 else lt_cv_prog_compiler_c_o=no $RM -r conftest 2>/dev/null mkdir conftest cd conftest mkdir out echo "$lt_simple_compile_test_code" > conftest.$ac_ext lt_compiler_flag="-o out/conftest2.$ac_objext" # Insert the option either (1) after the last *FLAGS variable, or # (2) before a word containing "conftest.", or (3) at the end. # Note that $ac_compile itself does not contain backslashes and begins # with a dollar sign (not a hyphen), so the echo should work correctly. lt_compile=`echo "$ac_compile" | $SED \ -e 's:.*FLAGS}\{0,1\} :&$lt_compiler_flag :; t' \ -e 's: [^ ]*conftest\.: $lt_compiler_flag&:; t' \ -e 's:$: $lt_compiler_flag:'` (eval echo "\"\$as_me:$LINENO: $lt_compile\"" >&5) (eval "$lt_compile" 2>out/conftest.err) ac_status=$? cat out/conftest.err >&5 echo "$as_me:$LINENO: \$? = $ac_status" >&5 if (exit $ac_status) && test -s out/conftest2.$ac_objext then # The compiler can only warn and ignore the option if not recognized # So say no if there are warnings $ECHO "$_lt_compiler_boilerplate" | $SED '/^$/d' > out/conftest.exp $SED '/^$/d; /^ *+/d' out/conftest.err >out/conftest.er2 if test ! -s out/conftest.er2 || diff out/conftest.exp out/conftest.er2 >/dev/null; then lt_cv_prog_compiler_c_o=yes fi fi chmod u+w . 2>&5 $RM conftest* # SGI C++ compiler will create directory out/ii_files/ for # template instantiation test -d out/ii_files && $RM out/ii_files/* && rmdir out/ii_files $RM out/* && rmdir out cd .. $RM -r conftest $RM conftest* fi { $as_echo "$as_me:${as_lineno-$LINENO}: result: $lt_cv_prog_compiler_c_o" >&5 $as_echo "$lt_cv_prog_compiler_c_o" >&6; } { $as_echo "$as_me:${as_lineno-$LINENO}: checking if $compiler supports -c -o file.$ac_objext" >&5 $as_echo_n "checking if $compiler supports -c -o file.$ac_objext... " >&6; } if ${lt_cv_prog_compiler_c_o+:} false; then : $as_echo_n "(cached) " >&6 else lt_cv_prog_compiler_c_o=no $RM -r conftest 2>/dev/null mkdir conftest cd conftest mkdir out echo "$lt_simple_compile_test_code" > conftest.$ac_ext lt_compiler_flag="-o out/conftest2.$ac_objext" # Insert the option either (1) after the last *FLAGS variable, or # (2) before a word containing "conftest.", or (3) at the end. # Note that $ac_compile itself does not contain backslashes and begins # with a dollar sign (not a hyphen), so the echo should work correctly. lt_compile=`echo "$ac_compile" | $SED \ -e 's:.*FLAGS}\{0,1\} :&$lt_compiler_flag :; t' \ -e 's: [^ ]*conftest\.: $lt_compiler_flag&:; t' \ -e 's:$: $lt_compiler_flag:'` (eval echo "\"\$as_me:$LINENO: $lt_compile\"" >&5) (eval "$lt_compile" 2>out/conftest.err) ac_status=$? cat out/conftest.err >&5 echo "$as_me:$LINENO: \$? = $ac_status" >&5 if (exit $ac_status) && test -s out/conftest2.$ac_objext then # The compiler can only warn and ignore the option if not recognized # So say no if there are warnings $ECHO "$_lt_compiler_boilerplate" | $SED '/^$/d' > out/conftest.exp $SED '/^$/d; /^ *+/d' out/conftest.err >out/conftest.er2 if test ! -s out/conftest.er2 || diff out/conftest.exp out/conftest.er2 >/dev/null; then lt_cv_prog_compiler_c_o=yes fi fi chmod u+w . 2>&5 $RM conftest* # SGI C++ compiler will create directory out/ii_files/ for # template instantiation test -d out/ii_files && $RM out/ii_files/* && rmdir out/ii_files $RM out/* && rmdir out cd .. $RM -r conftest $RM conftest* fi { $as_echo "$as_me:${as_lineno-$LINENO}: result: $lt_cv_prog_compiler_c_o" >&5 $as_echo "$lt_cv_prog_compiler_c_o" >&6; } hard_links="nottested" if test "$lt_cv_prog_compiler_c_o" = no && test "$need_locks" != no; then # do not overwrite the value of need_locks provided by the user { $as_echo "$as_me:${as_lineno-$LINENO}: checking if we can lock with hard links" >&5 $as_echo_n "checking if we can lock with hard links... " >&6; } hard_links=yes $RM conftest* ln conftest.a conftest.b 2>/dev/null && hard_links=no touch conftest.a ln conftest.a conftest.b 2>&5 || hard_links=no ln conftest.a conftest.b 2>/dev/null && hard_links=no { $as_echo "$as_me:${as_lineno-$LINENO}: result: $hard_links" >&5 $as_echo "$hard_links" >&6; } if test "$hard_links" = no; then { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: \`$CC' does not support \`-c -o', so \`make -j' may be unsafe" >&5 $as_echo "$as_me: WARNING: \`$CC' does not support \`-c -o', so \`make -j' may be unsafe" >&2;} need_locks=warn fi else need_locks=no fi { $as_echo "$as_me:${as_lineno-$LINENO}: checking whether the $compiler linker ($LD) supports shared libraries" >&5 $as_echo_n "checking whether the $compiler linker ($LD) supports shared libraries... " >&6; } runpath_var= allow_undefined_flag= always_export_symbols=no archive_cmds= archive_expsym_cmds= compiler_needs_object=no enable_shared_with_static_runtimes=no export_dynamic_flag_spec= export_symbols_cmds='$NM $libobjs $convenience | $global_symbol_pipe | $SED '\''s/.* //'\'' | sort | uniq > $export_symbols' hardcode_automatic=no hardcode_direct=no hardcode_direct_absolute=no hardcode_libdir_flag_spec= hardcode_libdir_separator= hardcode_minus_L=no hardcode_shlibpath_var=unsupported inherit_rpath=no link_all_deplibs=unknown module_cmds= module_expsym_cmds= old_archive_from_new_cmds= old_archive_from_expsyms_cmds= thread_safe_flag_spec= whole_archive_flag_spec= # include_expsyms should be a list of space-separated symbols to be *always* # included in the symbol list include_expsyms= # exclude_expsyms can be an extended regexp of symbols to exclude # it will be wrapped by ` (' and `)$', so one must not match beginning or # end of line. Example: `a|bc|.*d.*' will exclude the symbols `a' and `bc', # as well as any symbol that contains `d'. exclude_expsyms='_GLOBAL_OFFSET_TABLE_|_GLOBAL__F[ID]_.*' # Although _GLOBAL_OFFSET_TABLE_ is a valid symbol C name, most a.out # platforms (ab)use it in PIC code, but their linkers get confused if # the symbol is explicitly referenced. Since portable code cannot # rely on this symbol name, it's probably fine to never include it in # preloaded symbol tables. # Exclude shared library initialization/finalization symbols. extract_expsyms_cmds= case $host_os in cygwin* | mingw* | pw32* | cegcc*) # FIXME: the MSVC++ port hasn't been tested in a loooong time # When not using gcc, we currently assume that we are using # Microsoft Visual C++. if test "$GCC" != yes; then with_gnu_ld=no fi ;; interix*) # we just hope/assume this is gcc and not c89 (= MSVC++) with_gnu_ld=yes ;; openbsd*) with_gnu_ld=no ;; esac ld_shlibs=yes # On some targets, GNU ld is compatible enough with the native linker # that we're better off using the native interface for both. lt_use_gnu_ld_interface=no if test "$with_gnu_ld" = yes; then case $host_os in aix*) # The AIX port of GNU ld has always aspired to compatibility # with the native linker. However, as the warning in the GNU ld # block says, versions before 2.19.5* couldn't really create working # shared libraries, regardless of the interface used. case `$LD -v 2>&1` in *\ \(GNU\ Binutils\)\ 2.19.5*) ;; *\ \(GNU\ Binutils\)\ 2.[2-9]*) ;; *\ \(GNU\ Binutils\)\ [3-9]*) ;; *) lt_use_gnu_ld_interface=yes ;; esac ;; *) lt_use_gnu_ld_interface=yes ;; esac fi if test "$lt_use_gnu_ld_interface" = yes; then # If archive_cmds runs LD, not CC, wlarc should be empty wlarc='${wl}' # Set some defaults for GNU ld with shared library support. These # are reset later if shared libraries are not supported. Putting them # here allows them to be overridden if necessary. runpath_var=LD_RUN_PATH hardcode_libdir_flag_spec='${wl}-rpath ${wl}$libdir' export_dynamic_flag_spec='${wl}--export-dynamic' # ancient GNU ld didn't support --whole-archive et. al. if $LD --help 2>&1 | $GREP 'no-whole-archive' > /dev/null; then whole_archive_flag_spec="$wlarc"'--whole-archive$convenience '"$wlarc"'--no-whole-archive' else whole_archive_flag_spec= fi supports_anon_versioning=no case `$LD -v 2>&1` in *GNU\ gold*) supports_anon_versioning=yes ;; *\ [01].* | *\ 2.[0-9].* | *\ 2.10.*) ;; # catch versions < 2.11 *\ 2.11.93.0.2\ *) supports_anon_versioning=yes ;; # RH7.3 ... *\ 2.11.92.0.12\ *) supports_anon_versioning=yes ;; # Mandrake 8.2 ... *\ 2.11.*) ;; # other 2.11 versions *) supports_anon_versioning=yes ;; esac # See if GNU ld supports shared libraries. case $host_os in aix[3-9]*) # On AIX/PPC, the GNU linker is very broken if test "$host_cpu" != ia64; then ld_shlibs=no cat <<_LT_EOF 1>&2 *** Warning: the GNU linker, at least up to release 2.19, is reported *** to be unable to reliably create shared libraries on AIX. *** Therefore, libtool is disabling shared libraries support. If you *** really care for shared libraries, you may want to install binutils *** 2.20 or above, or modify your PATH so that a non-GNU linker is found. *** You will then need to restart the configuration process. _LT_EOF fi ;; amigaos*) case $host_cpu in powerpc) # see comment about AmigaOS4 .so support archive_cmds='$CC -shared $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname -o $lib' archive_expsym_cmds='' ;; m68k) archive_cmds='$RM $output_objdir/a2ixlibrary.data~$ECHO "#define NAME $libname" > $output_objdir/a2ixlibrary.data~$ECHO "#define LIBRARY_ID 1" >> $output_objdir/a2ixlibrary.data~$ECHO "#define VERSION $major" >> $output_objdir/a2ixlibrary.data~$ECHO "#define REVISION $revision" >> $output_objdir/a2ixlibrary.data~$AR $AR_FLAGS $lib $libobjs~$RANLIB $lib~(cd $output_objdir && a2ixlibrary -32)' hardcode_libdir_flag_spec='-L$libdir' hardcode_minus_L=yes ;; esac ;; beos*) if $LD --help 2>&1 | $GREP ': supported targets:.* elf' > /dev/null; then allow_undefined_flag=unsupported # Joseph Beckenbach says some releases of gcc # support --undefined. This deserves some investigation. FIXME archive_cmds='$CC -nostart $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname -o $lib' else ld_shlibs=no fi ;; cygwin* | mingw* | pw32* | cegcc*) # _LT_TAGVAR(hardcode_libdir_flag_spec, ) is actually meaningless, # as there is no search path for DLLs. hardcode_libdir_flag_spec='-L$libdir' export_dynamic_flag_spec='${wl}--export-all-symbols' allow_undefined_flag=unsupported always_export_symbols=no enable_shared_with_static_runtimes=yes export_symbols_cmds='$NM $libobjs $convenience | $global_symbol_pipe | $SED -e '\''/^[BCDGRS][ ]/s/.*[ ]\([^ ]*\)/\1 DATA/;s/^.*[ ]__nm__\([^ ]*\)[ ][^ ]*/\1 DATA/;/^I[ ]/d;/^[AITW][ ]/s/.* //'\'' | sort | uniq > $export_symbols' exclude_expsyms='[_]+GLOBAL_OFFSET_TABLE_|[_]+GLOBAL__[FID]_.*|[_]+head_[A-Za-z0-9_]+_dll|[A-Za-z0-9_]+_dll_iname' if $LD --help 2>&1 | $GREP 'auto-import' > /dev/null; then archive_cmds='$CC -shared $libobjs $deplibs $compiler_flags -o $output_objdir/$soname ${wl}--enable-auto-image-base -Xlinker --out-implib -Xlinker $lib' # If the export-symbols file already is a .def file (1st line # is EXPORTS), use it as is; otherwise, prepend... archive_expsym_cmds='if test "x`$SED 1q $export_symbols`" = xEXPORTS; then cp $export_symbols $output_objdir/$soname.def; else echo EXPORTS > $output_objdir/$soname.def; cat $export_symbols >> $output_objdir/$soname.def; fi~ $CC -shared $output_objdir/$soname.def $libobjs $deplibs $compiler_flags -o $output_objdir/$soname ${wl}--enable-auto-image-base -Xlinker --out-implib -Xlinker $lib' else ld_shlibs=no fi ;; haiku*) archive_cmds='$CC -shared $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname -o $lib' link_all_deplibs=yes ;; interix[3-9]*) hardcode_direct=no hardcode_shlibpath_var=no hardcode_libdir_flag_spec='${wl}-rpath,$libdir' export_dynamic_flag_spec='${wl}-E' # Hack: On Interix 3.x, we cannot compile PIC because of a broken gcc. # Instead, shared libraries are loaded at an image base (0x10000000 by # default) and relocated if they conflict, which is a slow very memory # consuming and fragmenting process. To avoid this, we pick a random, # 256 KiB-aligned image base between 0x50000000 and 0x6FFC0000 at link # time. Moving up from 0x10000000 also allows more sbrk(2) space. archive_cmds='$CC -shared $pic_flag $libobjs $deplibs $compiler_flags ${wl}-h,$soname ${wl}--image-base,`expr ${RANDOM-$$} % 4096 / 2 \* 262144 + 1342177280` -o $lib' archive_expsym_cmds='sed "s,^,_," $export_symbols >$output_objdir/$soname.expsym~$CC -shared $pic_flag $libobjs $deplibs $compiler_flags ${wl}-h,$soname ${wl}--retain-symbols-file,$output_objdir/$soname.expsym ${wl}--image-base,`expr ${RANDOM-$$} % 4096 / 2 \* 262144 + 1342177280` -o $lib' ;; gnu* | linux* | tpf* | k*bsd*-gnu | kopensolaris*-gnu) tmp_diet=no if test "$host_os" = linux-dietlibc; then case $cc_basename in diet\ *) tmp_diet=yes;; # linux-dietlibc with static linking (!diet-dyn) esac fi if $LD --help 2>&1 | $EGREP ': supported targets:.* elf' > /dev/null \ && test "$tmp_diet" = no then tmp_addflag=' $pic_flag' tmp_sharedflag='-shared' case $cc_basename,$host_cpu in pgcc*) # Portland Group C compiler whole_archive_flag_spec='${wl}--whole-archive`for conv in $convenience\"\"; do test -n \"$conv\" && new_convenience=\"$new_convenience,$conv\"; done; func_echo_all \"$new_convenience\"` ${wl}--no-whole-archive' tmp_addflag=' $pic_flag' ;; pgf77* | pgf90* | pgf95* | pgfortran*) # Portland Group f77 and f90 compilers whole_archive_flag_spec='${wl}--whole-archive`for conv in $convenience\"\"; do test -n \"$conv\" && new_convenience=\"$new_convenience,$conv\"; done; func_echo_all \"$new_convenience\"` ${wl}--no-whole-archive' tmp_addflag=' $pic_flag -Mnomain' ;; ecc*,ia64* | icc*,ia64*) # Intel C compiler on ia64 tmp_addflag=' -i_dynamic' ;; efc*,ia64* | ifort*,ia64*) # Intel Fortran compiler on ia64 tmp_addflag=' -i_dynamic -nofor_main' ;; ifc* | ifort*) # Intel Fortran compiler tmp_addflag=' -nofor_main' ;; lf95*) # Lahey Fortran 8.1 whole_archive_flag_spec= tmp_sharedflag='--shared' ;; xl[cC]* | bgxl[cC]* | mpixl[cC]*) # IBM XL C 8.0 on PPC (deal with xlf below) tmp_sharedflag='-qmkshrobj' tmp_addflag= ;; nvcc*) # Cuda Compiler Driver 2.2 whole_archive_flag_spec='${wl}--whole-archive`for conv in $convenience\"\"; do test -n \"$conv\" && new_convenience=\"$new_convenience,$conv\"; done; func_echo_all \"$new_convenience\"` ${wl}--no-whole-archive' compiler_needs_object=yes ;; esac case `$CC -V 2>&1 | sed 5q` in *Sun\ C*) # Sun C 5.9 whole_archive_flag_spec='${wl}--whole-archive`new_convenience=; for conv in $convenience\"\"; do test -z \"$conv\" || new_convenience=\"$new_convenience,$conv\"; done; func_echo_all \"$new_convenience\"` ${wl}--no-whole-archive' compiler_needs_object=yes tmp_sharedflag='-G' ;; *Sun\ F*) # Sun Fortran 8.3 tmp_sharedflag='-G' ;; esac archive_cmds='$CC '"$tmp_sharedflag""$tmp_addflag"' $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname -o $lib' if test "x$supports_anon_versioning" = xyes; then archive_expsym_cmds='echo "{ global:" > $output_objdir/$libname.ver~ cat $export_symbols | sed -e "s/\(.*\)/\1;/" >> $output_objdir/$libname.ver~ echo "local: *; };" >> $output_objdir/$libname.ver~ $CC '"$tmp_sharedflag""$tmp_addflag"' $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname ${wl}-version-script ${wl}$output_objdir/$libname.ver -o $lib' fi case $cc_basename in xlf* | bgf* | bgxlf* | mpixlf*) # IBM XL Fortran 10.1 on PPC cannot create shared libs itself whole_archive_flag_spec='--whole-archive$convenience --no-whole-archive' hardcode_libdir_flag_spec='${wl}-rpath ${wl}$libdir' archive_cmds='$LD -shared $libobjs $deplibs $linker_flags -soname $soname -o $lib' if test "x$supports_anon_versioning" = xyes; then archive_expsym_cmds='echo "{ global:" > $output_objdir/$libname.ver~ cat $export_symbols | sed -e "s/\(.*\)/\1;/" >> $output_objdir/$libname.ver~ echo "local: *; };" >> $output_objdir/$libname.ver~ $LD -shared $libobjs $deplibs $linker_flags -soname $soname -version-script $output_objdir/$libname.ver -o $lib' fi ;; esac else ld_shlibs=no fi ;; netbsd*) if echo __ELF__ | $CC -E - | $GREP __ELF__ >/dev/null; then archive_cmds='$LD -Bshareable $libobjs $deplibs $linker_flags -o $lib' wlarc= else archive_cmds='$CC -shared $pic_flag $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname -o $lib' archive_expsym_cmds='$CC -shared $pic_flag $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname ${wl}-retain-symbols-file $wl$export_symbols -o $lib' fi ;; solaris*) if $LD -v 2>&1 | $GREP 'BFD 2\.8' > /dev/null; then ld_shlibs=no cat <<_LT_EOF 1>&2 *** Warning: The releases 2.8.* of the GNU linker cannot reliably *** create shared libraries on Solaris systems. Therefore, libtool *** is disabling shared libraries support. We urge you to upgrade GNU *** binutils to release 2.9.1 or newer. Another option is to modify *** your PATH or compiler configuration so that the native linker is *** used, and then restart. _LT_EOF elif $LD --help 2>&1 | $GREP ': supported targets:.* elf' > /dev/null; then archive_cmds='$CC -shared $pic_flag $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname -o $lib' archive_expsym_cmds='$CC -shared $pic_flag $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname ${wl}-retain-symbols-file $wl$export_symbols -o $lib' else ld_shlibs=no fi ;; sysv5* | sco3.2v5* | sco5v6* | unixware* | OpenUNIX*) case `$LD -v 2>&1` in *\ [01].* | *\ 2.[0-9].* | *\ 2.1[0-5].*) ld_shlibs=no cat <<_LT_EOF 1>&2 *** Warning: Releases of the GNU linker prior to 2.16.91.0.3 can not *** reliably create shared libraries on SCO systems. Therefore, libtool *** is disabling shared libraries support. We urge you to upgrade GNU *** binutils to release 2.16.91.0.3 or newer. Another option is to modify *** your PATH or compiler configuration so that the native linker is *** used, and then restart. _LT_EOF ;; *) # For security reasons, it is highly recommended that you always # use absolute paths for naming shared libraries, and exclude the # DT_RUNPATH tag from executables and libraries. But doing so # requires that you compile everything twice, which is a pain. if $LD --help 2>&1 | $GREP ': supported targets:.* elf' > /dev/null; then hardcode_libdir_flag_spec='${wl}-rpath ${wl}$libdir' archive_cmds='$CC -shared $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname -o $lib' archive_expsym_cmds='$CC -shared $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname ${wl}-retain-symbols-file $wl$export_symbols -o $lib' else ld_shlibs=no fi ;; esac ;; sunos4*) archive_cmds='$LD -assert pure-text -Bshareable -o $lib $libobjs $deplibs $linker_flags' wlarc= hardcode_direct=yes hardcode_shlibpath_var=no ;; *) if $LD --help 2>&1 | $GREP ': supported targets:.* elf' > /dev/null; then archive_cmds='$CC -shared $pic_flag $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname -o $lib' archive_expsym_cmds='$CC -shared $pic_flag $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname ${wl}-retain-symbols-file $wl$export_symbols -o $lib' else ld_shlibs=no fi ;; esac if test "$ld_shlibs" = no; then runpath_var= hardcode_libdir_flag_spec= export_dynamic_flag_spec= whole_archive_flag_spec= fi else # PORTME fill in a description of your system's linker (not GNU ld) case $host_os in aix3*) allow_undefined_flag=unsupported always_export_symbols=yes archive_expsym_cmds='$LD -o $output_objdir/$soname $libobjs $deplibs $linker_flags -bE:$export_symbols -T512 -H512 -bM:SRE~$AR $AR_FLAGS $lib $output_objdir/$soname' # Note: this linker hardcodes the directories in LIBPATH if there # are no directories specified by -L. hardcode_minus_L=yes if test "$GCC" = yes && test -z "$lt_prog_compiler_static"; then # Neither direct hardcoding nor static linking is supported with a # broken collect2. hardcode_direct=unsupported fi ;; aix[4-9]*) if test "$host_cpu" = ia64; then # On IA64, the linker does run time linking by default, so we don't # have to do anything special. aix_use_runtimelinking=no exp_sym_flag='-Bexport' no_entry_flag="" else # If we're using GNU nm, then we don't want the "-C" option. # -C means demangle to AIX nm, but means don't demangle with GNU nm # Also, AIX nm treats weak defined symbols like other global # defined symbols, whereas GNU nm marks them as "W". if $NM -V 2>&1 | $GREP 'GNU' > /dev/null; then export_symbols_cmds='$NM -Bpg $libobjs $convenience | awk '\''{ if (((\$ 2 == "T") || (\$ 2 == "D") || (\$ 2 == "B") || (\$ 2 == "W")) && (substr(\$ 3,1,1) != ".")) { print \$ 3 } }'\'' | sort -u > $export_symbols' else export_symbols_cmds='$NM -BCpg $libobjs $convenience | awk '\''{ if (((\$ 2 == "T") || (\$ 2 == "D") || (\$ 2 == "B")) && (substr(\$ 3,1,1) != ".")) { print \$ 3 } }'\'' | sort -u > $export_symbols' fi aix_use_runtimelinking=no # Test if we are trying to use run time linking or normal # AIX style linking. If -brtl is somewhere in LDFLAGS, we # need to do runtime linking. case $host_os in aix4.[23]|aix4.[23].*|aix[5-9]*) for ld_flag in $LDFLAGS; do if (test $ld_flag = "-brtl" || test $ld_flag = "-Wl,-brtl"); then aix_use_runtimelinking=yes break fi done ;; esac exp_sym_flag='-bexport' no_entry_flag='-bnoentry' fi # When large executables or shared objects are built, AIX ld can # have problems creating the table of contents. If linking a library # or program results in "error TOC overflow" add -mminimal-toc to # CXXFLAGS/CFLAGS for g++/gcc. In the cases where that is not # enough to fix the problem, add -Wl,-bbigtoc to LDFLAGS. archive_cmds='' hardcode_direct=yes hardcode_direct_absolute=yes hardcode_libdir_separator=':' link_all_deplibs=yes file_list_spec='${wl}-f,' if test "$GCC" = yes; then case $host_os in aix4.[012]|aix4.[012].*) # We only want to do this on AIX 4.2 and lower, the check # below for broken collect2 doesn't work under 4.3+ collect2name=`${CC} -print-prog-name=collect2` if test -f "$collect2name" && strings "$collect2name" | $GREP resolve_lib_name >/dev/null then # We have reworked collect2 : else # We have old collect2 hardcode_direct=unsupported # It fails to find uninstalled libraries when the uninstalled # path is not listed in the libpath. Setting hardcode_minus_L # to unsupported forces relinking hardcode_minus_L=yes hardcode_libdir_flag_spec='-L$libdir' hardcode_libdir_separator= fi ;; esac shared_flag='-shared' if test "$aix_use_runtimelinking" = yes; then shared_flag="$shared_flag "'${wl}-G' fi else # not using gcc if test "$host_cpu" = ia64; then # VisualAge C++, Version 5.5 for AIX 5L for IA-64, Beta 3 Release # chokes on -Wl,-G. The following line is correct: shared_flag='-G' else if test "$aix_use_runtimelinking" = yes; then shared_flag='${wl}-G' else shared_flag='${wl}-bM:SRE' fi fi fi export_dynamic_flag_spec='${wl}-bexpall' # It seems that -bexpall does not export symbols beginning with # underscore (_), so it is better to generate a list of symbols to export. always_export_symbols=yes if test "$aix_use_runtimelinking" = yes; then # Warning - without using the other runtime loading flags (-brtl), # -berok will link without error, but may produce a broken library. allow_undefined_flag='-berok' # Determine the default libpath from the value encoded in an # empty executable. if test "${lt_cv_aix_libpath+set}" = set; then aix_libpath=$lt_cv_aix_libpath else if ${lt_cv_aix_libpath_+:} false; then : $as_echo_n "(cached) " >&6 else cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ int main () { ; return 0; } _ACEOF if ac_fn_c_try_link "$LINENO"; then : lt_aix_libpath_sed=' /Import File Strings/,/^$/ { /^0/ { s/^0 *\([^ ]*\) *$/\1/ p } }' lt_cv_aix_libpath_=`dump -H conftest$ac_exeext 2>/dev/null | $SED -n -e "$lt_aix_libpath_sed"` # Check for a 64-bit object if we didn't find anything. if test -z "$lt_cv_aix_libpath_"; then lt_cv_aix_libpath_=`dump -HX64 conftest$ac_exeext 2>/dev/null | $SED -n -e "$lt_aix_libpath_sed"` fi fi rm -f core conftest.err conftest.$ac_objext \ conftest$ac_exeext conftest.$ac_ext if test -z "$lt_cv_aix_libpath_"; then lt_cv_aix_libpath_="/usr/lib:/lib" fi fi aix_libpath=$lt_cv_aix_libpath_ fi hardcode_libdir_flag_spec='${wl}-blibpath:$libdir:'"$aix_libpath" archive_expsym_cmds='$CC -o $output_objdir/$soname $libobjs $deplibs '"\${wl}$no_entry_flag"' $compiler_flags `if test "x${allow_undefined_flag}" != "x"; then func_echo_all "${wl}${allow_undefined_flag}"; else :; fi` '"\${wl}$exp_sym_flag:\$export_symbols $shared_flag" else if test "$host_cpu" = ia64; then hardcode_libdir_flag_spec='${wl}-R $libdir:/usr/lib:/lib' allow_undefined_flag="-z nodefs" archive_expsym_cmds="\$CC $shared_flag"' -o $output_objdir/$soname $libobjs $deplibs '"\${wl}$no_entry_flag"' $compiler_flags ${wl}${allow_undefined_flag} '"\${wl}$exp_sym_flag:\$export_symbols" else # Determine the default libpath from the value encoded in an # empty executable. if test "${lt_cv_aix_libpath+set}" = set; then aix_libpath=$lt_cv_aix_libpath else if ${lt_cv_aix_libpath_+:} false; then : $as_echo_n "(cached) " >&6 else cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ int main () { ; return 0; } _ACEOF if ac_fn_c_try_link "$LINENO"; then : lt_aix_libpath_sed=' /Import File Strings/,/^$/ { /^0/ { s/^0 *\([^ ]*\) *$/\1/ p } }' lt_cv_aix_libpath_=`dump -H conftest$ac_exeext 2>/dev/null | $SED -n -e "$lt_aix_libpath_sed"` # Check for a 64-bit object if we didn't find anything. if test -z "$lt_cv_aix_libpath_"; then lt_cv_aix_libpath_=`dump -HX64 conftest$ac_exeext 2>/dev/null | $SED -n -e "$lt_aix_libpath_sed"` fi fi rm -f core conftest.err conftest.$ac_objext \ conftest$ac_exeext conftest.$ac_ext if test -z "$lt_cv_aix_libpath_"; then lt_cv_aix_libpath_="/usr/lib:/lib" fi fi aix_libpath=$lt_cv_aix_libpath_ fi hardcode_libdir_flag_spec='${wl}-blibpath:$libdir:'"$aix_libpath" # Warning - without using the other run time loading flags, # -berok will link without error, but may produce a broken library. no_undefined_flag=' ${wl}-bernotok' allow_undefined_flag=' ${wl}-berok' if test "$with_gnu_ld" = yes; then # We only use this code for GNU lds that support --whole-archive. whole_archive_flag_spec='${wl}--whole-archive$convenience ${wl}--no-whole-archive' else # Exported symbols can be pulled into shared objects from archives whole_archive_flag_spec='$convenience' fi archive_cmds_need_lc=yes # This is similar to how AIX traditionally builds its shared libraries. archive_expsym_cmds="\$CC $shared_flag"' -o $output_objdir/$soname $libobjs $deplibs ${wl}-bnoentry $compiler_flags ${wl}-bE:$export_symbols${allow_undefined_flag}~$AR $AR_FLAGS $output_objdir/$libname$release.a $output_objdir/$soname' fi fi ;; amigaos*) case $host_cpu in powerpc) # see comment about AmigaOS4 .so support archive_cmds='$CC -shared $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname -o $lib' archive_expsym_cmds='' ;; m68k) archive_cmds='$RM $output_objdir/a2ixlibrary.data~$ECHO "#define NAME $libname" > $output_objdir/a2ixlibrary.data~$ECHO "#define LIBRARY_ID 1" >> $output_objdir/a2ixlibrary.data~$ECHO "#define VERSION $major" >> $output_objdir/a2ixlibrary.data~$ECHO "#define REVISION $revision" >> $output_objdir/a2ixlibrary.data~$AR $AR_FLAGS $lib $libobjs~$RANLIB $lib~(cd $output_objdir && a2ixlibrary -32)' hardcode_libdir_flag_spec='-L$libdir' hardcode_minus_L=yes ;; esac ;; bsdi[45]*) export_dynamic_flag_spec=-rdynamic ;; cygwin* | mingw* | pw32* | cegcc*) # When not using gcc, we currently assume that we are using # Microsoft Visual C++. # hardcode_libdir_flag_spec is actually meaningless, as there is # no search path for DLLs. case $cc_basename in cl*) # Native MSVC hardcode_libdir_flag_spec=' ' allow_undefined_flag=unsupported always_export_symbols=yes file_list_spec='@' # Tell ltmain to make .lib files, not .a files. libext=lib # Tell ltmain to make .dll files, not .so files. shrext_cmds=".dll" # FIXME: Setting linknames here is a bad hack. archive_cmds='$CC -o $output_objdir/$soname $libobjs $compiler_flags $deplibs -Wl,-dll~linknames=' archive_expsym_cmds='if test "x`$SED 1q $export_symbols`" = xEXPORTS; then sed -n -e 's/\\\\\\\(.*\\\\\\\)/-link\\\ -EXPORT:\\\\\\\1/' -e '1\\\!p' < $export_symbols > $output_objdir/$soname.exp; else sed -e 's/\\\\\\\(.*\\\\\\\)/-link\\\ -EXPORT:\\\\\\\1/' < $export_symbols > $output_objdir/$soname.exp; fi~ $CC -o $tool_output_objdir$soname $libobjs $compiler_flags $deplibs "@$tool_output_objdir$soname.exp" -Wl,-DLL,-IMPLIB:"$tool_output_objdir$libname.dll.lib"~ linknames=' # The linker will not automatically build a static lib if we build a DLL. # _LT_TAGVAR(old_archive_from_new_cmds, )='true' enable_shared_with_static_runtimes=yes exclude_expsyms='_NULL_IMPORT_DESCRIPTOR|_IMPORT_DESCRIPTOR_.*' export_symbols_cmds='$NM $libobjs $convenience | $global_symbol_pipe | $SED -e '\''/^[BCDGRS][ ]/s/.*[ ]\([^ ]*\)/\1,DATA/'\'' | $SED -e '\''/^[AITW][ ]/s/.*[ ]//'\'' | sort | uniq > $export_symbols' # Don't use ranlib old_postinstall_cmds='chmod 644 $oldlib' postlink_cmds='lt_outputfile="@OUTPUT@"~ lt_tool_outputfile="@TOOL_OUTPUT@"~ case $lt_outputfile in *.exe|*.EXE) ;; *) lt_outputfile="$lt_outputfile.exe" lt_tool_outputfile="$lt_tool_outputfile.exe" ;; esac~ if test "$MANIFEST_TOOL" != ":" && test -f "$lt_outputfile.manifest"; then $MANIFEST_TOOL -manifest "$lt_tool_outputfile.manifest" -outputresource:"$lt_tool_outputfile" || exit 1; $RM "$lt_outputfile.manifest"; fi' ;; *) # Assume MSVC wrapper hardcode_libdir_flag_spec=' ' allow_undefined_flag=unsupported # Tell ltmain to make .lib files, not .a files. libext=lib # Tell ltmain to make .dll files, not .so files. shrext_cmds=".dll" # FIXME: Setting linknames here is a bad hack. archive_cmds='$CC -o $lib $libobjs $compiler_flags `func_echo_all "$deplibs" | $SED '\''s/ -lc$//'\''` -link -dll~linknames=' # The linker will automatically build a .lib file if we build a DLL. old_archive_from_new_cmds='true' # FIXME: Should let the user specify the lib program. old_archive_cmds='lib -OUT:$oldlib$oldobjs$old_deplibs' enable_shared_with_static_runtimes=yes ;; esac ;; darwin* | rhapsody*) archive_cmds_need_lc=no hardcode_direct=no hardcode_automatic=yes hardcode_shlibpath_var=unsupported if test "$lt_cv_ld_force_load" = "yes"; then whole_archive_flag_spec='`for conv in $convenience\"\"; do test -n \"$conv\" && new_convenience=\"$new_convenience ${wl}-force_load,$conv\"; done; func_echo_all \"$new_convenience\"`' else whole_archive_flag_spec='' fi link_all_deplibs=yes allow_undefined_flag="$_lt_dar_allow_undefined" case $cc_basename in ifort*) _lt_dar_can_shared=yes ;; *) _lt_dar_can_shared=$GCC ;; esac if test "$_lt_dar_can_shared" = "yes"; then output_verbose_link_cmd=func_echo_all archive_cmds="\$CC -dynamiclib \$allow_undefined_flag -o \$lib \$libobjs \$deplibs \$compiler_flags -install_name \$rpath/\$soname \$verstring $_lt_dar_single_mod${_lt_dsymutil}" module_cmds="\$CC \$allow_undefined_flag -o \$lib -bundle \$libobjs \$deplibs \$compiler_flags${_lt_dsymutil}" archive_expsym_cmds="sed 's,^,_,' < \$export_symbols > \$output_objdir/\${libname}-symbols.expsym~\$CC -dynamiclib \$allow_undefined_flag -o \$lib \$libobjs \$deplibs \$compiler_flags -install_name \$rpath/\$soname \$verstring ${_lt_dar_single_mod}${_lt_dar_export_syms}${_lt_dsymutil}" module_expsym_cmds="sed -e 's,^,_,' < \$export_symbols > \$output_objdir/\${libname}-symbols.expsym~\$CC \$allow_undefined_flag -o \$lib -bundle \$libobjs \$deplibs \$compiler_flags${_lt_dar_export_syms}${_lt_dsymutil}" else ld_shlibs=no fi ;; dgux*) archive_cmds='$LD -G -h $soname -o $lib $libobjs $deplibs $linker_flags' hardcode_libdir_flag_spec='-L$libdir' hardcode_shlibpath_var=no ;; # FreeBSD 2.2.[012] allows us to include c++rt0.o to get C++ constructor # support. Future versions do this automatically, but an explicit c++rt0.o # does not break anything, and helps significantly (at the cost of a little # extra space). freebsd2.2*) archive_cmds='$LD -Bshareable -o $lib $libobjs $deplibs $linker_flags /usr/lib/c++rt0.o' hardcode_libdir_flag_spec='-R$libdir' hardcode_direct=yes hardcode_shlibpath_var=no ;; # Unfortunately, older versions of FreeBSD 2 do not have this feature. freebsd2.*) archive_cmds='$LD -Bshareable -o $lib $libobjs $deplibs $linker_flags' hardcode_direct=yes hardcode_minus_L=yes hardcode_shlibpath_var=no ;; # FreeBSD 3 and greater uses gcc -shared to do shared libraries. freebsd* | dragonfly*) archive_cmds='$CC -shared $pic_flag -o $lib $libobjs $deplibs $compiler_flags' hardcode_libdir_flag_spec='-R$libdir' hardcode_direct=yes hardcode_shlibpath_var=no ;; hpux9*) if test "$GCC" = yes; then archive_cmds='$RM $output_objdir/$soname~$CC -shared $pic_flag ${wl}+b ${wl}$install_libdir -o $output_objdir/$soname $libobjs $deplibs $compiler_flags~test $output_objdir/$soname = $lib || mv $output_objdir/$soname $lib' else archive_cmds='$RM $output_objdir/$soname~$LD -b +b $install_libdir -o $output_objdir/$soname $libobjs $deplibs $linker_flags~test $output_objdir/$soname = $lib || mv $output_objdir/$soname $lib' fi hardcode_libdir_flag_spec='${wl}+b ${wl}$libdir' hardcode_libdir_separator=: hardcode_direct=yes # hardcode_minus_L: Not really in the search PATH, # but as the default location of the library. hardcode_minus_L=yes export_dynamic_flag_spec='${wl}-E' ;; hpux10*) if test "$GCC" = yes && test "$with_gnu_ld" = no; then archive_cmds='$CC -shared $pic_flag ${wl}+h ${wl}$soname ${wl}+b ${wl}$install_libdir -o $lib $libobjs $deplibs $compiler_flags' else archive_cmds='$LD -b +h $soname +b $install_libdir -o $lib $libobjs $deplibs $linker_flags' fi if test "$with_gnu_ld" = no; then hardcode_libdir_flag_spec='${wl}+b ${wl}$libdir' hardcode_libdir_separator=: hardcode_direct=yes hardcode_direct_absolute=yes export_dynamic_flag_spec='${wl}-E' # hardcode_minus_L: Not really in the search PATH, # but as the default location of the library. hardcode_minus_L=yes fi ;; hpux11*) if test "$GCC" = yes && test "$with_gnu_ld" = no; then case $host_cpu in hppa*64*) archive_cmds='$CC -shared ${wl}+h ${wl}$soname -o $lib $libobjs $deplibs $compiler_flags' ;; ia64*) archive_cmds='$CC -shared $pic_flag ${wl}+h ${wl}$soname ${wl}+nodefaultrpath -o $lib $libobjs $deplibs $compiler_flags' ;; *) archive_cmds='$CC -shared $pic_flag ${wl}+h ${wl}$soname ${wl}+b ${wl}$install_libdir -o $lib $libobjs $deplibs $compiler_flags' ;; esac else case $host_cpu in hppa*64*) archive_cmds='$CC -b ${wl}+h ${wl}$soname -o $lib $libobjs $deplibs $compiler_flags' ;; ia64*) archive_cmds='$CC -b ${wl}+h ${wl}$soname ${wl}+nodefaultrpath -o $lib $libobjs $deplibs $compiler_flags' ;; *) # Older versions of the 11.00 compiler do not understand -b yet # (HP92453-01 A.11.01.20 doesn't, HP92453-01 B.11.X.35175-35176.GP does) { $as_echo "$as_me:${as_lineno-$LINENO}: checking if $CC understands -b" >&5 $as_echo_n "checking if $CC understands -b... " >&6; } if ${lt_cv_prog_compiler__b+:} false; then : $as_echo_n "(cached) " >&6 else lt_cv_prog_compiler__b=no save_LDFLAGS="$LDFLAGS" LDFLAGS="$LDFLAGS -b" echo "$lt_simple_link_test_code" > conftest.$ac_ext if (eval $ac_link 2>conftest.err) && test -s conftest$ac_exeext; then # The linker can only warn and ignore the option if not recognized # So say no if there are warnings if test -s conftest.err; then # Append any errors to the config.log. cat conftest.err 1>&5 $ECHO "$_lt_linker_boilerplate" | $SED '/^$/d' > conftest.exp $SED '/^$/d; /^ *+/d' conftest.err >conftest.er2 if diff conftest.exp conftest.er2 >/dev/null; then lt_cv_prog_compiler__b=yes fi else lt_cv_prog_compiler__b=yes fi fi $RM -r conftest* LDFLAGS="$save_LDFLAGS" fi { $as_echo "$as_me:${as_lineno-$LINENO}: result: $lt_cv_prog_compiler__b" >&5 $as_echo "$lt_cv_prog_compiler__b" >&6; } if test x"$lt_cv_prog_compiler__b" = xyes; then archive_cmds='$CC -b ${wl}+h ${wl}$soname ${wl}+b ${wl}$install_libdir -o $lib $libobjs $deplibs $compiler_flags' else archive_cmds='$LD -b +h $soname +b $install_libdir -o $lib $libobjs $deplibs $linker_flags' fi ;; esac fi if test "$with_gnu_ld" = no; then hardcode_libdir_flag_spec='${wl}+b ${wl}$libdir' hardcode_libdir_separator=: case $host_cpu in hppa*64*|ia64*) hardcode_direct=no hardcode_shlibpath_var=no ;; *) hardcode_direct=yes hardcode_direct_absolute=yes export_dynamic_flag_spec='${wl}-E' # hardcode_minus_L: Not really in the search PATH, # but as the default location of the library. hardcode_minus_L=yes ;; esac fi ;; irix5* | irix6* | nonstopux*) if test "$GCC" = yes; then archive_cmds='$CC -shared $pic_flag $libobjs $deplibs $compiler_flags ${wl}-soname ${wl}$soname `test -n "$verstring" && func_echo_all "${wl}-set_version ${wl}$verstring"` ${wl}-update_registry ${wl}${output_objdir}/so_locations -o $lib' # Try to use the -exported_symbol ld option, if it does not # work, assume that -exports_file does not work either and # implicitly export all symbols. # This should be the same for all languages, so no per-tag cache variable. { $as_echo "$as_me:${as_lineno-$LINENO}: checking whether the $host_os linker accepts -exported_symbol" >&5 $as_echo_n "checking whether the $host_os linker accepts -exported_symbol... " >&6; } if ${lt_cv_irix_exported_symbol+:} false; then : $as_echo_n "(cached) " >&6 else save_LDFLAGS="$LDFLAGS" LDFLAGS="$LDFLAGS -shared ${wl}-exported_symbol ${wl}foo ${wl}-update_registry ${wl}/dev/null" cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ int foo (void) { return 0; } _ACEOF if ac_fn_c_try_link "$LINENO"; then : lt_cv_irix_exported_symbol=yes else lt_cv_irix_exported_symbol=no fi rm -f core conftest.err conftest.$ac_objext \ conftest$ac_exeext conftest.$ac_ext LDFLAGS="$save_LDFLAGS" fi { $as_echo "$as_me:${as_lineno-$LINENO}: result: $lt_cv_irix_exported_symbol" >&5 $as_echo "$lt_cv_irix_exported_symbol" >&6; } if test "$lt_cv_irix_exported_symbol" = yes; then archive_expsym_cmds='$CC -shared $pic_flag $libobjs $deplibs $compiler_flags ${wl}-soname ${wl}$soname `test -n "$verstring" && func_echo_all "${wl}-set_version ${wl}$verstring"` ${wl}-update_registry ${wl}${output_objdir}/so_locations ${wl}-exports_file ${wl}$export_symbols -o $lib' fi else archive_cmds='$CC -shared $libobjs $deplibs $compiler_flags -soname $soname `test -n "$verstring" && func_echo_all "-set_version $verstring"` -update_registry ${output_objdir}/so_locations -o $lib' archive_expsym_cmds='$CC -shared $libobjs $deplibs $compiler_flags -soname $soname `test -n "$verstring" && func_echo_all "-set_version $verstring"` -update_registry ${output_objdir}/so_locations -exports_file $export_symbols -o $lib' fi archive_cmds_need_lc='no' hardcode_libdir_flag_spec='${wl}-rpath ${wl}$libdir' hardcode_libdir_separator=: inherit_rpath=yes link_all_deplibs=yes ;; netbsd*) if echo __ELF__ | $CC -E - | $GREP __ELF__ >/dev/null; then archive_cmds='$LD -Bshareable -o $lib $libobjs $deplibs $linker_flags' # a.out else archive_cmds='$LD -shared -o $lib $libobjs $deplibs $linker_flags' # ELF fi hardcode_libdir_flag_spec='-R$libdir' hardcode_direct=yes hardcode_shlibpath_var=no ;; newsos6) archive_cmds='$LD -G -h $soname -o $lib $libobjs $deplibs $linker_flags' hardcode_direct=yes hardcode_libdir_flag_spec='${wl}-rpath ${wl}$libdir' hardcode_libdir_separator=: hardcode_shlibpath_var=no ;; *nto* | *qnx*) ;; openbsd*) if test -f /usr/libexec/ld.so; then hardcode_direct=yes hardcode_shlibpath_var=no hardcode_direct_absolute=yes if test -z "`echo __ELF__ | $CC -E - | $GREP __ELF__`" || test "$host_os-$host_cpu" = "openbsd2.8-powerpc"; then archive_cmds='$CC -shared $pic_flag -o $lib $libobjs $deplibs $compiler_flags' archive_expsym_cmds='$CC -shared $pic_flag -o $lib $libobjs $deplibs $compiler_flags ${wl}-retain-symbols-file,$export_symbols' hardcode_libdir_flag_spec='${wl}-rpath,$libdir' export_dynamic_flag_spec='${wl}-E' else case $host_os in openbsd[01].* | openbsd2.[0-7] | openbsd2.[0-7].*) archive_cmds='$LD -Bshareable -o $lib $libobjs $deplibs $linker_flags' hardcode_libdir_flag_spec='-R$libdir' ;; *) archive_cmds='$CC -shared $pic_flag -o $lib $libobjs $deplibs $compiler_flags' hardcode_libdir_flag_spec='${wl}-rpath,$libdir' ;; esac fi else ld_shlibs=no fi ;; os2*) hardcode_libdir_flag_spec='-L$libdir' hardcode_minus_L=yes allow_undefined_flag=unsupported archive_cmds='$ECHO "LIBRARY $libname INITINSTANCE" > $output_objdir/$libname.def~$ECHO "DESCRIPTION \"$libname\"" >> $output_objdir/$libname.def~echo DATA >> $output_objdir/$libname.def~echo " SINGLE NONSHARED" >> $output_objdir/$libname.def~echo EXPORTS >> $output_objdir/$libname.def~emxexp $libobjs >> $output_objdir/$libname.def~$CC -Zdll -Zcrtdll -o $lib $libobjs $deplibs $compiler_flags $output_objdir/$libname.def' old_archive_from_new_cmds='emximp -o $output_objdir/$libname.a $output_objdir/$libname.def' ;; osf3*) if test "$GCC" = yes; then allow_undefined_flag=' ${wl}-expect_unresolved ${wl}\*' archive_cmds='$CC -shared${allow_undefined_flag} $libobjs $deplibs $compiler_flags ${wl}-soname ${wl}$soname `test -n "$verstring" && func_echo_all "${wl}-set_version ${wl}$verstring"` ${wl}-update_registry ${wl}${output_objdir}/so_locations -o $lib' else allow_undefined_flag=' -expect_unresolved \*' archive_cmds='$CC -shared${allow_undefined_flag} $libobjs $deplibs $compiler_flags -soname $soname `test -n "$verstring" && func_echo_all "-set_version $verstring"` -update_registry ${output_objdir}/so_locations -o $lib' fi archive_cmds_need_lc='no' hardcode_libdir_flag_spec='${wl}-rpath ${wl}$libdir' hardcode_libdir_separator=: ;; osf4* | osf5*) # as osf3* with the addition of -msym flag if test "$GCC" = yes; then allow_undefined_flag=' ${wl}-expect_unresolved ${wl}\*' archive_cmds='$CC -shared${allow_undefined_flag} $pic_flag $libobjs $deplibs $compiler_flags ${wl}-msym ${wl}-soname ${wl}$soname `test -n "$verstring" && func_echo_all "${wl}-set_version ${wl}$verstring"` ${wl}-update_registry ${wl}${output_objdir}/so_locations -o $lib' hardcode_libdir_flag_spec='${wl}-rpath ${wl}$libdir' else allow_undefined_flag=' -expect_unresolved \*' archive_cmds='$CC -shared${allow_undefined_flag} $libobjs $deplibs $compiler_flags -msym -soname $soname `test -n "$verstring" && func_echo_all "-set_version $verstring"` -update_registry ${output_objdir}/so_locations -o $lib' archive_expsym_cmds='for i in `cat $export_symbols`; do printf "%s %s\\n" -exported_symbol "\$i" >> $lib.exp; done; printf "%s\\n" "-hidden">> $lib.exp~ $CC -shared${allow_undefined_flag} ${wl}-input ${wl}$lib.exp $compiler_flags $libobjs $deplibs -soname $soname `test -n "$verstring" && $ECHO "-set_version $verstring"` -update_registry ${output_objdir}/so_locations -o $lib~$RM $lib.exp' # Both c and cxx compiler support -rpath directly hardcode_libdir_flag_spec='-rpath $libdir' fi archive_cmds_need_lc='no' hardcode_libdir_separator=: ;; solaris*) no_undefined_flag=' -z defs' if test "$GCC" = yes; then wlarc='${wl}' archive_cmds='$CC -shared $pic_flag ${wl}-z ${wl}text ${wl}-h ${wl}$soname -o $lib $libobjs $deplibs $compiler_flags' archive_expsym_cmds='echo "{ global:" > $lib.exp~cat $export_symbols | $SED -e "s/\(.*\)/\1;/" >> $lib.exp~echo "local: *; };" >> $lib.exp~ $CC -shared $pic_flag ${wl}-z ${wl}text ${wl}-M ${wl}$lib.exp ${wl}-h ${wl}$soname -o $lib $libobjs $deplibs $compiler_flags~$RM $lib.exp' else case `$CC -V 2>&1` in *"Compilers 5.0"*) wlarc='' archive_cmds='$LD -G${allow_undefined_flag} -h $soname -o $lib $libobjs $deplibs $linker_flags' archive_expsym_cmds='echo "{ global:" > $lib.exp~cat $export_symbols | $SED -e "s/\(.*\)/\1;/" >> $lib.exp~echo "local: *; };" >> $lib.exp~ $LD -G${allow_undefined_flag} -M $lib.exp -h $soname -o $lib $libobjs $deplibs $linker_flags~$RM $lib.exp' ;; *) wlarc='${wl}' archive_cmds='$CC -G${allow_undefined_flag} -h $soname -o $lib $libobjs $deplibs $compiler_flags' archive_expsym_cmds='echo "{ global:" > $lib.exp~cat $export_symbols | $SED -e "s/\(.*\)/\1;/" >> $lib.exp~echo "local: *; };" >> $lib.exp~ $CC -G${allow_undefined_flag} -M $lib.exp -h $soname -o $lib $libobjs $deplibs $compiler_flags~$RM $lib.exp' ;; esac fi hardcode_libdir_flag_spec='-R$libdir' hardcode_shlibpath_var=no case $host_os in solaris2.[0-5] | solaris2.[0-5].*) ;; *) # The compiler driver will combine and reorder linker options, # but understands `-z linker_flag'. GCC discards it without `$wl', # but is careful enough not to reorder. # Supported since Solaris 2.6 (maybe 2.5.1?) if test "$GCC" = yes; then whole_archive_flag_spec='${wl}-z ${wl}allextract$convenience ${wl}-z ${wl}defaultextract' else whole_archive_flag_spec='-z allextract$convenience -z defaultextract' fi ;; esac link_all_deplibs=yes ;; sunos4*) if test "x$host_vendor" = xsequent; then # Use $CC to link under sequent, because it throws in some extra .o # files that make .init and .fini sections work. archive_cmds='$CC -G ${wl}-h $soname -o $lib $libobjs $deplibs $compiler_flags' else archive_cmds='$LD -assert pure-text -Bstatic -o $lib $libobjs $deplibs $linker_flags' fi hardcode_libdir_flag_spec='-L$libdir' hardcode_direct=yes hardcode_minus_L=yes hardcode_shlibpath_var=no ;; sysv4) case $host_vendor in sni) archive_cmds='$LD -G -h $soname -o $lib $libobjs $deplibs $linker_flags' hardcode_direct=yes # is this really true??? ;; siemens) ## LD is ld it makes a PLAMLIB ## CC just makes a GrossModule. archive_cmds='$LD -G -o $lib $libobjs $deplibs $linker_flags' reload_cmds='$CC -r -o $output$reload_objs' hardcode_direct=no ;; motorola) archive_cmds='$LD -G -h $soname -o $lib $libobjs $deplibs $linker_flags' hardcode_direct=no #Motorola manual says yes, but my tests say they lie ;; esac runpath_var='LD_RUN_PATH' hardcode_shlibpath_var=no ;; sysv4.3*) archive_cmds='$LD -G -h $soname -o $lib $libobjs $deplibs $linker_flags' hardcode_shlibpath_var=no export_dynamic_flag_spec='-Bexport' ;; sysv4*MP*) if test -d /usr/nec; then archive_cmds='$LD -G -h $soname -o $lib $libobjs $deplibs $linker_flags' hardcode_shlibpath_var=no runpath_var=LD_RUN_PATH hardcode_runpath_var=yes ld_shlibs=yes fi ;; sysv4*uw2* | sysv5OpenUNIX* | sysv5UnixWare7.[01].[10]* | unixware7* | sco3.2v5.0.[024]*) no_undefined_flag='${wl}-z,text' archive_cmds_need_lc=no hardcode_shlibpath_var=no runpath_var='LD_RUN_PATH' if test "$GCC" = yes; then archive_cmds='$CC -shared ${wl}-h,$soname -o $lib $libobjs $deplibs $compiler_flags' archive_expsym_cmds='$CC -shared ${wl}-Bexport:$export_symbols ${wl}-h,$soname -o $lib $libobjs $deplibs $compiler_flags' else archive_cmds='$CC -G ${wl}-h,$soname -o $lib $libobjs $deplibs $compiler_flags' archive_expsym_cmds='$CC -G ${wl}-Bexport:$export_symbols ${wl}-h,$soname -o $lib $libobjs $deplibs $compiler_flags' fi ;; sysv5* | sco3.2v5* | sco5v6*) # Note: We can NOT use -z defs as we might desire, because we do not # link with -lc, and that would cause any symbols used from libc to # always be unresolved, which means just about no library would # ever link correctly. If we're not using GNU ld we use -z text # though, which does catch some bad symbols but isn't as heavy-handed # as -z defs. no_undefined_flag='${wl}-z,text' allow_undefined_flag='${wl}-z,nodefs' archive_cmds_need_lc=no hardcode_shlibpath_var=no hardcode_libdir_flag_spec='${wl}-R,$libdir' hardcode_libdir_separator=':' link_all_deplibs=yes export_dynamic_flag_spec='${wl}-Bexport' runpath_var='LD_RUN_PATH' if test "$GCC" = yes; then archive_cmds='$CC -shared ${wl}-h,$soname -o $lib $libobjs $deplibs $compiler_flags' archive_expsym_cmds='$CC -shared ${wl}-Bexport:$export_symbols ${wl}-h,$soname -o $lib $libobjs $deplibs $compiler_flags' else archive_cmds='$CC -G ${wl}-h,$soname -o $lib $libobjs $deplibs $compiler_flags' archive_expsym_cmds='$CC -G ${wl}-Bexport:$export_symbols ${wl}-h,$soname -o $lib $libobjs $deplibs $compiler_flags' fi ;; uts4*) archive_cmds='$LD -G -h $soname -o $lib $libobjs $deplibs $linker_flags' hardcode_libdir_flag_spec='-L$libdir' hardcode_shlibpath_var=no ;; *) ld_shlibs=no ;; esac if test x$host_vendor = xsni; then case $host in sysv4 | sysv4.2uw2* | sysv4.3* | sysv5*) export_dynamic_flag_spec='${wl}-Blargedynsym' ;; esac fi fi { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ld_shlibs" >&5 $as_echo "$ld_shlibs" >&6; } test "$ld_shlibs" = no && can_build_shared=no with_gnu_ld=$with_gnu_ld # # Do we need to explicitly link libc? # case "x$archive_cmds_need_lc" in x|xyes) # Assume -lc should be added archive_cmds_need_lc=yes if test "$enable_shared" = yes && test "$GCC" = yes; then case $archive_cmds in *'~'*) # FIXME: we may have to deal with multi-command sequences. ;; '$CC '*) # Test whether the compiler implicitly links with -lc since on some # systems, -lgcc has to come before -lc. If gcc already passes -lc # to ld, don't add -lc before -lgcc. { $as_echo "$as_me:${as_lineno-$LINENO}: checking whether -lc should be explicitly linked in" >&5 $as_echo_n "checking whether -lc should be explicitly linked in... " >&6; } if ${lt_cv_archive_cmds_need_lc+:} false; then : $as_echo_n "(cached) " >&6 else $RM conftest* echo "$lt_simple_compile_test_code" > conftest.$ac_ext if { { eval echo "\"\$as_me\":${as_lineno-$LINENO}: \"$ac_compile\""; } >&5 (eval $ac_compile) 2>&5 ac_status=$? $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 test $ac_status = 0; } 2>conftest.err; then soname=conftest lib=conftest libobjs=conftest.$ac_objext deplibs= wl=$lt_prog_compiler_wl pic_flag=$lt_prog_compiler_pic compiler_flags=-v linker_flags=-v verstring= output_objdir=. libname=conftest lt_save_allow_undefined_flag=$allow_undefined_flag allow_undefined_flag= if { { eval echo "\"\$as_me\":${as_lineno-$LINENO}: \"$archive_cmds 2\>\&1 \| $GREP \" -lc \" \>/dev/null 2\>\&1\""; } >&5 (eval $archive_cmds 2\>\&1 \| $GREP \" -lc \" \>/dev/null 2\>\&1) 2>&5 ac_status=$? $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 test $ac_status = 0; } then lt_cv_archive_cmds_need_lc=no else lt_cv_archive_cmds_need_lc=yes fi allow_undefined_flag=$lt_save_allow_undefined_flag else cat conftest.err 1>&5 fi $RM conftest* fi { $as_echo "$as_me:${as_lineno-$LINENO}: result: $lt_cv_archive_cmds_need_lc" >&5 $as_echo "$lt_cv_archive_cmds_need_lc" >&6; } archive_cmds_need_lc=$lt_cv_archive_cmds_need_lc ;; esac fi ;; esac { $as_echo "$as_me:${as_lineno-$LINENO}: checking dynamic linker characteristics" >&5 $as_echo_n "checking dynamic linker characteristics... " >&6; } if test "$GCC" = yes; then case $host_os in darwin*) lt_awk_arg="/^libraries:/,/LR/" ;; *) lt_awk_arg="/^libraries:/" ;; esac case $host_os in mingw* | cegcc*) lt_sed_strip_eq="s,=\([A-Za-z]:\),\1,g" ;; *) lt_sed_strip_eq="s,=/,/,g" ;; esac lt_search_path_spec=`$CC -print-search-dirs | awk $lt_awk_arg | $SED -e "s/^libraries://" -e $lt_sed_strip_eq` case $lt_search_path_spec in *\;*) # if the path contains ";" then we assume it to be the separator # otherwise default to the standard path separator (i.e. ":") - it is # assumed that no part of a normal pathname contains ";" but that should # okay in the real world where ";" in dirpaths is itself problematic. lt_search_path_spec=`$ECHO "$lt_search_path_spec" | $SED 's/;/ /g'` ;; *) lt_search_path_spec=`$ECHO "$lt_search_path_spec" | $SED "s/$PATH_SEPARATOR/ /g"` ;; esac # Ok, now we have the path, separated by spaces, we can step through it # and add multilib dir if necessary. lt_tmp_lt_search_path_spec= lt_multi_os_dir=`$CC $CPPFLAGS $CFLAGS $LDFLAGS -print-multi-os-directory 2>/dev/null` for lt_sys_path in $lt_search_path_spec; do if test -d "$lt_sys_path/$lt_multi_os_dir"; then lt_tmp_lt_search_path_spec="$lt_tmp_lt_search_path_spec $lt_sys_path/$lt_multi_os_dir" else test -d "$lt_sys_path" && \ lt_tmp_lt_search_path_spec="$lt_tmp_lt_search_path_spec $lt_sys_path" fi done lt_search_path_spec=`$ECHO "$lt_tmp_lt_search_path_spec" | awk ' BEGIN {RS=" "; FS="/|\n";} { lt_foo=""; lt_count=0; for (lt_i = NF; lt_i > 0; lt_i--) { if ($lt_i != "" && $lt_i != ".") { if ($lt_i == "..") { lt_count++; } else { if (lt_count == 0) { lt_foo="/" $lt_i lt_foo; } else { lt_count--; } } } } if (lt_foo != "") { lt_freq[lt_foo]++; } if (lt_freq[lt_foo] == 1) { print lt_foo; } }'` # AWK program above erroneously prepends '/' to C:/dos/paths # for these hosts. case $host_os in mingw* | cegcc*) lt_search_path_spec=`$ECHO "$lt_search_path_spec" |\ $SED 's,/\([A-Za-z]:\),\1,g'` ;; esac sys_lib_search_path_spec=`$ECHO "$lt_search_path_spec" | $lt_NL2SP` else sys_lib_search_path_spec="/lib /usr/lib /usr/local/lib" fi library_names_spec= libname_spec='lib$name' soname_spec= shrext_cmds=".so" postinstall_cmds= postuninstall_cmds= finish_cmds= finish_eval= shlibpath_var= shlibpath_overrides_runpath=unknown version_type=none dynamic_linker="$host_os ld.so" sys_lib_dlsearch_path_spec="/lib /usr/lib" need_lib_prefix=unknown hardcode_into_libs=no # when you set need_version to no, make sure it does not cause -set_version # flags to be left without arguments need_version=unknown case $host_os in aix3*) version_type=linux # correct to gnu/linux during the next big refactor library_names_spec='${libname}${release}${shared_ext}$versuffix $libname.a' shlibpath_var=LIBPATH # AIX 3 has no versioning support, so we append a major version to the name. soname_spec='${libname}${release}${shared_ext}$major' ;; aix[4-9]*) version_type=linux # correct to gnu/linux during the next big refactor need_lib_prefix=no need_version=no hardcode_into_libs=yes if test "$host_cpu" = ia64; then # AIX 5 supports IA64 library_names_spec='${libname}${release}${shared_ext}$major ${libname}${release}${shared_ext}$versuffix $libname${shared_ext}' shlibpath_var=LD_LIBRARY_PATH else # With GCC up to 2.95.x, collect2 would create an import file # for dependence libraries. The import file would start with # the line `#! .'. This would cause the generated library to # depend on `.', always an invalid library. This was fixed in # development snapshots of GCC prior to 3.0. case $host_os in aix4 | aix4.[01] | aix4.[01].*) if { echo '#if __GNUC__ > 2 || (__GNUC__ == 2 && __GNUC_MINOR__ >= 97)' echo ' yes ' echo '#endif'; } | ${CC} -E - | $GREP yes > /dev/null; then : else can_build_shared=no fi ;; esac # AIX (on Power*) has no versioning support, so currently we can not hardcode correct # soname into executable. Probably we can add versioning support to # collect2, so additional links can be useful in future. if test "$aix_use_runtimelinking" = yes; then # If using run time linking (on AIX 4.2 or later) use lib.so # instead of lib.a to let people know that these are not # typical AIX shared libraries. library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}' else # We preserve .a as extension for shared libraries through AIX4.2 # and later when we are not doing run time linking. library_names_spec='${libname}${release}.a $libname.a' soname_spec='${libname}${release}${shared_ext}$major' fi shlibpath_var=LIBPATH fi ;; amigaos*) case $host_cpu in powerpc) # Since July 2007 AmigaOS4 officially supports .so libraries. # When compiling the executable, add -use-dynld -Lsobjs: to the compileline. library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}' ;; m68k) library_names_spec='$libname.ixlibrary $libname.a' # Create ${libname}_ixlibrary.a entries in /sys/libs. finish_eval='for lib in `ls $libdir/*.ixlibrary 2>/dev/null`; do libname=`func_echo_all "$lib" | $SED '\''s%^.*/\([^/]*\)\.ixlibrary$%\1%'\''`; test $RM /sys/libs/${libname}_ixlibrary.a; $show "cd /sys/libs && $LN_S $lib ${libname}_ixlibrary.a"; cd /sys/libs && $LN_S $lib ${libname}_ixlibrary.a || exit 1; done' ;; esac ;; beos*) library_names_spec='${libname}${shared_ext}' dynamic_linker="$host_os ld.so" shlibpath_var=LIBRARY_PATH ;; bsdi[45]*) version_type=linux # correct to gnu/linux during the next big refactor need_version=no library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}' soname_spec='${libname}${release}${shared_ext}$major' finish_cmds='PATH="\$PATH:/sbin" ldconfig $libdir' shlibpath_var=LD_LIBRARY_PATH sys_lib_search_path_spec="/shlib /usr/lib /usr/X11/lib /usr/contrib/lib /lib /usr/local/lib" sys_lib_dlsearch_path_spec="/shlib /usr/lib /usr/local/lib" # the default ld.so.conf also contains /usr/contrib/lib and # /usr/X11R6/lib (/usr/X11 is a link to /usr/X11R6), but let us allow # libtool to hard-code these into programs ;; cygwin* | mingw* | pw32* | cegcc*) version_type=windows shrext_cmds=".dll" need_version=no need_lib_prefix=no case $GCC,$cc_basename in yes,*) # gcc library_names_spec='$libname.dll.a' # DLL is installed to $(libdir)/../bin by postinstall_cmds postinstall_cmds='base_file=`basename \${file}`~ dlpath=`$SHELL 2>&1 -c '\''. $dir/'\''\${base_file}'\''i; echo \$dlname'\''`~ dldir=$destdir/`dirname \$dlpath`~ test -d \$dldir || mkdir -p \$dldir~ $install_prog $dir/$dlname \$dldir/$dlname~ chmod a+x \$dldir/$dlname~ if test -n '\''$stripme'\'' && test -n '\''$striplib'\''; then eval '\''$striplib \$dldir/$dlname'\'' || exit \$?; fi' postuninstall_cmds='dldll=`$SHELL 2>&1 -c '\''. $file; echo \$dlname'\''`~ dlpath=$dir/\$dldll~ $RM \$dlpath' shlibpath_overrides_runpath=yes case $host_os in cygwin*) # Cygwin DLLs use 'cyg' prefix rather than 'lib' soname_spec='`echo ${libname} | sed -e 's/^lib/cyg/'``echo ${release} | $SED -e 's/[.]/-/g'`${versuffix}${shared_ext}' sys_lib_search_path_spec="$sys_lib_search_path_spec /usr/lib/w32api" ;; mingw* | cegcc*) # MinGW DLLs use traditional 'lib' prefix soname_spec='${libname}`echo ${release} | $SED -e 's/[.]/-/g'`${versuffix}${shared_ext}' ;; pw32*) # pw32 DLLs use 'pw' prefix rather than 'lib' library_names_spec='`echo ${libname} | sed -e 's/^lib/pw/'``echo ${release} | $SED -e 's/[.]/-/g'`${versuffix}${shared_ext}' ;; esac dynamic_linker='Win32 ld.exe' ;; *,cl*) # Native MSVC libname_spec='$name' soname_spec='${libname}`echo ${release} | $SED -e 's/[.]/-/g'`${versuffix}${shared_ext}' library_names_spec='${libname}.dll.lib' case $build_os in mingw*) sys_lib_search_path_spec= lt_save_ifs=$IFS IFS=';' for lt_path in $LIB do IFS=$lt_save_ifs # Let DOS variable expansion print the short 8.3 style file name. lt_path=`cd "$lt_path" 2>/dev/null && cmd //C "for %i in (".") do @echo %~si"` sys_lib_search_path_spec="$sys_lib_search_path_spec $lt_path" done IFS=$lt_save_ifs # Convert to MSYS style. sys_lib_search_path_spec=`$ECHO "$sys_lib_search_path_spec" | sed -e 's|\\\\|/|g' -e 's| \\([a-zA-Z]\\):| /\\1|g' -e 's|^ ||'` ;; cygwin*) # Convert to unix form, then to dos form, then back to unix form # but this time dos style (no spaces!) so that the unix form looks # like /cygdrive/c/PROGRA~1:/cygdr... sys_lib_search_path_spec=`cygpath --path --unix "$LIB"` sys_lib_search_path_spec=`cygpath --path --dos "$sys_lib_search_path_spec" 2>/dev/null` sys_lib_search_path_spec=`cygpath --path --unix "$sys_lib_search_path_spec" | $SED -e "s/$PATH_SEPARATOR/ /g"` ;; *) sys_lib_search_path_spec="$LIB" if $ECHO "$sys_lib_search_path_spec" | $GREP ';[c-zC-Z]:/' >/dev/null; then # It is most probably a Windows format PATH. sys_lib_search_path_spec=`$ECHO "$sys_lib_search_path_spec" | $SED -e 's/;/ /g'` else sys_lib_search_path_spec=`$ECHO "$sys_lib_search_path_spec" | $SED -e "s/$PATH_SEPARATOR/ /g"` fi # FIXME: find the short name or the path components, as spaces are # common. (e.g. "Program Files" -> "PROGRA~1") ;; esac # DLL is installed to $(libdir)/../bin by postinstall_cmds postinstall_cmds='base_file=`basename \${file}`~ dlpath=`$SHELL 2>&1 -c '\''. $dir/'\''\${base_file}'\''i; echo \$dlname'\''`~ dldir=$destdir/`dirname \$dlpath`~ test -d \$dldir || mkdir -p \$dldir~ $install_prog $dir/$dlname \$dldir/$dlname' postuninstall_cmds='dldll=`$SHELL 2>&1 -c '\''. $file; echo \$dlname'\''`~ dlpath=$dir/\$dldll~ $RM \$dlpath' shlibpath_overrides_runpath=yes dynamic_linker='Win32 link.exe' ;; *) # Assume MSVC wrapper library_names_spec='${libname}`echo ${release} | $SED -e 's/[.]/-/g'`${versuffix}${shared_ext} $libname.lib' dynamic_linker='Win32 ld.exe' ;; esac # FIXME: first we should search . and the directory the executable is in shlibpath_var=PATH ;; darwin* | rhapsody*) dynamic_linker="$host_os dyld" version_type=darwin need_lib_prefix=no need_version=no library_names_spec='${libname}${release}${major}$shared_ext ${libname}$shared_ext' soname_spec='${libname}${release}${major}$shared_ext' shlibpath_overrides_runpath=yes shlibpath_var=DYLD_LIBRARY_PATH shrext_cmds='`test .$module = .yes && echo .so || echo .dylib`' sys_lib_search_path_spec="$sys_lib_search_path_spec /usr/local/lib" sys_lib_dlsearch_path_spec='/usr/local/lib /lib /usr/lib' ;; dgux*) version_type=linux # correct to gnu/linux during the next big refactor need_lib_prefix=no need_version=no library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname$shared_ext' soname_spec='${libname}${release}${shared_ext}$major' shlibpath_var=LD_LIBRARY_PATH ;; freebsd* | dragonfly*) # DragonFly does not have aout. When/if they implement a new # versioning mechanism, adjust this. if test -x /usr/bin/objformat; then objformat=`/usr/bin/objformat` else case $host_os in freebsd[23].*) objformat=aout ;; *) objformat=elf ;; esac fi # Handle Gentoo/FreeBSD as it was Linux case $host_vendor in gentoo) version_type=linux ;; *) version_type=freebsd-$objformat ;; esac case $version_type in freebsd-elf*) library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext} $libname${shared_ext}' need_version=no need_lib_prefix=no ;; freebsd-*) library_names_spec='${libname}${release}${shared_ext}$versuffix $libname${shared_ext}$versuffix' need_version=yes ;; linux) library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major ${libname}${shared_ext}' soname_spec='${libname}${release}${shared_ext}$major' need_lib_prefix=no need_version=no ;; esac shlibpath_var=LD_LIBRARY_PATH case $host_os in freebsd2.*) shlibpath_overrides_runpath=yes ;; freebsd3.[01]* | freebsdelf3.[01]*) shlibpath_overrides_runpath=yes hardcode_into_libs=yes ;; freebsd3.[2-9]* | freebsdelf3.[2-9]* | \ freebsd4.[0-5] | freebsdelf4.[0-5] | freebsd4.1.1 | freebsdelf4.1.1) shlibpath_overrides_runpath=no hardcode_into_libs=yes ;; *) # from 4.6 on, and DragonFly shlibpath_overrides_runpath=yes hardcode_into_libs=yes ;; esac ;; gnu*) version_type=linux # correct to gnu/linux during the next big refactor need_lib_prefix=no need_version=no library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}${major} ${libname}${shared_ext}' soname_spec='${libname}${release}${shared_ext}$major' shlibpath_var=LD_LIBRARY_PATH shlibpath_overrides_runpath=no hardcode_into_libs=yes ;; haiku*) version_type=linux # correct to gnu/linux during the next big refactor need_lib_prefix=no need_version=no dynamic_linker="$host_os runtime_loader" library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}${major} ${libname}${shared_ext}' soname_spec='${libname}${release}${shared_ext}$major' shlibpath_var=LIBRARY_PATH shlibpath_overrides_runpath=yes sys_lib_dlsearch_path_spec='/boot/home/config/lib /boot/common/lib /boot/system/lib' hardcode_into_libs=yes ;; hpux9* | hpux10* | hpux11*) # Give a soname corresponding to the major version so that dld.sl refuses to # link against other versions. version_type=sunos need_lib_prefix=no need_version=no case $host_cpu in ia64*) shrext_cmds='.so' hardcode_into_libs=yes dynamic_linker="$host_os dld.so" shlibpath_var=LD_LIBRARY_PATH shlibpath_overrides_runpath=yes # Unless +noenvvar is specified. library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}' soname_spec='${libname}${release}${shared_ext}$major' if test "X$HPUX_IA64_MODE" = X32; then sys_lib_search_path_spec="/usr/lib/hpux32 /usr/local/lib/hpux32 /usr/local/lib" else sys_lib_search_path_spec="/usr/lib/hpux64 /usr/local/lib/hpux64" fi sys_lib_dlsearch_path_spec=$sys_lib_search_path_spec ;; hppa*64*) shrext_cmds='.sl' hardcode_into_libs=yes dynamic_linker="$host_os dld.sl" shlibpath_var=LD_LIBRARY_PATH # How should we handle SHLIB_PATH shlibpath_overrides_runpath=yes # Unless +noenvvar is specified. library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}' soname_spec='${libname}${release}${shared_ext}$major' sys_lib_search_path_spec="/usr/lib/pa20_64 /usr/ccs/lib/pa20_64" sys_lib_dlsearch_path_spec=$sys_lib_search_path_spec ;; *) shrext_cmds='.sl' dynamic_linker="$host_os dld.sl" shlibpath_var=SHLIB_PATH shlibpath_overrides_runpath=no # +s is required to enable SHLIB_PATH library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}' soname_spec='${libname}${release}${shared_ext}$major' ;; esac # HP-UX runs *really* slowly unless shared libraries are mode 555, ... postinstall_cmds='chmod 555 $lib' # or fails outright, so override atomically: install_override_mode=555 ;; interix[3-9]*) version_type=linux # correct to gnu/linux during the next big refactor need_lib_prefix=no need_version=no library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major ${libname}${shared_ext}' soname_spec='${libname}${release}${shared_ext}$major' dynamic_linker='Interix 3.x ld.so.1 (PE, like ELF)' shlibpath_var=LD_LIBRARY_PATH shlibpath_overrides_runpath=no hardcode_into_libs=yes ;; irix5* | irix6* | nonstopux*) case $host_os in nonstopux*) version_type=nonstopux ;; *) if test "$lt_cv_prog_gnu_ld" = yes; then version_type=linux # correct to gnu/linux during the next big refactor else version_type=irix fi ;; esac need_lib_prefix=no need_version=no soname_spec='${libname}${release}${shared_ext}$major' library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major ${libname}${release}${shared_ext} $libname${shared_ext}' case $host_os in irix5* | nonstopux*) libsuff= shlibsuff= ;; *) case $LD in # libtool.m4 will add one of these switches to LD *-32|*"-32 "|*-melf32bsmip|*"-melf32bsmip ") libsuff= shlibsuff= libmagic=32-bit;; *-n32|*"-n32 "|*-melf32bmipn32|*"-melf32bmipn32 ") libsuff=32 shlibsuff=N32 libmagic=N32;; *-64|*"-64 "|*-melf64bmip|*"-melf64bmip ") libsuff=64 shlibsuff=64 libmagic=64-bit;; *) libsuff= shlibsuff= libmagic=never-match;; esac ;; esac shlibpath_var=LD_LIBRARY${shlibsuff}_PATH shlibpath_overrides_runpath=no sys_lib_search_path_spec="/usr/lib${libsuff} /lib${libsuff} /usr/local/lib${libsuff}" sys_lib_dlsearch_path_spec="/usr/lib${libsuff} /lib${libsuff}" hardcode_into_libs=yes ;; # No shared lib support for Linux oldld, aout, or coff. linux*oldld* | linux*aout* | linux*coff*) dynamic_linker=no ;; # This must be glibc/ELF. linux* | k*bsd*-gnu | kopensolaris*-gnu) version_type=linux # correct to gnu/linux during the next big refactor need_lib_prefix=no need_version=no library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}' soname_spec='${libname}${release}${shared_ext}$major' finish_cmds='PATH="\$PATH:/sbin" ldconfig -n $libdir' shlibpath_var=LD_LIBRARY_PATH shlibpath_overrides_runpath=no # Some binutils ld are patched to set DT_RUNPATH if ${lt_cv_shlibpath_overrides_runpath+:} false; then : $as_echo_n "(cached) " >&6 else lt_cv_shlibpath_overrides_runpath=no save_LDFLAGS=$LDFLAGS save_libdir=$libdir eval "libdir=/foo; wl=\"$lt_prog_compiler_wl\"; \ LDFLAGS=\"\$LDFLAGS $hardcode_libdir_flag_spec\"" cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ int main () { ; return 0; } _ACEOF if ac_fn_c_try_link "$LINENO"; then : if ($OBJDUMP -p conftest$ac_exeext) 2>/dev/null | grep "RUNPATH.*$libdir" >/dev/null; then : lt_cv_shlibpath_overrides_runpath=yes fi fi rm -f core conftest.err conftest.$ac_objext \ conftest$ac_exeext conftest.$ac_ext LDFLAGS=$save_LDFLAGS libdir=$save_libdir fi shlibpath_overrides_runpath=$lt_cv_shlibpath_overrides_runpath # This implies no fast_install, which is unacceptable. # Some rework will be needed to allow for fast_install # before this can be enabled. hardcode_into_libs=yes # Append ld.so.conf contents to the search path if test -f /etc/ld.so.conf; then lt_ld_extra=`awk '/^include / { system(sprintf("cd /etc; cat %s 2>/dev/null", \$2)); skip = 1; } { if (!skip) print \$0; skip = 0; }' < /etc/ld.so.conf | $SED -e 's/#.*//;/^[ ]*hwcap[ ]/d;s/[:, ]/ /g;s/=[^=]*$//;s/=[^= ]* / /g;s/"//g;/^$/d' | tr '\n' ' '` sys_lib_dlsearch_path_spec="/lib /usr/lib $lt_ld_extra" fi # We used to test for /lib/ld.so.1 and disable shared libraries on # powerpc, because MkLinux only supported shared libraries with the # GNU dynamic linker. Since this was broken with cross compilers, # most powerpc-linux boxes support dynamic linking these days and # people can always --disable-shared, the test was removed, and we # assume the GNU/Linux dynamic linker is in use. dynamic_linker='GNU/Linux ld.so' ;; netbsd*) version_type=sunos need_lib_prefix=no need_version=no if echo __ELF__ | $CC -E - | $GREP __ELF__ >/dev/null; then library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${shared_ext}$versuffix' finish_cmds='PATH="\$PATH:/sbin" ldconfig -m $libdir' dynamic_linker='NetBSD (a.out) ld.so' else library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major ${libname}${shared_ext}' soname_spec='${libname}${release}${shared_ext}$major' dynamic_linker='NetBSD ld.elf_so' fi shlibpath_var=LD_LIBRARY_PATH shlibpath_overrides_runpath=yes hardcode_into_libs=yes ;; newsos6) version_type=linux # correct to gnu/linux during the next big refactor library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}' shlibpath_var=LD_LIBRARY_PATH shlibpath_overrides_runpath=yes ;; *nto* | *qnx*) version_type=qnx need_lib_prefix=no need_version=no library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}' soname_spec='${libname}${release}${shared_ext}$major' shlibpath_var=LD_LIBRARY_PATH shlibpath_overrides_runpath=no hardcode_into_libs=yes dynamic_linker='ldqnx.so' ;; openbsd*) version_type=sunos sys_lib_dlsearch_path_spec="/usr/lib" need_lib_prefix=no # Some older versions of OpenBSD (3.3 at least) *do* need versioned libs. case $host_os in openbsd3.3 | openbsd3.3.*) need_version=yes ;; *) need_version=no ;; esac library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${shared_ext}$versuffix' finish_cmds='PATH="\$PATH:/sbin" ldconfig -m $libdir' shlibpath_var=LD_LIBRARY_PATH if test -z "`echo __ELF__ | $CC -E - | $GREP __ELF__`" || test "$host_os-$host_cpu" = "openbsd2.8-powerpc"; then case $host_os in openbsd2.[89] | openbsd2.[89].*) shlibpath_overrides_runpath=no ;; *) shlibpath_overrides_runpath=yes ;; esac else shlibpath_overrides_runpath=yes fi ;; os2*) libname_spec='$name' shrext_cmds=".dll" need_lib_prefix=no library_names_spec='$libname${shared_ext} $libname.a' dynamic_linker='OS/2 ld.exe' shlibpath_var=LIBPATH ;; osf3* | osf4* | osf5*) version_type=osf need_lib_prefix=no need_version=no soname_spec='${libname}${release}${shared_ext}$major' library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}' shlibpath_var=LD_LIBRARY_PATH sys_lib_search_path_spec="/usr/shlib /usr/ccs/lib /usr/lib/cmplrs/cc /usr/lib /usr/local/lib /var/shlib" sys_lib_dlsearch_path_spec="$sys_lib_search_path_spec" ;; rdos*) dynamic_linker=no ;; solaris*) version_type=linux # correct to gnu/linux during the next big refactor need_lib_prefix=no need_version=no library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}' soname_spec='${libname}${release}${shared_ext}$major' shlibpath_var=LD_LIBRARY_PATH shlibpath_overrides_runpath=yes hardcode_into_libs=yes # ldd complains unless libraries are executable postinstall_cmds='chmod +x $lib' ;; sunos4*) version_type=sunos library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${shared_ext}$versuffix' finish_cmds='PATH="\$PATH:/usr/etc" ldconfig $libdir' shlibpath_var=LD_LIBRARY_PATH shlibpath_overrides_runpath=yes if test "$with_gnu_ld" = yes; then need_lib_prefix=no fi need_version=yes ;; sysv4 | sysv4.3*) version_type=linux # correct to gnu/linux during the next big refactor library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}' soname_spec='${libname}${release}${shared_ext}$major' shlibpath_var=LD_LIBRARY_PATH case $host_vendor in sni) shlibpath_overrides_runpath=no need_lib_prefix=no runpath_var=LD_RUN_PATH ;; siemens) need_lib_prefix=no ;; motorola) need_lib_prefix=no need_version=no shlibpath_overrides_runpath=no sys_lib_search_path_spec='/lib /usr/lib /usr/ccs/lib' ;; esac ;; sysv4*MP*) if test -d /usr/nec ;then version_type=linux # correct to gnu/linux during the next big refactor library_names_spec='$libname${shared_ext}.$versuffix $libname${shared_ext}.$major $libname${shared_ext}' soname_spec='$libname${shared_ext}.$major' shlibpath_var=LD_LIBRARY_PATH fi ;; sysv5* | sco3.2v5* | sco5v6* | unixware* | OpenUNIX* | sysv4*uw2*) version_type=freebsd-elf need_lib_prefix=no need_version=no library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext} $libname${shared_ext}' soname_spec='${libname}${release}${shared_ext}$major' shlibpath_var=LD_LIBRARY_PATH shlibpath_overrides_runpath=yes hardcode_into_libs=yes if test "$with_gnu_ld" = yes; then sys_lib_search_path_spec='/usr/local/lib /usr/gnu/lib /usr/ccs/lib /usr/lib /lib' else sys_lib_search_path_spec='/usr/ccs/lib /usr/lib' case $host_os in sco3.2v5*) sys_lib_search_path_spec="$sys_lib_search_path_spec /lib" ;; esac fi sys_lib_dlsearch_path_spec='/usr/lib' ;; tpf*) # TPF is a cross-target only. Preferred cross-host = GNU/Linux. version_type=linux # correct to gnu/linux during the next big refactor need_lib_prefix=no need_version=no library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}' shlibpath_var=LD_LIBRARY_PATH shlibpath_overrides_runpath=no hardcode_into_libs=yes ;; uts4*) version_type=linux # correct to gnu/linux during the next big refactor library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}' soname_spec='${libname}${release}${shared_ext}$major' shlibpath_var=LD_LIBRARY_PATH ;; *) dynamic_linker=no ;; esac { $as_echo "$as_me:${as_lineno-$LINENO}: result: $dynamic_linker" >&5 $as_echo "$dynamic_linker" >&6; } test "$dynamic_linker" = no && can_build_shared=no variables_saved_for_relink="PATH $shlibpath_var $runpath_var" if test "$GCC" = yes; then variables_saved_for_relink="$variables_saved_for_relink GCC_EXEC_PREFIX COMPILER_PATH LIBRARY_PATH" fi if test "${lt_cv_sys_lib_search_path_spec+set}" = set; then sys_lib_search_path_spec="$lt_cv_sys_lib_search_path_spec" fi if test "${lt_cv_sys_lib_dlsearch_path_spec+set}" = set; then sys_lib_dlsearch_path_spec="$lt_cv_sys_lib_dlsearch_path_spec" fi { $as_echo "$as_me:${as_lineno-$LINENO}: checking how to hardcode library paths into programs" >&5 $as_echo_n "checking how to hardcode library paths into programs... " >&6; } hardcode_action= if test -n "$hardcode_libdir_flag_spec" || test -n "$runpath_var" || test "X$hardcode_automatic" = "Xyes" ; then # We can hardcode non-existent directories. if test "$hardcode_direct" != no && # If the only mechanism to avoid hardcoding is shlibpath_var, we # have to relink, otherwise we might link with an installed library # when we should be linking with a yet-to-be-installed one ## test "$_LT_TAGVAR(hardcode_shlibpath_var, )" != no && test "$hardcode_minus_L" != no; then # Linking always hardcodes the temporary library directory. hardcode_action=relink else # We can link without hardcoding, and we can hardcode nonexisting dirs. hardcode_action=immediate fi else # We cannot hardcode anything, or else we can only hardcode existing # directories. hardcode_action=unsupported fi { $as_echo "$as_me:${as_lineno-$LINENO}: result: $hardcode_action" >&5 $as_echo "$hardcode_action" >&6; } if test "$hardcode_action" = relink || test "$inherit_rpath" = yes; then # Fast installation is not supported enable_fast_install=no elif test "$shlibpath_overrides_runpath" = yes || test "$enable_shared" = no; then # Fast installation is not necessary enable_fast_install=needless fi if test "x$enable_dlopen" != xyes; then enable_dlopen=unknown enable_dlopen_self=unknown enable_dlopen_self_static=unknown else lt_cv_dlopen=no lt_cv_dlopen_libs= case $host_os in beos*) lt_cv_dlopen="load_add_on" lt_cv_dlopen_libs= lt_cv_dlopen_self=yes ;; mingw* | pw32* | cegcc*) lt_cv_dlopen="LoadLibrary" lt_cv_dlopen_libs= ;; cygwin*) lt_cv_dlopen="dlopen" lt_cv_dlopen_libs= ;; darwin*) # if libdl is installed we need to link against it { $as_echo "$as_me:${as_lineno-$LINENO}: checking for dlopen in -ldl" >&5 $as_echo_n "checking for dlopen in -ldl... " >&6; } if ${ac_cv_lib_dl_dlopen+:} false; then : $as_echo_n "(cached) " >&6 else ac_check_lib_save_LIBS=$LIBS LIBS="-ldl $LIBS" cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ /* Override any GCC internal prototype to avoid an error. Use char because int might match the return type of a GCC builtin and then its argument prototype would still apply. */ #ifdef __cplusplus extern "C" #endif char dlopen (); int main () { return dlopen (); ; return 0; } _ACEOF if ac_fn_c_try_link "$LINENO"; then : ac_cv_lib_dl_dlopen=yes else ac_cv_lib_dl_dlopen=no fi rm -f core conftest.err conftest.$ac_objext \ conftest$ac_exeext conftest.$ac_ext LIBS=$ac_check_lib_save_LIBS fi { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_lib_dl_dlopen" >&5 $as_echo "$ac_cv_lib_dl_dlopen" >&6; } if test "x$ac_cv_lib_dl_dlopen" = xyes; then : lt_cv_dlopen="dlopen" lt_cv_dlopen_libs="-ldl" else lt_cv_dlopen="dyld" lt_cv_dlopen_libs= lt_cv_dlopen_self=yes fi ;; *) ac_fn_c_check_func "$LINENO" "shl_load" "ac_cv_func_shl_load" if test "x$ac_cv_func_shl_load" = xyes; then : lt_cv_dlopen="shl_load" else { $as_echo "$as_me:${as_lineno-$LINENO}: checking for shl_load in -ldld" >&5 $as_echo_n "checking for shl_load in -ldld... " >&6; } if ${ac_cv_lib_dld_shl_load+:} false; then : $as_echo_n "(cached) " >&6 else ac_check_lib_save_LIBS=$LIBS LIBS="-ldld $LIBS" cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ /* Override any GCC internal prototype to avoid an error. Use char because int might match the return type of a GCC builtin and then its argument prototype would still apply. */ #ifdef __cplusplus extern "C" #endif char shl_load (); int main () { return shl_load (); ; return 0; } _ACEOF if ac_fn_c_try_link "$LINENO"; then : ac_cv_lib_dld_shl_load=yes else ac_cv_lib_dld_shl_load=no fi rm -f core conftest.err conftest.$ac_objext \ conftest$ac_exeext conftest.$ac_ext LIBS=$ac_check_lib_save_LIBS fi { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_lib_dld_shl_load" >&5 $as_echo "$ac_cv_lib_dld_shl_load" >&6; } if test "x$ac_cv_lib_dld_shl_load" = xyes; then : lt_cv_dlopen="shl_load" lt_cv_dlopen_libs="-ldld" else ac_fn_c_check_func "$LINENO" "dlopen" "ac_cv_func_dlopen" if test "x$ac_cv_func_dlopen" = xyes; then : lt_cv_dlopen="dlopen" else { $as_echo "$as_me:${as_lineno-$LINENO}: checking for dlopen in -ldl" >&5 $as_echo_n "checking for dlopen in -ldl... " >&6; } if ${ac_cv_lib_dl_dlopen+:} false; then : $as_echo_n "(cached) " >&6 else ac_check_lib_save_LIBS=$LIBS LIBS="-ldl $LIBS" cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ /* Override any GCC internal prototype to avoid an error. Use char because int might match the return type of a GCC builtin and then its argument prototype would still apply. */ #ifdef __cplusplus extern "C" #endif char dlopen (); int main () { return dlopen (); ; return 0; } _ACEOF if ac_fn_c_try_link "$LINENO"; then : ac_cv_lib_dl_dlopen=yes else ac_cv_lib_dl_dlopen=no fi rm -f core conftest.err conftest.$ac_objext \ conftest$ac_exeext conftest.$ac_ext LIBS=$ac_check_lib_save_LIBS fi { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_lib_dl_dlopen" >&5 $as_echo "$ac_cv_lib_dl_dlopen" >&6; } if test "x$ac_cv_lib_dl_dlopen" = xyes; then : lt_cv_dlopen="dlopen" lt_cv_dlopen_libs="-ldl" else { $as_echo "$as_me:${as_lineno-$LINENO}: checking for dlopen in -lsvld" >&5 $as_echo_n "checking for dlopen in -lsvld... " >&6; } if ${ac_cv_lib_svld_dlopen+:} false; then : $as_echo_n "(cached) " >&6 else ac_check_lib_save_LIBS=$LIBS LIBS="-lsvld $LIBS" cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ /* Override any GCC internal prototype to avoid an error. Use char because int might match the return type of a GCC builtin and then its argument prototype would still apply. */ #ifdef __cplusplus extern "C" #endif char dlopen (); int main () { return dlopen (); ; return 0; } _ACEOF if ac_fn_c_try_link "$LINENO"; then : ac_cv_lib_svld_dlopen=yes else ac_cv_lib_svld_dlopen=no fi rm -f core conftest.err conftest.$ac_objext \ conftest$ac_exeext conftest.$ac_ext LIBS=$ac_check_lib_save_LIBS fi { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_lib_svld_dlopen" >&5 $as_echo "$ac_cv_lib_svld_dlopen" >&6; } if test "x$ac_cv_lib_svld_dlopen" = xyes; then : lt_cv_dlopen="dlopen" lt_cv_dlopen_libs="-lsvld" else { $as_echo "$as_me:${as_lineno-$LINENO}: checking for dld_link in -ldld" >&5 $as_echo_n "checking for dld_link in -ldld... " >&6; } if ${ac_cv_lib_dld_dld_link+:} false; then : $as_echo_n "(cached) " >&6 else ac_check_lib_save_LIBS=$LIBS LIBS="-ldld $LIBS" cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ /* Override any GCC internal prototype to avoid an error. Use char because int might match the return type of a GCC builtin and then its argument prototype would still apply. */ #ifdef __cplusplus extern "C" #endif char dld_link (); int main () { return dld_link (); ; return 0; } _ACEOF if ac_fn_c_try_link "$LINENO"; then : ac_cv_lib_dld_dld_link=yes else ac_cv_lib_dld_dld_link=no fi rm -f core conftest.err conftest.$ac_objext \ conftest$ac_exeext conftest.$ac_ext LIBS=$ac_check_lib_save_LIBS fi { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_lib_dld_dld_link" >&5 $as_echo "$ac_cv_lib_dld_dld_link" >&6; } if test "x$ac_cv_lib_dld_dld_link" = xyes; then : lt_cv_dlopen="dld_link" lt_cv_dlopen_libs="-ldld" fi fi fi fi fi fi ;; esac if test "x$lt_cv_dlopen" != xno; then enable_dlopen=yes else enable_dlopen=no fi case $lt_cv_dlopen in dlopen) save_CPPFLAGS="$CPPFLAGS" test "x$ac_cv_header_dlfcn_h" = xyes && CPPFLAGS="$CPPFLAGS -DHAVE_DLFCN_H" save_LDFLAGS="$LDFLAGS" wl=$lt_prog_compiler_wl eval LDFLAGS=\"\$LDFLAGS $export_dynamic_flag_spec\" save_LIBS="$LIBS" LIBS="$lt_cv_dlopen_libs $LIBS" { $as_echo "$as_me:${as_lineno-$LINENO}: checking whether a program can dlopen itself" >&5 $as_echo_n "checking whether a program can dlopen itself... " >&6; } if ${lt_cv_dlopen_self+:} false; then : $as_echo_n "(cached) " >&6 else if test "$cross_compiling" = yes; then : lt_cv_dlopen_self=cross else lt_dlunknown=0; lt_dlno_uscore=1; lt_dlneed_uscore=2 lt_status=$lt_dlunknown cat > conftest.$ac_ext <<_LT_EOF #line $LINENO "configure" #include "confdefs.h" #if HAVE_DLFCN_H #include #endif #include #ifdef RTLD_GLOBAL # define LT_DLGLOBAL RTLD_GLOBAL #else # ifdef DL_GLOBAL # define LT_DLGLOBAL DL_GLOBAL # else # define LT_DLGLOBAL 0 # endif #endif /* We may have to define LT_DLLAZY_OR_NOW in the command line if we find out it does not work in some platform. */ #ifndef LT_DLLAZY_OR_NOW # ifdef RTLD_LAZY # define LT_DLLAZY_OR_NOW RTLD_LAZY # else # ifdef DL_LAZY # define LT_DLLAZY_OR_NOW DL_LAZY # else # ifdef RTLD_NOW # define LT_DLLAZY_OR_NOW RTLD_NOW # else # ifdef DL_NOW # define LT_DLLAZY_OR_NOW DL_NOW # else # define LT_DLLAZY_OR_NOW 0 # endif # endif # endif # endif #endif /* When -fvisbility=hidden is used, assume the code has been annotated correspondingly for the symbols needed. */ #if defined(__GNUC__) && (((__GNUC__ == 3) && (__GNUC_MINOR__ >= 3)) || (__GNUC__ > 3)) int fnord () __attribute__((visibility("default"))); #endif int fnord () { return 42; } int main () { void *self = dlopen (0, LT_DLGLOBAL|LT_DLLAZY_OR_NOW); int status = $lt_dlunknown; if (self) { if (dlsym (self,"fnord")) status = $lt_dlno_uscore; else { if (dlsym( self,"_fnord")) status = $lt_dlneed_uscore; else puts (dlerror ()); } /* dlclose (self); */ } else puts (dlerror ()); return status; } _LT_EOF if { { eval echo "\"\$as_me\":${as_lineno-$LINENO}: \"$ac_link\""; } >&5 (eval $ac_link) 2>&5 ac_status=$? $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 test $ac_status = 0; } && test -s conftest${ac_exeext} 2>/dev/null; then (./conftest; exit; ) >&5 2>/dev/null lt_status=$? case x$lt_status in x$lt_dlno_uscore) lt_cv_dlopen_self=yes ;; x$lt_dlneed_uscore) lt_cv_dlopen_self=yes ;; x$lt_dlunknown|x*) lt_cv_dlopen_self=no ;; esac else : # compilation failed lt_cv_dlopen_self=no fi fi rm -fr conftest* fi { $as_echo "$as_me:${as_lineno-$LINENO}: result: $lt_cv_dlopen_self" >&5 $as_echo "$lt_cv_dlopen_self" >&6; } if test "x$lt_cv_dlopen_self" = xyes; then wl=$lt_prog_compiler_wl eval LDFLAGS=\"\$LDFLAGS $lt_prog_compiler_static\" { $as_echo "$as_me:${as_lineno-$LINENO}: checking whether a statically linked program can dlopen itself" >&5 $as_echo_n "checking whether a statically linked program can dlopen itself... " >&6; } if ${lt_cv_dlopen_self_static+:} false; then : $as_echo_n "(cached) " >&6 else if test "$cross_compiling" = yes; then : lt_cv_dlopen_self_static=cross else lt_dlunknown=0; lt_dlno_uscore=1; lt_dlneed_uscore=2 lt_status=$lt_dlunknown cat > conftest.$ac_ext <<_LT_EOF #line $LINENO "configure" #include "confdefs.h" #if HAVE_DLFCN_H #include #endif #include #ifdef RTLD_GLOBAL # define LT_DLGLOBAL RTLD_GLOBAL #else # ifdef DL_GLOBAL # define LT_DLGLOBAL DL_GLOBAL # else # define LT_DLGLOBAL 0 # endif #endif /* We may have to define LT_DLLAZY_OR_NOW in the command line if we find out it does not work in some platform. */ #ifndef LT_DLLAZY_OR_NOW # ifdef RTLD_LAZY # define LT_DLLAZY_OR_NOW RTLD_LAZY # else # ifdef DL_LAZY # define LT_DLLAZY_OR_NOW DL_LAZY # else # ifdef RTLD_NOW # define LT_DLLAZY_OR_NOW RTLD_NOW # else # ifdef DL_NOW # define LT_DLLAZY_OR_NOW DL_NOW # else # define LT_DLLAZY_OR_NOW 0 # endif # endif # endif # endif #endif /* When -fvisbility=hidden is used, assume the code has been annotated correspondingly for the symbols needed. */ #if defined(__GNUC__) && (((__GNUC__ == 3) && (__GNUC_MINOR__ >= 3)) || (__GNUC__ > 3)) int fnord () __attribute__((visibility("default"))); #endif int fnord () { return 42; } int main () { void *self = dlopen (0, LT_DLGLOBAL|LT_DLLAZY_OR_NOW); int status = $lt_dlunknown; if (self) { if (dlsym (self,"fnord")) status = $lt_dlno_uscore; else { if (dlsym( self,"_fnord")) status = $lt_dlneed_uscore; else puts (dlerror ()); } /* dlclose (self); */ } else puts (dlerror ()); return status; } _LT_EOF if { { eval echo "\"\$as_me\":${as_lineno-$LINENO}: \"$ac_link\""; } >&5 (eval $ac_link) 2>&5 ac_status=$? $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 test $ac_status = 0; } && test -s conftest${ac_exeext} 2>/dev/null; then (./conftest; exit; ) >&5 2>/dev/null lt_status=$? case x$lt_status in x$lt_dlno_uscore) lt_cv_dlopen_self_static=yes ;; x$lt_dlneed_uscore) lt_cv_dlopen_self_static=yes ;; x$lt_dlunknown|x*) lt_cv_dlopen_self_static=no ;; esac else : # compilation failed lt_cv_dlopen_self_static=no fi fi rm -fr conftest* fi { $as_echo "$as_me:${as_lineno-$LINENO}: result: $lt_cv_dlopen_self_static" >&5 $as_echo "$lt_cv_dlopen_self_static" >&6; } fi CPPFLAGS="$save_CPPFLAGS" LDFLAGS="$save_LDFLAGS" LIBS="$save_LIBS" ;; esac case $lt_cv_dlopen_self in yes|no) enable_dlopen_self=$lt_cv_dlopen_self ;; *) enable_dlopen_self=unknown ;; esac case $lt_cv_dlopen_self_static in yes|no) enable_dlopen_self_static=$lt_cv_dlopen_self_static ;; *) enable_dlopen_self_static=unknown ;; esac fi striplib= old_striplib= { $as_echo "$as_me:${as_lineno-$LINENO}: checking whether stripping libraries is possible" >&5 $as_echo_n "checking whether stripping libraries is possible... " >&6; } if test -n "$STRIP" && $STRIP -V 2>&1 | $GREP "GNU strip" >/dev/null; then test -z "$old_striplib" && old_striplib="$STRIP --strip-debug" test -z "$striplib" && striplib="$STRIP --strip-unneeded" { $as_echo "$as_me:${as_lineno-$LINENO}: result: yes" >&5 $as_echo "yes" >&6; } else # FIXME - insert some real tests, host_os isn't really good enough case $host_os in darwin*) if test -n "$STRIP" ; then striplib="$STRIP -x" old_striplib="$STRIP -S" { $as_echo "$as_me:${as_lineno-$LINENO}: result: yes" >&5 $as_echo "yes" >&6; } else { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 $as_echo "no" >&6; } fi ;; *) { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 $as_echo "no" >&6; } ;; esac fi # Report which library types will actually be built { $as_echo "$as_me:${as_lineno-$LINENO}: checking if libtool supports shared libraries" >&5 $as_echo_n "checking if libtool supports shared libraries... " >&6; } { $as_echo "$as_me:${as_lineno-$LINENO}: result: $can_build_shared" >&5 $as_echo "$can_build_shared" >&6; } { $as_echo "$as_me:${as_lineno-$LINENO}: checking whether to build shared libraries" >&5 $as_echo_n "checking whether to build shared libraries... " >&6; } test "$can_build_shared" = "no" && enable_shared=no # On AIX, shared libraries and static libraries use the same namespace, and # are all built from PIC. case $host_os in aix3*) test "$enable_shared" = yes && enable_static=no if test -n "$RANLIB"; then archive_cmds="$archive_cmds~\$RANLIB \$lib" postinstall_cmds='$RANLIB $lib' fi ;; aix[4-9]*) if test "$host_cpu" != ia64 && test "$aix_use_runtimelinking" = no ; then test "$enable_shared" = yes && enable_static=no fi ;; esac { $as_echo "$as_me:${as_lineno-$LINENO}: result: $enable_shared" >&5 $as_echo "$enable_shared" >&6; } { $as_echo "$as_me:${as_lineno-$LINENO}: checking whether to build static libraries" >&5 $as_echo_n "checking whether to build static libraries... " >&6; } # Make sure either enable_shared or enable_static is yes. test "$enable_shared" = yes || enable_static=yes { $as_echo "$as_me:${as_lineno-$LINENO}: result: $enable_static" >&5 $as_echo "$enable_static" >&6; } fi ac_ext=c ac_cpp='$CPP $CPPFLAGS' ac_compile='$CC -c $CFLAGS $CPPFLAGS conftest.$ac_ext >&5' ac_link='$CC -o conftest$ac_exeext $CFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5' ac_compiler_gnu=$ac_cv_c_compiler_gnu CC="$lt_save_CC" ac_config_commands="$ac_config_commands libtool" # Only expand once: { $as_echo "$as_me:${as_lineno-$LINENO}: checking whether ln -s works" >&5 $as_echo_n "checking whether ln -s works... " >&6; } LN_S=$as_ln_s if test "$LN_S" = "ln -s"; then { $as_echo "$as_me:${as_lineno-$LINENO}: result: yes" >&5 $as_echo "yes" >&6; } else { $as_echo "$as_me:${as_lineno-$LINENO}: result: no, using $LN_S" >&5 $as_echo "no, using $LN_S" >&6; } fi if test "x$ac_cv_env_PKG_CONFIG_set" != "xset"; then if test -n "$ac_tool_prefix"; then # Extract the first word of "${ac_tool_prefix}pkg-config", so it can be a program name with args. set dummy ${ac_tool_prefix}pkg-config; ac_word=$2 { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 $as_echo_n "checking for $ac_word... " >&6; } if ${ac_cv_path_PKG_CONFIG+:} false; then : $as_echo_n "(cached) " >&6 else case $PKG_CONFIG in [\\/]* | ?:[\\/]*) ac_cv_path_PKG_CONFIG="$PKG_CONFIG" # Let the user override the test with a path. ;; *) as_save_IFS=$IFS; IFS=$PATH_SEPARATOR for as_dir in $PATH do IFS=$as_save_IFS test -z "$as_dir" && as_dir=. for ac_exec_ext in '' $ac_executable_extensions; do if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then ac_cv_path_PKG_CONFIG="$as_dir/$ac_word$ac_exec_ext" $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5 break 2 fi done done IFS=$as_save_IFS ;; esac fi PKG_CONFIG=$ac_cv_path_PKG_CONFIG if test -n "$PKG_CONFIG"; then { $as_echo "$as_me:${as_lineno-$LINENO}: result: $PKG_CONFIG" >&5 $as_echo "$PKG_CONFIG" >&6; } else { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 $as_echo "no" >&6; } fi fi if test -z "$ac_cv_path_PKG_CONFIG"; then ac_pt_PKG_CONFIG=$PKG_CONFIG # Extract the first word of "pkg-config", so it can be a program name with args. set dummy pkg-config; ac_word=$2 { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 $as_echo_n "checking for $ac_word... " >&6; } if ${ac_cv_path_ac_pt_PKG_CONFIG+:} false; then : $as_echo_n "(cached) " >&6 else case $ac_pt_PKG_CONFIG in [\\/]* | ?:[\\/]*) ac_cv_path_ac_pt_PKG_CONFIG="$ac_pt_PKG_CONFIG" # Let the user override the test with a path. ;; *) as_save_IFS=$IFS; IFS=$PATH_SEPARATOR for as_dir in $PATH do IFS=$as_save_IFS test -z "$as_dir" && as_dir=. for ac_exec_ext in '' $ac_executable_extensions; do if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then ac_cv_path_ac_pt_PKG_CONFIG="$as_dir/$ac_word$ac_exec_ext" $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5 break 2 fi done done IFS=$as_save_IFS ;; esac fi ac_pt_PKG_CONFIG=$ac_cv_path_ac_pt_PKG_CONFIG if test -n "$ac_pt_PKG_CONFIG"; then { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_pt_PKG_CONFIG" >&5 $as_echo "$ac_pt_PKG_CONFIG" >&6; } else { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 $as_echo "no" >&6; } fi if test "x$ac_pt_PKG_CONFIG" = x; then PKG_CONFIG="" else case $cross_compiling:$ac_tool_warned in yes:) { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: using cross tools not prefixed with host triplet" >&5 $as_echo "$as_me: WARNING: using cross tools not prefixed with host triplet" >&2;} ac_tool_warned=yes ;; esac PKG_CONFIG=$ac_pt_PKG_CONFIG fi else PKG_CONFIG="$ac_cv_path_PKG_CONFIG" fi fi if test -n "$PKG_CONFIG"; then _pkg_min_version=0.9.0 { $as_echo "$as_me:${as_lineno-$LINENO}: checking pkg-config is at least version $_pkg_min_version" >&5 $as_echo_n "checking pkg-config is at least version $_pkg_min_version... " >&6; } if $PKG_CONFIG --atleast-pkgconfig-version $_pkg_min_version; then { $as_echo "$as_me:${as_lineno-$LINENO}: result: yes" >&5 $as_echo "yes" >&6; } else { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 $as_echo "no" >&6; } PKG_CONFIG="" fi fi ac_ext=cpp ac_cpp='$CXXCPP $CPPFLAGS' ac_compile='$CXX -c $CXXFLAGS $CPPFLAGS conftest.$ac_ext >&5' ac_link='$CXX -o conftest$ac_exeext $CXXFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5' ac_compiler_gnu=$ac_cv_cxx_compiler_gnu if test -z "$CXX"; then if test -n "$CCC"; then CXX=$CCC else if test -n "$ac_tool_prefix"; then for ac_prog in g++ c++ gpp aCC CC cxx cc++ cl.exe FCC KCC RCC xlC_r xlC do # Extract the first word of "$ac_tool_prefix$ac_prog", so it can be a program name with args. set dummy $ac_tool_prefix$ac_prog; ac_word=$2 { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 $as_echo_n "checking for $ac_word... " >&6; } if ${ac_cv_prog_CXX+:} false; then : $as_echo_n "(cached) " >&6 else if test -n "$CXX"; then ac_cv_prog_CXX="$CXX" # Let the user override the test. else as_save_IFS=$IFS; IFS=$PATH_SEPARATOR for as_dir in $PATH do IFS=$as_save_IFS test -z "$as_dir" && as_dir=. for ac_exec_ext in '' $ac_executable_extensions; do if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then ac_cv_prog_CXX="$ac_tool_prefix$ac_prog" $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5 break 2 fi done done IFS=$as_save_IFS fi fi CXX=$ac_cv_prog_CXX if test -n "$CXX"; then { $as_echo "$as_me:${as_lineno-$LINENO}: result: $CXX" >&5 $as_echo "$CXX" >&6; } else { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 $as_echo "no" >&6; } fi test -n "$CXX" && break done fi if test -z "$CXX"; then ac_ct_CXX=$CXX for ac_prog in g++ c++ gpp aCC CC cxx cc++ cl.exe FCC KCC RCC xlC_r xlC do # Extract the first word of "$ac_prog", so it can be a program name with args. set dummy $ac_prog; ac_word=$2 { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 $as_echo_n "checking for $ac_word... " >&6; } if ${ac_cv_prog_ac_ct_CXX+:} false; then : $as_echo_n "(cached) " >&6 else if test -n "$ac_ct_CXX"; then ac_cv_prog_ac_ct_CXX="$ac_ct_CXX" # Let the user override the test. else as_save_IFS=$IFS; IFS=$PATH_SEPARATOR for as_dir in $PATH do IFS=$as_save_IFS test -z "$as_dir" && as_dir=. for ac_exec_ext in '' $ac_executable_extensions; do if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then ac_cv_prog_ac_ct_CXX="$ac_prog" $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5 break 2 fi done done IFS=$as_save_IFS fi fi ac_ct_CXX=$ac_cv_prog_ac_ct_CXX if test -n "$ac_ct_CXX"; then { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_ct_CXX" >&5 $as_echo "$ac_ct_CXX" >&6; } else { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 $as_echo "no" >&6; } fi test -n "$ac_ct_CXX" && break done if test "x$ac_ct_CXX" = x; then CXX="g++" else case $cross_compiling:$ac_tool_warned in yes:) { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: using cross tools not prefixed with host triplet" >&5 $as_echo "$as_me: WARNING: using cross tools not prefixed with host triplet" >&2;} ac_tool_warned=yes ;; esac CXX=$ac_ct_CXX fi fi fi fi # Provide some information about the compiler. $as_echo "$as_me:${as_lineno-$LINENO}: checking for C++ compiler version" >&5 set X $ac_compile ac_compiler=$2 for ac_option in --version -v -V -qversion; do { { ac_try="$ac_compiler $ac_option >&5" case "(($ac_try" in *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac eval ac_try_echo="\"\$as_me:${as_lineno-$LINENO}: $ac_try_echo\"" $as_echo "$ac_try_echo"; } >&5 (eval "$ac_compiler $ac_option >&5") 2>conftest.err ac_status=$? if test -s conftest.err; then sed '10a\ ... rest of stderr output deleted ... 10q' conftest.err >conftest.er1 cat conftest.er1 >&5 fi rm -f conftest.er1 conftest.err $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 test $ac_status = 0; } done { $as_echo "$as_me:${as_lineno-$LINENO}: checking whether we are using the GNU C++ compiler" >&5 $as_echo_n "checking whether we are using the GNU C++ compiler... " >&6; } if ${ac_cv_cxx_compiler_gnu+:} false; then : $as_echo_n "(cached) " >&6 else cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ int main () { #ifndef __GNUC__ choke me #endif ; return 0; } _ACEOF if ac_fn_cxx_try_compile "$LINENO"; then : ac_compiler_gnu=yes else ac_compiler_gnu=no fi rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext ac_cv_cxx_compiler_gnu=$ac_compiler_gnu fi { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_cxx_compiler_gnu" >&5 $as_echo "$ac_cv_cxx_compiler_gnu" >&6; } if test $ac_compiler_gnu = yes; then GXX=yes else GXX= fi ac_test_CXXFLAGS=${CXXFLAGS+set} ac_save_CXXFLAGS=$CXXFLAGS { $as_echo "$as_me:${as_lineno-$LINENO}: checking whether $CXX accepts -g" >&5 $as_echo_n "checking whether $CXX accepts -g... " >&6; } if ${ac_cv_prog_cxx_g+:} false; then : $as_echo_n "(cached) " >&6 else ac_save_cxx_werror_flag=$ac_cxx_werror_flag ac_cxx_werror_flag=yes ac_cv_prog_cxx_g=no CXXFLAGS="-g" cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ int main () { ; return 0; } _ACEOF if ac_fn_cxx_try_compile "$LINENO"; then : ac_cv_prog_cxx_g=yes else CXXFLAGS="" cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ int main () { ; return 0; } _ACEOF if ac_fn_cxx_try_compile "$LINENO"; then : else ac_cxx_werror_flag=$ac_save_cxx_werror_flag CXXFLAGS="-g" cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ int main () { ; return 0; } _ACEOF if ac_fn_cxx_try_compile "$LINENO"; then : ac_cv_prog_cxx_g=yes fi rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext fi rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext fi rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext ac_cxx_werror_flag=$ac_save_cxx_werror_flag fi { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_prog_cxx_g" >&5 $as_echo "$ac_cv_prog_cxx_g" >&6; } if test "$ac_test_CXXFLAGS" = set; then CXXFLAGS=$ac_save_CXXFLAGS elif test $ac_cv_prog_cxx_g = yes; then if test "$GXX" = yes; then CXXFLAGS="-g -O2" else CXXFLAGS="-g" fi else if test "$GXX" = yes; then CXXFLAGS="-O2" else CXXFLAGS= fi fi ac_ext=c ac_cpp='$CPP $CPPFLAGS' ac_compile='$CC -c $CFLAGS $CPPFLAGS conftest.$ac_ext >&5' ac_link='$CC -o conftest$ac_exeext $CFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5' ac_compiler_gnu=$ac_cv_c_compiler_gnu depcc="$CXX" am_compiler_list= { $as_echo "$as_me:${as_lineno-$LINENO}: checking dependency style of $depcc" >&5 $as_echo_n "checking dependency style of $depcc... " >&6; } if ${am_cv_CXX_dependencies_compiler_type+:} false; then : $as_echo_n "(cached) " >&6 else if test -z "$AMDEP_TRUE" && test -f "$am_depcomp"; then # We make a subdir and do the tests there. Otherwise we can end up # making bogus files that we don't know about and never remove. For # instance it was reported that on HP-UX the gcc test will end up # making a dummy file named `D' -- because `-MD' means `put the output # in D'. rm -rf conftest.dir mkdir conftest.dir # Copy depcomp to subdir because otherwise we won't find it if we're # using a relative directory. cp "$am_depcomp" conftest.dir cd conftest.dir # We will build objects and dependencies in a subdirectory because # it helps to detect inapplicable dependency modes. For instance # both Tru64's cc and ICC support -MD to output dependencies as a # side effect of compilation, but ICC will put the dependencies in # the current directory while Tru64 will put them in the object # directory. mkdir sub am_cv_CXX_dependencies_compiler_type=none if test "$am_compiler_list" = ""; then am_compiler_list=`sed -n 's/^#*\([a-zA-Z0-9]*\))$/\1/p' < ./depcomp` fi am__universal=false case " $depcc " in #( *\ -arch\ *\ -arch\ *) am__universal=true ;; esac for depmode in $am_compiler_list; do # Setup a source with many dependencies, because some compilers # like to wrap large dependency lists on column 80 (with \), and # we should not choose a depcomp mode which is confused by this. # # We need to recreate these files for each test, as the compiler may # overwrite some of them when testing with obscure command lines. # This happens at least with the AIX C compiler. : > sub/conftest.c for i in 1 2 3 4 5 6; do echo '#include "conftst'$i'.h"' >> sub/conftest.c # Using `: > sub/conftst$i.h' creates only sub/conftst1.h with # Solaris 8's {/usr,}/bin/sh. touch sub/conftst$i.h done echo "${am__include} ${am__quote}sub/conftest.Po${am__quote}" > confmf # We check with `-c' and `-o' for the sake of the "dashmstdout" # mode. It turns out that the SunPro C++ compiler does not properly # handle `-M -o', and we need to detect this. Also, some Intel # versions had trouble with output in subdirs am__obj=sub/conftest.${OBJEXT-o} am__minus_obj="-o $am__obj" case $depmode in gcc) # This depmode causes a compiler race in universal mode. test "$am__universal" = false || continue ;; nosideeffect) # after this tag, mechanisms are not by side-effect, so they'll # only be used when explicitly requested if test "x$enable_dependency_tracking" = xyes; then continue else break fi ;; msvc7 | msvc7msys | msvisualcpp | msvcmsys) # This compiler won't grok `-c -o', but also, the minuso test has # not run yet. These depmodes are late enough in the game, and # so weak that their functioning should not be impacted. am__obj=conftest.${OBJEXT-o} am__minus_obj= ;; none) break ;; esac if depmode=$depmode \ source=sub/conftest.c object=$am__obj \ depfile=sub/conftest.Po tmpdepfile=sub/conftest.TPo \ $SHELL ./depcomp $depcc -c $am__minus_obj sub/conftest.c \ >/dev/null 2>conftest.err && grep sub/conftst1.h sub/conftest.Po > /dev/null 2>&1 && grep sub/conftst6.h sub/conftest.Po > /dev/null 2>&1 && grep $am__obj sub/conftest.Po > /dev/null 2>&1 && ${MAKE-make} -s -f confmf > /dev/null 2>&1; then # icc doesn't choke on unknown options, it will just issue warnings # or remarks (even with -Werror). So we grep stderr for any message # that says an option was ignored or not supported. # When given -MP, icc 7.0 and 7.1 complain thusly: # icc: Command line warning: ignoring option '-M'; no argument required # The diagnosis changed in icc 8.0: # icc: Command line remark: option '-MP' not supported if (grep 'ignoring option' conftest.err || grep 'not supported' conftest.err) >/dev/null 2>&1; then :; else am_cv_CXX_dependencies_compiler_type=$depmode break fi fi done cd .. rm -rf conftest.dir else am_cv_CXX_dependencies_compiler_type=none fi fi { $as_echo "$as_me:${as_lineno-$LINENO}: result: $am_cv_CXX_dependencies_compiler_type" >&5 $as_echo "$am_cv_CXX_dependencies_compiler_type" >&6; } CXXDEPMODE=depmode=$am_cv_CXX_dependencies_compiler_type if test "x$enable_dependency_tracking" != xno \ && test "$am_cv_CXX_dependencies_compiler_type" = gcc3; then am__fastdepCXX_TRUE= am__fastdepCXX_FALSE='#' else am__fastdepCXX_TRUE='#' am__fastdepCXX_FALSE= fi func_stripname_cnf () { case ${2} in .*) func_stripname_result=`$ECHO "${3}" | $SED "s%^${1}%%; s%\\\\${2}\$%%"`;; *) func_stripname_result=`$ECHO "${3}" | $SED "s%^${1}%%; s%${2}\$%%"`;; esac } # func_stripname_cnf if test -n "$CXX" && ( test "X$CXX" != "Xno" && ( (test "X$CXX" = "Xg++" && `g++ -v >/dev/null 2>&1` ) || (test "X$CXX" != "Xg++"))) ; then ac_ext=cpp ac_cpp='$CXXCPP $CPPFLAGS' ac_compile='$CXX -c $CXXFLAGS $CPPFLAGS conftest.$ac_ext >&5' ac_link='$CXX -o conftest$ac_exeext $CXXFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5' ac_compiler_gnu=$ac_cv_cxx_compiler_gnu { $as_echo "$as_me:${as_lineno-$LINENO}: checking how to run the C++ preprocessor" >&5 $as_echo_n "checking how to run the C++ preprocessor... " >&6; } if test -z "$CXXCPP"; then if ${ac_cv_prog_CXXCPP+:} false; then : $as_echo_n "(cached) " >&6 else # Double quotes because CXXCPP needs to be expanded for CXXCPP in "$CXX -E" "/lib/cpp" do ac_preproc_ok=false for ac_cxx_preproc_warn_flag in '' yes do # Use a header file that comes with gcc, so configuring glibc # with a fresh cross-compiler works. # Prefer to if __STDC__ is defined, since # exists even on freestanding compilers. # On the NeXT, cc -E runs the code through the compiler's parser, # not just through cpp. "Syntax error" is here to catch this case. cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ #ifdef __STDC__ # include #else # include #endif Syntax error _ACEOF if ac_fn_cxx_try_cpp "$LINENO"; then : else # Broken: fails on valid input. continue fi rm -f conftest.err conftest.i conftest.$ac_ext # OK, works on sane cases. Now check whether nonexistent headers # can be detected and how. cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ #include _ACEOF if ac_fn_cxx_try_cpp "$LINENO"; then : # Broken: success on invalid input. continue else # Passes both tests. ac_preproc_ok=: break fi rm -f conftest.err conftest.i conftest.$ac_ext done # Because of `break', _AC_PREPROC_IFELSE's cleaning code was skipped. rm -f conftest.i conftest.err conftest.$ac_ext if $ac_preproc_ok; then : break fi done ac_cv_prog_CXXCPP=$CXXCPP fi CXXCPP=$ac_cv_prog_CXXCPP else ac_cv_prog_CXXCPP=$CXXCPP fi { $as_echo "$as_me:${as_lineno-$LINENO}: result: $CXXCPP" >&5 $as_echo "$CXXCPP" >&6; } ac_preproc_ok=false for ac_cxx_preproc_warn_flag in '' yes do # Use a header file that comes with gcc, so configuring glibc # with a fresh cross-compiler works. # Prefer to if __STDC__ is defined, since # exists even on freestanding compilers. # On the NeXT, cc -E runs the code through the compiler's parser, # not just through cpp. "Syntax error" is here to catch this case. cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ #ifdef __STDC__ # include #else # include #endif Syntax error _ACEOF if ac_fn_cxx_try_cpp "$LINENO"; then : else # Broken: fails on valid input. continue fi rm -f conftest.err conftest.i conftest.$ac_ext # OK, works on sane cases. Now check whether nonexistent headers # can be detected and how. cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ #include _ACEOF if ac_fn_cxx_try_cpp "$LINENO"; then : # Broken: success on invalid input. continue else # Passes both tests. ac_preproc_ok=: break fi rm -f conftest.err conftest.i conftest.$ac_ext done # Because of `break', _AC_PREPROC_IFELSE's cleaning code was skipped. rm -f conftest.i conftest.err conftest.$ac_ext if $ac_preproc_ok; then : else { { $as_echo "$as_me:${as_lineno-$LINENO}: error: in \`$ac_pwd':" >&5 $as_echo "$as_me: error: in \`$ac_pwd':" >&2;} as_fn_error $? "C++ preprocessor \"$CXXCPP\" fails sanity check See \`config.log' for more details" "$LINENO" 5; } fi ac_ext=c ac_cpp='$CPP $CPPFLAGS' ac_compile='$CC -c $CFLAGS $CPPFLAGS conftest.$ac_ext >&5' ac_link='$CC -o conftest$ac_exeext $CFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5' ac_compiler_gnu=$ac_cv_c_compiler_gnu else _lt_caught_CXX_error=yes fi ac_ext=cpp ac_cpp='$CXXCPP $CPPFLAGS' ac_compile='$CXX -c $CXXFLAGS $CPPFLAGS conftest.$ac_ext >&5' ac_link='$CXX -o conftest$ac_exeext $CXXFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5' ac_compiler_gnu=$ac_cv_cxx_compiler_gnu archive_cmds_need_lc_CXX=no allow_undefined_flag_CXX= always_export_symbols_CXX=no archive_expsym_cmds_CXX= compiler_needs_object_CXX=no export_dynamic_flag_spec_CXX= hardcode_direct_CXX=no hardcode_direct_absolute_CXX=no hardcode_libdir_flag_spec_CXX= hardcode_libdir_separator_CXX= hardcode_minus_L_CXX=no hardcode_shlibpath_var_CXX=unsupported hardcode_automatic_CXX=no inherit_rpath_CXX=no module_cmds_CXX= module_expsym_cmds_CXX= link_all_deplibs_CXX=unknown old_archive_cmds_CXX=$old_archive_cmds reload_flag_CXX=$reload_flag reload_cmds_CXX=$reload_cmds no_undefined_flag_CXX= whole_archive_flag_spec_CXX= enable_shared_with_static_runtimes_CXX=no # Source file extension for C++ test sources. ac_ext=cpp # Object file extension for compiled C++ test sources. objext=o objext_CXX=$objext # No sense in running all these tests if we already determined that # the CXX compiler isn't working. Some variables (like enable_shared) # are currently assumed to apply to all compilers on this platform, # and will be corrupted by setting them based on a non-working compiler. if test "$_lt_caught_CXX_error" != yes; then # Code to be used in simple compile tests lt_simple_compile_test_code="int some_variable = 0;" # Code to be used in simple link tests lt_simple_link_test_code='int main(int, char *[]) { return(0); }' # ltmain only uses $CC for tagged configurations so make sure $CC is set. # If no C compiler was specified, use CC. LTCC=${LTCC-"$CC"} # If no C compiler flags were specified, use CFLAGS. LTCFLAGS=${LTCFLAGS-"$CFLAGS"} # Allow CC to be a program name with arguments. compiler=$CC # save warnings/boilerplate of simple test code ac_outfile=conftest.$ac_objext echo "$lt_simple_compile_test_code" >conftest.$ac_ext eval "$ac_compile" 2>&1 >/dev/null | $SED '/^$/d; /^ *+/d' >conftest.err _lt_compiler_boilerplate=`cat conftest.err` $RM conftest* ac_outfile=conftest.$ac_objext echo "$lt_simple_link_test_code" >conftest.$ac_ext eval "$ac_link" 2>&1 >/dev/null | $SED '/^$/d; /^ *+/d' >conftest.err _lt_linker_boilerplate=`cat conftest.err` $RM -r conftest* # Allow CC to be a program name with arguments. lt_save_CC=$CC lt_save_CFLAGS=$CFLAGS lt_save_LD=$LD lt_save_GCC=$GCC GCC=$GXX lt_save_with_gnu_ld=$with_gnu_ld lt_save_path_LD=$lt_cv_path_LD if test -n "${lt_cv_prog_gnu_ldcxx+set}"; then lt_cv_prog_gnu_ld=$lt_cv_prog_gnu_ldcxx else $as_unset lt_cv_prog_gnu_ld fi if test -n "${lt_cv_path_LDCXX+set}"; then lt_cv_path_LD=$lt_cv_path_LDCXX else $as_unset lt_cv_path_LD fi test -z "${LDCXX+set}" || LD=$LDCXX CC=${CXX-"c++"} CFLAGS=$CXXFLAGS compiler=$CC compiler_CXX=$CC for cc_temp in $compiler""; do case $cc_temp in compile | *[\\/]compile | ccache | *[\\/]ccache ) ;; distcc | *[\\/]distcc | purify | *[\\/]purify ) ;; \-*) ;; *) break;; esac done cc_basename=`$ECHO "$cc_temp" | $SED "s%.*/%%; s%^$host_alias-%%"` if test -n "$compiler"; then # We don't want -fno-exception when compiling C++ code, so set the # no_builtin_flag separately if test "$GXX" = yes; then lt_prog_compiler_no_builtin_flag_CXX=' -fno-builtin' else lt_prog_compiler_no_builtin_flag_CXX= fi if test "$GXX" = yes; then # Set up default GNU C++ configuration # Check whether --with-gnu-ld was given. if test "${with_gnu_ld+set}" = set; then : withval=$with_gnu_ld; test "$withval" = no || with_gnu_ld=yes else with_gnu_ld=no fi ac_prog=ld if test "$GCC" = yes; then # Check if gcc -print-prog-name=ld gives a path. { $as_echo "$as_me:${as_lineno-$LINENO}: checking for ld used by $CC" >&5 $as_echo_n "checking for ld used by $CC... " >&6; } case $host in *-*-mingw*) # gcc leaves a trailing carriage return which upsets mingw ac_prog=`($CC -print-prog-name=ld) 2>&5 | tr -d '\015'` ;; *) ac_prog=`($CC -print-prog-name=ld) 2>&5` ;; esac case $ac_prog in # Accept absolute paths. [\\/]* | ?:[\\/]*) re_direlt='/[^/][^/]*/\.\./' # Canonicalize the pathname of ld ac_prog=`$ECHO "$ac_prog"| $SED 's%\\\\%/%g'` while $ECHO "$ac_prog" | $GREP "$re_direlt" > /dev/null 2>&1; do ac_prog=`$ECHO $ac_prog| $SED "s%$re_direlt%/%"` done test -z "$LD" && LD="$ac_prog" ;; "") # If it fails, then pretend we aren't using GCC. ac_prog=ld ;; *) # If it is relative, then search for the first ld in PATH. with_gnu_ld=unknown ;; esac elif test "$with_gnu_ld" = yes; then { $as_echo "$as_me:${as_lineno-$LINENO}: checking for GNU ld" >&5 $as_echo_n "checking for GNU ld... " >&6; } else { $as_echo "$as_me:${as_lineno-$LINENO}: checking for non-GNU ld" >&5 $as_echo_n "checking for non-GNU ld... " >&6; } fi if ${lt_cv_path_LD+:} false; then : $as_echo_n "(cached) " >&6 else if test -z "$LD"; then lt_save_ifs="$IFS"; IFS=$PATH_SEPARATOR for ac_dir in $PATH; do IFS="$lt_save_ifs" test -z "$ac_dir" && ac_dir=. if test -f "$ac_dir/$ac_prog" || test -f "$ac_dir/$ac_prog$ac_exeext"; then lt_cv_path_LD="$ac_dir/$ac_prog" # Check to see if the program is GNU ld. I'd rather use --version, # but apparently some variants of GNU ld only accept -v. # Break only if it was the GNU/non-GNU ld that we prefer. case `"$lt_cv_path_LD" -v 2>&1 &5 $as_echo "$LD" >&6; } else { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 $as_echo "no" >&6; } fi test -z "$LD" && as_fn_error $? "no acceptable ld found in \$PATH" "$LINENO" 5 { $as_echo "$as_me:${as_lineno-$LINENO}: checking if the linker ($LD) is GNU ld" >&5 $as_echo_n "checking if the linker ($LD) is GNU ld... " >&6; } if ${lt_cv_prog_gnu_ld+:} false; then : $as_echo_n "(cached) " >&6 else # I'd rather use --version here, but apparently some GNU lds only accept -v. case `$LD -v 2>&1 &5 $as_echo "$lt_cv_prog_gnu_ld" >&6; } with_gnu_ld=$lt_cv_prog_gnu_ld # Check if GNU C++ uses GNU ld as the underlying linker, since the # archiving commands below assume that GNU ld is being used. if test "$with_gnu_ld" = yes; then archive_cmds_CXX='$CC $pic_flag -shared -nostdlib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags ${wl}-soname $wl$soname -o $lib' archive_expsym_cmds_CXX='$CC $pic_flag -shared -nostdlib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags ${wl}-soname $wl$soname ${wl}-retain-symbols-file $wl$export_symbols -o $lib' hardcode_libdir_flag_spec_CXX='${wl}-rpath ${wl}$libdir' export_dynamic_flag_spec_CXX='${wl}--export-dynamic' # If archive_cmds runs LD, not CC, wlarc should be empty # XXX I think wlarc can be eliminated in ltcf-cxx, but I need to # investigate it a little bit more. (MM) wlarc='${wl}' # ancient GNU ld didn't support --whole-archive et. al. if eval "`$CC -print-prog-name=ld` --help 2>&1" | $GREP 'no-whole-archive' > /dev/null; then whole_archive_flag_spec_CXX="$wlarc"'--whole-archive$convenience '"$wlarc"'--no-whole-archive' else whole_archive_flag_spec_CXX= fi else with_gnu_ld=no wlarc= # A generic and very simple default shared library creation # command for GNU C++ for the case where it uses the native # linker, instead of GNU ld. If possible, this setting should # overridden to take advantage of the native linker features on # the platform it is being used on. archive_cmds_CXX='$CC -shared -nostdlib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags -o $lib' fi # Commands to make compiler produce verbose output that lists # what "hidden" libraries, object files and flags are used when # linking a shared library. output_verbose_link_cmd='$CC -shared $CFLAGS -v conftest.$objext 2>&1 | $GREP -v "^Configured with:" | $GREP "\-L"' else GXX=no with_gnu_ld=no wlarc= fi # PORTME: fill in a description of your system's C++ link characteristics { $as_echo "$as_me:${as_lineno-$LINENO}: checking whether the $compiler linker ($LD) supports shared libraries" >&5 $as_echo_n "checking whether the $compiler linker ($LD) supports shared libraries... " >&6; } ld_shlibs_CXX=yes case $host_os in aix3*) # FIXME: insert proper C++ library support ld_shlibs_CXX=no ;; aix[4-9]*) if test "$host_cpu" = ia64; then # On IA64, the linker does run time linking by default, so we don't # have to do anything special. aix_use_runtimelinking=no exp_sym_flag='-Bexport' no_entry_flag="" else aix_use_runtimelinking=no # Test if we are trying to use run time linking or normal # AIX style linking. If -brtl is somewhere in LDFLAGS, we # need to do runtime linking. case $host_os in aix4.[23]|aix4.[23].*|aix[5-9]*) for ld_flag in $LDFLAGS; do case $ld_flag in *-brtl*) aix_use_runtimelinking=yes break ;; esac done ;; esac exp_sym_flag='-bexport' no_entry_flag='-bnoentry' fi # When large executables or shared objects are built, AIX ld can # have problems creating the table of contents. If linking a library # or program results in "error TOC overflow" add -mminimal-toc to # CXXFLAGS/CFLAGS for g++/gcc. In the cases where that is not # enough to fix the problem, add -Wl,-bbigtoc to LDFLAGS. archive_cmds_CXX='' hardcode_direct_CXX=yes hardcode_direct_absolute_CXX=yes hardcode_libdir_separator_CXX=':' link_all_deplibs_CXX=yes file_list_spec_CXX='${wl}-f,' if test "$GXX" = yes; then case $host_os in aix4.[012]|aix4.[012].*) # We only want to do this on AIX 4.2 and lower, the check # below for broken collect2 doesn't work under 4.3+ collect2name=`${CC} -print-prog-name=collect2` if test -f "$collect2name" && strings "$collect2name" | $GREP resolve_lib_name >/dev/null then # We have reworked collect2 : else # We have old collect2 hardcode_direct_CXX=unsupported # It fails to find uninstalled libraries when the uninstalled # path is not listed in the libpath. Setting hardcode_minus_L # to unsupported forces relinking hardcode_minus_L_CXX=yes hardcode_libdir_flag_spec_CXX='-L$libdir' hardcode_libdir_separator_CXX= fi esac shared_flag='-shared' if test "$aix_use_runtimelinking" = yes; then shared_flag="$shared_flag "'${wl}-G' fi else # not using gcc if test "$host_cpu" = ia64; then # VisualAge C++, Version 5.5 for AIX 5L for IA-64, Beta 3 Release # chokes on -Wl,-G. The following line is correct: shared_flag='-G' else if test "$aix_use_runtimelinking" = yes; then shared_flag='${wl}-G' else shared_flag='${wl}-bM:SRE' fi fi fi export_dynamic_flag_spec_CXX='${wl}-bexpall' # It seems that -bexpall does not export symbols beginning with # underscore (_), so it is better to generate a list of symbols to # export. always_export_symbols_CXX=yes if test "$aix_use_runtimelinking" = yes; then # Warning - without using the other runtime loading flags (-brtl), # -berok will link without error, but may produce a broken library. allow_undefined_flag_CXX='-berok' # Determine the default libpath from the value encoded in an empty # executable. if test "${lt_cv_aix_libpath+set}" = set; then aix_libpath=$lt_cv_aix_libpath else if ${lt_cv_aix_libpath__CXX+:} false; then : $as_echo_n "(cached) " >&6 else cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ int main () { ; return 0; } _ACEOF if ac_fn_cxx_try_link "$LINENO"; then : lt_aix_libpath_sed=' /Import File Strings/,/^$/ { /^0/ { s/^0 *\([^ ]*\) *$/\1/ p } }' lt_cv_aix_libpath__CXX=`dump -H conftest$ac_exeext 2>/dev/null | $SED -n -e "$lt_aix_libpath_sed"` # Check for a 64-bit object if we didn't find anything. if test -z "$lt_cv_aix_libpath__CXX"; then lt_cv_aix_libpath__CXX=`dump -HX64 conftest$ac_exeext 2>/dev/null | $SED -n -e "$lt_aix_libpath_sed"` fi fi rm -f core conftest.err conftest.$ac_objext \ conftest$ac_exeext conftest.$ac_ext if test -z "$lt_cv_aix_libpath__CXX"; then lt_cv_aix_libpath__CXX="/usr/lib:/lib" fi fi aix_libpath=$lt_cv_aix_libpath__CXX fi hardcode_libdir_flag_spec_CXX='${wl}-blibpath:$libdir:'"$aix_libpath" archive_expsym_cmds_CXX='$CC -o $output_objdir/$soname $libobjs $deplibs '"\${wl}$no_entry_flag"' $compiler_flags `if test "x${allow_undefined_flag}" != "x"; then func_echo_all "${wl}${allow_undefined_flag}"; else :; fi` '"\${wl}$exp_sym_flag:\$export_symbols $shared_flag" else if test "$host_cpu" = ia64; then hardcode_libdir_flag_spec_CXX='${wl}-R $libdir:/usr/lib:/lib' allow_undefined_flag_CXX="-z nodefs" archive_expsym_cmds_CXX="\$CC $shared_flag"' -o $output_objdir/$soname $libobjs $deplibs '"\${wl}$no_entry_flag"' $compiler_flags ${wl}${allow_undefined_flag} '"\${wl}$exp_sym_flag:\$export_symbols" else # Determine the default libpath from the value encoded in an # empty executable. if test "${lt_cv_aix_libpath+set}" = set; then aix_libpath=$lt_cv_aix_libpath else if ${lt_cv_aix_libpath__CXX+:} false; then : $as_echo_n "(cached) " >&6 else cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ int main () { ; return 0; } _ACEOF if ac_fn_cxx_try_link "$LINENO"; then : lt_aix_libpath_sed=' /Import File Strings/,/^$/ { /^0/ { s/^0 *\([^ ]*\) *$/\1/ p } }' lt_cv_aix_libpath__CXX=`dump -H conftest$ac_exeext 2>/dev/null | $SED -n -e "$lt_aix_libpath_sed"` # Check for a 64-bit object if we didn't find anything. if test -z "$lt_cv_aix_libpath__CXX"; then lt_cv_aix_libpath__CXX=`dump -HX64 conftest$ac_exeext 2>/dev/null | $SED -n -e "$lt_aix_libpath_sed"` fi fi rm -f core conftest.err conftest.$ac_objext \ conftest$ac_exeext conftest.$ac_ext if test -z "$lt_cv_aix_libpath__CXX"; then lt_cv_aix_libpath__CXX="/usr/lib:/lib" fi fi aix_libpath=$lt_cv_aix_libpath__CXX fi hardcode_libdir_flag_spec_CXX='${wl}-blibpath:$libdir:'"$aix_libpath" # Warning - without using the other run time loading flags, # -berok will link without error, but may produce a broken library. no_undefined_flag_CXX=' ${wl}-bernotok' allow_undefined_flag_CXX=' ${wl}-berok' if test "$with_gnu_ld" = yes; then # We only use this code for GNU lds that support --whole-archive. whole_archive_flag_spec_CXX='${wl}--whole-archive$convenience ${wl}--no-whole-archive' else # Exported symbols can be pulled into shared objects from archives whole_archive_flag_spec_CXX='$convenience' fi archive_cmds_need_lc_CXX=yes # This is similar to how AIX traditionally builds its shared # libraries. archive_expsym_cmds_CXX="\$CC $shared_flag"' -o $output_objdir/$soname $libobjs $deplibs ${wl}-bnoentry $compiler_flags ${wl}-bE:$export_symbols${allow_undefined_flag}~$AR $AR_FLAGS $output_objdir/$libname$release.a $output_objdir/$soname' fi fi ;; beos*) if $LD --help 2>&1 | $GREP ': supported targets:.* elf' > /dev/null; then allow_undefined_flag_CXX=unsupported # Joseph Beckenbach says some releases of gcc # support --undefined. This deserves some investigation. FIXME archive_cmds_CXX='$CC -nostart $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname -o $lib' else ld_shlibs_CXX=no fi ;; chorus*) case $cc_basename in *) # FIXME: insert proper C++ library support ld_shlibs_CXX=no ;; esac ;; cygwin* | mingw* | pw32* | cegcc*) case $GXX,$cc_basename in ,cl* | no,cl*) # Native MSVC # hardcode_libdir_flag_spec is actually meaningless, as there is # no search path for DLLs. hardcode_libdir_flag_spec_CXX=' ' allow_undefined_flag_CXX=unsupported always_export_symbols_CXX=yes file_list_spec_CXX='@' # Tell ltmain to make .lib files, not .a files. libext=lib # Tell ltmain to make .dll files, not .so files. shrext_cmds=".dll" # FIXME: Setting linknames here is a bad hack. archive_cmds_CXX='$CC -o $output_objdir/$soname $libobjs $compiler_flags $deplibs -Wl,-dll~linknames=' archive_expsym_cmds_CXX='if test "x`$SED 1q $export_symbols`" = xEXPORTS; then $SED -n -e 's/\\\\\\\(.*\\\\\\\)/-link\\\ -EXPORT:\\\\\\\1/' -e '1\\\!p' < $export_symbols > $output_objdir/$soname.exp; else $SED -e 's/\\\\\\\(.*\\\\\\\)/-link\\\ -EXPORT:\\\\\\\1/' < $export_symbols > $output_objdir/$soname.exp; fi~ $CC -o $tool_output_objdir$soname $libobjs $compiler_flags $deplibs "@$tool_output_objdir$soname.exp" -Wl,-DLL,-IMPLIB:"$tool_output_objdir$libname.dll.lib"~ linknames=' # The linker will not automatically build a static lib if we build a DLL. # _LT_TAGVAR(old_archive_from_new_cmds, CXX)='true' enable_shared_with_static_runtimes_CXX=yes # Don't use ranlib old_postinstall_cmds_CXX='chmod 644 $oldlib' postlink_cmds_CXX='lt_outputfile="@OUTPUT@"~ lt_tool_outputfile="@TOOL_OUTPUT@"~ case $lt_outputfile in *.exe|*.EXE) ;; *) lt_outputfile="$lt_outputfile.exe" lt_tool_outputfile="$lt_tool_outputfile.exe" ;; esac~ func_to_tool_file "$lt_outputfile"~ if test "$MANIFEST_TOOL" != ":" && test -f "$lt_outputfile.manifest"; then $MANIFEST_TOOL -manifest "$lt_tool_outputfile.manifest" -outputresource:"$lt_tool_outputfile" || exit 1; $RM "$lt_outputfile.manifest"; fi' ;; *) # g++ # _LT_TAGVAR(hardcode_libdir_flag_spec, CXX) is actually meaningless, # as there is no search path for DLLs. hardcode_libdir_flag_spec_CXX='-L$libdir' export_dynamic_flag_spec_CXX='${wl}--export-all-symbols' allow_undefined_flag_CXX=unsupported always_export_symbols_CXX=no enable_shared_with_static_runtimes_CXX=yes if $LD --help 2>&1 | $GREP 'auto-import' > /dev/null; then archive_cmds_CXX='$CC -shared -nostdlib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags -o $output_objdir/$soname ${wl}--enable-auto-image-base -Xlinker --out-implib -Xlinker $lib' # If the export-symbols file already is a .def file (1st line # is EXPORTS), use it as is; otherwise, prepend... archive_expsym_cmds_CXX='if test "x`$SED 1q $export_symbols`" = xEXPORTS; then cp $export_symbols $output_objdir/$soname.def; else echo EXPORTS > $output_objdir/$soname.def; cat $export_symbols >> $output_objdir/$soname.def; fi~ $CC -shared -nostdlib $output_objdir/$soname.def $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags -o $output_objdir/$soname ${wl}--enable-auto-image-base -Xlinker --out-implib -Xlinker $lib' else ld_shlibs_CXX=no fi ;; esac ;; darwin* | rhapsody*) archive_cmds_need_lc_CXX=no hardcode_direct_CXX=no hardcode_automatic_CXX=yes hardcode_shlibpath_var_CXX=unsupported if test "$lt_cv_ld_force_load" = "yes"; then whole_archive_flag_spec_CXX='`for conv in $convenience\"\"; do test -n \"$conv\" && new_convenience=\"$new_convenience ${wl}-force_load,$conv\"; done; func_echo_all \"$new_convenience\"`' else whole_archive_flag_spec_CXX='' fi link_all_deplibs_CXX=yes allow_undefined_flag_CXX="$_lt_dar_allow_undefined" case $cc_basename in ifort*) _lt_dar_can_shared=yes ;; *) _lt_dar_can_shared=$GCC ;; esac if test "$_lt_dar_can_shared" = "yes"; then output_verbose_link_cmd=func_echo_all archive_cmds_CXX="\$CC -dynamiclib \$allow_undefined_flag -o \$lib \$libobjs \$deplibs \$compiler_flags -install_name \$rpath/\$soname \$verstring $_lt_dar_single_mod${_lt_dsymutil}" module_cmds_CXX="\$CC \$allow_undefined_flag -o \$lib -bundle \$libobjs \$deplibs \$compiler_flags${_lt_dsymutil}" archive_expsym_cmds_CXX="sed 's,^,_,' < \$export_symbols > \$output_objdir/\${libname}-symbols.expsym~\$CC -dynamiclib \$allow_undefined_flag -o \$lib \$libobjs \$deplibs \$compiler_flags -install_name \$rpath/\$soname \$verstring ${_lt_dar_single_mod}${_lt_dar_export_syms}${_lt_dsymutil}" module_expsym_cmds_CXX="sed -e 's,^,_,' < \$export_symbols > \$output_objdir/\${libname}-symbols.expsym~\$CC \$allow_undefined_flag -o \$lib -bundle \$libobjs \$deplibs \$compiler_flags${_lt_dar_export_syms}${_lt_dsymutil}" if test "$lt_cv_apple_cc_single_mod" != "yes"; then archive_cmds_CXX="\$CC -r -keep_private_externs -nostdlib -o \${lib}-master.o \$libobjs~\$CC -dynamiclib \$allow_undefined_flag -o \$lib \${lib}-master.o \$deplibs \$compiler_flags -install_name \$rpath/\$soname \$verstring${_lt_dsymutil}" archive_expsym_cmds_CXX="sed 's,^,_,' < \$export_symbols > \$output_objdir/\${libname}-symbols.expsym~\$CC -r -keep_private_externs -nostdlib -o \${lib}-master.o \$libobjs~\$CC -dynamiclib \$allow_undefined_flag -o \$lib \${lib}-master.o \$deplibs \$compiler_flags -install_name \$rpath/\$soname \$verstring${_lt_dar_export_syms}${_lt_dsymutil}" fi else ld_shlibs_CXX=no fi ;; dgux*) case $cc_basename in ec++*) # FIXME: insert proper C++ library support ld_shlibs_CXX=no ;; ghcx*) # Green Hills C++ Compiler # FIXME: insert proper C++ library support ld_shlibs_CXX=no ;; *) # FIXME: insert proper C++ library support ld_shlibs_CXX=no ;; esac ;; freebsd2.*) # C++ shared libraries reported to be fairly broken before # switch to ELF ld_shlibs_CXX=no ;; freebsd-elf*) archive_cmds_need_lc_CXX=no ;; freebsd* | dragonfly*) # FreeBSD 3 and later use GNU C++ and GNU ld with standard ELF # conventions ld_shlibs_CXX=yes ;; gnu*) ;; haiku*) archive_cmds_CXX='$CC -shared $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname -o $lib' link_all_deplibs_CXX=yes ;; hpux9*) hardcode_libdir_flag_spec_CXX='${wl}+b ${wl}$libdir' hardcode_libdir_separator_CXX=: export_dynamic_flag_spec_CXX='${wl}-E' hardcode_direct_CXX=yes hardcode_minus_L_CXX=yes # Not in the search PATH, # but as the default # location of the library. case $cc_basename in CC*) # FIXME: insert proper C++ library support ld_shlibs_CXX=no ;; aCC*) archive_cmds_CXX='$RM $output_objdir/$soname~$CC -b ${wl}+b ${wl}$install_libdir -o $output_objdir/$soname $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags~test $output_objdir/$soname = $lib || mv $output_objdir/$soname $lib' # Commands to make compiler produce verbose output that lists # what "hidden" libraries, object files and flags are used when # linking a shared library. # # There doesn't appear to be a way to prevent this compiler from # explicitly linking system object files so we need to strip them # from the output so that they don't get included in the library # dependencies. output_verbose_link_cmd='templist=`($CC -b $CFLAGS -v conftest.$objext 2>&1) | $EGREP "\-L"`; list=""; for z in $templist; do case $z in conftest.$objext) list="$list $z";; *.$objext);; *) list="$list $z";;esac; done; func_echo_all "$list"' ;; *) if test "$GXX" = yes; then archive_cmds_CXX='$RM $output_objdir/$soname~$CC -shared -nostdlib $pic_flag ${wl}+b ${wl}$install_libdir -o $output_objdir/$soname $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags~test $output_objdir/$soname = $lib || mv $output_objdir/$soname $lib' else # FIXME: insert proper C++ library support ld_shlibs_CXX=no fi ;; esac ;; hpux10*|hpux11*) if test $with_gnu_ld = no; then hardcode_libdir_flag_spec_CXX='${wl}+b ${wl}$libdir' hardcode_libdir_separator_CXX=: case $host_cpu in hppa*64*|ia64*) ;; *) export_dynamic_flag_spec_CXX='${wl}-E' ;; esac fi case $host_cpu in hppa*64*|ia64*) hardcode_direct_CXX=no hardcode_shlibpath_var_CXX=no ;; *) hardcode_direct_CXX=yes hardcode_direct_absolute_CXX=yes hardcode_minus_L_CXX=yes # Not in the search PATH, # but as the default # location of the library. ;; esac case $cc_basename in CC*) # FIXME: insert proper C++ library support ld_shlibs_CXX=no ;; aCC*) case $host_cpu in hppa*64*) archive_cmds_CXX='$CC -b ${wl}+h ${wl}$soname -o $lib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags' ;; ia64*) archive_cmds_CXX='$CC -b ${wl}+h ${wl}$soname ${wl}+nodefaultrpath -o $lib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags' ;; *) archive_cmds_CXX='$CC -b ${wl}+h ${wl}$soname ${wl}+b ${wl}$install_libdir -o $lib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags' ;; esac # Commands to make compiler produce verbose output that lists # what "hidden" libraries, object files and flags are used when # linking a shared library. # # There doesn't appear to be a way to prevent this compiler from # explicitly linking system object files so we need to strip them # from the output so that they don't get included in the library # dependencies. output_verbose_link_cmd='templist=`($CC -b $CFLAGS -v conftest.$objext 2>&1) | $GREP "\-L"`; list=""; for z in $templist; do case $z in conftest.$objext) list="$list $z";; *.$objext);; *) list="$list $z";;esac; done; func_echo_all "$list"' ;; *) if test "$GXX" = yes; then if test $with_gnu_ld = no; then case $host_cpu in hppa*64*) archive_cmds_CXX='$CC -shared -nostdlib -fPIC ${wl}+h ${wl}$soname -o $lib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags' ;; ia64*) archive_cmds_CXX='$CC -shared -nostdlib $pic_flag ${wl}+h ${wl}$soname ${wl}+nodefaultrpath -o $lib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags' ;; *) archive_cmds_CXX='$CC -shared -nostdlib $pic_flag ${wl}+h ${wl}$soname ${wl}+b ${wl}$install_libdir -o $lib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags' ;; esac fi else # FIXME: insert proper C++ library support ld_shlibs_CXX=no fi ;; esac ;; interix[3-9]*) hardcode_direct_CXX=no hardcode_shlibpath_var_CXX=no hardcode_libdir_flag_spec_CXX='${wl}-rpath,$libdir' export_dynamic_flag_spec_CXX='${wl}-E' # Hack: On Interix 3.x, we cannot compile PIC because of a broken gcc. # Instead, shared libraries are loaded at an image base (0x10000000 by # default) and relocated if they conflict, which is a slow very memory # consuming and fragmenting process. To avoid this, we pick a random, # 256 KiB-aligned image base between 0x50000000 and 0x6FFC0000 at link # time. Moving up from 0x10000000 also allows more sbrk(2) space. archive_cmds_CXX='$CC -shared $pic_flag $libobjs $deplibs $compiler_flags ${wl}-h,$soname ${wl}--image-base,`expr ${RANDOM-$$} % 4096 / 2 \* 262144 + 1342177280` -o $lib' archive_expsym_cmds_CXX='sed "s,^,_," $export_symbols >$output_objdir/$soname.expsym~$CC -shared $pic_flag $libobjs $deplibs $compiler_flags ${wl}-h,$soname ${wl}--retain-symbols-file,$output_objdir/$soname.expsym ${wl}--image-base,`expr ${RANDOM-$$} % 4096 / 2 \* 262144 + 1342177280` -o $lib' ;; irix5* | irix6*) case $cc_basename in CC*) # SGI C++ archive_cmds_CXX='$CC -shared -all -multigot $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags -soname $soname `test -n "$verstring" && func_echo_all "-set_version $verstring"` -update_registry ${output_objdir}/so_locations -o $lib' # Archives containing C++ object files must be created using # "CC -ar", where "CC" is the IRIX C++ compiler. This is # necessary to make sure instantiated templates are included # in the archive. old_archive_cmds_CXX='$CC -ar -WR,-u -o $oldlib $oldobjs' ;; *) if test "$GXX" = yes; then if test "$with_gnu_ld" = no; then archive_cmds_CXX='$CC -shared $pic_flag -nostdlib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags ${wl}-soname ${wl}$soname `test -n "$verstring" && func_echo_all "${wl}-set_version ${wl}$verstring"` ${wl}-update_registry ${wl}${output_objdir}/so_locations -o $lib' else archive_cmds_CXX='$CC -shared $pic_flag -nostdlib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags ${wl}-soname ${wl}$soname `test -n "$verstring" && func_echo_all "${wl}-set_version ${wl}$verstring"` -o $lib' fi fi link_all_deplibs_CXX=yes ;; esac hardcode_libdir_flag_spec_CXX='${wl}-rpath ${wl}$libdir' hardcode_libdir_separator_CXX=: inherit_rpath_CXX=yes ;; linux* | k*bsd*-gnu | kopensolaris*-gnu) case $cc_basename in KCC*) # Kuck and Associates, Inc. (KAI) C++ Compiler # KCC will only create a shared library if the output file # ends with ".so" (or ".sl" for HP-UX), so rename the library # to its proper name (with version) after linking. archive_cmds_CXX='tempext=`echo $shared_ext | $SED -e '\''s/\([^()0-9A-Za-z{}]\)/\\\\\1/g'\''`; templib=`echo $lib | $SED -e "s/\${tempext}\..*/.so/"`; $CC $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags --soname $soname -o \$templib; mv \$templib $lib' archive_expsym_cmds_CXX='tempext=`echo $shared_ext | $SED -e '\''s/\([^()0-9A-Za-z{}]\)/\\\\\1/g'\''`; templib=`echo $lib | $SED -e "s/\${tempext}\..*/.so/"`; $CC $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags --soname $soname -o \$templib ${wl}-retain-symbols-file,$export_symbols; mv \$templib $lib' # Commands to make compiler produce verbose output that lists # what "hidden" libraries, object files and flags are used when # linking a shared library. # # There doesn't appear to be a way to prevent this compiler from # explicitly linking system object files so we need to strip them # from the output so that they don't get included in the library # dependencies. output_verbose_link_cmd='templist=`$CC $CFLAGS -v conftest.$objext -o libconftest$shared_ext 2>&1 | $GREP "ld"`; rm -f libconftest$shared_ext; list=""; for z in $templist; do case $z in conftest.$objext) list="$list $z";; *.$objext);; *) list="$list $z";;esac; done; func_echo_all "$list"' hardcode_libdir_flag_spec_CXX='${wl}-rpath,$libdir' export_dynamic_flag_spec_CXX='${wl}--export-dynamic' # Archives containing C++ object files must be created using # "CC -Bstatic", where "CC" is the KAI C++ compiler. old_archive_cmds_CXX='$CC -Bstatic -o $oldlib $oldobjs' ;; icpc* | ecpc* ) # Intel C++ with_gnu_ld=yes # version 8.0 and above of icpc choke on multiply defined symbols # if we add $predep_objects and $postdep_objects, however 7.1 and # earlier do not add the objects themselves. case `$CC -V 2>&1` in *"Version 7."*) archive_cmds_CXX='$CC -shared $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags ${wl}-soname $wl$soname -o $lib' archive_expsym_cmds_CXX='$CC -shared $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags ${wl}-soname $wl$soname ${wl}-retain-symbols-file $wl$export_symbols -o $lib' ;; *) # Version 8.0 or newer tmp_idyn= case $host_cpu in ia64*) tmp_idyn=' -i_dynamic';; esac archive_cmds_CXX='$CC -shared'"$tmp_idyn"' $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname -o $lib' archive_expsym_cmds_CXX='$CC -shared'"$tmp_idyn"' $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname ${wl}-retain-symbols-file $wl$export_symbols -o $lib' ;; esac archive_cmds_need_lc_CXX=no hardcode_libdir_flag_spec_CXX='${wl}-rpath,$libdir' export_dynamic_flag_spec_CXX='${wl}--export-dynamic' whole_archive_flag_spec_CXX='${wl}--whole-archive$convenience ${wl}--no-whole-archive' ;; pgCC* | pgcpp*) # Portland Group C++ compiler case `$CC -V` in *pgCC\ [1-5].* | *pgcpp\ [1-5].*) prelink_cmds_CXX='tpldir=Template.dir~ rm -rf $tpldir~ $CC --prelink_objects --instantiation_dir $tpldir $objs $libobjs $compile_deplibs~ compile_command="$compile_command `find $tpldir -name \*.o | sort | $NL2SP`"' old_archive_cmds_CXX='tpldir=Template.dir~ rm -rf $tpldir~ $CC --prelink_objects --instantiation_dir $tpldir $oldobjs$old_deplibs~ $AR $AR_FLAGS $oldlib$oldobjs$old_deplibs `find $tpldir -name \*.o | sort | $NL2SP`~ $RANLIB $oldlib' archive_cmds_CXX='tpldir=Template.dir~ rm -rf $tpldir~ $CC --prelink_objects --instantiation_dir $tpldir $predep_objects $libobjs $deplibs $convenience $postdep_objects~ $CC -shared $pic_flag $predep_objects $libobjs $deplibs `find $tpldir -name \*.o | sort | $NL2SP` $postdep_objects $compiler_flags ${wl}-soname ${wl}$soname -o $lib' archive_expsym_cmds_CXX='tpldir=Template.dir~ rm -rf $tpldir~ $CC --prelink_objects --instantiation_dir $tpldir $predep_objects $libobjs $deplibs $convenience $postdep_objects~ $CC -shared $pic_flag $predep_objects $libobjs $deplibs `find $tpldir -name \*.o | sort | $NL2SP` $postdep_objects $compiler_flags ${wl}-soname ${wl}$soname ${wl}-retain-symbols-file ${wl}$export_symbols -o $lib' ;; *) # Version 6 and above use weak symbols archive_cmds_CXX='$CC -shared $pic_flag $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags ${wl}-soname ${wl}$soname -o $lib' archive_expsym_cmds_CXX='$CC -shared $pic_flag $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags ${wl}-soname ${wl}$soname ${wl}-retain-symbols-file ${wl}$export_symbols -o $lib' ;; esac hardcode_libdir_flag_spec_CXX='${wl}--rpath ${wl}$libdir' export_dynamic_flag_spec_CXX='${wl}--export-dynamic' whole_archive_flag_spec_CXX='${wl}--whole-archive`for conv in $convenience\"\"; do test -n \"$conv\" && new_convenience=\"$new_convenience,$conv\"; done; func_echo_all \"$new_convenience\"` ${wl}--no-whole-archive' ;; cxx*) # Compaq C++ archive_cmds_CXX='$CC -shared $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags ${wl}-soname $wl$soname -o $lib' archive_expsym_cmds_CXX='$CC -shared $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags ${wl}-soname $wl$soname -o $lib ${wl}-retain-symbols-file $wl$export_symbols' runpath_var=LD_RUN_PATH hardcode_libdir_flag_spec_CXX='-rpath $libdir' hardcode_libdir_separator_CXX=: # Commands to make compiler produce verbose output that lists # what "hidden" libraries, object files and flags are used when # linking a shared library. # # There doesn't appear to be a way to prevent this compiler from # explicitly linking system object files so we need to strip them # from the output so that they don't get included in the library # dependencies. output_verbose_link_cmd='templist=`$CC -shared $CFLAGS -v conftest.$objext 2>&1 | $GREP "ld"`; templist=`func_echo_all "$templist" | $SED "s/\(^.*ld.*\)\( .*ld .*$\)/\1/"`; list=""; for z in $templist; do case $z in conftest.$objext) list="$list $z";; *.$objext);; *) list="$list $z";;esac; done; func_echo_all "X$list" | $Xsed' ;; xl* | mpixl* | bgxl*) # IBM XL 8.0 on PPC, with GNU ld hardcode_libdir_flag_spec_CXX='${wl}-rpath ${wl}$libdir' export_dynamic_flag_spec_CXX='${wl}--export-dynamic' archive_cmds_CXX='$CC -qmkshrobj $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname -o $lib' if test "x$supports_anon_versioning" = xyes; then archive_expsym_cmds_CXX='echo "{ global:" > $output_objdir/$libname.ver~ cat $export_symbols | sed -e "s/\(.*\)/\1;/" >> $output_objdir/$libname.ver~ echo "local: *; };" >> $output_objdir/$libname.ver~ $CC -qmkshrobj $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname ${wl}-version-script ${wl}$output_objdir/$libname.ver -o $lib' fi ;; *) case `$CC -V 2>&1 | sed 5q` in *Sun\ C*) # Sun C++ 5.9 no_undefined_flag_CXX=' -zdefs' archive_cmds_CXX='$CC -G${allow_undefined_flag} -h$soname -o $lib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags' archive_expsym_cmds_CXX='$CC -G${allow_undefined_flag} -h$soname -o $lib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags ${wl}-retain-symbols-file ${wl}$export_symbols' hardcode_libdir_flag_spec_CXX='-R$libdir' whole_archive_flag_spec_CXX='${wl}--whole-archive`new_convenience=; for conv in $convenience\"\"; do test -z \"$conv\" || new_convenience=\"$new_convenience,$conv\"; done; func_echo_all \"$new_convenience\"` ${wl}--no-whole-archive' compiler_needs_object_CXX=yes # Not sure whether something based on # $CC $CFLAGS -v conftest.$objext -o libconftest$shared_ext 2>&1 # would be better. output_verbose_link_cmd='func_echo_all' # Archives containing C++ object files must be created using # "CC -xar", where "CC" is the Sun C++ compiler. This is # necessary to make sure instantiated templates are included # in the archive. old_archive_cmds_CXX='$CC -xar -o $oldlib $oldobjs' ;; esac ;; esac ;; lynxos*) # FIXME: insert proper C++ library support ld_shlibs_CXX=no ;; m88k*) # FIXME: insert proper C++ library support ld_shlibs_CXX=no ;; mvs*) case $cc_basename in cxx*) # FIXME: insert proper C++ library support ld_shlibs_CXX=no ;; *) # FIXME: insert proper C++ library support ld_shlibs_CXX=no ;; esac ;; netbsd*) if echo __ELF__ | $CC -E - | $GREP __ELF__ >/dev/null; then archive_cmds_CXX='$LD -Bshareable -o $lib $predep_objects $libobjs $deplibs $postdep_objects $linker_flags' wlarc= hardcode_libdir_flag_spec_CXX='-R$libdir' hardcode_direct_CXX=yes hardcode_shlibpath_var_CXX=no fi # Workaround some broken pre-1.5 toolchains output_verbose_link_cmd='$CC -shared $CFLAGS -v conftest.$objext 2>&1 | $GREP conftest.$objext | $SED -e "s:-lgcc -lc -lgcc::"' ;; *nto* | *qnx*) ld_shlibs_CXX=yes ;; openbsd2*) # C++ shared libraries are fairly broken ld_shlibs_CXX=no ;; openbsd*) if test -f /usr/libexec/ld.so; then hardcode_direct_CXX=yes hardcode_shlibpath_var_CXX=no hardcode_direct_absolute_CXX=yes archive_cmds_CXX='$CC -shared $pic_flag $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags -o $lib' hardcode_libdir_flag_spec_CXX='${wl}-rpath,$libdir' if test -z "`echo __ELF__ | $CC -E - | grep __ELF__`" || test "$host_os-$host_cpu" = "openbsd2.8-powerpc"; then archive_expsym_cmds_CXX='$CC -shared $pic_flag $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags ${wl}-retain-symbols-file,$export_symbols -o $lib' export_dynamic_flag_spec_CXX='${wl}-E' whole_archive_flag_spec_CXX="$wlarc"'--whole-archive$convenience '"$wlarc"'--no-whole-archive' fi output_verbose_link_cmd=func_echo_all else ld_shlibs_CXX=no fi ;; osf3* | osf4* | osf5*) case $cc_basename in KCC*) # Kuck and Associates, Inc. (KAI) C++ Compiler # KCC will only create a shared library if the output file # ends with ".so" (or ".sl" for HP-UX), so rename the library # to its proper name (with version) after linking. archive_cmds_CXX='tempext=`echo $shared_ext | $SED -e '\''s/\([^()0-9A-Za-z{}]\)/\\\\\1/g'\''`; templib=`echo "$lib" | $SED -e "s/\${tempext}\..*/.so/"`; $CC $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags --soname $soname -o \$templib; mv \$templib $lib' hardcode_libdir_flag_spec_CXX='${wl}-rpath,$libdir' hardcode_libdir_separator_CXX=: # Archives containing C++ object files must be created using # the KAI C++ compiler. case $host in osf3*) old_archive_cmds_CXX='$CC -Bstatic -o $oldlib $oldobjs' ;; *) old_archive_cmds_CXX='$CC -o $oldlib $oldobjs' ;; esac ;; RCC*) # Rational C++ 2.4.1 # FIXME: insert proper C++ library support ld_shlibs_CXX=no ;; cxx*) case $host in osf3*) allow_undefined_flag_CXX=' ${wl}-expect_unresolved ${wl}\*' archive_cmds_CXX='$CC -shared${allow_undefined_flag} $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags ${wl}-soname $soname `test -n "$verstring" && func_echo_all "${wl}-set_version $verstring"` -update_registry ${output_objdir}/so_locations -o $lib' hardcode_libdir_flag_spec_CXX='${wl}-rpath ${wl}$libdir' ;; *) allow_undefined_flag_CXX=' -expect_unresolved \*' archive_cmds_CXX='$CC -shared${allow_undefined_flag} $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags -msym -soname $soname `test -n "$verstring" && func_echo_all "-set_version $verstring"` -update_registry ${output_objdir}/so_locations -o $lib' archive_expsym_cmds_CXX='for i in `cat $export_symbols`; do printf "%s %s\\n" -exported_symbol "\$i" >> $lib.exp; done~ echo "-hidden">> $lib.exp~ $CC -shared$allow_undefined_flag $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags -msym -soname $soname ${wl}-input ${wl}$lib.exp `test -n "$verstring" && $ECHO "-set_version $verstring"` -update_registry ${output_objdir}/so_locations -o $lib~ $RM $lib.exp' hardcode_libdir_flag_spec_CXX='-rpath $libdir' ;; esac hardcode_libdir_separator_CXX=: # Commands to make compiler produce verbose output that lists # what "hidden" libraries, object files and flags are used when # linking a shared library. # # There doesn't appear to be a way to prevent this compiler from # explicitly linking system object files so we need to strip them # from the output so that they don't get included in the library # dependencies. output_verbose_link_cmd='templist=`$CC -shared $CFLAGS -v conftest.$objext 2>&1 | $GREP "ld" | $GREP -v "ld:"`; templist=`func_echo_all "$templist" | $SED "s/\(^.*ld.*\)\( .*ld.*$\)/\1/"`; list=""; for z in $templist; do case $z in conftest.$objext) list="$list $z";; *.$objext);; *) list="$list $z";;esac; done; func_echo_all "$list"' ;; *) if test "$GXX" = yes && test "$with_gnu_ld" = no; then allow_undefined_flag_CXX=' ${wl}-expect_unresolved ${wl}\*' case $host in osf3*) archive_cmds_CXX='$CC -shared -nostdlib ${allow_undefined_flag} $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags ${wl}-soname ${wl}$soname `test -n "$verstring" && func_echo_all "${wl}-set_version ${wl}$verstring"` ${wl}-update_registry ${wl}${output_objdir}/so_locations -o $lib' ;; *) archive_cmds_CXX='$CC -shared $pic_flag -nostdlib ${allow_undefined_flag} $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags ${wl}-msym ${wl}-soname ${wl}$soname `test -n "$verstring" && func_echo_all "${wl}-set_version ${wl}$verstring"` ${wl}-update_registry ${wl}${output_objdir}/so_locations -o $lib' ;; esac hardcode_libdir_flag_spec_CXX='${wl}-rpath ${wl}$libdir' hardcode_libdir_separator_CXX=: # Commands to make compiler produce verbose output that lists # what "hidden" libraries, object files and flags are used when # linking a shared library. output_verbose_link_cmd='$CC -shared $CFLAGS -v conftest.$objext 2>&1 | $GREP -v "^Configured with:" | $GREP "\-L"' else # FIXME: insert proper C++ library support ld_shlibs_CXX=no fi ;; esac ;; psos*) # FIXME: insert proper C++ library support ld_shlibs_CXX=no ;; sunos4*) case $cc_basename in CC*) # Sun C++ 4.x # FIXME: insert proper C++ library support ld_shlibs_CXX=no ;; lcc*) # Lucid # FIXME: insert proper C++ library support ld_shlibs_CXX=no ;; *) # FIXME: insert proper C++ library support ld_shlibs_CXX=no ;; esac ;; solaris*) case $cc_basename in CC* | sunCC*) # Sun C++ 4.2, 5.x and Centerline C++ archive_cmds_need_lc_CXX=yes no_undefined_flag_CXX=' -zdefs' archive_cmds_CXX='$CC -G${allow_undefined_flag} -h$soname -o $lib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags' archive_expsym_cmds_CXX='echo "{ global:" > $lib.exp~cat $export_symbols | $SED -e "s/\(.*\)/\1;/" >> $lib.exp~echo "local: *; };" >> $lib.exp~ $CC -G${allow_undefined_flag} ${wl}-M ${wl}$lib.exp -h$soname -o $lib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags~$RM $lib.exp' hardcode_libdir_flag_spec_CXX='-R$libdir' hardcode_shlibpath_var_CXX=no case $host_os in solaris2.[0-5] | solaris2.[0-5].*) ;; *) # The compiler driver will combine and reorder linker options, # but understands `-z linker_flag'. # Supported since Solaris 2.6 (maybe 2.5.1?) whole_archive_flag_spec_CXX='-z allextract$convenience -z defaultextract' ;; esac link_all_deplibs_CXX=yes output_verbose_link_cmd='func_echo_all' # Archives containing C++ object files must be created using # "CC -xar", where "CC" is the Sun C++ compiler. This is # necessary to make sure instantiated templates are included # in the archive. old_archive_cmds_CXX='$CC -xar -o $oldlib $oldobjs' ;; gcx*) # Green Hills C++ Compiler archive_cmds_CXX='$CC -shared $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags ${wl}-h $wl$soname -o $lib' # The C++ compiler must be used to create the archive. old_archive_cmds_CXX='$CC $LDFLAGS -archive -o $oldlib $oldobjs' ;; *) # GNU C++ compiler with Solaris linker if test "$GXX" = yes && test "$with_gnu_ld" = no; then no_undefined_flag_CXX=' ${wl}-z ${wl}defs' if $CC --version | $GREP -v '^2\.7' > /dev/null; then archive_cmds_CXX='$CC -shared $pic_flag -nostdlib $LDFLAGS $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags ${wl}-h $wl$soname -o $lib' archive_expsym_cmds_CXX='echo "{ global:" > $lib.exp~cat $export_symbols | $SED -e "s/\(.*\)/\1;/" >> $lib.exp~echo "local: *; };" >> $lib.exp~ $CC -shared $pic_flag -nostdlib ${wl}-M $wl$lib.exp -o $lib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags~$RM $lib.exp' # Commands to make compiler produce verbose output that lists # what "hidden" libraries, object files and flags are used when # linking a shared library. output_verbose_link_cmd='$CC -shared $CFLAGS -v conftest.$objext 2>&1 | $GREP -v "^Configured with:" | $GREP "\-L"' else # g++ 2.7 appears to require `-G' NOT `-shared' on this # platform. archive_cmds_CXX='$CC -G -nostdlib $LDFLAGS $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags ${wl}-h $wl$soname -o $lib' archive_expsym_cmds_CXX='echo "{ global:" > $lib.exp~cat $export_symbols | $SED -e "s/\(.*\)/\1;/" >> $lib.exp~echo "local: *; };" >> $lib.exp~ $CC -G -nostdlib ${wl}-M $wl$lib.exp -o $lib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags~$RM $lib.exp' # Commands to make compiler produce verbose output that lists # what "hidden" libraries, object files and flags are used when # linking a shared library. output_verbose_link_cmd='$CC -G $CFLAGS -v conftest.$objext 2>&1 | $GREP -v "^Configured with:" | $GREP "\-L"' fi hardcode_libdir_flag_spec_CXX='${wl}-R $wl$libdir' case $host_os in solaris2.[0-5] | solaris2.[0-5].*) ;; *) whole_archive_flag_spec_CXX='${wl}-z ${wl}allextract$convenience ${wl}-z ${wl}defaultextract' ;; esac fi ;; esac ;; sysv4*uw2* | sysv5OpenUNIX* | sysv5UnixWare7.[01].[10]* | unixware7* | sco3.2v5.0.[024]*) no_undefined_flag_CXX='${wl}-z,text' archive_cmds_need_lc_CXX=no hardcode_shlibpath_var_CXX=no runpath_var='LD_RUN_PATH' case $cc_basename in CC*) archive_cmds_CXX='$CC -G ${wl}-h,$soname -o $lib $libobjs $deplibs $compiler_flags' archive_expsym_cmds_CXX='$CC -G ${wl}-Bexport:$export_symbols ${wl}-h,$soname -o $lib $libobjs $deplibs $compiler_flags' ;; *) archive_cmds_CXX='$CC -shared ${wl}-h,$soname -o $lib $libobjs $deplibs $compiler_flags' archive_expsym_cmds_CXX='$CC -shared ${wl}-Bexport:$export_symbols ${wl}-h,$soname -o $lib $libobjs $deplibs $compiler_flags' ;; esac ;; sysv5* | sco3.2v5* | sco5v6*) # Note: We can NOT use -z defs as we might desire, because we do not # link with -lc, and that would cause any symbols used from libc to # always be unresolved, which means just about no library would # ever link correctly. If we're not using GNU ld we use -z text # though, which does catch some bad symbols but isn't as heavy-handed # as -z defs. no_undefined_flag_CXX='${wl}-z,text' allow_undefined_flag_CXX='${wl}-z,nodefs' archive_cmds_need_lc_CXX=no hardcode_shlibpath_var_CXX=no hardcode_libdir_flag_spec_CXX='${wl}-R,$libdir' hardcode_libdir_separator_CXX=':' link_all_deplibs_CXX=yes export_dynamic_flag_spec_CXX='${wl}-Bexport' runpath_var='LD_RUN_PATH' case $cc_basename in CC*) archive_cmds_CXX='$CC -G ${wl}-h,$soname -o $lib $libobjs $deplibs $compiler_flags' archive_expsym_cmds_CXX='$CC -G ${wl}-Bexport:$export_symbols ${wl}-h,$soname -o $lib $libobjs $deplibs $compiler_flags' old_archive_cmds_CXX='$CC -Tprelink_objects $oldobjs~ '"$old_archive_cmds_CXX" reload_cmds_CXX='$CC -Tprelink_objects $reload_objs~ '"$reload_cmds_CXX" ;; *) archive_cmds_CXX='$CC -shared ${wl}-h,$soname -o $lib $libobjs $deplibs $compiler_flags' archive_expsym_cmds_CXX='$CC -shared ${wl}-Bexport:$export_symbols ${wl}-h,$soname -o $lib $libobjs $deplibs $compiler_flags' ;; esac ;; tandem*) case $cc_basename in NCC*) # NonStop-UX NCC 3.20 # FIXME: insert proper C++ library support ld_shlibs_CXX=no ;; *) # FIXME: insert proper C++ library support ld_shlibs_CXX=no ;; esac ;; vxworks*) # FIXME: insert proper C++ library support ld_shlibs_CXX=no ;; *) # FIXME: insert proper C++ library support ld_shlibs_CXX=no ;; esac { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ld_shlibs_CXX" >&5 $as_echo "$ld_shlibs_CXX" >&6; } test "$ld_shlibs_CXX" = no && can_build_shared=no GCC_CXX="$GXX" LD_CXX="$LD" ## CAVEAT EMPTOR: ## There is no encapsulation within the following macros, do not change ## the running order or otherwise move them around unless you know exactly ## what you are doing... # Dependencies to place before and after the object being linked: predep_objects_CXX= postdep_objects_CXX= predeps_CXX= postdeps_CXX= compiler_lib_search_path_CXX= cat > conftest.$ac_ext <<_LT_EOF class Foo { public: Foo (void) { a = 0; } private: int a; }; _LT_EOF _lt_libdeps_save_CFLAGS=$CFLAGS case "$CC $CFLAGS " in #( *\ -flto*\ *) CFLAGS="$CFLAGS -fno-lto" ;; *\ -fwhopr*\ *) CFLAGS="$CFLAGS -fno-whopr" ;; *\ -fuse-linker-plugin*\ *) CFLAGS="$CFLAGS -fno-use-linker-plugin" ;; esac if { { eval echo "\"\$as_me\":${as_lineno-$LINENO}: \"$ac_compile\""; } >&5 (eval $ac_compile) 2>&5 ac_status=$? $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 test $ac_status = 0; }; then # Parse the compiler output and extract the necessary # objects, libraries and library flags. # Sentinel used to keep track of whether or not we are before # the conftest object file. pre_test_object_deps_done=no for p in `eval "$output_verbose_link_cmd"`; do case ${prev}${p} in -L* | -R* | -l*) # Some compilers place space between "-{L,R}" and the path. # Remove the space. if test $p = "-L" || test $p = "-R"; then prev=$p continue fi # Expand the sysroot to ease extracting the directories later. if test -z "$prev"; then case $p in -L*) func_stripname_cnf '-L' '' "$p"; prev=-L; p=$func_stripname_result ;; -R*) func_stripname_cnf '-R' '' "$p"; prev=-R; p=$func_stripname_result ;; -l*) func_stripname_cnf '-l' '' "$p"; prev=-l; p=$func_stripname_result ;; esac fi case $p in =*) func_stripname_cnf '=' '' "$p"; p=$lt_sysroot$func_stripname_result ;; esac if test "$pre_test_object_deps_done" = no; then case ${prev} in -L | -R) # Internal compiler library paths should come after those # provided the user. The postdeps already come after the # user supplied libs so there is no need to process them. if test -z "$compiler_lib_search_path_CXX"; then compiler_lib_search_path_CXX="${prev}${p}" else compiler_lib_search_path_CXX="${compiler_lib_search_path_CXX} ${prev}${p}" fi ;; # The "-l" case would never come before the object being # linked, so don't bother handling this case. esac else if test -z "$postdeps_CXX"; then postdeps_CXX="${prev}${p}" else postdeps_CXX="${postdeps_CXX} ${prev}${p}" fi fi prev= ;; *.lto.$objext) ;; # Ignore GCC LTO objects *.$objext) # This assumes that the test object file only shows up # once in the compiler output. if test "$p" = "conftest.$objext"; then pre_test_object_deps_done=yes continue fi if test "$pre_test_object_deps_done" = no; then if test -z "$predep_objects_CXX"; then predep_objects_CXX="$p" else predep_objects_CXX="$predep_objects_CXX $p" fi else if test -z "$postdep_objects_CXX"; then postdep_objects_CXX="$p" else postdep_objects_CXX="$postdep_objects_CXX $p" fi fi ;; *) ;; # Ignore the rest. esac done # Clean up. rm -f a.out a.exe else echo "libtool.m4: error: problem compiling CXX test program" fi $RM -f confest.$objext CFLAGS=$_lt_libdeps_save_CFLAGS # PORTME: override above test on systems where it is broken case $host_os in interix[3-9]*) # Interix 3.5 installs completely hosed .la files for C++, so rather than # hack all around it, let's just trust "g++" to DTRT. predep_objects_CXX= postdep_objects_CXX= postdeps_CXX= ;; linux*) case `$CC -V 2>&1 | sed 5q` in *Sun\ C*) # Sun C++ 5.9 # The more standards-conforming stlport4 library is # incompatible with the Cstd library. Avoid specifying # it if it's in CXXFLAGS. Ignore libCrun as # -library=stlport4 depends on it. case " $CXX $CXXFLAGS " in *" -library=stlport4 "*) solaris_use_stlport4=yes ;; esac if test "$solaris_use_stlport4" != yes; then postdeps_CXX='-library=Cstd -library=Crun' fi ;; esac ;; solaris*) case $cc_basename in CC* | sunCC*) # The more standards-conforming stlport4 library is # incompatible with the Cstd library. Avoid specifying # it if it's in CXXFLAGS. Ignore libCrun as # -library=stlport4 depends on it. case " $CXX $CXXFLAGS " in *" -library=stlport4 "*) solaris_use_stlport4=yes ;; esac # Adding this requires a known-good setup of shared libraries for # Sun compiler versions before 5.6, else PIC objects from an old # archive will be linked into the output, leading to subtle bugs. if test "$solaris_use_stlport4" != yes; then postdeps_CXX='-library=Cstd -library=Crun' fi ;; esac ;; esac case " $postdeps_CXX " in *" -lc "*) archive_cmds_need_lc_CXX=no ;; esac compiler_lib_search_dirs_CXX= if test -n "${compiler_lib_search_path_CXX}"; then compiler_lib_search_dirs_CXX=`echo " ${compiler_lib_search_path_CXX}" | ${SED} -e 's! -L! !g' -e 's!^ !!'` fi lt_prog_compiler_wl_CXX= lt_prog_compiler_pic_CXX= lt_prog_compiler_static_CXX= # C++ specific cases for pic, static, wl, etc. if test "$GXX" = yes; then lt_prog_compiler_wl_CXX='-Wl,' lt_prog_compiler_static_CXX='-static' case $host_os in aix*) # All AIX code is PIC. if test "$host_cpu" = ia64; then # AIX 5 now supports IA64 processor lt_prog_compiler_static_CXX='-Bstatic' fi ;; amigaos*) case $host_cpu in powerpc) # see comment about AmigaOS4 .so support lt_prog_compiler_pic_CXX='-fPIC' ;; m68k) # FIXME: we need at least 68020 code to build shared libraries, but # adding the `-m68020' flag to GCC prevents building anything better, # like `-m68040'. lt_prog_compiler_pic_CXX='-m68020 -resident32 -malways-restore-a4' ;; esac ;; beos* | irix5* | irix6* | nonstopux* | osf3* | osf4* | osf5*) # PIC is the default for these OSes. ;; mingw* | cygwin* | os2* | pw32* | cegcc*) # This hack is so that the source file can tell whether it is being # built for inclusion in a dll (and should export symbols for example). # Although the cygwin gcc ignores -fPIC, still need this for old-style # (--disable-auto-import) libraries lt_prog_compiler_pic_CXX='-DDLL_EXPORT' ;; darwin* | rhapsody*) # PIC is the default on this platform # Common symbols not allowed in MH_DYLIB files lt_prog_compiler_pic_CXX='-fno-common' ;; *djgpp*) # DJGPP does not support shared libraries at all lt_prog_compiler_pic_CXX= ;; haiku*) # PIC is the default for Haiku. # The "-static" flag exists, but is broken. lt_prog_compiler_static_CXX= ;; interix[3-9]*) # Interix 3.x gcc -fpic/-fPIC options generate broken code. # Instead, we relocate shared libraries at runtime. ;; sysv4*MP*) if test -d /usr/nec; then lt_prog_compiler_pic_CXX=-Kconform_pic fi ;; hpux*) # PIC is the default for 64-bit PA HP-UX, but not for 32-bit # PA HP-UX. On IA64 HP-UX, PIC is the default but the pic flag # sets the default TLS model and affects inlining. case $host_cpu in hppa*64*) ;; *) lt_prog_compiler_pic_CXX='-fPIC' ;; esac ;; *qnx* | *nto*) # QNX uses GNU C++, but need to define -shared option too, otherwise # it will coredump. lt_prog_compiler_pic_CXX='-fPIC -shared' ;; *) lt_prog_compiler_pic_CXX='-fPIC' ;; esac else case $host_os in aix[4-9]*) # All AIX code is PIC. if test "$host_cpu" = ia64; then # AIX 5 now supports IA64 processor lt_prog_compiler_static_CXX='-Bstatic' else lt_prog_compiler_static_CXX='-bnso -bI:/lib/syscalls.exp' fi ;; chorus*) case $cc_basename in cxch68*) # Green Hills C++ Compiler # _LT_TAGVAR(lt_prog_compiler_static, CXX)="--no_auto_instantiation -u __main -u __premain -u _abort -r $COOL_DIR/lib/libOrb.a $MVME_DIR/lib/CC/libC.a $MVME_DIR/lib/classix/libcx.s.a" ;; esac ;; mingw* | cygwin* | os2* | pw32* | cegcc*) # This hack is so that the source file can tell whether it is being # built for inclusion in a dll (and should export symbols for example). lt_prog_compiler_pic_CXX='-DDLL_EXPORT' ;; dgux*) case $cc_basename in ec++*) lt_prog_compiler_pic_CXX='-KPIC' ;; ghcx*) # Green Hills C++ Compiler lt_prog_compiler_pic_CXX='-pic' ;; *) ;; esac ;; freebsd* | dragonfly*) # FreeBSD uses GNU C++ ;; hpux9* | hpux10* | hpux11*) case $cc_basename in CC*) lt_prog_compiler_wl_CXX='-Wl,' lt_prog_compiler_static_CXX='${wl}-a ${wl}archive' if test "$host_cpu" != ia64; then lt_prog_compiler_pic_CXX='+Z' fi ;; aCC*) lt_prog_compiler_wl_CXX='-Wl,' lt_prog_compiler_static_CXX='${wl}-a ${wl}archive' case $host_cpu in hppa*64*|ia64*) # +Z the default ;; *) lt_prog_compiler_pic_CXX='+Z' ;; esac ;; *) ;; esac ;; interix*) # This is c89, which is MS Visual C++ (no shared libs) # Anyone wants to do a port? ;; irix5* | irix6* | nonstopux*) case $cc_basename in CC*) lt_prog_compiler_wl_CXX='-Wl,' lt_prog_compiler_static_CXX='-non_shared' # CC pic flag -KPIC is the default. ;; *) ;; esac ;; linux* | k*bsd*-gnu | kopensolaris*-gnu) case $cc_basename in KCC*) # KAI C++ Compiler lt_prog_compiler_wl_CXX='--backend -Wl,' lt_prog_compiler_pic_CXX='-fPIC' ;; ecpc* ) # old Intel C++ for x86_64 which still supported -KPIC. lt_prog_compiler_wl_CXX='-Wl,' lt_prog_compiler_pic_CXX='-KPIC' lt_prog_compiler_static_CXX='-static' ;; icpc* ) # Intel C++, used to be incompatible with GCC. # ICC 10 doesn't accept -KPIC any more. lt_prog_compiler_wl_CXX='-Wl,' lt_prog_compiler_pic_CXX='-fPIC' lt_prog_compiler_static_CXX='-static' ;; pgCC* | pgcpp*) # Portland Group C++ compiler lt_prog_compiler_wl_CXX='-Wl,' lt_prog_compiler_pic_CXX='-fpic' lt_prog_compiler_static_CXX='-Bstatic' ;; cxx*) # Compaq C++ # Make sure the PIC flag is empty. It appears that all Alpha # Linux and Compaq Tru64 Unix objects are PIC. lt_prog_compiler_pic_CXX= lt_prog_compiler_static_CXX='-non_shared' ;; xlc* | xlC* | bgxl[cC]* | mpixl[cC]*) # IBM XL 8.0, 9.0 on PPC and BlueGene lt_prog_compiler_wl_CXX='-Wl,' lt_prog_compiler_pic_CXX='-qpic' lt_prog_compiler_static_CXX='-qstaticlink' ;; *) case `$CC -V 2>&1 | sed 5q` in *Sun\ C*) # Sun C++ 5.9 lt_prog_compiler_pic_CXX='-KPIC' lt_prog_compiler_static_CXX='-Bstatic' lt_prog_compiler_wl_CXX='-Qoption ld ' ;; esac ;; esac ;; lynxos*) ;; m88k*) ;; mvs*) case $cc_basename in cxx*) lt_prog_compiler_pic_CXX='-W c,exportall' ;; *) ;; esac ;; netbsd*) ;; *qnx* | *nto*) # QNX uses GNU C++, but need to define -shared option too, otherwise # it will coredump. lt_prog_compiler_pic_CXX='-fPIC -shared' ;; osf3* | osf4* | osf5*) case $cc_basename in KCC*) lt_prog_compiler_wl_CXX='--backend -Wl,' ;; RCC*) # Rational C++ 2.4.1 lt_prog_compiler_pic_CXX='-pic' ;; cxx*) # Digital/Compaq C++ lt_prog_compiler_wl_CXX='-Wl,' # Make sure the PIC flag is empty. It appears that all Alpha # Linux and Compaq Tru64 Unix objects are PIC. lt_prog_compiler_pic_CXX= lt_prog_compiler_static_CXX='-non_shared' ;; *) ;; esac ;; psos*) ;; solaris*) case $cc_basename in CC* | sunCC*) # Sun C++ 4.2, 5.x and Centerline C++ lt_prog_compiler_pic_CXX='-KPIC' lt_prog_compiler_static_CXX='-Bstatic' lt_prog_compiler_wl_CXX='-Qoption ld ' ;; gcx*) # Green Hills C++ Compiler lt_prog_compiler_pic_CXX='-PIC' ;; *) ;; esac ;; sunos4*) case $cc_basename in CC*) # Sun C++ 4.x lt_prog_compiler_pic_CXX='-pic' lt_prog_compiler_static_CXX='-Bstatic' ;; lcc*) # Lucid lt_prog_compiler_pic_CXX='-pic' ;; *) ;; esac ;; sysv5* | unixware* | sco3.2v5* | sco5v6* | OpenUNIX*) case $cc_basename in CC*) lt_prog_compiler_wl_CXX='-Wl,' lt_prog_compiler_pic_CXX='-KPIC' lt_prog_compiler_static_CXX='-Bstatic' ;; esac ;; tandem*) case $cc_basename in NCC*) # NonStop-UX NCC 3.20 lt_prog_compiler_pic_CXX='-KPIC' ;; *) ;; esac ;; vxworks*) ;; *) lt_prog_compiler_can_build_shared_CXX=no ;; esac fi case $host_os in # For platforms which do not support PIC, -DPIC is meaningless: *djgpp*) lt_prog_compiler_pic_CXX= ;; *) lt_prog_compiler_pic_CXX="$lt_prog_compiler_pic_CXX -DPIC" ;; esac { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $compiler option to produce PIC" >&5 $as_echo_n "checking for $compiler option to produce PIC... " >&6; } if ${lt_cv_prog_compiler_pic_CXX+:} false; then : $as_echo_n "(cached) " >&6 else lt_cv_prog_compiler_pic_CXX=$lt_prog_compiler_pic_CXX fi { $as_echo "$as_me:${as_lineno-$LINENO}: result: $lt_cv_prog_compiler_pic_CXX" >&5 $as_echo "$lt_cv_prog_compiler_pic_CXX" >&6; } lt_prog_compiler_pic_CXX=$lt_cv_prog_compiler_pic_CXX # # Check to make sure the PIC flag actually works. # if test -n "$lt_prog_compiler_pic_CXX"; then { $as_echo "$as_me:${as_lineno-$LINENO}: checking if $compiler PIC flag $lt_prog_compiler_pic_CXX works" >&5 $as_echo_n "checking if $compiler PIC flag $lt_prog_compiler_pic_CXX works... " >&6; } if ${lt_cv_prog_compiler_pic_works_CXX+:} false; then : $as_echo_n "(cached) " >&6 else lt_cv_prog_compiler_pic_works_CXX=no ac_outfile=conftest.$ac_objext echo "$lt_simple_compile_test_code" > conftest.$ac_ext lt_compiler_flag="$lt_prog_compiler_pic_CXX -DPIC" # Insert the option either (1) after the last *FLAGS variable, or # (2) before a word containing "conftest.", or (3) at the end. # Note that $ac_compile itself does not contain backslashes and begins # with a dollar sign (not a hyphen), so the echo should work correctly. # The option is referenced via a variable to avoid confusing sed. lt_compile=`echo "$ac_compile" | $SED \ -e 's:.*FLAGS}\{0,1\} :&$lt_compiler_flag :; t' \ -e 's: [^ ]*conftest\.: $lt_compiler_flag&:; t' \ -e 's:$: $lt_compiler_flag:'` (eval echo "\"\$as_me:$LINENO: $lt_compile\"" >&5) (eval "$lt_compile" 2>conftest.err) ac_status=$? cat conftest.err >&5 echo "$as_me:$LINENO: \$? = $ac_status" >&5 if (exit $ac_status) && test -s "$ac_outfile"; then # The compiler can only warn and ignore the option if not recognized # So say no if there are warnings other than the usual output. $ECHO "$_lt_compiler_boilerplate" | $SED '/^$/d' >conftest.exp $SED '/^$/d; /^ *+/d' conftest.err >conftest.er2 if test ! -s conftest.er2 || diff conftest.exp conftest.er2 >/dev/null; then lt_cv_prog_compiler_pic_works_CXX=yes fi fi $RM conftest* fi { $as_echo "$as_me:${as_lineno-$LINENO}: result: $lt_cv_prog_compiler_pic_works_CXX" >&5 $as_echo "$lt_cv_prog_compiler_pic_works_CXX" >&6; } if test x"$lt_cv_prog_compiler_pic_works_CXX" = xyes; then case $lt_prog_compiler_pic_CXX in "" | " "*) ;; *) lt_prog_compiler_pic_CXX=" $lt_prog_compiler_pic_CXX" ;; esac else lt_prog_compiler_pic_CXX= lt_prog_compiler_can_build_shared_CXX=no fi fi # # Check to make sure the static flag actually works. # wl=$lt_prog_compiler_wl_CXX eval lt_tmp_static_flag=\"$lt_prog_compiler_static_CXX\" { $as_echo "$as_me:${as_lineno-$LINENO}: checking if $compiler static flag $lt_tmp_static_flag works" >&5 $as_echo_n "checking if $compiler static flag $lt_tmp_static_flag works... " >&6; } if ${lt_cv_prog_compiler_static_works_CXX+:} false; then : $as_echo_n "(cached) " >&6 else lt_cv_prog_compiler_static_works_CXX=no save_LDFLAGS="$LDFLAGS" LDFLAGS="$LDFLAGS $lt_tmp_static_flag" echo "$lt_simple_link_test_code" > conftest.$ac_ext if (eval $ac_link 2>conftest.err) && test -s conftest$ac_exeext; then # The linker can only warn and ignore the option if not recognized # So say no if there are warnings if test -s conftest.err; then # Append any errors to the config.log. cat conftest.err 1>&5 $ECHO "$_lt_linker_boilerplate" | $SED '/^$/d' > conftest.exp $SED '/^$/d; /^ *+/d' conftest.err >conftest.er2 if diff conftest.exp conftest.er2 >/dev/null; then lt_cv_prog_compiler_static_works_CXX=yes fi else lt_cv_prog_compiler_static_works_CXX=yes fi fi $RM -r conftest* LDFLAGS="$save_LDFLAGS" fi { $as_echo "$as_me:${as_lineno-$LINENO}: result: $lt_cv_prog_compiler_static_works_CXX" >&5 $as_echo "$lt_cv_prog_compiler_static_works_CXX" >&6; } if test x"$lt_cv_prog_compiler_static_works_CXX" = xyes; then : else lt_prog_compiler_static_CXX= fi { $as_echo "$as_me:${as_lineno-$LINENO}: checking if $compiler supports -c -o file.$ac_objext" >&5 $as_echo_n "checking if $compiler supports -c -o file.$ac_objext... " >&6; } if ${lt_cv_prog_compiler_c_o_CXX+:} false; then : $as_echo_n "(cached) " >&6 else lt_cv_prog_compiler_c_o_CXX=no $RM -r conftest 2>/dev/null mkdir conftest cd conftest mkdir out echo "$lt_simple_compile_test_code" > conftest.$ac_ext lt_compiler_flag="-o out/conftest2.$ac_objext" # Insert the option either (1) after the last *FLAGS variable, or # (2) before a word containing "conftest.", or (3) at the end. # Note that $ac_compile itself does not contain backslashes and begins # with a dollar sign (not a hyphen), so the echo should work correctly. lt_compile=`echo "$ac_compile" | $SED \ -e 's:.*FLAGS}\{0,1\} :&$lt_compiler_flag :; t' \ -e 's: [^ ]*conftest\.: $lt_compiler_flag&:; t' \ -e 's:$: $lt_compiler_flag:'` (eval echo "\"\$as_me:$LINENO: $lt_compile\"" >&5) (eval "$lt_compile" 2>out/conftest.err) ac_status=$? cat out/conftest.err >&5 echo "$as_me:$LINENO: \$? = $ac_status" >&5 if (exit $ac_status) && test -s out/conftest2.$ac_objext then # The compiler can only warn and ignore the option if not recognized # So say no if there are warnings $ECHO "$_lt_compiler_boilerplate" | $SED '/^$/d' > out/conftest.exp $SED '/^$/d; /^ *+/d' out/conftest.err >out/conftest.er2 if test ! -s out/conftest.er2 || diff out/conftest.exp out/conftest.er2 >/dev/null; then lt_cv_prog_compiler_c_o_CXX=yes fi fi chmod u+w . 2>&5 $RM conftest* # SGI C++ compiler will create directory out/ii_files/ for # template instantiation test -d out/ii_files && $RM out/ii_files/* && rmdir out/ii_files $RM out/* && rmdir out cd .. $RM -r conftest $RM conftest* fi { $as_echo "$as_me:${as_lineno-$LINENO}: result: $lt_cv_prog_compiler_c_o_CXX" >&5 $as_echo "$lt_cv_prog_compiler_c_o_CXX" >&6; } { $as_echo "$as_me:${as_lineno-$LINENO}: checking if $compiler supports -c -o file.$ac_objext" >&5 $as_echo_n "checking if $compiler supports -c -o file.$ac_objext... " >&6; } if ${lt_cv_prog_compiler_c_o_CXX+:} false; then : $as_echo_n "(cached) " >&6 else lt_cv_prog_compiler_c_o_CXX=no $RM -r conftest 2>/dev/null mkdir conftest cd conftest mkdir out echo "$lt_simple_compile_test_code" > conftest.$ac_ext lt_compiler_flag="-o out/conftest2.$ac_objext" # Insert the option either (1) after the last *FLAGS variable, or # (2) before a word containing "conftest.", or (3) at the end. # Note that $ac_compile itself does not contain backslashes and begins # with a dollar sign (not a hyphen), so the echo should work correctly. lt_compile=`echo "$ac_compile" | $SED \ -e 's:.*FLAGS}\{0,1\} :&$lt_compiler_flag :; t' \ -e 's: [^ ]*conftest\.: $lt_compiler_flag&:; t' \ -e 's:$: $lt_compiler_flag:'` (eval echo "\"\$as_me:$LINENO: $lt_compile\"" >&5) (eval "$lt_compile" 2>out/conftest.err) ac_status=$? cat out/conftest.err >&5 echo "$as_me:$LINENO: \$? = $ac_status" >&5 if (exit $ac_status) && test -s out/conftest2.$ac_objext then # The compiler can only warn and ignore the option if not recognized # So say no if there are warnings $ECHO "$_lt_compiler_boilerplate" | $SED '/^$/d' > out/conftest.exp $SED '/^$/d; /^ *+/d' out/conftest.err >out/conftest.er2 if test ! -s out/conftest.er2 || diff out/conftest.exp out/conftest.er2 >/dev/null; then lt_cv_prog_compiler_c_o_CXX=yes fi fi chmod u+w . 2>&5 $RM conftest* # SGI C++ compiler will create directory out/ii_files/ for # template instantiation test -d out/ii_files && $RM out/ii_files/* && rmdir out/ii_files $RM out/* && rmdir out cd .. $RM -r conftest $RM conftest* fi { $as_echo "$as_me:${as_lineno-$LINENO}: result: $lt_cv_prog_compiler_c_o_CXX" >&5 $as_echo "$lt_cv_prog_compiler_c_o_CXX" >&6; } hard_links="nottested" if test "$lt_cv_prog_compiler_c_o_CXX" = no && test "$need_locks" != no; then # do not overwrite the value of need_locks provided by the user { $as_echo "$as_me:${as_lineno-$LINENO}: checking if we can lock with hard links" >&5 $as_echo_n "checking if we can lock with hard links... " >&6; } hard_links=yes $RM conftest* ln conftest.a conftest.b 2>/dev/null && hard_links=no touch conftest.a ln conftest.a conftest.b 2>&5 || hard_links=no ln conftest.a conftest.b 2>/dev/null && hard_links=no { $as_echo "$as_me:${as_lineno-$LINENO}: result: $hard_links" >&5 $as_echo "$hard_links" >&6; } if test "$hard_links" = no; then { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: \`$CC' does not support \`-c -o', so \`make -j' may be unsafe" >&5 $as_echo "$as_me: WARNING: \`$CC' does not support \`-c -o', so \`make -j' may be unsafe" >&2;} need_locks=warn fi else need_locks=no fi { $as_echo "$as_me:${as_lineno-$LINENO}: checking whether the $compiler linker ($LD) supports shared libraries" >&5 $as_echo_n "checking whether the $compiler linker ($LD) supports shared libraries... " >&6; } export_symbols_cmds_CXX='$NM $libobjs $convenience | $global_symbol_pipe | $SED '\''s/.* //'\'' | sort | uniq > $export_symbols' exclude_expsyms_CXX='_GLOBAL_OFFSET_TABLE_|_GLOBAL__F[ID]_.*' case $host_os in aix[4-9]*) # If we're using GNU nm, then we don't want the "-C" option. # -C means demangle to AIX nm, but means don't demangle with GNU nm # Also, AIX nm treats weak defined symbols like other global defined # symbols, whereas GNU nm marks them as "W". if $NM -V 2>&1 | $GREP 'GNU' > /dev/null; then export_symbols_cmds_CXX='$NM -Bpg $libobjs $convenience | awk '\''{ if (((\$ 2 == "T") || (\$ 2 == "D") || (\$ 2 == "B") || (\$ 2 == "W")) && (substr(\$ 3,1,1) != ".")) { print \$ 3 } }'\'' | sort -u > $export_symbols' else export_symbols_cmds_CXX='$NM -BCpg $libobjs $convenience | awk '\''{ if (((\$ 2 == "T") || (\$ 2 == "D") || (\$ 2 == "B")) && (substr(\$ 3,1,1) != ".")) { print \$ 3 } }'\'' | sort -u > $export_symbols' fi ;; pw32*) export_symbols_cmds_CXX="$ltdll_cmds" ;; cygwin* | mingw* | cegcc*) case $cc_basename in cl*) exclude_expsyms_CXX='_NULL_IMPORT_DESCRIPTOR|_IMPORT_DESCRIPTOR_.*' ;; *) export_symbols_cmds_CXX='$NM $libobjs $convenience | $global_symbol_pipe | $SED -e '\''/^[BCDGRS][ ]/s/.*[ ]\([^ ]*\)/\1 DATA/;s/^.*[ ]__nm__\([^ ]*\)[ ][^ ]*/\1 DATA/;/^I[ ]/d;/^[AITW][ ]/s/.* //'\'' | sort | uniq > $export_symbols' exclude_expsyms_CXX='[_]+GLOBAL_OFFSET_TABLE_|[_]+GLOBAL__[FID]_.*|[_]+head_[A-Za-z0-9_]+_dll|[A-Za-z0-9_]+_dll_iname' ;; esac ;; *) export_symbols_cmds_CXX='$NM $libobjs $convenience | $global_symbol_pipe | $SED '\''s/.* //'\'' | sort | uniq > $export_symbols' ;; esac { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ld_shlibs_CXX" >&5 $as_echo "$ld_shlibs_CXX" >&6; } test "$ld_shlibs_CXX" = no && can_build_shared=no with_gnu_ld_CXX=$with_gnu_ld # # Do we need to explicitly link libc? # case "x$archive_cmds_need_lc_CXX" in x|xyes) # Assume -lc should be added archive_cmds_need_lc_CXX=yes if test "$enable_shared" = yes && test "$GCC" = yes; then case $archive_cmds_CXX in *'~'*) # FIXME: we may have to deal with multi-command sequences. ;; '$CC '*) # Test whether the compiler implicitly links with -lc since on some # systems, -lgcc has to come before -lc. If gcc already passes -lc # to ld, don't add -lc before -lgcc. { $as_echo "$as_me:${as_lineno-$LINENO}: checking whether -lc should be explicitly linked in" >&5 $as_echo_n "checking whether -lc should be explicitly linked in... " >&6; } if ${lt_cv_archive_cmds_need_lc_CXX+:} false; then : $as_echo_n "(cached) " >&6 else $RM conftest* echo "$lt_simple_compile_test_code" > conftest.$ac_ext if { { eval echo "\"\$as_me\":${as_lineno-$LINENO}: \"$ac_compile\""; } >&5 (eval $ac_compile) 2>&5 ac_status=$? $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 test $ac_status = 0; } 2>conftest.err; then soname=conftest lib=conftest libobjs=conftest.$ac_objext deplibs= wl=$lt_prog_compiler_wl_CXX pic_flag=$lt_prog_compiler_pic_CXX compiler_flags=-v linker_flags=-v verstring= output_objdir=. libname=conftest lt_save_allow_undefined_flag=$allow_undefined_flag_CXX allow_undefined_flag_CXX= if { { eval echo "\"\$as_me\":${as_lineno-$LINENO}: \"$archive_cmds_CXX 2\>\&1 \| $GREP \" -lc \" \>/dev/null 2\>\&1\""; } >&5 (eval $archive_cmds_CXX 2\>\&1 \| $GREP \" -lc \" \>/dev/null 2\>\&1) 2>&5 ac_status=$? $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 test $ac_status = 0; } then lt_cv_archive_cmds_need_lc_CXX=no else lt_cv_archive_cmds_need_lc_CXX=yes fi allow_undefined_flag_CXX=$lt_save_allow_undefined_flag else cat conftest.err 1>&5 fi $RM conftest* fi { $as_echo "$as_me:${as_lineno-$LINENO}: result: $lt_cv_archive_cmds_need_lc_CXX" >&5 $as_echo "$lt_cv_archive_cmds_need_lc_CXX" >&6; } archive_cmds_need_lc_CXX=$lt_cv_archive_cmds_need_lc_CXX ;; esac fi ;; esac { $as_echo "$as_me:${as_lineno-$LINENO}: checking dynamic linker characteristics" >&5 $as_echo_n "checking dynamic linker characteristics... " >&6; } library_names_spec= libname_spec='lib$name' soname_spec= shrext_cmds=".so" postinstall_cmds= postuninstall_cmds= finish_cmds= finish_eval= shlibpath_var= shlibpath_overrides_runpath=unknown version_type=none dynamic_linker="$host_os ld.so" sys_lib_dlsearch_path_spec="/lib /usr/lib" need_lib_prefix=unknown hardcode_into_libs=no # when you set need_version to no, make sure it does not cause -set_version # flags to be left without arguments need_version=unknown case $host_os in aix3*) version_type=linux # correct to gnu/linux during the next big refactor library_names_spec='${libname}${release}${shared_ext}$versuffix $libname.a' shlibpath_var=LIBPATH # AIX 3 has no versioning support, so we append a major version to the name. soname_spec='${libname}${release}${shared_ext}$major' ;; aix[4-9]*) version_type=linux # correct to gnu/linux during the next big refactor need_lib_prefix=no need_version=no hardcode_into_libs=yes if test "$host_cpu" = ia64; then # AIX 5 supports IA64 library_names_spec='${libname}${release}${shared_ext}$major ${libname}${release}${shared_ext}$versuffix $libname${shared_ext}' shlibpath_var=LD_LIBRARY_PATH else # With GCC up to 2.95.x, collect2 would create an import file # for dependence libraries. The import file would start with # the line `#! .'. This would cause the generated library to # depend on `.', always an invalid library. This was fixed in # development snapshots of GCC prior to 3.0. case $host_os in aix4 | aix4.[01] | aix4.[01].*) if { echo '#if __GNUC__ > 2 || (__GNUC__ == 2 && __GNUC_MINOR__ >= 97)' echo ' yes ' echo '#endif'; } | ${CC} -E - | $GREP yes > /dev/null; then : else can_build_shared=no fi ;; esac # AIX (on Power*) has no versioning support, so currently we can not hardcode correct # soname into executable. Probably we can add versioning support to # collect2, so additional links can be useful in future. if test "$aix_use_runtimelinking" = yes; then # If using run time linking (on AIX 4.2 or later) use lib.so # instead of lib.a to let people know that these are not # typical AIX shared libraries. library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}' else # We preserve .a as extension for shared libraries through AIX4.2 # and later when we are not doing run time linking. library_names_spec='${libname}${release}.a $libname.a' soname_spec='${libname}${release}${shared_ext}$major' fi shlibpath_var=LIBPATH fi ;; amigaos*) case $host_cpu in powerpc) # Since July 2007 AmigaOS4 officially supports .so libraries. # When compiling the executable, add -use-dynld -Lsobjs: to the compileline. library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}' ;; m68k) library_names_spec='$libname.ixlibrary $libname.a' # Create ${libname}_ixlibrary.a entries in /sys/libs. finish_eval='for lib in `ls $libdir/*.ixlibrary 2>/dev/null`; do libname=`func_echo_all "$lib" | $SED '\''s%^.*/\([^/]*\)\.ixlibrary$%\1%'\''`; test $RM /sys/libs/${libname}_ixlibrary.a; $show "cd /sys/libs && $LN_S $lib ${libname}_ixlibrary.a"; cd /sys/libs && $LN_S $lib ${libname}_ixlibrary.a || exit 1; done' ;; esac ;; beos*) library_names_spec='${libname}${shared_ext}' dynamic_linker="$host_os ld.so" shlibpath_var=LIBRARY_PATH ;; bsdi[45]*) version_type=linux # correct to gnu/linux during the next big refactor need_version=no library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}' soname_spec='${libname}${release}${shared_ext}$major' finish_cmds='PATH="\$PATH:/sbin" ldconfig $libdir' shlibpath_var=LD_LIBRARY_PATH sys_lib_search_path_spec="/shlib /usr/lib /usr/X11/lib /usr/contrib/lib /lib /usr/local/lib" sys_lib_dlsearch_path_spec="/shlib /usr/lib /usr/local/lib" # the default ld.so.conf also contains /usr/contrib/lib and # /usr/X11R6/lib (/usr/X11 is a link to /usr/X11R6), but let us allow # libtool to hard-code these into programs ;; cygwin* | mingw* | pw32* | cegcc*) version_type=windows shrext_cmds=".dll" need_version=no need_lib_prefix=no case $GCC,$cc_basename in yes,*) # gcc library_names_spec='$libname.dll.a' # DLL is installed to $(libdir)/../bin by postinstall_cmds postinstall_cmds='base_file=`basename \${file}`~ dlpath=`$SHELL 2>&1 -c '\''. $dir/'\''\${base_file}'\''i; echo \$dlname'\''`~ dldir=$destdir/`dirname \$dlpath`~ test -d \$dldir || mkdir -p \$dldir~ $install_prog $dir/$dlname \$dldir/$dlname~ chmod a+x \$dldir/$dlname~ if test -n '\''$stripme'\'' && test -n '\''$striplib'\''; then eval '\''$striplib \$dldir/$dlname'\'' || exit \$?; fi' postuninstall_cmds='dldll=`$SHELL 2>&1 -c '\''. $file; echo \$dlname'\''`~ dlpath=$dir/\$dldll~ $RM \$dlpath' shlibpath_overrides_runpath=yes case $host_os in cygwin*) # Cygwin DLLs use 'cyg' prefix rather than 'lib' soname_spec='`echo ${libname} | sed -e 's/^lib/cyg/'``echo ${release} | $SED -e 's/[.]/-/g'`${versuffix}${shared_ext}' ;; mingw* | cegcc*) # MinGW DLLs use traditional 'lib' prefix soname_spec='${libname}`echo ${release} | $SED -e 's/[.]/-/g'`${versuffix}${shared_ext}' ;; pw32*) # pw32 DLLs use 'pw' prefix rather than 'lib' library_names_spec='`echo ${libname} | sed -e 's/^lib/pw/'``echo ${release} | $SED -e 's/[.]/-/g'`${versuffix}${shared_ext}' ;; esac dynamic_linker='Win32 ld.exe' ;; *,cl*) # Native MSVC libname_spec='$name' soname_spec='${libname}`echo ${release} | $SED -e 's/[.]/-/g'`${versuffix}${shared_ext}' library_names_spec='${libname}.dll.lib' case $build_os in mingw*) sys_lib_search_path_spec= lt_save_ifs=$IFS IFS=';' for lt_path in $LIB do IFS=$lt_save_ifs # Let DOS variable expansion print the short 8.3 style file name. lt_path=`cd "$lt_path" 2>/dev/null && cmd //C "for %i in (".") do @echo %~si"` sys_lib_search_path_spec="$sys_lib_search_path_spec $lt_path" done IFS=$lt_save_ifs # Convert to MSYS style. sys_lib_search_path_spec=`$ECHO "$sys_lib_search_path_spec" | sed -e 's|\\\\|/|g' -e 's| \\([a-zA-Z]\\):| /\\1|g' -e 's|^ ||'` ;; cygwin*) # Convert to unix form, then to dos form, then back to unix form # but this time dos style (no spaces!) so that the unix form looks # like /cygdrive/c/PROGRA~1:/cygdr... sys_lib_search_path_spec=`cygpath --path --unix "$LIB"` sys_lib_search_path_spec=`cygpath --path --dos "$sys_lib_search_path_spec" 2>/dev/null` sys_lib_search_path_spec=`cygpath --path --unix "$sys_lib_search_path_spec" | $SED -e "s/$PATH_SEPARATOR/ /g"` ;; *) sys_lib_search_path_spec="$LIB" if $ECHO "$sys_lib_search_path_spec" | $GREP ';[c-zC-Z]:/' >/dev/null; then # It is most probably a Windows format PATH. sys_lib_search_path_spec=`$ECHO "$sys_lib_search_path_spec" | $SED -e 's/;/ /g'` else sys_lib_search_path_spec=`$ECHO "$sys_lib_search_path_spec" | $SED -e "s/$PATH_SEPARATOR/ /g"` fi # FIXME: find the short name or the path components, as spaces are # common. (e.g. "Program Files" -> "PROGRA~1") ;; esac # DLL is installed to $(libdir)/../bin by postinstall_cmds postinstall_cmds='base_file=`basename \${file}`~ dlpath=`$SHELL 2>&1 -c '\''. $dir/'\''\${base_file}'\''i; echo \$dlname'\''`~ dldir=$destdir/`dirname \$dlpath`~ test -d \$dldir || mkdir -p \$dldir~ $install_prog $dir/$dlname \$dldir/$dlname' postuninstall_cmds='dldll=`$SHELL 2>&1 -c '\''. $file; echo \$dlname'\''`~ dlpath=$dir/\$dldll~ $RM \$dlpath' shlibpath_overrides_runpath=yes dynamic_linker='Win32 link.exe' ;; *) # Assume MSVC wrapper library_names_spec='${libname}`echo ${release} | $SED -e 's/[.]/-/g'`${versuffix}${shared_ext} $libname.lib' dynamic_linker='Win32 ld.exe' ;; esac # FIXME: first we should search . and the directory the executable is in shlibpath_var=PATH ;; darwin* | rhapsody*) dynamic_linker="$host_os dyld" version_type=darwin need_lib_prefix=no need_version=no library_names_spec='${libname}${release}${major}$shared_ext ${libname}$shared_ext' soname_spec='${libname}${release}${major}$shared_ext' shlibpath_overrides_runpath=yes shlibpath_var=DYLD_LIBRARY_PATH shrext_cmds='`test .$module = .yes && echo .so || echo .dylib`' sys_lib_dlsearch_path_spec='/usr/local/lib /lib /usr/lib' ;; dgux*) version_type=linux # correct to gnu/linux during the next big refactor need_lib_prefix=no need_version=no library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname$shared_ext' soname_spec='${libname}${release}${shared_ext}$major' shlibpath_var=LD_LIBRARY_PATH ;; freebsd* | dragonfly*) # DragonFly does not have aout. When/if they implement a new # versioning mechanism, adjust this. if test -x /usr/bin/objformat; then objformat=`/usr/bin/objformat` else case $host_os in freebsd[23].*) objformat=aout ;; *) objformat=elf ;; esac fi # Handle Gentoo/FreeBSD as it was Linux case $host_vendor in gentoo) version_type=linux ;; *) version_type=freebsd-$objformat ;; esac case $version_type in freebsd-elf*) library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext} $libname${shared_ext}' need_version=no need_lib_prefix=no ;; freebsd-*) library_names_spec='${libname}${release}${shared_ext}$versuffix $libname${shared_ext}$versuffix' need_version=yes ;; linux) library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major ${libname}${shared_ext}' soname_spec='${libname}${release}${shared_ext}$major' need_lib_prefix=no need_version=no ;; esac shlibpath_var=LD_LIBRARY_PATH case $host_os in freebsd2.*) shlibpath_overrides_runpath=yes ;; freebsd3.[01]* | freebsdelf3.[01]*) shlibpath_overrides_runpath=yes hardcode_into_libs=yes ;; freebsd3.[2-9]* | freebsdelf3.[2-9]* | \ freebsd4.[0-5] | freebsdelf4.[0-5] | freebsd4.1.1 | freebsdelf4.1.1) shlibpath_overrides_runpath=no hardcode_into_libs=yes ;; *) # from 4.6 on, and DragonFly shlibpath_overrides_runpath=yes hardcode_into_libs=yes ;; esac ;; gnu*) version_type=linux # correct to gnu/linux during the next big refactor need_lib_prefix=no need_version=no library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}${major} ${libname}${shared_ext}' soname_spec='${libname}${release}${shared_ext}$major' shlibpath_var=LD_LIBRARY_PATH shlibpath_overrides_runpath=no hardcode_into_libs=yes ;; haiku*) version_type=linux # correct to gnu/linux during the next big refactor need_lib_prefix=no need_version=no dynamic_linker="$host_os runtime_loader" library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}${major} ${libname}${shared_ext}' soname_spec='${libname}${release}${shared_ext}$major' shlibpath_var=LIBRARY_PATH shlibpath_overrides_runpath=yes sys_lib_dlsearch_path_spec='/boot/home/config/lib /boot/common/lib /boot/system/lib' hardcode_into_libs=yes ;; hpux9* | hpux10* | hpux11*) # Give a soname corresponding to the major version so that dld.sl refuses to # link against other versions. version_type=sunos need_lib_prefix=no need_version=no case $host_cpu in ia64*) shrext_cmds='.so' hardcode_into_libs=yes dynamic_linker="$host_os dld.so" shlibpath_var=LD_LIBRARY_PATH shlibpath_overrides_runpath=yes # Unless +noenvvar is specified. library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}' soname_spec='${libname}${release}${shared_ext}$major' if test "X$HPUX_IA64_MODE" = X32; then sys_lib_search_path_spec="/usr/lib/hpux32 /usr/local/lib/hpux32 /usr/local/lib" else sys_lib_search_path_spec="/usr/lib/hpux64 /usr/local/lib/hpux64" fi sys_lib_dlsearch_path_spec=$sys_lib_search_path_spec ;; hppa*64*) shrext_cmds='.sl' hardcode_into_libs=yes dynamic_linker="$host_os dld.sl" shlibpath_var=LD_LIBRARY_PATH # How should we handle SHLIB_PATH shlibpath_overrides_runpath=yes # Unless +noenvvar is specified. library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}' soname_spec='${libname}${release}${shared_ext}$major' sys_lib_search_path_spec="/usr/lib/pa20_64 /usr/ccs/lib/pa20_64" sys_lib_dlsearch_path_spec=$sys_lib_search_path_spec ;; *) shrext_cmds='.sl' dynamic_linker="$host_os dld.sl" shlibpath_var=SHLIB_PATH shlibpath_overrides_runpath=no # +s is required to enable SHLIB_PATH library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}' soname_spec='${libname}${release}${shared_ext}$major' ;; esac # HP-UX runs *really* slowly unless shared libraries are mode 555, ... postinstall_cmds='chmod 555 $lib' # or fails outright, so override atomically: install_override_mode=555 ;; interix[3-9]*) version_type=linux # correct to gnu/linux during the next big refactor need_lib_prefix=no need_version=no library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major ${libname}${shared_ext}' soname_spec='${libname}${release}${shared_ext}$major' dynamic_linker='Interix 3.x ld.so.1 (PE, like ELF)' shlibpath_var=LD_LIBRARY_PATH shlibpath_overrides_runpath=no hardcode_into_libs=yes ;; irix5* | irix6* | nonstopux*) case $host_os in nonstopux*) version_type=nonstopux ;; *) if test "$lt_cv_prog_gnu_ld" = yes; then version_type=linux # correct to gnu/linux during the next big refactor else version_type=irix fi ;; esac need_lib_prefix=no need_version=no soname_spec='${libname}${release}${shared_ext}$major' library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major ${libname}${release}${shared_ext} $libname${shared_ext}' case $host_os in irix5* | nonstopux*) libsuff= shlibsuff= ;; *) case $LD in # libtool.m4 will add one of these switches to LD *-32|*"-32 "|*-melf32bsmip|*"-melf32bsmip ") libsuff= shlibsuff= libmagic=32-bit;; *-n32|*"-n32 "|*-melf32bmipn32|*"-melf32bmipn32 ") libsuff=32 shlibsuff=N32 libmagic=N32;; *-64|*"-64 "|*-melf64bmip|*"-melf64bmip ") libsuff=64 shlibsuff=64 libmagic=64-bit;; *) libsuff= shlibsuff= libmagic=never-match;; esac ;; esac shlibpath_var=LD_LIBRARY${shlibsuff}_PATH shlibpath_overrides_runpath=no sys_lib_search_path_spec="/usr/lib${libsuff} /lib${libsuff} /usr/local/lib${libsuff}" sys_lib_dlsearch_path_spec="/usr/lib${libsuff} /lib${libsuff}" hardcode_into_libs=yes ;; # No shared lib support for Linux oldld, aout, or coff. linux*oldld* | linux*aout* | linux*coff*) dynamic_linker=no ;; # This must be glibc/ELF. linux* | k*bsd*-gnu | kopensolaris*-gnu) version_type=linux # correct to gnu/linux during the next big refactor need_lib_prefix=no need_version=no library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}' soname_spec='${libname}${release}${shared_ext}$major' finish_cmds='PATH="\$PATH:/sbin" ldconfig -n $libdir' shlibpath_var=LD_LIBRARY_PATH shlibpath_overrides_runpath=no # Some binutils ld are patched to set DT_RUNPATH if ${lt_cv_shlibpath_overrides_runpath+:} false; then : $as_echo_n "(cached) " >&6 else lt_cv_shlibpath_overrides_runpath=no save_LDFLAGS=$LDFLAGS save_libdir=$libdir eval "libdir=/foo; wl=\"$lt_prog_compiler_wl_CXX\"; \ LDFLAGS=\"\$LDFLAGS $hardcode_libdir_flag_spec_CXX\"" cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ int main () { ; return 0; } _ACEOF if ac_fn_cxx_try_link "$LINENO"; then : if ($OBJDUMP -p conftest$ac_exeext) 2>/dev/null | grep "RUNPATH.*$libdir" >/dev/null; then : lt_cv_shlibpath_overrides_runpath=yes fi fi rm -f core conftest.err conftest.$ac_objext \ conftest$ac_exeext conftest.$ac_ext LDFLAGS=$save_LDFLAGS libdir=$save_libdir fi shlibpath_overrides_runpath=$lt_cv_shlibpath_overrides_runpath # This implies no fast_install, which is unacceptable. # Some rework will be needed to allow for fast_install # before this can be enabled. hardcode_into_libs=yes # Append ld.so.conf contents to the search path if test -f /etc/ld.so.conf; then lt_ld_extra=`awk '/^include / { system(sprintf("cd /etc; cat %s 2>/dev/null", \$2)); skip = 1; } { if (!skip) print \$0; skip = 0; }' < /etc/ld.so.conf | $SED -e 's/#.*//;/^[ ]*hwcap[ ]/d;s/[:, ]/ /g;s/=[^=]*$//;s/=[^= ]* / /g;s/"//g;/^$/d' | tr '\n' ' '` sys_lib_dlsearch_path_spec="/lib /usr/lib $lt_ld_extra" fi # We used to test for /lib/ld.so.1 and disable shared libraries on # powerpc, because MkLinux only supported shared libraries with the # GNU dynamic linker. Since this was broken with cross compilers, # most powerpc-linux boxes support dynamic linking these days and # people can always --disable-shared, the test was removed, and we # assume the GNU/Linux dynamic linker is in use. dynamic_linker='GNU/Linux ld.so' ;; netbsd*) version_type=sunos need_lib_prefix=no need_version=no if echo __ELF__ | $CC -E - | $GREP __ELF__ >/dev/null; then library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${shared_ext}$versuffix' finish_cmds='PATH="\$PATH:/sbin" ldconfig -m $libdir' dynamic_linker='NetBSD (a.out) ld.so' else library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major ${libname}${shared_ext}' soname_spec='${libname}${release}${shared_ext}$major' dynamic_linker='NetBSD ld.elf_so' fi shlibpath_var=LD_LIBRARY_PATH shlibpath_overrides_runpath=yes hardcode_into_libs=yes ;; newsos6) version_type=linux # correct to gnu/linux during the next big refactor library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}' shlibpath_var=LD_LIBRARY_PATH shlibpath_overrides_runpath=yes ;; *nto* | *qnx*) version_type=qnx need_lib_prefix=no need_version=no library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}' soname_spec='${libname}${release}${shared_ext}$major' shlibpath_var=LD_LIBRARY_PATH shlibpath_overrides_runpath=no hardcode_into_libs=yes dynamic_linker='ldqnx.so' ;; openbsd*) version_type=sunos sys_lib_dlsearch_path_spec="/usr/lib" need_lib_prefix=no # Some older versions of OpenBSD (3.3 at least) *do* need versioned libs. case $host_os in openbsd3.3 | openbsd3.3.*) need_version=yes ;; *) need_version=no ;; esac library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${shared_ext}$versuffix' finish_cmds='PATH="\$PATH:/sbin" ldconfig -m $libdir' shlibpath_var=LD_LIBRARY_PATH if test -z "`echo __ELF__ | $CC -E - | $GREP __ELF__`" || test "$host_os-$host_cpu" = "openbsd2.8-powerpc"; then case $host_os in openbsd2.[89] | openbsd2.[89].*) shlibpath_overrides_runpath=no ;; *) shlibpath_overrides_runpath=yes ;; esac else shlibpath_overrides_runpath=yes fi ;; os2*) libname_spec='$name' shrext_cmds=".dll" need_lib_prefix=no library_names_spec='$libname${shared_ext} $libname.a' dynamic_linker='OS/2 ld.exe' shlibpath_var=LIBPATH ;; osf3* | osf4* | osf5*) version_type=osf need_lib_prefix=no need_version=no soname_spec='${libname}${release}${shared_ext}$major' library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}' shlibpath_var=LD_LIBRARY_PATH sys_lib_search_path_spec="/usr/shlib /usr/ccs/lib /usr/lib/cmplrs/cc /usr/lib /usr/local/lib /var/shlib" sys_lib_dlsearch_path_spec="$sys_lib_search_path_spec" ;; rdos*) dynamic_linker=no ;; solaris*) version_type=linux # correct to gnu/linux during the next big refactor need_lib_prefix=no need_version=no library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}' soname_spec='${libname}${release}${shared_ext}$major' shlibpath_var=LD_LIBRARY_PATH shlibpath_overrides_runpath=yes hardcode_into_libs=yes # ldd complains unless libraries are executable postinstall_cmds='chmod +x $lib' ;; sunos4*) version_type=sunos library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${shared_ext}$versuffix' finish_cmds='PATH="\$PATH:/usr/etc" ldconfig $libdir' shlibpath_var=LD_LIBRARY_PATH shlibpath_overrides_runpath=yes if test "$with_gnu_ld" = yes; then need_lib_prefix=no fi need_version=yes ;; sysv4 | sysv4.3*) version_type=linux # correct to gnu/linux during the next big refactor library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}' soname_spec='${libname}${release}${shared_ext}$major' shlibpath_var=LD_LIBRARY_PATH case $host_vendor in sni) shlibpath_overrides_runpath=no need_lib_prefix=no runpath_var=LD_RUN_PATH ;; siemens) need_lib_prefix=no ;; motorola) need_lib_prefix=no need_version=no shlibpath_overrides_runpath=no sys_lib_search_path_spec='/lib /usr/lib /usr/ccs/lib' ;; esac ;; sysv4*MP*) if test -d /usr/nec ;then version_type=linux # correct to gnu/linux during the next big refactor library_names_spec='$libname${shared_ext}.$versuffix $libname${shared_ext}.$major $libname${shared_ext}' soname_spec='$libname${shared_ext}.$major' shlibpath_var=LD_LIBRARY_PATH fi ;; sysv5* | sco3.2v5* | sco5v6* | unixware* | OpenUNIX* | sysv4*uw2*) version_type=freebsd-elf need_lib_prefix=no need_version=no library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext} $libname${shared_ext}' soname_spec='${libname}${release}${shared_ext}$major' shlibpath_var=LD_LIBRARY_PATH shlibpath_overrides_runpath=yes hardcode_into_libs=yes if test "$with_gnu_ld" = yes; then sys_lib_search_path_spec='/usr/local/lib /usr/gnu/lib /usr/ccs/lib /usr/lib /lib' else sys_lib_search_path_spec='/usr/ccs/lib /usr/lib' case $host_os in sco3.2v5*) sys_lib_search_path_spec="$sys_lib_search_path_spec /lib" ;; esac fi sys_lib_dlsearch_path_spec='/usr/lib' ;; tpf*) # TPF is a cross-target only. Preferred cross-host = GNU/Linux. version_type=linux # correct to gnu/linux during the next big refactor need_lib_prefix=no need_version=no library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}' shlibpath_var=LD_LIBRARY_PATH shlibpath_overrides_runpath=no hardcode_into_libs=yes ;; uts4*) version_type=linux # correct to gnu/linux during the next big refactor library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}' soname_spec='${libname}${release}${shared_ext}$major' shlibpath_var=LD_LIBRARY_PATH ;; *) dynamic_linker=no ;; esac { $as_echo "$as_me:${as_lineno-$LINENO}: result: $dynamic_linker" >&5 $as_echo "$dynamic_linker" >&6; } test "$dynamic_linker" = no && can_build_shared=no variables_saved_for_relink="PATH $shlibpath_var $runpath_var" if test "$GCC" = yes; then variables_saved_for_relink="$variables_saved_for_relink GCC_EXEC_PREFIX COMPILER_PATH LIBRARY_PATH" fi if test "${lt_cv_sys_lib_search_path_spec+set}" = set; then sys_lib_search_path_spec="$lt_cv_sys_lib_search_path_spec" fi if test "${lt_cv_sys_lib_dlsearch_path_spec+set}" = set; then sys_lib_dlsearch_path_spec="$lt_cv_sys_lib_dlsearch_path_spec" fi { $as_echo "$as_me:${as_lineno-$LINENO}: checking how to hardcode library paths into programs" >&5 $as_echo_n "checking how to hardcode library paths into programs... " >&6; } hardcode_action_CXX= if test -n "$hardcode_libdir_flag_spec_CXX" || test -n "$runpath_var_CXX" || test "X$hardcode_automatic_CXX" = "Xyes" ; then # We can hardcode non-existent directories. if test "$hardcode_direct_CXX" != no && # If the only mechanism to avoid hardcoding is shlibpath_var, we # have to relink, otherwise we might link with an installed library # when we should be linking with a yet-to-be-installed one ## test "$_LT_TAGVAR(hardcode_shlibpath_var, CXX)" != no && test "$hardcode_minus_L_CXX" != no; then # Linking always hardcodes the temporary library directory. hardcode_action_CXX=relink else # We can link without hardcoding, and we can hardcode nonexisting dirs. hardcode_action_CXX=immediate fi else # We cannot hardcode anything, or else we can only hardcode existing # directories. hardcode_action_CXX=unsupported fi { $as_echo "$as_me:${as_lineno-$LINENO}: result: $hardcode_action_CXX" >&5 $as_echo "$hardcode_action_CXX" >&6; } if test "$hardcode_action_CXX" = relink || test "$inherit_rpath_CXX" = yes; then # Fast installation is not supported enable_fast_install=no elif test "$shlibpath_overrides_runpath" = yes || test "$enable_shared" = no; then # Fast installation is not necessary enable_fast_install=needless fi fi # test -n "$compiler" CC=$lt_save_CC CFLAGS=$lt_save_CFLAGS LDCXX=$LD LD=$lt_save_LD GCC=$lt_save_GCC with_gnu_ld=$lt_save_with_gnu_ld lt_cv_path_LDCXX=$lt_cv_path_LD lt_cv_path_LD=$lt_save_path_LD lt_cv_prog_gnu_ldcxx=$lt_cv_prog_gnu_ld lt_cv_prog_gnu_ld=$lt_save_with_gnu_ld fi # test "$_lt_caught_CXX_error" != yes ac_ext=c ac_cpp='$CPP $CPPFLAGS' ac_compile='$CC -c $CFLAGS $CPPFLAGS conftest.$ac_ext >&5' ac_link='$CC -o conftest$ac_exeext $CFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5' ac_compiler_gnu=$ac_cv_c_compiler_gnu ac_ext=cpp ac_cpp='$CXXCPP $CPPFLAGS' ac_compile='$CXX -c $CXXFLAGS $CPPFLAGS conftest.$ac_ext >&5' ac_link='$CXX -o conftest$ac_exeext $CXXFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5' ac_compiler_gnu=$ac_cv_cxx_compiler_gnu cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ int main () { ; return 0; } _ACEOF if ac_fn_cxx_try_link "$LINENO"; then : else as_fn_error $? "A C++ compiler is required." "$LINENO" 5 fi rm -f core conftest.err conftest.$ac_objext \ conftest$ac_exeext conftest.$ac_ext { $as_echo "$as_me:${as_lineno-$LINENO}: checking whether byte ordering is bigendian" >&5 $as_echo_n "checking whether byte ordering is bigendian... " >&6; } if ${ac_cv_c_bigendian+:} false; then : $as_echo_n "(cached) " >&6 else ac_cv_c_bigendian=unknown # See if we're dealing with a universal compiler. cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ #ifndef __APPLE_CC__ not a universal capable compiler #endif typedef int dummy; _ACEOF if ac_fn_cxx_try_compile "$LINENO"; then : # Check for potential -arch flags. It is not universal unless # there are at least two -arch flags with different values. ac_arch= ac_prev= for ac_word in $CC $CFLAGS $CPPFLAGS $LDFLAGS; do if test -n "$ac_prev"; then case $ac_word in i?86 | x86_64 | ppc | ppc64) if test -z "$ac_arch" || test "$ac_arch" = "$ac_word"; then ac_arch=$ac_word else ac_cv_c_bigendian=universal break fi ;; esac ac_prev= elif test "x$ac_word" = "x-arch"; then ac_prev=arch fi done fi rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext if test $ac_cv_c_bigendian = unknown; then # See if sys/param.h defines the BYTE_ORDER macro. cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ #include #include int main () { #if ! (defined BYTE_ORDER && defined BIG_ENDIAN \ && defined LITTLE_ENDIAN && BYTE_ORDER && BIG_ENDIAN \ && LITTLE_ENDIAN) bogus endian macros #endif ; return 0; } _ACEOF if ac_fn_cxx_try_compile "$LINENO"; then : # It does; now see whether it defined to BIG_ENDIAN or not. cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ #include #include int main () { #if BYTE_ORDER != BIG_ENDIAN not big endian #endif ; return 0; } _ACEOF if ac_fn_cxx_try_compile "$LINENO"; then : ac_cv_c_bigendian=yes else ac_cv_c_bigendian=no fi rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext fi rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext fi if test $ac_cv_c_bigendian = unknown; then # See if defines _LITTLE_ENDIAN or _BIG_ENDIAN (e.g., Solaris). cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ #include int main () { #if ! (defined _LITTLE_ENDIAN || defined _BIG_ENDIAN) bogus endian macros #endif ; return 0; } _ACEOF if ac_fn_cxx_try_compile "$LINENO"; then : # It does; now see whether it defined to _BIG_ENDIAN or not. cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ #include int main () { #ifndef _BIG_ENDIAN not big endian #endif ; return 0; } _ACEOF if ac_fn_cxx_try_compile "$LINENO"; then : ac_cv_c_bigendian=yes else ac_cv_c_bigendian=no fi rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext fi rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext fi if test $ac_cv_c_bigendian = unknown; then # Compile a test program. if test "$cross_compiling" = yes; then : # Try to guess by grepping values from an object file. cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ short int ascii_mm[] = { 0x4249, 0x4765, 0x6E44, 0x6961, 0x6E53, 0x7953, 0 }; short int ascii_ii[] = { 0x694C, 0x5454, 0x656C, 0x6E45, 0x6944, 0x6E61, 0 }; int use_ascii (int i) { return ascii_mm[i] + ascii_ii[i]; } short int ebcdic_ii[] = { 0x89D3, 0xE3E3, 0x8593, 0x95C5, 0x89C4, 0x9581, 0 }; short int ebcdic_mm[] = { 0xC2C9, 0xC785, 0x95C4, 0x8981, 0x95E2, 0xA8E2, 0 }; int use_ebcdic (int i) { return ebcdic_mm[i] + ebcdic_ii[i]; } extern int foo; int main () { return use_ascii (foo) == use_ebcdic (foo); ; return 0; } _ACEOF if ac_fn_cxx_try_compile "$LINENO"; then : if grep BIGenDianSyS conftest.$ac_objext >/dev/null; then ac_cv_c_bigendian=yes fi if grep LiTTleEnDian conftest.$ac_objext >/dev/null ; then if test "$ac_cv_c_bigendian" = unknown; then ac_cv_c_bigendian=no else # finding both strings is unlikely to happen, but who knows? ac_cv_c_bigendian=unknown fi fi fi rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext else cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ $ac_includes_default int main () { /* Are we little or big endian? From Harbison&Steele. */ union { long int l; char c[sizeof (long int)]; } u; u.l = 1; return u.c[sizeof (long int) - 1] == 1; ; return 0; } _ACEOF if ac_fn_cxx_try_run "$LINENO"; then : ac_cv_c_bigendian=no else ac_cv_c_bigendian=yes fi rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext \ conftest.$ac_objext conftest.beam conftest.$ac_ext fi fi fi { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_c_bigendian" >&5 $as_echo "$ac_cv_c_bigendian" >&6; } case $ac_cv_c_bigendian in #( yes) $as_echo "#define WORDS_BIGENDIAN 1" >>confdefs.h ;; #( no) ;; #( universal) $as_echo "#define AC_APPLE_UNIVERSAL_BUILD 1" >>confdefs.h ;; #( *) as_fn_error $? "unknown endianness presetting ac_cv_c_bigendian=no (or yes) will help" "$LINENO" 5 ;; esac for ac_header in stdint.h stddef.h sys/mman.h sys/resource.h do : as_ac_Header=`$as_echo "ac_cv_header_$ac_header" | $as_tr_sh` ac_fn_cxx_check_header_mongrel "$LINENO" "$ac_header" "$as_ac_Header" "$ac_includes_default" if eval test \"x\$"$as_ac_Header"\" = x"yes"; then : cat >>confdefs.h <<_ACEOF #define `$as_echo "HAVE_$ac_header" | $as_tr_cpp` 1 _ACEOF fi done ac_fn_cxx_check_func "$LINENO" "mmap" "ac_cv_func_mmap" if test "x$ac_cv_func_mmap" = xyes; then : fi { $as_echo "$as_me:${as_lineno-$LINENO}: checking if the compiler supports __builtin_expect" >&5 $as_echo_n "checking if the compiler supports __builtin_expect... " >&6; } cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ int main () { return __builtin_expect(1, 1) ? 1 : 0 ; return 0; } _ACEOF if ac_fn_cxx_try_compile "$LINENO"; then : snappy_have_builtin_expect=yes { $as_echo "$as_me:${as_lineno-$LINENO}: result: yes" >&5 $as_echo "yes" >&6; } else snappy_have_builtin_expect=no { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 $as_echo "no" >&6; } fi rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext if test x$snappy_have_builtin_expect = xyes ; then $as_echo "#define HAVE_BUILTIN_EXPECT 1" >>confdefs.h fi { $as_echo "$as_me:${as_lineno-$LINENO}: checking if the compiler supports __builtin_ctzll" >&5 $as_echo_n "checking if the compiler supports __builtin_ctzll... " >&6; } cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ int main () { return (__builtin_ctzll(0x100000000LL) == 32) ? 1 : 0 ; return 0; } _ACEOF if ac_fn_cxx_try_compile "$LINENO"; then : snappy_have_builtin_ctz=yes { $as_echo "$as_me:${as_lineno-$LINENO}: result: yes" >&5 $as_echo "yes" >&6; } else snappy_have_builtin_ctz=no { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 $as_echo "no" >&6; } fi rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext if test x$snappy_have_builtin_ctz = xyes ; then $as_echo "#define HAVE_BUILTIN_CTZ 1" >>confdefs.h fi if test "$ac_cv_header_stdint_h" = "yes"; then ac_cv_have_stdint_h=1 else ac_cv_have_stdint_h=0 fi if test "$ac_cv_header_stddef_h" = "yes"; then ac_cv_have_stddef_h=1 else ac_cv_have_stddef_h=0 fi SNAPPY_MAJOR="1" SNAPPY_MINOR="0" SNAPPY_PATCHLEVEL="5" { $as_echo "$as_me:${as_lineno-$LINENO}: checking for pthread_create in -lpthread" >&5 $as_echo_n "checking for pthread_create in -lpthread... " >&6; } original_LIBS="$LIBS" LIBS="-lpthread $original_LIBS" cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ #include int main () { pthread_create((void *)0, (void *)0, (void *)0, (void *)0) ; return 0; } _ACEOF if ac_fn_cxx_try_link "$LINENO"; then : pthread=yes else pthread=no fi rm -f core conftest.err conftest.$ac_objext \ conftest$ac_exeext conftest.$ac_ext if test x${pthread} = xyes; then { $as_echo "$as_me:${as_lineno-$LINENO}: result: yes" >&5 $as_echo "yes" >&6; } else LIBS="$original_LIBS" { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 $as_echo "no" >&6; } fi # Extract the first word of "erl", so it can be a program name with args. set dummy erl; ac_word=$2 { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 $as_echo_n "checking for $ac_word... " >&6; } if ${ac_cv_path_ERL+:} false; then : $as_echo_n "(cached) " >&6 else case $ERL in [\\/]* | ?:[\\/]*) ac_cv_path_ERL="$ERL" # Let the user override the test with a path. ;; *) as_save_IFS=$IFS; IFS=$PATH_SEPARATOR for as_dir in $PATH do IFS=$as_save_IFS test -z "$as_dir" && as_dir=. for ac_exec_ext in '' $ac_executable_extensions; do if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then ac_cv_path_ERL="$as_dir/$ac_word$ac_exec_ext" $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5 break 2 fi done done IFS=$as_save_IFS ;; esac fi ERL=$ac_cv_path_ERL if test -n "$ERL"; then { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ERL" >&5 $as_echo "$ERL" >&6; } else { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 $as_echo "no" >&6; } fi # Extract the first word of "escript", so it can be a program name with args. set dummy escript; ac_word=$2 { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 $as_echo_n "checking for $ac_word... " >&6; } if ${ac_cv_path_ESCRIPT+:} false; then : $as_echo_n "(cached) " >&6 else case $ESCRIPT in [\\/]* | ?:[\\/]*) ac_cv_path_ESCRIPT="$ESCRIPT" # Let the user override the test with a path. ;; *) as_save_IFS=$IFS; IFS=$PATH_SEPARATOR for as_dir in $PATH do IFS=$as_save_IFS test -z "$as_dir" && as_dir=. for ac_exec_ext in '' $ac_executable_extensions; do if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then ac_cv_path_ESCRIPT="$as_dir/$ac_word$ac_exec_ext" $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5 break 2 fi done done IFS=$as_save_IFS ;; esac fi ESCRIPT=$ac_cv_path_ESCRIPT if test -n "$ESCRIPT"; then { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ESCRIPT" >&5 $as_echo "$ESCRIPT" >&6; } else { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 $as_echo "no" >&6; } fi if test x${ERL} = x; then : as_fn_error $? "Could not find the \`erl' executable. Is Erlang installed?" "$LINENO" 5 fi # Check whether --with-erlang was given. if test "${with_erlang+set}" = set; then : withval=$with_erlang; ERLANG_FLAGS="-I$withval" else realerl=`readlink -f $ERL 2>/dev/null` if test $? -eq 0; then : erlbase=`dirname $realerl` erlbase=`dirname $erlbase` ERLANG_FLAGS="-I${erlbase}/usr/include" else # Failed to figure out where erl is installed.. # try to add some default directories to search ERLANG_FLAGS="-I${libdir}/erlang/usr/include" ERLANG_FLAGS="$ERLANG_FLAGS -I/usr/lib/erlang/usr/include" ERLANG_FLAGS="$ERLANG_FLAGS -I/usr/local/lib/erlang/usr/include" ERLANG_FLAGS="$ERLANG_FLAGS -I/opt/local/lib/erlang/usr/include" fi fi pkg_failed=no { $as_echo "$as_me:${as_lineno-$LINENO}: checking for JS" >&5 $as_echo_n "checking for JS... " >&6; } if test -n "$JS_CFLAGS"; then pkg_cv_JS_CFLAGS="$JS_CFLAGS" elif test -n "$PKG_CONFIG"; then if test -n "$PKG_CONFIG" && \ { { $as_echo "$as_me:${as_lineno-$LINENO}: \$PKG_CONFIG --exists --print-errors \"mozjs185\""; } >&5 ($PKG_CONFIG --exists --print-errors "mozjs185") 2>&5 ac_status=$? $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 test $ac_status = 0; }; then pkg_cv_JS_CFLAGS=`$PKG_CONFIG --cflags "mozjs185" 2>/dev/null` test "x$?" != "x0" && pkg_failed=yes else pkg_failed=yes fi else pkg_failed=untried fi if test -n "$JS_LIBS"; then pkg_cv_JS_LIBS="$JS_LIBS" elif test -n "$PKG_CONFIG"; then if test -n "$PKG_CONFIG" && \ { { $as_echo "$as_me:${as_lineno-$LINENO}: \$PKG_CONFIG --exists --print-errors \"mozjs185\""; } >&5 ($PKG_CONFIG --exists --print-errors "mozjs185") 2>&5 ac_status=$? $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 test $ac_status = 0; }; then pkg_cv_JS_LIBS=`$PKG_CONFIG --libs "mozjs185" 2>/dev/null` test "x$?" != "x0" && pkg_failed=yes else pkg_failed=yes fi else pkg_failed=untried fi if test $pkg_failed = yes; then { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 $as_echo "no" >&6; } if $PKG_CONFIG --atleast-pkgconfig-version 0.20; then _pkg_short_errors_supported=yes else _pkg_short_errors_supported=no fi if test $_pkg_short_errors_supported = yes; then JS_PKG_ERRORS=`$PKG_CONFIG --short-errors --print-errors --cflags --libs "mozjs185" 2>&1` else JS_PKG_ERRORS=`$PKG_CONFIG --print-errors --cflags --libs "mozjs185" 2>&1` fi # Put the nasty error message in config.log where it belongs echo "$JS_PKG_ERRORS" >&5 pkg_failed=no { $as_echo "$as_me:${as_lineno-$LINENO}: checking for JS" >&5 $as_echo_n "checking for JS... " >&6; } if test -n "$JS_CFLAGS"; then pkg_cv_JS_CFLAGS="$JS_CFLAGS" elif test -n "$PKG_CONFIG"; then if test -n "$PKG_CONFIG" && \ { { $as_echo "$as_me:${as_lineno-$LINENO}: \$PKG_CONFIG --exists --print-errors \"mozilla-js >= 1.7\""; } >&5 ($PKG_CONFIG --exists --print-errors "mozilla-js >= 1.7") 2>&5 ac_status=$? $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 test $ac_status = 0; }; then pkg_cv_JS_CFLAGS=`$PKG_CONFIG --cflags "mozilla-js >= 1.7" 2>/dev/null` test "x$?" != "x0" && pkg_failed=yes else pkg_failed=yes fi else pkg_failed=untried fi if test -n "$JS_LIBS"; then pkg_cv_JS_LIBS="$JS_LIBS" elif test -n "$PKG_CONFIG"; then if test -n "$PKG_CONFIG" && \ { { $as_echo "$as_me:${as_lineno-$LINENO}: \$PKG_CONFIG --exists --print-errors \"mozilla-js >= 1.7\""; } >&5 ($PKG_CONFIG --exists --print-errors "mozilla-js >= 1.7") 2>&5 ac_status=$? $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 test $ac_status = 0; }; then pkg_cv_JS_LIBS=`$PKG_CONFIG --libs "mozilla-js >= 1.7" 2>/dev/null` test "x$?" != "x0" && pkg_failed=yes else pkg_failed=yes fi else pkg_failed=untried fi if test $pkg_failed = yes; then { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 $as_echo "no" >&6; } if $PKG_CONFIG --atleast-pkgconfig-version 0.20; then _pkg_short_errors_supported=yes else _pkg_short_errors_supported=no fi if test $_pkg_short_errors_supported = yes; then JS_PKG_ERRORS=`$PKG_CONFIG --short-errors --print-errors --cflags --libs "mozilla-js >= 1.7" 2>&1` else JS_PKG_ERRORS=`$PKG_CONFIG --print-errors --cflags --libs "mozilla-js >= 1.7" 2>&1` fi # Put the nasty error message in config.log where it belongs echo "$JS_PKG_ERRORS" >&5 JS_LIB_DIR="${libdir}" JS_CFLAGS="-I/usr/include" JS_CFLAGS="$JS_CFLAGS -I/usr/include/js" JS_CFLAGS="$JS_CFLAGS -I/usr/include/mozjs" JS_CFLAGS="$JS_CFLAGS -I/usr/local/include/js" JS_CFLAGS="$JS_CFLAGS -I/opt/local/include/js" elif test $pkg_failed = untried; then { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 $as_echo "no" >&6; } JS_LIB_DIR="${libdir}" JS_CFLAGS="-I/usr/include" JS_CFLAGS="$JS_CFLAGS -I/usr/include/js" JS_CFLAGS="$JS_CFLAGS -I/usr/include/mozjs" JS_CFLAGS="$JS_CFLAGS -I/usr/local/include/js" JS_CFLAGS="$JS_CFLAGS -I/opt/local/include/js" else JS_CFLAGS=$pkg_cv_JS_CFLAGS JS_LIBS=$pkg_cv_JS_LIBS { $as_echo "$as_me:${as_lineno-$LINENO}: result: yes" >&5 $as_echo "yes" >&6; } JS_LIB_DIR="$(${PKG_CONFIG} --variable=sdkdir mozilla-js)/lib" fi elif test $pkg_failed = untried; then { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 $as_echo "no" >&6; } pkg_failed=no { $as_echo "$as_me:${as_lineno-$LINENO}: checking for JS" >&5 $as_echo_n "checking for JS... " >&6; } if test -n "$JS_CFLAGS"; then pkg_cv_JS_CFLAGS="$JS_CFLAGS" elif test -n "$PKG_CONFIG"; then if test -n "$PKG_CONFIG" && \ { { $as_echo "$as_me:${as_lineno-$LINENO}: \$PKG_CONFIG --exists --print-errors \"mozilla-js >= 1.7\""; } >&5 ($PKG_CONFIG --exists --print-errors "mozilla-js >= 1.7") 2>&5 ac_status=$? $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 test $ac_status = 0; }; then pkg_cv_JS_CFLAGS=`$PKG_CONFIG --cflags "mozilla-js >= 1.7" 2>/dev/null` test "x$?" != "x0" && pkg_failed=yes else pkg_failed=yes fi else pkg_failed=untried fi if test -n "$JS_LIBS"; then pkg_cv_JS_LIBS="$JS_LIBS" elif test -n "$PKG_CONFIG"; then if test -n "$PKG_CONFIG" && \ { { $as_echo "$as_me:${as_lineno-$LINENO}: \$PKG_CONFIG --exists --print-errors \"mozilla-js >= 1.7\""; } >&5 ($PKG_CONFIG --exists --print-errors "mozilla-js >= 1.7") 2>&5 ac_status=$? $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 test $ac_status = 0; }; then pkg_cv_JS_LIBS=`$PKG_CONFIG --libs "mozilla-js >= 1.7" 2>/dev/null` test "x$?" != "x0" && pkg_failed=yes else pkg_failed=yes fi else pkg_failed=untried fi if test $pkg_failed = yes; then { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 $as_echo "no" >&6; } if $PKG_CONFIG --atleast-pkgconfig-version 0.20; then _pkg_short_errors_supported=yes else _pkg_short_errors_supported=no fi if test $_pkg_short_errors_supported = yes; then JS_PKG_ERRORS=`$PKG_CONFIG --short-errors --print-errors --cflags --libs "mozilla-js >= 1.7" 2>&1` else JS_PKG_ERRORS=`$PKG_CONFIG --print-errors --cflags --libs "mozilla-js >= 1.7" 2>&1` fi # Put the nasty error message in config.log where it belongs echo "$JS_PKG_ERRORS" >&5 JS_LIB_DIR="${libdir}" JS_CFLAGS="-I/usr/include" JS_CFLAGS="$JS_CFLAGS -I/usr/include/js" JS_CFLAGS="$JS_CFLAGS -I/usr/include/mozjs" JS_CFLAGS="$JS_CFLAGS -I/usr/local/include/js" JS_CFLAGS="$JS_CFLAGS -I/opt/local/include/js" elif test $pkg_failed = untried; then { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 $as_echo "no" >&6; } JS_LIB_DIR="${libdir}" JS_CFLAGS="-I/usr/include" JS_CFLAGS="$JS_CFLAGS -I/usr/include/js" JS_CFLAGS="$JS_CFLAGS -I/usr/include/mozjs" JS_CFLAGS="$JS_CFLAGS -I/usr/local/include/js" JS_CFLAGS="$JS_CFLAGS -I/opt/local/include/js" else JS_CFLAGS=$pkg_cv_JS_CFLAGS JS_LIBS=$pkg_cv_JS_LIBS { $as_echo "$as_me:${as_lineno-$LINENO}: result: yes" >&5 $as_echo "yes" >&6; } JS_LIB_DIR="$(${PKG_CONFIG} --variable=sdkdir mozilla-js)/lib" fi else JS_CFLAGS=$pkg_cv_JS_CFLAGS JS_LIBS=$pkg_cv_JS_LIBS { $as_echo "$as_me:${as_lineno-$LINENO}: result: yes" >&5 $as_echo "yes" >&6; } JS_LIB_DIR="$(${PKG_CONFIG} --variable=libdir mozjs185)" fi # Check whether --with-js-include was given. if test "${with_js_include+set}" = set; then : withval=$with_js_include; JS_INCLUDE="$withval" JS_CFLAGS="-I$JS_INCLUDE" fi # Check whether --with-js-lib was given. if test "${with_js_lib+set}" = set; then : withval=$with_js_lib; JS_LIB_DIR=$withval JS_LIBS="-L$withval" fi use_js_trunk=no # Check whether --enable-js-trunk was given. if test "${enable_js_trunk+set}" = set; then : enableval=$enable_js_trunk; use_js_trunk=$enableval fi case $(uname -s) in #( CYGWIN*) : ;; #( *) : CPPFLAGS="$CPPFLAGS -I/opt/local/include" CPPFLAGS="$CPPFLAGS -I/opt/local/include/js" CPPFLAGS="$CPPFLAGS -I/usr/local/include" CPPFLAGS="$CPPFLAGS -I/usr/local/include/js" CPPFLAGS="$CPPFLAGS -I/usr/include" CPPFLAGS="$CPPFLAGS -I/usr/include/js" LDFLAGS="$LDFLAGS -L/opt/local/lib" LDFLAGS="$LDFLAGS -L/usr/local/lib" ;; #( *) : ;; esac CPPFLAGS="$CPPFLAGS $FLAGS" LDFLAGS="$LDFLAGS $FLAGS" # The erlang cc.sh/ld.sh scripts will convert a -O option # into the same optimization flags erlang itself uses. CFLAGS="-O2 $CFLAGS" LIBS="$LIBS $LDFLAGS" case $(uname -s) in #( CYGWIN*) : JS_CFLAGS="-DXP_WIN $JS_CFLAGS" IS_WINDOWS="TRUE" ;; #( *) : # XP_UNIX required for jsapi.h, tested on Linux and Darwin. JS_CFLAGS="-DXP_UNIX $JS_CFLAGS" ;; #( *) : ;; esac if test x$IS_WINDOWS = xTRUE; then WINDOWS_TRUE= WINDOWS_FALSE='#' else WINDOWS_TRUE='#' WINDOWS_FALSE= fi OLD_LIBS="$LIBS" LIBS="$JS_LIBS $LIBS" OLD_CPPFLAGS="$CPPFLAGS" CPPFLAGS="$JS_CFLAGS $CPPFLAGS" ac_fn_cxx_check_header_mongrel "$LINENO" "jsapi.h" "ac_cv_header_jsapi_h" "$ac_includes_default" if test "x$ac_cv_header_jsapi_h" = xyes; then : else ac_fn_cxx_check_header_mongrel "$LINENO" "js/jsapi.h" "ac_cv_header_js_jsapi_h" "$ac_includes_default" if test "x$ac_cv_header_js_jsapi_h" = xyes; then : CPPFLAGS="$CPPFLAGS -I$JS_INCLUDE/js" else as_fn_error $? "Could not find the jsapi header. Are the Mozilla SpiderMonkey headers installed?" "$LINENO" 5 fi fi { $as_echo "$as_me:${as_lineno-$LINENO}: checking for JS_NewContext in -lmozjs185" >&5 $as_echo_n "checking for JS_NewContext in -lmozjs185... " >&6; } if ${ac_cv_lib_mozjs185_JS_NewContext+:} false; then : $as_echo_n "(cached) " >&6 else ac_check_lib_save_LIBS=$LIBS LIBS="-lmozjs185 $LIBS" cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ /* Override any GCC internal prototype to avoid an error. Use char because int might match the return type of a GCC builtin and then its argument prototype would still apply. */ #ifdef __cplusplus extern "C" #endif char JS_NewContext (); int main () { return JS_NewContext (); ; return 0; } _ACEOF if ac_fn_cxx_try_link "$LINENO"; then : ac_cv_lib_mozjs185_JS_NewContext=yes else ac_cv_lib_mozjs185_JS_NewContext=no fi rm -f core conftest.err conftest.$ac_objext \ conftest$ac_exeext conftest.$ac_ext LIBS=$ac_check_lib_save_LIBS fi { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_lib_mozjs185_JS_NewContext" >&5 $as_echo "$ac_cv_lib_mozjs185_JS_NewContext" >&6; } if test "x$ac_cv_lib_mozjs185_JS_NewContext" = xyes; then : JS_LIB_BASE=mozjs185 else { $as_echo "$as_me:${as_lineno-$LINENO}: checking for JS_NewContext in -lmozjs185-1.0" >&5 $as_echo_n "checking for JS_NewContext in -lmozjs185-1.0... " >&6; } if ${ac_cv_lib_mozjs185_1_0_JS_NewContext+:} false; then : $as_echo_n "(cached) " >&6 else ac_check_lib_save_LIBS=$LIBS LIBS="-lmozjs185-1.0 $LIBS" cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ /* Override any GCC internal prototype to avoid an error. Use char because int might match the return type of a GCC builtin and then its argument prototype would still apply. */ #ifdef __cplusplus extern "C" #endif char JS_NewContext (); int main () { return JS_NewContext (); ; return 0; } _ACEOF if ac_fn_cxx_try_link "$LINENO"; then : ac_cv_lib_mozjs185_1_0_JS_NewContext=yes else ac_cv_lib_mozjs185_1_0_JS_NewContext=no fi rm -f core conftest.err conftest.$ac_objext \ conftest$ac_exeext conftest.$ac_ext LIBS=$ac_check_lib_save_LIBS fi { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_lib_mozjs185_1_0_JS_NewContext" >&5 $as_echo "$ac_cv_lib_mozjs185_1_0_JS_NewContext" >&6; } if test "x$ac_cv_lib_mozjs185_1_0_JS_NewContext" = xyes; then : JS_LIB_BASE=mozjs185-1.0 else { $as_echo "$as_me:${as_lineno-$LINENO}: checking for JS_NewContext in -lmozjs" >&5 $as_echo_n "checking for JS_NewContext in -lmozjs... " >&6; } if ${ac_cv_lib_mozjs_JS_NewContext+:} false; then : $as_echo_n "(cached) " >&6 else ac_check_lib_save_LIBS=$LIBS LIBS="-lmozjs $LIBS" cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ /* Override any GCC internal prototype to avoid an error. Use char because int might match the return type of a GCC builtin and then its argument prototype would still apply. */ #ifdef __cplusplus extern "C" #endif char JS_NewContext (); int main () { return JS_NewContext (); ; return 0; } _ACEOF if ac_fn_cxx_try_link "$LINENO"; then : ac_cv_lib_mozjs_JS_NewContext=yes else ac_cv_lib_mozjs_JS_NewContext=no fi rm -f core conftest.err conftest.$ac_objext \ conftest$ac_exeext conftest.$ac_ext LIBS=$ac_check_lib_save_LIBS fi { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_lib_mozjs_JS_NewContext" >&5 $as_echo "$ac_cv_lib_mozjs_JS_NewContext" >&6; } if test "x$ac_cv_lib_mozjs_JS_NewContext" = xyes; then : JS_LIB_BASE=mozjs else { $as_echo "$as_me:${as_lineno-$LINENO}: checking for JS_NewContext in -ljs" >&5 $as_echo_n "checking for JS_NewContext in -ljs... " >&6; } if ${ac_cv_lib_js_JS_NewContext+:} false; then : $as_echo_n "(cached) " >&6 else ac_check_lib_save_LIBS=$LIBS LIBS="-ljs $LIBS" cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ /* Override any GCC internal prototype to avoid an error. Use char because int might match the return type of a GCC builtin and then its argument prototype would still apply. */ #ifdef __cplusplus extern "C" #endif char JS_NewContext (); int main () { return JS_NewContext (); ; return 0; } _ACEOF if ac_fn_cxx_try_link "$LINENO"; then : ac_cv_lib_js_JS_NewContext=yes else ac_cv_lib_js_JS_NewContext=no fi rm -f core conftest.err conftest.$ac_objext \ conftest$ac_exeext conftest.$ac_ext LIBS=$ac_check_lib_save_LIBS fi { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_lib_js_JS_NewContext" >&5 $as_echo "$ac_cv_lib_js_JS_NewContext" >&6; } if test "x$ac_cv_lib_js_JS_NewContext" = xyes; then : JS_LIB_BASE=js else { $as_echo "$as_me:${as_lineno-$LINENO}: checking for JS_NewContext in -ljs3250" >&5 $as_echo_n "checking for JS_NewContext in -ljs3250... " >&6; } if ${ac_cv_lib_js3250_JS_NewContext+:} false; then : $as_echo_n "(cached) " >&6 else ac_check_lib_save_LIBS=$LIBS LIBS="-ljs3250 $LIBS" cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ /* Override any GCC internal prototype to avoid an error. Use char because int might match the return type of a GCC builtin and then its argument prototype would still apply. */ #ifdef __cplusplus extern "C" #endif char JS_NewContext (); int main () { return JS_NewContext (); ; return 0; } _ACEOF if ac_fn_cxx_try_link "$LINENO"; then : ac_cv_lib_js3250_JS_NewContext=yes else ac_cv_lib_js3250_JS_NewContext=no fi rm -f core conftest.err conftest.$ac_objext \ conftest$ac_exeext conftest.$ac_ext LIBS=$ac_check_lib_save_LIBS fi { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_lib_js3250_JS_NewContext" >&5 $as_echo "$ac_cv_lib_js3250_JS_NewContext" >&6; } if test "x$ac_cv_lib_js3250_JS_NewContext" = xyes; then : JS_LIB_BASE=js3250 else { $as_echo "$as_me:${as_lineno-$LINENO}: checking for JS_NewContext in -ljs32" >&5 $as_echo_n "checking for JS_NewContext in -ljs32... " >&6; } if ${ac_cv_lib_js32_JS_NewContext+:} false; then : $as_echo_n "(cached) " >&6 else ac_check_lib_save_LIBS=$LIBS LIBS="-ljs32 $LIBS" cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ /* Override any GCC internal prototype to avoid an error. Use char because int might match the return type of a GCC builtin and then its argument prototype would still apply. */ #ifdef __cplusplus extern "C" #endif char JS_NewContext (); int main () { return JS_NewContext (); ; return 0; } _ACEOF if ac_fn_cxx_try_link "$LINENO"; then : ac_cv_lib_js32_JS_NewContext=yes else ac_cv_lib_js32_JS_NewContext=no fi rm -f core conftest.err conftest.$ac_objext \ conftest$ac_exeext conftest.$ac_ext LIBS=$ac_check_lib_save_LIBS fi { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_lib_js32_JS_NewContext" >&5 $as_echo "$ac_cv_lib_js32_JS_NewContext" >&6; } if test "x$ac_cv_lib_js32_JS_NewContext" = xyes; then : JS_LIB_BASE=js32 else as_fn_error $? "Could not find the js library. Is the Mozilla SpiderMonkey library installed?" "$LINENO" 5 fi fi fi fi fi fi # Figure out what version of SpiderMonkey to use as_ac_Lib=`$as_echo "ac_cv_lib_$JS_LIB_BASE''_JS_NewCompartmentAndGlobalObject" | $as_tr_sh` { $as_echo "$as_me:${as_lineno-$LINENO}: checking for JS_NewCompartmentAndGlobalObject in -l$JS_LIB_BASE" >&5 $as_echo_n "checking for JS_NewCompartmentAndGlobalObject in -l$JS_LIB_BASE... " >&6; } if eval \${$as_ac_Lib+:} false; then : $as_echo_n "(cached) " >&6 else ac_check_lib_save_LIBS=$LIBS LIBS="-l$JS_LIB_BASE $LIBS" cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ /* Override any GCC internal prototype to avoid an error. Use char because int might match the return type of a GCC builtin and then its argument prototype would still apply. */ #ifdef __cplusplus extern "C" #endif char JS_NewCompartmentAndGlobalObject (); int main () { return JS_NewCompartmentAndGlobalObject (); ; return 0; } _ACEOF if ac_fn_cxx_try_link "$LINENO"; then : eval "$as_ac_Lib=yes" else eval "$as_ac_Lib=no" fi rm -f core conftest.err conftest.$ac_objext \ conftest$ac_exeext conftest.$ac_ext LIBS=$ac_check_lib_save_LIBS fi eval ac_res=\$$as_ac_Lib { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_res" >&5 $as_echo "$ac_res" >&6; } if eval test \"x\$"$as_ac_Lib"\" = x"yes"; then : # Prevent people from accidentally using SpiderMonkey's that are too new if test "$use_js_trunk" = "no"; then # ac_fn_cxx_check_decl LINENO SYMBOL VAR INCLUDES # ----------------------------------------------- # Tests whether SYMBOL is declared in INCLUDES, setting cache variable VAR # accordingly. ac_fn_cxx_check_decl () { as_lineno=${as_lineno-"$1"} as_lineno_stack=as_lineno_stack=$as_lineno_stack as_decl_name=`echo $2|sed 's/ *(.*//'` as_decl_use=`echo $2|sed -e 's/(/((/' -e 's/)/) 0&/' -e 's/,/) 0& (/g'` { $as_echo "$as_me:${as_lineno-$LINENO}: checking whether $as_decl_name is declared" >&5 $as_echo_n "checking whether $as_decl_name is declared... " >&6; } if eval \${$3+:} false; then : $as_echo_n "(cached) " >&6 else cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ $4 int main () { #ifndef $as_decl_name #ifdef __cplusplus (void) $as_decl_use; #else (void) $as_decl_name; #endif #endif ; return 0; } _ACEOF if ac_fn_cxx_try_compile "$LINENO"; then : eval "$3=yes" else eval "$3=no" fi rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext fi eval ac_res=\$$3 { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_res" >&5 $as_echo "$ac_res" >&6; } eval $as_lineno_stack; ${as_lineno_stack:+:} unset as_lineno } # ac_fn_cxx_check_decl ac_fn_cxx_check_decl "$LINENO" "JSOPTION_ANONFUNFIX" "ac_cv_have_decl_JSOPTION_ANONFUNFIX" " #include " if test "x$ac_cv_have_decl_JSOPTION_ANONFUNFIX" = xyes; then : else as_fn_error $? "Your SpiderMonkey library is too new. Versions of SpiderMonkey after the js185-1.0.0 release remove the optional enforcement of preventing anonymous functions in a statement context. This will most likely break your existing JavaScript code as well as render all example code invalid. If you wish to ignore this error pass --enable-js-trunk to ./configure." "$LINENO" 5 fi fi $as_echo "#define SM185 1" >>confdefs.h fi as_ac_Lib=`$as_echo "ac_cv_lib_$JS_LIB_BASE''_JS_ThrowStopIteration" | $as_tr_sh` { $as_echo "$as_me:${as_lineno-$LINENO}: checking for JS_ThrowStopIteration in -l$JS_LIB_BASE" >&5 $as_echo_n "checking for JS_ThrowStopIteration in -l$JS_LIB_BASE... " >&6; } if eval \${$as_ac_Lib+:} false; then : $as_echo_n "(cached) " >&6 else ac_check_lib_save_LIBS=$LIBS LIBS="-l$JS_LIB_BASE $LIBS" cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ /* Override any GCC internal prototype to avoid an error. Use char because int might match the return type of a GCC builtin and then its argument prototype would still apply. */ #ifdef __cplusplus extern "C" #endif char JS_ThrowStopIteration (); int main () { return JS_ThrowStopIteration (); ; return 0; } _ACEOF if ac_fn_cxx_try_link "$LINENO"; then : eval "$as_ac_Lib=yes" else eval "$as_ac_Lib=no" fi rm -f core conftest.err conftest.$ac_objext \ conftest$ac_exeext conftest.$ac_ext LIBS=$ac_check_lib_save_LIBS fi eval ac_res=\$$as_ac_Lib { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_res" >&5 $as_echo "$ac_res" >&6; } if eval test \"x\$"$as_ac_Lib"\" = x"yes"; then : $as_echo "#define SM180 1" >>confdefs.h fi as_ac_Lib=`$as_echo "ac_cv_lib_$JS_LIB_BASE''_JS_GetStringCharsAndLength" | $as_tr_sh` { $as_echo "$as_me:${as_lineno-$LINENO}: checking for JS_GetStringCharsAndLength in -l$JS_LIB_BASE" >&5 $as_echo_n "checking for JS_GetStringCharsAndLength in -l$JS_LIB_BASE... " >&6; } if eval \${$as_ac_Lib+:} false; then : $as_echo_n "(cached) " >&6 else ac_check_lib_save_LIBS=$LIBS LIBS="-l$JS_LIB_BASE $LIBS" cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ /* Override any GCC internal prototype to avoid an error. Use char because int might match the return type of a GCC builtin and then its argument prototype would still apply. */ #ifdef __cplusplus extern "C" #endif char JS_GetStringCharsAndLength (); int main () { return JS_GetStringCharsAndLength (); ; return 0; } _ACEOF if ac_fn_cxx_try_link "$LINENO"; then : eval "$as_ac_Lib=yes" else eval "$as_ac_Lib=no" fi rm -f core conftest.err conftest.$ac_objext \ conftest$ac_exeext conftest.$ac_ext LIBS=$ac_check_lib_save_LIBS fi eval ac_res=\$$as_ac_Lib { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_res" >&5 $as_echo "$ac_res" >&6; } if eval test \"x\$"$as_ac_Lib"\" = x"yes"; then : $as_echo "#define HAVE_JS_GET_STRING_CHARS_AND_LENGTH 1" >>confdefs.h fi # Else, hope that 1.7.0 works # Deal with JSScript to JSObject to JSScript switcheroo as_ac_Type=`$as_echo "ac_cv_type_JSScript*" | $as_tr_sh` ac_fn_cxx_check_type "$LINENO" "JSScript*" "$as_ac_Type" "#include " if eval test \"x\$"$as_ac_Type"\" = x"yes"; then : $as_echo "#define JSSCRIPT_TYPE JSScript*" >>confdefs.h else $as_echo "#define JSSCRIPT_TYPE JSObject*" >>confdefs.h fi $as_echo "#define COUCHJS_NAME \"couchjs\"" >>confdefs.h if test x${IS_WINDOWS} = xTRUE; then $as_echo "#define COUCHJS_NAME \"couchjs.exe\"" >>confdefs.h if test -f "$JS_LIB_DIR/$JS_LIB_BASE.dll"; then # seamonkey 1.7- build layout on Windows JS_LIB_BINARY="$JS_LIB_DIR/$JS_LIB_BASE.dll" else # seamonkey 1.8+ build layout on Windows if test -f "$JS_LIB_DIR/../bin/$JS_LIB_BASE.dll"; then JS_LIB_BINARY="$JS_LIB_DIR/../bin/$JS_LIB_BASE.dll" else as_fn_error $? "Could not find $JS_LIB_BASE.dll." "$LINENO" 5 fi fi # On windows we need to know the path to the openssl binaries. # Check whether --with-openssl-bin-dir was given. if test "${with_openssl_bin_dir+set}" = set; then : withval=$with_openssl_bin_dir; openssl_bin_dir=`cygpath -m "$withval"` fi # Windows uses Inno setup - look for its compiler. # Extract the first word of "iscc", so it can be a program name with args. set dummy iscc; ac_word=$2 { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 $as_echo_n "checking for $ac_word... " >&6; } if ${ac_cv_path_INNO_COMPILER_EXECUTABLE+:} false; then : $as_echo_n "(cached) " >&6 else case $INNO_COMPILER_EXECUTABLE in [\\/]* | ?:[\\/]*) ac_cv_path_INNO_COMPILER_EXECUTABLE="$INNO_COMPILER_EXECUTABLE" # Let the user override the test with a path. ;; *) as_save_IFS=$IFS; IFS=$PATH_SEPARATOR for as_dir in $PATH do IFS=$as_save_IFS test -z "$as_dir" && as_dir=. for ac_exec_ext in '' $ac_executable_extensions; do if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then ac_cv_path_INNO_COMPILER_EXECUTABLE="$as_dir/$ac_word$ac_exec_ext" $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5 break 2 fi done done IFS=$as_save_IFS ;; esac fi INNO_COMPILER_EXECUTABLE=$ac_cv_path_INNO_COMPILER_EXECUTABLE if test -n "$INNO_COMPILER_EXECUTABLE"; then { $as_echo "$as_me:${as_lineno-$LINENO}: result: $INNO_COMPILER_EXECUTABLE" >&5 $as_echo "$INNO_COMPILER_EXECUTABLE" >&6; } else { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 $as_echo "no" >&6; } fi if test x${INNO_COMPILER_EXECUTABLE} = x; then { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: You will be unable to build the Windows installer." >&5 $as_echo "$as_me: WARNING: You will be unable to build the Windows installer." >&2;} fi # We need the msvc redistributables for this platform too # (in theory we could just install the assembly locally - but # there are at least 4 directories with binaries, meaning 4 copies; # so using the redist .exe means it ends up installed globally...) # Check whether --with-msvc-redist-dir was given. if test "${with_msvc_redist_dir+set}" = set; then : withval=$with_msvc_redist_dir; msvc_redist_dir=`cygpath -m "$withval"` msvc_redist_name="vcredist_x86.exe" fi if test ! -f ${msvc_redist_dir}/${msvc_redist_name}; then { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: Installer may fail due to missing MSVC redistributable." >&5 $as_echo "$as_me: WARNING: Installer may fail due to missing MSVC redistributable." >&2;} fi fi JS_LIBS="-l$JS_LIB_BASE -lm $JS_LIBS" LIBS="$OLD_LIBS" CPPFLAGS="$OLD_CPPFLAGS" %% auto detect "kegged" icu4c on Mac / Homebrew PATH="/usr/local/opt/icu4c/bin:$PATH" # Check whether --with-win32-icu-binaries was given. if test "${with_win32_icu_binaries+set}" = set; then : withval=$with_win32_icu_binaries; ICU_CPPFLAGS="-I$withval/include" ICU_LIBS="-L$withval/lib -licuuc -licudt -licuin" ICU_BIN=$withval/bin else succeeded=no if test -z "$ICU_CONFIG"; then # Extract the first word of "icu-config", so it can be a program name with args. set dummy icu-config; ac_word=$2 { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 $as_echo_n "checking for $ac_word... " >&6; } if ${ac_cv_path_ICU_CONFIG+:} false; then : $as_echo_n "(cached) " >&6 else case $ICU_CONFIG in [\\/]* | ?:[\\/]*) ac_cv_path_ICU_CONFIG="$ICU_CONFIG" # Let the user override the test with a path. ;; *) as_save_IFS=$IFS; IFS=$PATH_SEPARATOR for as_dir in $PATH do IFS=$as_save_IFS test -z "$as_dir" && as_dir=. for ac_exec_ext in '' $ac_executable_extensions; do if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then ac_cv_path_ICU_CONFIG="$as_dir/$ac_word$ac_exec_ext" $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5 break 2 fi done done IFS=$as_save_IFS test -z "$ac_cv_path_ICU_CONFIG" && ac_cv_path_ICU_CONFIG="no" ;; esac fi ICU_CONFIG=$ac_cv_path_ICU_CONFIG if test -n "$ICU_CONFIG"; then { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ICU_CONFIG" >&5 $as_echo "$ICU_CONFIG" >&6; } else { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 $as_echo "no" >&6; } fi fi if test "$ICU_CONFIG" = "no" ; then echo "*** The icu-config script could not be found. Make sure it is" echo "*** in your path, and that taglib is properly installed." echo "*** Or see http://ibm.com/software/globalization/icu/" else ICU_VERSION=`$ICU_CONFIG --version` { $as_echo "$as_me:${as_lineno-$LINENO}: checking for ICU >= 3.4.1" >&5 $as_echo_n "checking for ICU >= 3.4.1... " >&6; } VERSION_CHECK=`expr $ICU_VERSION \>\= 3.4.1` if test "$VERSION_CHECK" = "1" ; then { $as_echo "$as_me:${as_lineno-$LINENO}: result: yes" >&5 $as_echo "yes" >&6; } succeeded=yes { $as_echo "$as_me:${as_lineno-$LINENO}: checking ICU_CPPFLAGS" >&5 $as_echo_n "checking ICU_CPPFLAGS... " >&6; } ICU_CPPFLAGS=`$ICU_CONFIG --cppflags` { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ICU_CPPFLAGS" >&5 $as_echo "$ICU_CPPFLAGS" >&6; } { $as_echo "$as_me:${as_lineno-$LINENO}: checking ICU_CFLAGS" >&5 $as_echo_n "checking ICU_CFLAGS... " >&6; } ICU_CFLAGS=`$ICU_CONFIG --cflags` { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ICU_CFLAGS" >&5 $as_echo "$ICU_CFLAGS" >&6; } { $as_echo "$as_me:${as_lineno-$LINENO}: checking ICU_CXXFLAGS" >&5 $as_echo_n "checking ICU_CXXFLAGS... " >&6; } ICU_CXXFLAGS=`$ICU_CONFIG --cxxflags` { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ICU_CXXFLAGS" >&5 $as_echo "$ICU_CXXFLAGS" >&6; } { $as_echo "$as_me:${as_lineno-$LINENO}: checking ICU_LIBS" >&5 $as_echo_n "checking ICU_LIBS... " >&6; } ICU_LIBS=`$ICU_CONFIG --ldflags` { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ICU_LIBS" >&5 $as_echo "$ICU_LIBS" >&6; } else ICU_CPPFLAGS="" ICU_CFLAGS="" ICU_CXXFLAGS="" ICU_LIBS="" ## If we have a custom action on failure, don't print errors, but ## do set a variable so people can do so. echo "can't find ICU >= 3.4.1" fi fi if test $succeeded = yes; then : else as_fn_error $? "Library requirements (ICU) not met." "$LINENO" 5 fi ICU_BIN= fi use_curl=yes # Check whether --with-win32-curl was given. if test "${with_win32_curl+set}" = set; then : withval=$with_win32_curl; # default build on windows is a static lib, and that's what we want too CURL_CFLAGS="-I$withval/include -DCURL_STATICLIB" CURL_LIBS="-L$withval/lib -llibcurl -lWs2_32 -lkernel32 -luser32 -ladvapi32 -lWldap32" # OpenSSL libraries may be pulled in via libcurl if it was built with SSL # these are libeay32 ssleay32 instead of crypto ssl on unix else # Check whether --with-curl-prefix was given. if test "${with_curl_prefix+set}" = set; then : withval=$with_curl_prefix; curl_config_prefix="$withval" else curl_config_prefix="" fi # Check whether --with-curl-exec-prefix was given. if test "${with_curl_exec_prefix+set}" = set; then : withval=$with_curl_exec_prefix; curl_config_exec_prefix="$withval" else curl_config_exec_prefix="" fi if test x$CURL_CFLAGS != x -o x$CURL_LIBS != x; then : : $as_echo "#define HAVE_CURL 1" >>confdefs.h else if test x$curl_config_exec_prefix != x; then : curl_config_args="$curl_config_args --exec-prefix=$curl_config_exec_prefix" if test x${CURL_CONFIG+set} != xset; then : CURL_CONFIG=$curl_config_exec_prefix/bin/curl-config fi fi if test x$curl_config_prefix != x; then : curl_config_args="$curl_config_args --prefix=$curl_config_prefix" if test x${CURL_CONFIG+set} != xset; then : CURL_CONFIG=$curl_config_prefix/bin/curl-config fi fi for ac_prog in curl-config do # Extract the first word of "$ac_prog", so it can be a program name with args. set dummy $ac_prog; ac_word=$2 { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 $as_echo_n "checking for $ac_word... " >&6; } if ${ac_cv_path_CURL_CONFIG+:} false; then : $as_echo_n "(cached) " >&6 else case $CURL_CONFIG in [\\/]* | ?:[\\/]*) ac_cv_path_CURL_CONFIG="$CURL_CONFIG" # Let the user override the test with a path. ;; *) as_save_IFS=$IFS; IFS=$PATH_SEPARATOR for as_dir in $PATH do IFS=$as_save_IFS test -z "$as_dir" && as_dir=. for ac_exec_ext in '' $ac_executable_extensions; do if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then ac_cv_path_CURL_CONFIG="$as_dir/$ac_word$ac_exec_ext" $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5 break 2 fi done done IFS=$as_save_IFS ;; esac fi CURL_CONFIG=$ac_cv_path_CURL_CONFIG if test -n "$CURL_CONFIG"; then { $as_echo "$as_me:${as_lineno-$LINENO}: result: $CURL_CONFIG" >&5 $as_echo "$CURL_CONFIG" >&6; } else { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 $as_echo "no" >&6; } fi test -n "$CURL_CONFIG" && break done test -n "$CURL_CONFIG" || CURL_CONFIG="no" if test "$CURL_CONFIG" == "no"; then : : { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: You will be unable to run some JavaScript unit tests." >&5 $as_echo "$as_me: WARNING: You will be unable to run some JavaScript unit tests." >&2;} use_curl=no CURL_LIBS= else if test x"" == x; then : CURL_CFLAGS="`$CURL_CONFIG $curl_config_args --cflags`" else CURL_CFLAGS="`$CURL_CONFIG $curl_config_args `" fi if test x"" == x; then : CURL_LIBS="`$CURL_CONFIG $curl_config_args --libs`" else CURL_LIBS="`$CURL_CONFIG $curl_config_args `" fi if test x"7.18.0" != x; then : if test x"'s/^libcurl\ \+//'" != x; then : curl_version="`$CURL_CONFIG $curl_config_args --version | $SED -e 's/^libcurl\ \+//'`" else curl_version="`$CURL_CONFIG $curl_config_args --version | $SED -e 's/^\ *\(.*\)\ *$/\1/'`" fi { $as_echo "$as_me:${as_lineno-$LINENO}: checking for curl ($curl_version) >= 7.18.0" >&5 $as_echo_n "checking for curl ($curl_version) >= 7.18.0... " >&6; } # Used to indicate true or false condition ax_compare_version=false # Convert the two version strings to be compared into a format that # allows a simple string comparison. The end result is that a version # string of the form 1.12.5-r617 will be converted to the form # 0001001200050617. In other words, each number is zero padded to four # digits, and non digits are removed. ax_compare_version_A=`echo "$curl_version" | sed -e 's/\([0-9]*\)/Z\1Z/g' \ -e 's/Z\([0-9]\)Z/Z0\1Z/g' \ -e 's/Z\([0-9][0-9]\)Z/Z0\1Z/g' \ -e 's/Z\([0-9][0-9][0-9]\)Z/Z0\1Z/g' \ -e 's/[^0-9]//g'` ax_compare_version_B=`echo "7.18.0" | sed -e 's/\([0-9]*\)/Z\1Z/g' \ -e 's/Z\([0-9]\)Z/Z0\1Z/g' \ -e 's/Z\([0-9][0-9]\)Z/Z0\1Z/g' \ -e 's/Z\([0-9][0-9][0-9]\)Z/Z0\1Z/g' \ -e 's/[^0-9]//g'` ax_compare_version=`echo "x$ax_compare_version_A x$ax_compare_version_B" | sed 's/^ *//' | sort -r | sed "s/x${ax_compare_version_A}/true/;s/x${ax_compare_version_B}/false/;1q"` if test "$ax_compare_version" = "true" ; then { $as_echo "$as_me:${as_lineno-$LINENO}: result: yes" >&5 $as_echo "yes" >&6; } : $as_echo "#define HAVE_CURL 1" >>confdefs.h else { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 $as_echo "no" >&6; } : { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: You will be unable to run some JavaScript unit tests." >&5 $as_echo "$as_me: WARNING: You will be unable to run some JavaScript unit tests." >&2;} use_curl=no CURL_LIBS= fi else : $as_echo "#define HAVE_CURL 1" >>confdefs.h fi fi fi fi case "$(uname -s)" in Linux) LIBS="$LIBS -lcrypt" CPPFLAGS="-D_XOPEN_SOURCE $CPPFLAGS" ;; FreeBSD) LIBS="$LIBS -lcrypt" ;; OpenBSD) LIBS="$LIBS -lcrypto" ;; esac { $as_echo "$as_me:${as_lineno-$LINENO}: checking Erlang version compatibility" >&5 $as_echo_n "checking Erlang version compatibility... " >&6; } erlang_version_error="The installed Erlang version must be >= R14B (erts-5.8.1) and &5 $as_echo "compatible" >&6; } otp_release="`\ ${ERL} -noshell \ -eval 'io:put_chars(erlang:system_info(otp_release)).' \ -s erlang halt`" if test x$otp_release \> xR13B03; then USE_OTP_NIFS_TRUE= USE_OTP_NIFS_FALSE='#' else USE_OTP_NIFS_TRUE='#' USE_OTP_NIFS_FALSE= fi if test x$otp_release \> xR14B03; then USE_EJSON_COMPARE_NIF_TRUE= USE_EJSON_COMPARE_NIF_FALSE='#' else USE_EJSON_COMPARE_NIF_TRUE='#' USE_EJSON_COMPARE_NIF_FALSE= fi has_crypto=`\ ${ERL} -eval "\ case application:load(crypto) of ok -> ok; _ -> exit(no_crypto) end. \ " -noshell -s init stop` if test -n "$has_crypto"; then as_fn_error $? "Could not find the Erlang crypto library. Has Erlang been compiled with OpenSSL support?" "$LINENO" 5 fi # Extract the first word of "erlc", so it can be a program name with args. set dummy erlc; ac_word=$2 { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 $as_echo_n "checking for $ac_word... " >&6; } if ${ac_cv_path_ERLC+:} false; then : $as_echo_n "(cached) " >&6 else case $ERLC in [\\/]* | ?:[\\/]*) ac_cv_path_ERLC="$ERLC" # Let the user override the test with a path. ;; *) as_save_IFS=$IFS; IFS=$PATH_SEPARATOR for as_dir in $PATH do IFS=$as_save_IFS test -z "$as_dir" && as_dir=. for ac_exec_ext in '' $ac_executable_extensions; do if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then ac_cv_path_ERLC="$as_dir/$ac_word$ac_exec_ext" $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5 break 2 fi done done IFS=$as_save_IFS ;; esac fi ERLC=$ac_cv_path_ERLC if test -n "$ERLC"; then { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ERLC" >&5 $as_echo "$ERLC" >&6; } else { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 $as_echo "no" >&6; } fi if test x${ERLC} = x; then as_fn_error $? "Could not find the \`erlc' executable. Is Erlang installed?" "$LINENO" 5 fi OLD_CPPFLAGS="$CPPFLAGS" CPPFLAGS="$ERLANG_FLAGS $CPPFLAGS" ac_fn_cxx_check_header_mongrel "$LINENO" "erl_driver.h" "ac_cv_header_erl_driver_h" "$ac_includes_default" if test "x$ac_cv_header_erl_driver_h" = xyes; then : else as_fn_error $? "Could not find the \`erl_driver.h' header. Are the Erlang headers installed? Use the \`--with-erlang' option to specify the Erlang include directory." "$LINENO" 5 fi CPPFLAGS="$OLD_CPPFLAGS" use_init=yes use_launchd=yes native_mochijson_enabled=no tests_enabled=yes docs_enabled=yes strictness_enabled=no # Check whether --enable-init was given. if test "${enable_init+set}" = set; then : enableval=$enable_init; use_init=$enableval fi # Check whether --enable-launchd was given. if test "${enable_launchd+set}" = set; then : enableval=$enable_launchd; use_launchd=$enableval fi # Check whether --enable-native-mochijson was given. if test "${enable_native_mochijson+set}" = set; then : enableval=$enable_native_mochijson; native_mochijson_enabled=$enableval fi # Check whether --enable-tests was given. if test "${enable_tests+set}" = set; then : enableval=$enable_tests; tests_enabled=$enableval fi # Check whether --enable-docs was given. if test "${enable_docs+set}" = set; then : enableval=$enable_docs; docs_enabled=$enableval fi # Check whether --enable-strictness was given. if test "${enable_strictness+set}" = set; then : enableval=$enable_strictness; strictness_enabled=$enableval fi init_enabled=false launchd_enabled=false if test "$use_init" = "yes"; then { $as_echo "$as_me:${as_lineno-$LINENO}: checking location of init directory" >&5 $as_echo_n "checking location of init directory... " >&6; } if test -d /etc/rc.d; then init_enabled=true initdir='${sysconfdir}/rc.d' { $as_echo "$as_me:${as_lineno-$LINENO}: result: ${initdir}" >&5 $as_echo "${initdir}" >&6; } else if test -d /etc/init.d; then init_enabled=true initdir='${sysconfdir}/init.d' { $as_echo "$as_me:${as_lineno-$LINENO}: result: ${initdir}" >&5 $as_echo "${initdir}" >&6; } else { $as_echo "$as_me:${as_lineno-$LINENO}: result: not found" >&5 $as_echo "not found" >&6; } fi fi fi if test "$use_launchd" = "yes"; then { $as_echo "$as_me:${as_lineno-$LINENO}: checking location of launchd directory" >&5 $as_echo_n "checking location of launchd directory... " >&6; } if test -d /Library/LaunchDaemons; then init_enabled=false launchd_enabled=true launchddir='${prefix}/Library/LaunchDaemons' { $as_echo "$as_me:${as_lineno-$LINENO}: result: ${launchddir}" >&5 $as_echo "${launchddir}" >&6; } else { $as_echo "$as_me:${as_lineno-$LINENO}: result: not found" >&5 $as_echo "not found" >&6; } fi fi # Extract the first word of "help2man", so it can be a program name with args. set dummy help2man; ac_word=$2 { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 $as_echo_n "checking for $ac_word... " >&6; } if ${ac_cv_prog_HAS_HELP2MAN+:} false; then : $as_echo_n "(cached) " >&6 else if test -n "$HAS_HELP2MAN"; then ac_cv_prog_HAS_HELP2MAN="$HAS_HELP2MAN" # Let the user override the test. else as_save_IFS=$IFS; IFS=$PATH_SEPARATOR for as_dir in $PATH do IFS=$as_save_IFS test -z "$as_dir" && as_dir=. for ac_exec_ext in '' $ac_executable_extensions; do if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then ac_cv_prog_HAS_HELP2MAN="yes" $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5 break 2 fi done done IFS=$as_save_IFS fi fi HAS_HELP2MAN=$ac_cv_prog_HAS_HELP2MAN if test -n "$HAS_HELP2MAN"; then { $as_echo "$as_me:${as_lineno-$LINENO}: result: $HAS_HELP2MAN" >&5 $as_echo "$HAS_HELP2MAN" >&6; } else { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 $as_echo "no" >&6; } fi if test x${HAS_HELP2MAN} = x; then if test x${strictness_enabled} = xyes; then as_fn_error $? "Could not find the \`help2man' executable." "$LINENO" 5 else { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: You will be unable to regenerate man pages." >&5 $as_echo "$as_me: WARNING: You will be unable to regenerate man pages." >&2;} fi fi # Extract the first word of "pdflatex", so it can be a program name with args. set dummy pdflatex; ac_word=$2 { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 $as_echo_n "checking for $ac_word... " >&6; } if ${ac_cv_prog_HAS_PDFLATEX+:} false; then : $as_echo_n "(cached) " >&6 else if test -n "$HAS_PDFLATEX"; then ac_cv_prog_HAS_PDFLATEX="$HAS_PDFLATEX" # Let the user override the test. else as_save_IFS=$IFS; IFS=$PATH_SEPARATOR for as_dir in $PATH do IFS=$as_save_IFS test -z "$as_dir" && as_dir=. for ac_exec_ext in '' $ac_executable_extensions; do if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then ac_cv_prog_HAS_PDFLATEX="yes" $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5 break 2 fi done done IFS=$as_save_IFS fi fi HAS_PDFLATEX=$ac_cv_prog_HAS_PDFLATEX if test -n "$HAS_PDFLATEX"; then { $as_echo "$as_me:${as_lineno-$LINENO}: result: $HAS_PDFLATEX" >&5 $as_echo "$HAS_PDFLATEX" >&6; } else { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 $as_echo "no" >&6; } fi if test x${HAS_PDFLATEX} = x; then if test x${strictness_enabled} = xyes; then as_fn_error $? "Could not find the \`pdflatex' executable. Is LaTeX installed?" "$LINENO" 5 else { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: You will be unable to regenerate PDF documentation." >&5 $as_echo "$as_me: WARNING: You will be unable to regenerate PDF documentation." >&2;} fi fi # Extract the first word of "makeinfo", so it can be a program name with args. set dummy makeinfo; ac_word=$2 { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 $as_echo_n "checking for $ac_word... " >&6; } if ${ac_cv_prog_HAS_MAKEINFO+:} false; then : $as_echo_n "(cached) " >&6 else if test -n "$HAS_MAKEINFO"; then ac_cv_prog_HAS_MAKEINFO="$HAS_MAKEINFO" # Let the user override the test. else as_save_IFS=$IFS; IFS=$PATH_SEPARATOR for as_dir in $PATH do IFS=$as_save_IFS test -z "$as_dir" && as_dir=. for ac_exec_ext in '' $ac_executable_extensions; do if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then ac_cv_prog_HAS_MAKEINFO="yes" $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5 break 2 fi done done IFS=$as_save_IFS fi fi HAS_MAKEINFO=$ac_cv_prog_HAS_MAKEINFO if test -n "$HAS_MAKEINFO"; then { $as_echo "$as_me:${as_lineno-$LINENO}: result: $HAS_MAKEINFO" >&5 $as_echo "$HAS_MAKEINFO" >&6; } else { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 $as_echo "no" >&6; } fi if test x${HAS_MAKEINFO} = x; then if test x${strictness_enabled} = xyes; then as_fn_error $? "Could not find the \`makeinfo' executable. Is GNU Texinfo installed?" "$LINENO" 5 else { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: You will be unable to regenerate info documentation." >&5 $as_echo "$as_me: WARNING: You will be unable to regenerate info documentation." >&2;} fi fi # Extract the first word of "install-info", so it can be a program name with args. set dummy install-info; ac_word=$2 { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 $as_echo_n "checking for $ac_word... " >&6; } if ${ac_cv_prog_HAS_INSTALLINFO+:} false; then : $as_echo_n "(cached) " >&6 else if test -n "$HAS_INSTALLINFO"; then ac_cv_prog_HAS_INSTALLINFO="$HAS_INSTALLINFO" # Let the user override the test. else as_save_IFS=$IFS; IFS=$PATH_SEPARATOR for as_dir in $PATH do IFS=$as_save_IFS test -z "$as_dir" && as_dir=. for ac_exec_ext in '' $ac_executable_extensions; do if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then ac_cv_prog_HAS_INSTALLINFO="yes" $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5 break 2 fi done done IFS=$as_save_IFS fi fi HAS_INSTALLINFO=$ac_cv_prog_HAS_INSTALLINFO if test -n "$HAS_INSTALLINFO"; then { $as_echo "$as_me:${as_lineno-$LINENO}: result: $HAS_INSTALLINFO" >&5 $as_echo "$HAS_INSTALLINFO" >&6; } else { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 $as_echo "no" >&6; } fi if test x${HAS_INSTALLINFO} = x; then if test x${strictness_enabled} = xyes; then as_fn_error $? "Could not find the \`install-info' executable. Is GNU Texinfo installed?" "$LINENO" 5 else { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: You will be unable to install info documentation." >&5 $as_echo "$as_me: WARNING: You will be unable to install info documentation." >&2;} fi fi # Extract the first word of "sphinx-build", so it can be a program name with args. set dummy sphinx-build; ac_word=$2 { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 $as_echo_n "checking for $ac_word... " >&6; } if ${ac_cv_prog_HAS_SPHINX_BUILD+:} false; then : $as_echo_n "(cached) " >&6 else if test -n "$HAS_SPHINX_BUILD"; then ac_cv_prog_HAS_SPHINX_BUILD="$HAS_SPHINX_BUILD" # Let the user override the test. else as_save_IFS=$IFS; IFS=$PATH_SEPARATOR for as_dir in $PATH do IFS=$as_save_IFS test -z "$as_dir" && as_dir=. for ac_exec_ext in '' $ac_executable_extensions; do if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then ac_cv_prog_HAS_SPHINX_BUILD="yes" $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5 break 2 fi done done IFS=$as_save_IFS fi fi HAS_SPHINX_BUILD=$ac_cv_prog_HAS_SPHINX_BUILD if test -n "$HAS_SPHINX_BUILD"; then { $as_echo "$as_me:${as_lineno-$LINENO}: result: $HAS_SPHINX_BUILD" >&5 $as_echo "$HAS_SPHINX_BUILD" >&6; } else { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 $as_echo "no" >&6; } fi if test x${HAS_SPHINX_BUILD} = x; then if test x${strictness_enabled} = xyes; then as_fn_error $? "Could not find the \`sphinx-build' executable." "$LINENO" 5 else { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: You will be unable to regenerate documentation." >&5 $as_echo "$as_me: WARNING: You will be unable to regenerate documentation." >&2;} fi fi if test x${docs_enabled} = xyes; then if test x${HAS_HELP2MAN} = xyes; then build_man=yes fi if test x${HAS_SPHINX_BUILD} = xyes; then build_html=yes if test x${HAS_MAKEINFO} = xyes; then build_info=yes fi if test x${HAS_PDFLATEX} = xyes; then build_pdf=yes fi fi fi if test x${strictness_enabled} = xyes; then if test -z $PYTHON; then PYTHON="python" fi PYTHON_NAME=`basename $PYTHON` { $as_echo "$as_me:${as_lineno-$LINENO}: checking $PYTHON_NAME module: pygments" >&5 $as_echo_n "checking $PYTHON_NAME module: pygments... " >&6; } $PYTHON -c "import pygments" 2>/dev/null if test $? -eq 0; then { $as_echo "$as_me:${as_lineno-$LINENO}: result: yes" >&5 $as_echo "yes" >&6; } eval HAVE_PYMOD_PYGMENTS=yes else { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 $as_echo "no" >&6; } eval HAVE_PYMOD_PYGMENTS=no # if test -n "fatal" then as_fn_error $? "failed to find required module pygments" "$LINENO" 5 exit 1 fi fi else if test -z $PYTHON; then PYTHON="python" fi PYTHON_NAME=`basename $PYTHON` { $as_echo "$as_me:${as_lineno-$LINENO}: checking $PYTHON_NAME module: pygments" >&5 $as_echo_n "checking $PYTHON_NAME module: pygments... " >&6; } $PYTHON -c "import pygments" 2>/dev/null if test $? -eq 0; then { $as_echo "$as_me:${as_lineno-$LINENO}: result: yes" >&5 $as_echo "yes" >&6; } eval HAVE_PYMOD_PYGMENTS=yes else { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 $as_echo "no" >&6; } eval HAVE_PYMOD_PYGMENTS=no # if test -n "" then as_fn_error $? "failed to find required module pygments" "$LINENO" 5 exit 1 fi fi fi { $as_echo "$as_me:${as_lineno-$LINENO}: checking pygments version >= 1.5" >&5 $as_echo_n "checking pygments version >= 1.5... " >&6; } python 2> /dev/null << EOF import sys import pygments if float(pygments.__version__) >= 1.5: sys.exit(0) else: sys.exit(1) EOF if test $? -eq 0; then { $as_echo "$as_me:${as_lineno-$LINENO}: result: yes" >&5 $as_echo "yes" >&6; } else { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 $as_echo "no" >&6; } if test x${strictness_enabled} = xyes; then as_fn_error 1 "Your copy of pygments is out of date." "$LINENO" 5 else { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: Syntax highlighting may not work." >&5 $as_echo "$as_me: WARNING: Syntax highlighting may not work." >&2;} fi fi ERL_VERSION_COMMAND="${ESCRIPT} bin/erlang-version.escript" erlangversion=`${ERL_VERSION_COMMAND}` if test x${init_enabled} = xtrue; then INIT_TRUE= INIT_FALSE='#' else INIT_TRUE='#' INIT_FALSE= fi if test x${launchd_enabled} = xtrue; then LAUNCHD_TRUE= LAUNCHD_FALSE='#' else LAUNCHD_TRUE='#' LAUNCHD_FALSE= fi if test x${native_mochijson_enabled} = xyes; then USE_NATIVE_MOCHIJSON_TRUE= USE_NATIVE_MOCHIJSON_FALSE='#' else USE_NATIVE_MOCHIJSON_TRUE='#' USE_NATIVE_MOCHIJSON_FALSE= fi if test x${use_curl} = xyes; then USE_CURL_TRUE= USE_CURL_FALSE='#' else USE_CURL_TRUE='#' USE_CURL_FALSE= fi if test x${build_man} = xyes; then BUILD_MAN_TRUE= BUILD_MAN_FALSE='#' else BUILD_MAN_TRUE='#' BUILD_MAN_FALSE= fi if test x${build_info} = xyes; then BUILD_INFO_TRUE= BUILD_INFO_FALSE='#' else BUILD_INFO_TRUE='#' BUILD_INFO_FALSE= fi if test x${build_pdf} = xyes; then BUILD_PDF_TRUE= BUILD_PDF_FALSE='#' else BUILD_PDF_TRUE='#' BUILD_PDF_FALSE= fi if test x${build_html} = xyes; then BUILD_HTML_TRUE= BUILD_HTML_FALSE='#' else BUILD_HTML_TRUE='#' BUILD_HTML_FALSE= fi if test x${tests_enabled} = xyes; then TESTS_TRUE= TESTS_FALSE='#' else TESTS_TRUE='#' TESTS_FALSE= fi if test x${strictness_enabled} = xyes; then STRICTNESS_TRUE= STRICTNESS_FALSE='#' else STRICTNESS_TRUE='#' STRICTNESS_FALSE= fi package_author_name="The Apache Software Foundation" package_author_address="dev@couchdb.apache.org" package_identifier="couchdb" package_tarname="apache-couchdb" package_name="Apache CouchDB" version="1.5.0" version_major="1" version_minor="5" version_revision="0" version_stage="" version_release="" bug_uri="https://issues.apache.org/jira/browse/COUCHDB" localconfdir=${sysconfdir}/${package_identifier} localdatadir=${datadir}/${package_identifier} localdocdir=${datadir}/doc/${package_identifier} locallibdir=${libdir}/${package_identifier} localstatelibdir=${localstatedir}/lib/${package_identifier} localstatelogdir=${localstatedir}/log/${package_identifier} localstaterundir=${localstatedir}/run/${package_identifier} erlangversion=${erlangversion} erlangbin=${ERL} # On Windows we install directly into our erlang distribution. if test x${IS_WINDOWS} = xTRUE; then locallibbindir=${prefix}/bin localerlanglibdir=${libdir} else locallibbindir=${locallibdir}/bin localerlanglibdir=${locallibdir}/erlang/lib fi # fix for older autotools that don't define "abs_top_YYY" by default ac_config_files="$ac_config_files Makefile" ac_config_files="$ac_config_files bin/couch-config.tpl" ac_config_files="$ac_config_files bin/couchdb.tpl" ac_config_files="$ac_config_files bin/couchdb.bat.tpl" ac_config_files="$ac_config_files bin/Makefile" ac_config_files="$ac_config_files etc/couchdb/Makefile" ac_config_files="$ac_config_files etc/couchdb/default.ini.tpl" ac_config_files="$ac_config_files etc/default/Makefile" ac_config_files="$ac_config_files etc/init/couchdb.tpl" ac_config_files="$ac_config_files etc/init/Makefile" ac_config_files="$ac_config_files etc/launchd/org.apache.couchdb.plist.tpl" ac_config_files="$ac_config_files etc/launchd/Makefile" ac_config_files="$ac_config_files etc/logrotate.d/couchdb.tpl" ac_config_files="$ac_config_files etc/logrotate.d/Makefile" ac_config_files="$ac_config_files etc/windows/Makefile" ac_config_files="$ac_config_files etc/Makefile" ac_config_files="$ac_config_files share/Makefile" ac_config_files="$ac_config_files share/doc/Makefile" ac_config_files="$ac_config_files share/doc/build/Makefile" ac_config_files="$ac_config_files src/Makefile" ac_config_files="$ac_config_files src/couch_dbupdates/Makefile" ac_config_files="$ac_config_files src/couch_index/Makefile" ac_config_files="$ac_config_files src/couch_mrview/Makefile" ac_config_files="$ac_config_files src/couch_plugins/Makefile" ac_config_files="$ac_config_files src/couch_replicator/Makefile" ac_config_files="$ac_config_files src/couchjs-node/Makefile" ac_config_files="$ac_config_files src/couchdb/couch.app.tpl" ac_config_files="$ac_config_files src/couchdb/Makefile" ac_config_files="$ac_config_files src/couchdb/priv/Makefile" ac_config_files="$ac_config_files src/erlang-oauth/Makefile" ac_config_files="$ac_config_files src/etap/Makefile" ac_config_files="$ac_config_files src/ibrowse/Makefile" ac_config_files="$ac_config_files src/mochiweb/Makefile" ac_config_files="$ac_config_files src/snappy/Makefile" ac_config_files="$ac_config_files src/snappy/google-snappy/snappy-stubs-public.h" ac_config_files="$ac_config_files src/ejson/Makefile" ac_config_files="$ac_config_files test/Makefile" ac_config_files="$ac_config_files test/bench/Makefile" ac_config_files="$ac_config_files test/etap/Makefile" ac_config_files="$ac_config_files test/etap/test_util.erl" ac_config_files="$ac_config_files test/javascript/Makefile" ac_config_files="$ac_config_files test/view_server/Makefile" ac_config_files="$ac_config_files utils/Makefile" ac_config_files="$ac_config_files var/Makefile" cat >confcache <<\_ACEOF # This file is a shell script that caches the results of configure # tests run on this system so they can be shared between configure # scripts and configure runs, see configure's option --config-cache. # It is not useful on other systems. If it contains results you don't # want to keep, you may remove or edit it. # # config.status only pays attention to the cache file if you give it # the --recheck option to rerun configure. # # `ac_cv_env_foo' variables (set or unset) will be overridden when # loading this file, other *unset* `ac_cv_foo' will be assigned the # following values. _ACEOF # The following way of writing the cache mishandles newlines in values, # but we know of no workaround that is simple, portable, and efficient. # So, we kill variables containing newlines. # Ultrix sh set writes to stderr and can't be redirected directly, # and sets the high bit in the cache file unless we assign to the vars. ( for ac_var in `(set) 2>&1 | sed -n 's/^\([a-zA-Z_][a-zA-Z0-9_]*\)=.*/\1/p'`; do eval ac_val=\$$ac_var case $ac_val in #( *${as_nl}*) case $ac_var in #( *_cv_*) { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: cache variable $ac_var contains a newline" >&5 $as_echo "$as_me: WARNING: cache variable $ac_var contains a newline" >&2;} ;; esac case $ac_var in #( _ | IFS | as_nl) ;; #( BASH_ARGV | BASH_SOURCE) eval $ac_var= ;; #( *) { eval $ac_var=; unset $ac_var;} ;; esac ;; esac done (set) 2>&1 | case $as_nl`(ac_space=' '; set) 2>&1` in #( *${as_nl}ac_space=\ *) # `set' does not quote correctly, so add quotes: double-quote # substitution turns \\\\ into \\, and sed turns \\ into \. sed -n \ "s/'/'\\\\''/g; s/^\\([_$as_cr_alnum]*_cv_[_$as_cr_alnum]*\\)=\\(.*\\)/\\1='\\2'/p" ;; #( *) # `set' quotes correctly as required by POSIX, so do not add quotes. sed -n "/^[_$as_cr_alnum]*_cv_[_$as_cr_alnum]*=/p" ;; esac | sort ) | sed ' /^ac_cv_env_/b end t clear :clear s/^\([^=]*\)=\(.*[{}].*\)$/test "${\1+set}" = set || &/ t end s/^\([^=]*\)=\(.*\)$/\1=${\1=\2}/ :end' >>confcache if diff "$cache_file" confcache >/dev/null 2>&1; then :; else if test -w "$cache_file"; then if test "x$cache_file" != "x/dev/null"; then { $as_echo "$as_me:${as_lineno-$LINENO}: updating cache $cache_file" >&5 $as_echo "$as_me: updating cache $cache_file" >&6;} if test ! -f "$cache_file" || test -h "$cache_file"; then cat confcache >"$cache_file" else case $cache_file in #( */* | ?:*) mv -f confcache "$cache_file"$$ && mv -f "$cache_file"$$ "$cache_file" ;; #( *) mv -f confcache "$cache_file" ;; esac fi fi else { $as_echo "$as_me:${as_lineno-$LINENO}: not updating unwritable cache $cache_file" >&5 $as_echo "$as_me: not updating unwritable cache $cache_file" >&6;} fi fi rm -f confcache test "x$prefix" = xNONE && prefix=$ac_default_prefix # Let make expand exec_prefix. test "x$exec_prefix" = xNONE && exec_prefix='${prefix}' DEFS=-DHAVE_CONFIG_H ac_libobjs= ac_ltlibobjs= U= for ac_i in : $LIBOBJS; do test "x$ac_i" = x: && continue # 1. Remove the extension, and $U if already installed. ac_script='s/\$U\././;s/\.o$//;s/\.obj$//' ac_i=`$as_echo "$ac_i" | sed "$ac_script"` # 2. Prepend LIBOBJDIR. When used with automake>=1.10 LIBOBJDIR # will be set to the directory where LIBOBJS objects are built. as_fn_append ac_libobjs " \${LIBOBJDIR}$ac_i\$U.$ac_objext" as_fn_append ac_ltlibobjs " \${LIBOBJDIR}$ac_i"'$U.lo' done LIBOBJS=$ac_libobjs LTLIBOBJS=$ac_ltlibobjs if test -n "$EXEEXT"; then am__EXEEXT_TRUE= am__EXEEXT_FALSE='#' else am__EXEEXT_TRUE='#' am__EXEEXT_FALSE= fi if test -z "${AMDEP_TRUE}" && test -z "${AMDEP_FALSE}"; then as_fn_error $? "conditional \"AMDEP\" was never defined. Usually this means the macro was only invoked conditionally." "$LINENO" 5 fi if test -z "${am__fastdepCC_TRUE}" && test -z "${am__fastdepCC_FALSE}"; then as_fn_error $? "conditional \"am__fastdepCC\" was never defined. Usually this means the macro was only invoked conditionally." "$LINENO" 5 fi if test -z "${am__fastdepCC_TRUE}" && test -z "${am__fastdepCC_FALSE}"; then as_fn_error $? "conditional \"am__fastdepCC\" was never defined. Usually this means the macro was only invoked conditionally." "$LINENO" 5 fi if test -z "${am__fastdepCXX_TRUE}" && test -z "${am__fastdepCXX_FALSE}"; then as_fn_error $? "conditional \"am__fastdepCXX\" was never defined. Usually this means the macro was only invoked conditionally." "$LINENO" 5 fi if test -z "${WINDOWS_TRUE}" && test -z "${WINDOWS_FALSE}"; then as_fn_error $? "conditional \"WINDOWS\" was never defined. Usually this means the macro was only invoked conditionally." "$LINENO" 5 fi if test -z "${USE_OTP_NIFS_TRUE}" && test -z "${USE_OTP_NIFS_FALSE}"; then as_fn_error $? "conditional \"USE_OTP_NIFS\" was never defined. Usually this means the macro was only invoked conditionally." "$LINENO" 5 fi if test -z "${USE_EJSON_COMPARE_NIF_TRUE}" && test -z "${USE_EJSON_COMPARE_NIF_FALSE}"; then as_fn_error $? "conditional \"USE_EJSON_COMPARE_NIF\" was never defined. Usually this means the macro was only invoked conditionally." "$LINENO" 5 fi if test -z "${INIT_TRUE}" && test -z "${INIT_FALSE}"; then as_fn_error $? "conditional \"INIT\" was never defined. Usually this means the macro was only invoked conditionally." "$LINENO" 5 fi if test -z "${LAUNCHD_TRUE}" && test -z "${LAUNCHD_FALSE}"; then as_fn_error $? "conditional \"LAUNCHD\" was never defined. Usually this means the macro was only invoked conditionally." "$LINENO" 5 fi if test -z "${USE_NATIVE_MOCHIJSON_TRUE}" && test -z "${USE_NATIVE_MOCHIJSON_FALSE}"; then as_fn_error $? "conditional \"USE_NATIVE_MOCHIJSON\" was never defined. Usually this means the macro was only invoked conditionally." "$LINENO" 5 fi if test -z "${USE_CURL_TRUE}" && test -z "${USE_CURL_FALSE}"; then as_fn_error $? "conditional \"USE_CURL\" was never defined. Usually this means the macro was only invoked conditionally." "$LINENO" 5 fi if test -z "${BUILD_MAN_TRUE}" && test -z "${BUILD_MAN_FALSE}"; then as_fn_error $? "conditional \"BUILD_MAN\" was never defined. Usually this means the macro was only invoked conditionally." "$LINENO" 5 fi if test -z "${BUILD_INFO_TRUE}" && test -z "${BUILD_INFO_FALSE}"; then as_fn_error $? "conditional \"BUILD_INFO\" was never defined. Usually this means the macro was only invoked conditionally." "$LINENO" 5 fi if test -z "${BUILD_PDF_TRUE}" && test -z "${BUILD_PDF_FALSE}"; then as_fn_error $? "conditional \"BUILD_PDF\" was never defined. Usually this means the macro was only invoked conditionally." "$LINENO" 5 fi if test -z "${BUILD_HTML_TRUE}" && test -z "${BUILD_HTML_FALSE}"; then as_fn_error $? "conditional \"BUILD_HTML\" was never defined. Usually this means the macro was only invoked conditionally." "$LINENO" 5 fi if test -z "${TESTS_TRUE}" && test -z "${TESTS_FALSE}"; then as_fn_error $? "conditional \"TESTS\" was never defined. Usually this means the macro was only invoked conditionally." "$LINENO" 5 fi if test -z "${STRICTNESS_TRUE}" && test -z "${STRICTNESS_FALSE}"; then as_fn_error $? "conditional \"STRICTNESS\" was never defined. Usually this means the macro was only invoked conditionally." "$LINENO" 5 fi : "${CONFIG_STATUS=./config.status}" ac_write_fail=0 ac_clean_files_save=$ac_clean_files ac_clean_files="$ac_clean_files $CONFIG_STATUS" { $as_echo "$as_me:${as_lineno-$LINENO}: creating $CONFIG_STATUS" >&5 $as_echo "$as_me: creating $CONFIG_STATUS" >&6;} as_write_fail=0 cat >$CONFIG_STATUS <<_ASEOF || as_write_fail=1 #! $SHELL # Generated by $as_me. # Run this file to recreate the current configuration. # Compiler output produced by configure, useful for debugging # configure, is in config.log if it exists. debug=false ac_cs_recheck=false ac_cs_silent=false SHELL=\${CONFIG_SHELL-$SHELL} export SHELL _ASEOF cat >>$CONFIG_STATUS <<\_ASEOF || as_write_fail=1 ## -------------------- ## ## M4sh Initialization. ## ## -------------------- ## # Be more Bourne compatible DUALCASE=1; export DUALCASE # for MKS sh if test -n "${ZSH_VERSION+set}" && (emulate sh) >/dev/null 2>&1; then : emulate sh NULLCMD=: # Pre-4.2 versions of Zsh do word splitting on ${1+"$@"}, which # is contrary to our usage. Disable this feature. alias -g '${1+"$@"}'='"$@"' setopt NO_GLOB_SUBST else case `(set -o) 2>/dev/null` in #( *posix*) : set -o posix ;; #( *) : ;; esac fi as_nl=' ' export as_nl # Printing a long string crashes Solaris 7 /usr/bin/printf. as_echo='\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\' as_echo=$as_echo$as_echo$as_echo$as_echo$as_echo as_echo=$as_echo$as_echo$as_echo$as_echo$as_echo$as_echo # Prefer a ksh shell builtin over an external printf program on Solaris, # but without wasting forks for bash or zsh. if test -z "$BASH_VERSION$ZSH_VERSION" \ && (test "X`print -r -- $as_echo`" = "X$as_echo") 2>/dev/null; then as_echo='print -r --' as_echo_n='print -rn --' elif (test "X`printf %s $as_echo`" = "X$as_echo") 2>/dev/null; then as_echo='printf %s\n' as_echo_n='printf %s' else if test "X`(/usr/ucb/echo -n -n $as_echo) 2>/dev/null`" = "X-n $as_echo"; then as_echo_body='eval /usr/ucb/echo -n "$1$as_nl"' as_echo_n='/usr/ucb/echo -n' else as_echo_body='eval expr "X$1" : "X\\(.*\\)"' as_echo_n_body='eval arg=$1; case $arg in #( *"$as_nl"*) expr "X$arg" : "X\\(.*\\)$as_nl"; arg=`expr "X$arg" : ".*$as_nl\\(.*\\)"`;; esac; expr "X$arg" : "X\\(.*\\)" | tr -d "$as_nl" ' export as_echo_n_body as_echo_n='sh -c $as_echo_n_body as_echo' fi export as_echo_body as_echo='sh -c $as_echo_body as_echo' fi # The user is always right. if test "${PATH_SEPARATOR+set}" != set; then PATH_SEPARATOR=: (PATH='/bin;/bin'; FPATH=$PATH; sh -c :) >/dev/null 2>&1 && { (PATH='/bin:/bin'; FPATH=$PATH; sh -c :) >/dev/null 2>&1 || PATH_SEPARATOR=';' } fi # IFS # We need space, tab and new line, in precisely that order. Quoting is # there to prevent editors from complaining about space-tab. # (If _AS_PATH_WALK were called with IFS unset, it would disable word # splitting by setting IFS to empty value.) IFS=" "" $as_nl" # Find who we are. Look in the path if we contain no directory separator. as_myself= case $0 in #(( *[\\/]* ) as_myself=$0 ;; *) as_save_IFS=$IFS; IFS=$PATH_SEPARATOR for as_dir in $PATH do IFS=$as_save_IFS test -z "$as_dir" && as_dir=. test -r "$as_dir/$0" && as_myself=$as_dir/$0 && break done IFS=$as_save_IFS ;; esac # We did not find ourselves, most probably we were run as `sh COMMAND' # in which case we are not to be found in the path. if test "x$as_myself" = x; then as_myself=$0 fi if test ! -f "$as_myself"; then $as_echo "$as_myself: error: cannot find myself; rerun with an absolute file name" >&2 exit 1 fi # Unset variables that we do not need and which cause bugs (e.g. in # pre-3.0 UWIN ksh). But do not cause bugs in bash 2.01; the "|| exit 1" # suppresses any "Segmentation fault" message there. '((' could # trigger a bug in pdksh 5.2.14. for as_var in BASH_ENV ENV MAIL MAILPATH do eval test x\${$as_var+set} = xset \ && ( (unset $as_var) || exit 1) >/dev/null 2>&1 && unset $as_var || : done PS1='$ ' PS2='> ' PS4='+ ' # NLS nuisances. LC_ALL=C export LC_ALL LANGUAGE=C export LANGUAGE # CDPATH. (unset CDPATH) >/dev/null 2>&1 && unset CDPATH # as_fn_error STATUS ERROR [LINENO LOG_FD] # ---------------------------------------- # Output "`basename $0`: error: ERROR" to stderr. If LINENO and LOG_FD are # provided, also output the error to LOG_FD, referencing LINENO. Then exit the # script with STATUS, using 1 if that was 0. as_fn_error () { as_status=$1; test $as_status -eq 0 && as_status=1 if test "$4"; then as_lineno=${as_lineno-"$3"} as_lineno_stack=as_lineno_stack=$as_lineno_stack $as_echo "$as_me:${as_lineno-$LINENO}: error: $2" >&$4 fi $as_echo "$as_me: error: $2" >&2 as_fn_exit $as_status } # as_fn_error # as_fn_set_status STATUS # ----------------------- # Set $? to STATUS, without forking. as_fn_set_status () { return $1 } # as_fn_set_status # as_fn_exit STATUS # ----------------- # Exit the shell with STATUS, even in a "trap 0" or "set -e" context. as_fn_exit () { set +e as_fn_set_status $1 exit $1 } # as_fn_exit # as_fn_unset VAR # --------------- # Portably unset VAR. as_fn_unset () { { eval $1=; unset $1;} } as_unset=as_fn_unset # as_fn_append VAR VALUE # ---------------------- # Append the text in VALUE to the end of the definition contained in VAR. Take # advantage of any shell optimizations that allow amortized linear growth over # repeated appends, instead of the typical quadratic growth present in naive # implementations. if (eval "as_var=1; as_var+=2; test x\$as_var = x12") 2>/dev/null; then : eval 'as_fn_append () { eval $1+=\$2 }' else as_fn_append () { eval $1=\$$1\$2 } fi # as_fn_append # as_fn_arith ARG... # ------------------ # Perform arithmetic evaluation on the ARGs, and store the result in the # global $as_val. Take advantage of shells that can avoid forks. The arguments # must be portable across $(()) and expr. if (eval "test \$(( 1 + 1 )) = 2") 2>/dev/null; then : eval 'as_fn_arith () { as_val=$(( $* )) }' else as_fn_arith () { as_val=`expr "$@" || test $? -eq 1` } fi # as_fn_arith if expr a : '\(a\)' >/dev/null 2>&1 && test "X`expr 00001 : '.*\(...\)'`" = X001; then as_expr=expr else as_expr=false fi if (basename -- /) >/dev/null 2>&1 && test "X`basename -- / 2>&1`" = "X/"; then as_basename=basename else as_basename=false fi if (as_dir=`dirname -- /` && test "X$as_dir" = X/) >/dev/null 2>&1; then as_dirname=dirname else as_dirname=false fi as_me=`$as_basename -- "$0" || $as_expr X/"$0" : '.*/\([^/][^/]*\)/*$' \| \ X"$0" : 'X\(//\)$' \| \ X"$0" : 'X\(/\)' \| . 2>/dev/null || $as_echo X/"$0" | sed '/^.*\/\([^/][^/]*\)\/*$/{ s//\1/ q } /^X\/\(\/\/\)$/{ s//\1/ q } /^X\/\(\/\).*/{ s//\1/ q } s/.*/./; q'` # Avoid depending upon Character Ranges. as_cr_letters='abcdefghijklmnopqrstuvwxyz' as_cr_LETTERS='ABCDEFGHIJKLMNOPQRSTUVWXYZ' as_cr_Letters=$as_cr_letters$as_cr_LETTERS as_cr_digits='0123456789' as_cr_alnum=$as_cr_Letters$as_cr_digits ECHO_C= ECHO_N= ECHO_T= case `echo -n x` in #((((( -n*) case `echo 'xy\c'` in *c*) ECHO_T=' ';; # ECHO_T is single tab character. xy) ECHO_C='\c';; *) echo `echo ksh88 bug on AIX 6.1` > /dev/null ECHO_T=' ';; esac;; *) ECHO_N='-n';; esac rm -f conf$$ conf$$.exe conf$$.file if test -d conf$$.dir; then rm -f conf$$.dir/conf$$.file else rm -f conf$$.dir mkdir conf$$.dir 2>/dev/null fi if (echo >conf$$.file) 2>/dev/null; then if ln -s conf$$.file conf$$ 2>/dev/null; then as_ln_s='ln -s' # ... but there are two gotchas: # 1) On MSYS, both `ln -s file dir' and `ln file dir' fail. # 2) DJGPP < 2.04 has no symlinks; `ln -s' creates a wrapper executable. # In both cases, we have to default to `cp -pR'. ln -s conf$$.file conf$$.dir 2>/dev/null && test ! -f conf$$.exe || as_ln_s='cp -pR' elif ln conf$$.file conf$$ 2>/dev/null; then as_ln_s=ln else as_ln_s='cp -pR' fi else as_ln_s='cp -pR' fi rm -f conf$$ conf$$.exe conf$$.dir/conf$$.file conf$$.file rmdir conf$$.dir 2>/dev/null # as_fn_mkdir_p # ------------- # Create "$as_dir" as a directory, including parents if necessary. as_fn_mkdir_p () { case $as_dir in #( -*) as_dir=./$as_dir;; esac test -d "$as_dir" || eval $as_mkdir_p || { as_dirs= while :; do case $as_dir in #( *\'*) as_qdir=`$as_echo "$as_dir" | sed "s/'/'\\\\\\\\''/g"`;; #'( *) as_qdir=$as_dir;; esac as_dirs="'$as_qdir' $as_dirs" as_dir=`$as_dirname -- "$as_dir" || $as_expr X"$as_dir" : 'X\(.*[^/]\)//*[^/][^/]*/*$' \| \ X"$as_dir" : 'X\(//\)[^/]' \| \ X"$as_dir" : 'X\(//\)$' \| \ X"$as_dir" : 'X\(/\)' \| . 2>/dev/null || $as_echo X"$as_dir" | sed '/^X\(.*[^/]\)\/\/*[^/][^/]*\/*$/{ s//\1/ q } /^X\(\/\/\)[^/].*/{ s//\1/ q } /^X\(\/\/\)$/{ s//\1/ q } /^X\(\/\).*/{ s//\1/ q } s/.*/./; q'` test -d "$as_dir" && break done test -z "$as_dirs" || eval "mkdir $as_dirs" } || test -d "$as_dir" || as_fn_error $? "cannot create directory $as_dir" } # as_fn_mkdir_p if mkdir -p . 2>/dev/null; then as_mkdir_p='mkdir -p "$as_dir"' else test -d ./-p && rmdir ./-p as_mkdir_p=false fi # as_fn_executable_p FILE # ----------------------- # Test if FILE is an executable regular file. as_fn_executable_p () { test -f "$1" && test -x "$1" } # as_fn_executable_p as_test_x='test -x' as_executable_p=as_fn_executable_p # Sed expression to map a string onto a valid CPP name. as_tr_cpp="eval sed 'y%*$as_cr_letters%P$as_cr_LETTERS%;s%[^_$as_cr_alnum]%_%g'" # Sed expression to map a string onto a valid variable name. as_tr_sh="eval sed 'y%*+%pp%;s%[^_$as_cr_alnum]%_%g'" exec 6>&1 ## ----------------------------------- ## ## Main body of $CONFIG_STATUS script. ## ## ----------------------------------- ## _ASEOF test $as_write_fail = 0 && chmod +x $CONFIG_STATUS || ac_write_fail=1 cat >>$CONFIG_STATUS <<\_ACEOF || ac_write_fail=1 # Save the log message, to keep $0 and so on meaningful, and to # report actual input values of CONFIG_FILES etc. instead of their # values after options handling. ac_log=" This file was extended by Apache CouchDB $as_me 1.5.0, which was generated by GNU Autoconf 2.69. Invocation command line was CONFIG_FILES = $CONFIG_FILES CONFIG_HEADERS = $CONFIG_HEADERS CONFIG_LINKS = $CONFIG_LINKS CONFIG_COMMANDS = $CONFIG_COMMANDS $ $0 $@ on `(hostname || uname -n) 2>/dev/null | sed 1q` " _ACEOF case $ac_config_files in *" "*) set x $ac_config_files; shift; ac_config_files=$*;; esac case $ac_config_headers in *" "*) set x $ac_config_headers; shift; ac_config_headers=$*;; esac cat >>$CONFIG_STATUS <<_ACEOF || ac_write_fail=1 # Files that config.status was made for. config_files="$ac_config_files" config_headers="$ac_config_headers" config_commands="$ac_config_commands" _ACEOF cat >>$CONFIG_STATUS <<\_ACEOF || ac_write_fail=1 ac_cs_usage="\ \`$as_me' instantiates files and other configuration actions from templates according to the current configuration. Unless the files and actions are specified as TAGs, all are instantiated by default. Usage: $0 [OPTION]... [TAG]... -h, --help print this help, then exit -V, --version print version number and configuration settings, then exit --config print configuration, then exit -q, --quiet, --silent do not print progress messages -d, --debug don't remove temporary files --recheck update $as_me by reconfiguring in the same conditions --file=FILE[:TEMPLATE] instantiate the configuration file FILE --header=FILE[:TEMPLATE] instantiate the configuration header FILE Configuration files: $config_files Configuration headers: $config_headers Configuration commands: $config_commands Report bugs to ." _ACEOF cat >>$CONFIG_STATUS <<_ACEOF || ac_write_fail=1 ac_cs_config="`$as_echo "$ac_configure_args" | sed 's/^ //; s/[\\""\`\$]/\\\\&/g'`" ac_cs_version="\\ Apache CouchDB config.status 1.5.0 configured by $0, generated by GNU Autoconf 2.69, with options \\"\$ac_cs_config\\" Copyright (C) 2012 Free Software Foundation, Inc. This config.status script is free software; the Free Software Foundation gives unlimited permission to copy, distribute and modify it." ac_pwd='$ac_pwd' srcdir='$srcdir' INSTALL='$INSTALL' MKDIR_P='$MKDIR_P' AWK='$AWK' test -n "\$AWK" || AWK=awk _ACEOF cat >>$CONFIG_STATUS <<\_ACEOF || ac_write_fail=1 # The default lists apply if the user does not specify any file. ac_need_defaults=: while test $# != 0 do case $1 in --*=?*) ac_option=`expr "X$1" : 'X\([^=]*\)='` ac_optarg=`expr "X$1" : 'X[^=]*=\(.*\)'` ac_shift=: ;; --*=) ac_option=`expr "X$1" : 'X\([^=]*\)='` ac_optarg= ac_shift=: ;; *) ac_option=$1 ac_optarg=$2 ac_shift=shift ;; esac case $ac_option in # Handling of the options. -recheck | --recheck | --rechec | --reche | --rech | --rec | --re | --r) ac_cs_recheck=: ;; --version | --versio | --versi | --vers | --ver | --ve | --v | -V ) $as_echo "$ac_cs_version"; exit ;; --config | --confi | --conf | --con | --co | --c ) $as_echo "$ac_cs_config"; exit ;; --debug | --debu | --deb | --de | --d | -d ) debug=: ;; --file | --fil | --fi | --f ) $ac_shift case $ac_optarg in *\'*) ac_optarg=`$as_echo "$ac_optarg" | sed "s/'/'\\\\\\\\''/g"` ;; '') as_fn_error $? "missing file argument" ;; esac as_fn_append CONFIG_FILES " '$ac_optarg'" ac_need_defaults=false;; --header | --heade | --head | --hea ) $ac_shift case $ac_optarg in *\'*) ac_optarg=`$as_echo "$ac_optarg" | sed "s/'/'\\\\\\\\''/g"` ;; esac as_fn_append CONFIG_HEADERS " '$ac_optarg'" ac_need_defaults=false;; --he | --h) # Conflict between --help and --header as_fn_error $? "ambiguous option: \`$1' Try \`$0 --help' for more information.";; --help | --hel | -h ) $as_echo "$ac_cs_usage"; exit ;; -q | -quiet | --quiet | --quie | --qui | --qu | --q \ | -silent | --silent | --silen | --sile | --sil | --si | --s) ac_cs_silent=: ;; # This is an error. -*) as_fn_error $? "unrecognized option: \`$1' Try \`$0 --help' for more information." ;; *) as_fn_append ac_config_targets " $1" ac_need_defaults=false ;; esac shift done ac_configure_extra_args= if $ac_cs_silent; then exec 6>/dev/null ac_configure_extra_args="$ac_configure_extra_args --silent" fi _ACEOF cat >>$CONFIG_STATUS <<_ACEOF || ac_write_fail=1 if \$ac_cs_recheck; then set X $SHELL '$0' $ac_configure_args \$ac_configure_extra_args --no-create --no-recursion shift \$as_echo "running CONFIG_SHELL=$SHELL \$*" >&6 CONFIG_SHELL='$SHELL' export CONFIG_SHELL exec "\$@" fi _ACEOF cat >>$CONFIG_STATUS <<\_ACEOF || ac_write_fail=1 exec 5>>config.log { echo sed 'h;s/./-/g;s/^.../## /;s/...$/ ##/;p;x;p;x' <<_ASBOX ## Running $as_me. ## _ASBOX $as_echo "$ac_log" } >&5 _ACEOF cat >>$CONFIG_STATUS <<_ACEOF || ac_write_fail=1 # # INIT-COMMANDS # AMDEP_TRUE="$AMDEP_TRUE" ac_aux_dir="$ac_aux_dir" # The HP-UX ksh and POSIX shell print the target directory to stdout # if CDPATH is set. (unset CDPATH) >/dev/null 2>&1 && unset CDPATH sed_quote_subst='$sed_quote_subst' double_quote_subst='$double_quote_subst' delay_variable_subst='$delay_variable_subst' enable_shared='`$ECHO "$enable_shared" | $SED "$delay_single_quote_subst"`' enable_static='`$ECHO "$enable_static" | $SED "$delay_single_quote_subst"`' macro_version='`$ECHO "$macro_version" | $SED "$delay_single_quote_subst"`' macro_revision='`$ECHO "$macro_revision" | $SED "$delay_single_quote_subst"`' AS='`$ECHO "$AS" | $SED "$delay_single_quote_subst"`' DLLTOOL='`$ECHO "$DLLTOOL" | $SED "$delay_single_quote_subst"`' OBJDUMP='`$ECHO "$OBJDUMP" | $SED "$delay_single_quote_subst"`' pic_mode='`$ECHO "$pic_mode" | $SED "$delay_single_quote_subst"`' enable_fast_install='`$ECHO "$enable_fast_install" | $SED "$delay_single_quote_subst"`' SHELL='`$ECHO "$SHELL" | $SED "$delay_single_quote_subst"`' ECHO='`$ECHO "$ECHO" | $SED "$delay_single_quote_subst"`' PATH_SEPARATOR='`$ECHO "$PATH_SEPARATOR" | $SED "$delay_single_quote_subst"`' host_alias='`$ECHO "$host_alias" | $SED "$delay_single_quote_subst"`' host='`$ECHO "$host" | $SED "$delay_single_quote_subst"`' host_os='`$ECHO "$host_os" | $SED "$delay_single_quote_subst"`' build_alias='`$ECHO "$build_alias" | $SED "$delay_single_quote_subst"`' build='`$ECHO "$build" | $SED "$delay_single_quote_subst"`' build_os='`$ECHO "$build_os" | $SED "$delay_single_quote_subst"`' SED='`$ECHO "$SED" | $SED "$delay_single_quote_subst"`' Xsed='`$ECHO "$Xsed" | $SED "$delay_single_quote_subst"`' GREP='`$ECHO "$GREP" | $SED "$delay_single_quote_subst"`' EGREP='`$ECHO "$EGREP" | $SED "$delay_single_quote_subst"`' FGREP='`$ECHO "$FGREP" | $SED "$delay_single_quote_subst"`' LD='`$ECHO "$LD" | $SED "$delay_single_quote_subst"`' NM='`$ECHO "$NM" | $SED "$delay_single_quote_subst"`' LN_S='`$ECHO "$LN_S" | $SED "$delay_single_quote_subst"`' max_cmd_len='`$ECHO "$max_cmd_len" | $SED "$delay_single_quote_subst"`' ac_objext='`$ECHO "$ac_objext" | $SED "$delay_single_quote_subst"`' exeext='`$ECHO "$exeext" | $SED "$delay_single_quote_subst"`' lt_unset='`$ECHO "$lt_unset" | $SED "$delay_single_quote_subst"`' lt_SP2NL='`$ECHO "$lt_SP2NL" | $SED "$delay_single_quote_subst"`' lt_NL2SP='`$ECHO "$lt_NL2SP" | $SED "$delay_single_quote_subst"`' lt_cv_to_host_file_cmd='`$ECHO "$lt_cv_to_host_file_cmd" | $SED "$delay_single_quote_subst"`' lt_cv_to_tool_file_cmd='`$ECHO "$lt_cv_to_tool_file_cmd" | $SED "$delay_single_quote_subst"`' reload_flag='`$ECHO "$reload_flag" | $SED "$delay_single_quote_subst"`' reload_cmds='`$ECHO "$reload_cmds" | $SED "$delay_single_quote_subst"`' deplibs_check_method='`$ECHO "$deplibs_check_method" | $SED "$delay_single_quote_subst"`' file_magic_cmd='`$ECHO "$file_magic_cmd" | $SED "$delay_single_quote_subst"`' file_magic_glob='`$ECHO "$file_magic_glob" | $SED "$delay_single_quote_subst"`' want_nocaseglob='`$ECHO "$want_nocaseglob" | $SED "$delay_single_quote_subst"`' sharedlib_from_linklib_cmd='`$ECHO "$sharedlib_from_linklib_cmd" | $SED "$delay_single_quote_subst"`' AR='`$ECHO "$AR" | $SED "$delay_single_quote_subst"`' AR_FLAGS='`$ECHO "$AR_FLAGS" | $SED "$delay_single_quote_subst"`' archiver_list_spec='`$ECHO "$archiver_list_spec" | $SED "$delay_single_quote_subst"`' STRIP='`$ECHO "$STRIP" | $SED "$delay_single_quote_subst"`' RANLIB='`$ECHO "$RANLIB" | $SED "$delay_single_quote_subst"`' old_postinstall_cmds='`$ECHO "$old_postinstall_cmds" | $SED "$delay_single_quote_subst"`' old_postuninstall_cmds='`$ECHO "$old_postuninstall_cmds" | $SED "$delay_single_quote_subst"`' old_archive_cmds='`$ECHO "$old_archive_cmds" | $SED "$delay_single_quote_subst"`' lock_old_archive_extraction='`$ECHO "$lock_old_archive_extraction" | $SED "$delay_single_quote_subst"`' CC='`$ECHO "$CC" | $SED "$delay_single_quote_subst"`' CFLAGS='`$ECHO "$CFLAGS" | $SED "$delay_single_quote_subst"`' compiler='`$ECHO "$compiler" | $SED "$delay_single_quote_subst"`' GCC='`$ECHO "$GCC" | $SED "$delay_single_quote_subst"`' lt_cv_sys_global_symbol_pipe='`$ECHO "$lt_cv_sys_global_symbol_pipe" | $SED "$delay_single_quote_subst"`' lt_cv_sys_global_symbol_to_cdecl='`$ECHO "$lt_cv_sys_global_symbol_to_cdecl" | $SED "$delay_single_quote_subst"`' lt_cv_sys_global_symbol_to_c_name_address='`$ECHO "$lt_cv_sys_global_symbol_to_c_name_address" | $SED "$delay_single_quote_subst"`' lt_cv_sys_global_symbol_to_c_name_address_lib_prefix='`$ECHO "$lt_cv_sys_global_symbol_to_c_name_address_lib_prefix" | $SED "$delay_single_quote_subst"`' nm_file_list_spec='`$ECHO "$nm_file_list_spec" | $SED "$delay_single_quote_subst"`' lt_sysroot='`$ECHO "$lt_sysroot" | $SED "$delay_single_quote_subst"`' objdir='`$ECHO "$objdir" | $SED "$delay_single_quote_subst"`' MAGIC_CMD='`$ECHO "$MAGIC_CMD" | $SED "$delay_single_quote_subst"`' lt_prog_compiler_no_builtin_flag='`$ECHO "$lt_prog_compiler_no_builtin_flag" | $SED "$delay_single_quote_subst"`' lt_prog_compiler_pic='`$ECHO "$lt_prog_compiler_pic" | $SED "$delay_single_quote_subst"`' lt_prog_compiler_wl='`$ECHO "$lt_prog_compiler_wl" | $SED "$delay_single_quote_subst"`' lt_prog_compiler_static='`$ECHO "$lt_prog_compiler_static" | $SED "$delay_single_quote_subst"`' lt_cv_prog_compiler_c_o='`$ECHO "$lt_cv_prog_compiler_c_o" | $SED "$delay_single_quote_subst"`' need_locks='`$ECHO "$need_locks" | $SED "$delay_single_quote_subst"`' MANIFEST_TOOL='`$ECHO "$MANIFEST_TOOL" | $SED "$delay_single_quote_subst"`' DSYMUTIL='`$ECHO "$DSYMUTIL" | $SED "$delay_single_quote_subst"`' NMEDIT='`$ECHO "$NMEDIT" | $SED "$delay_single_quote_subst"`' LIPO='`$ECHO "$LIPO" | $SED "$delay_single_quote_subst"`' OTOOL='`$ECHO "$OTOOL" | $SED "$delay_single_quote_subst"`' OTOOL64='`$ECHO "$OTOOL64" | $SED "$delay_single_quote_subst"`' libext='`$ECHO "$libext" | $SED "$delay_single_quote_subst"`' shrext_cmds='`$ECHO "$shrext_cmds" | $SED "$delay_single_quote_subst"`' extract_expsyms_cmds='`$ECHO "$extract_expsyms_cmds" | $SED "$delay_single_quote_subst"`' archive_cmds_need_lc='`$ECHO "$archive_cmds_need_lc" | $SED "$delay_single_quote_subst"`' enable_shared_with_static_runtimes='`$ECHO "$enable_shared_with_static_runtimes" | $SED "$delay_single_quote_subst"`' export_dynamic_flag_spec='`$ECHO "$export_dynamic_flag_spec" | $SED "$delay_single_quote_subst"`' whole_archive_flag_spec='`$ECHO "$whole_archive_flag_spec" | $SED "$delay_single_quote_subst"`' compiler_needs_object='`$ECHO "$compiler_needs_object" | $SED "$delay_single_quote_subst"`' old_archive_from_new_cmds='`$ECHO "$old_archive_from_new_cmds" | $SED "$delay_single_quote_subst"`' old_archive_from_expsyms_cmds='`$ECHO "$old_archive_from_expsyms_cmds" | $SED "$delay_single_quote_subst"`' archive_cmds='`$ECHO "$archive_cmds" | $SED "$delay_single_quote_subst"`' archive_expsym_cmds='`$ECHO "$archive_expsym_cmds" | $SED "$delay_single_quote_subst"`' module_cmds='`$ECHO "$module_cmds" | $SED "$delay_single_quote_subst"`' module_expsym_cmds='`$ECHO "$module_expsym_cmds" | $SED "$delay_single_quote_subst"`' with_gnu_ld='`$ECHO "$with_gnu_ld" | $SED "$delay_single_quote_subst"`' allow_undefined_flag='`$ECHO "$allow_undefined_flag" | $SED "$delay_single_quote_subst"`' no_undefined_flag='`$ECHO "$no_undefined_flag" | $SED "$delay_single_quote_subst"`' hardcode_libdir_flag_spec='`$ECHO "$hardcode_libdir_flag_spec" | $SED "$delay_single_quote_subst"`' hardcode_libdir_separator='`$ECHO "$hardcode_libdir_separator" | $SED "$delay_single_quote_subst"`' hardcode_direct='`$ECHO "$hardcode_direct" | $SED "$delay_single_quote_subst"`' hardcode_direct_absolute='`$ECHO "$hardcode_direct_absolute" | $SED "$delay_single_quote_subst"`' hardcode_minus_L='`$ECHO "$hardcode_minus_L" | $SED "$delay_single_quote_subst"`' hardcode_shlibpath_var='`$ECHO "$hardcode_shlibpath_var" | $SED "$delay_single_quote_subst"`' hardcode_automatic='`$ECHO "$hardcode_automatic" | $SED "$delay_single_quote_subst"`' inherit_rpath='`$ECHO "$inherit_rpath" | $SED "$delay_single_quote_subst"`' link_all_deplibs='`$ECHO "$link_all_deplibs" | $SED "$delay_single_quote_subst"`' always_export_symbols='`$ECHO "$always_export_symbols" | $SED "$delay_single_quote_subst"`' export_symbols_cmds='`$ECHO "$export_symbols_cmds" | $SED "$delay_single_quote_subst"`' exclude_expsyms='`$ECHO "$exclude_expsyms" | $SED "$delay_single_quote_subst"`' include_expsyms='`$ECHO "$include_expsyms" | $SED "$delay_single_quote_subst"`' prelink_cmds='`$ECHO "$prelink_cmds" | $SED "$delay_single_quote_subst"`' postlink_cmds='`$ECHO "$postlink_cmds" | $SED "$delay_single_quote_subst"`' file_list_spec='`$ECHO "$file_list_spec" | $SED "$delay_single_quote_subst"`' variables_saved_for_relink='`$ECHO "$variables_saved_for_relink" | $SED "$delay_single_quote_subst"`' need_lib_prefix='`$ECHO "$need_lib_prefix" | $SED "$delay_single_quote_subst"`' need_version='`$ECHO "$need_version" | $SED "$delay_single_quote_subst"`' version_type='`$ECHO "$version_type" | $SED "$delay_single_quote_subst"`' runpath_var='`$ECHO "$runpath_var" | $SED "$delay_single_quote_subst"`' shlibpath_var='`$ECHO "$shlibpath_var" | $SED "$delay_single_quote_subst"`' shlibpath_overrides_runpath='`$ECHO "$shlibpath_overrides_runpath" | $SED "$delay_single_quote_subst"`' libname_spec='`$ECHO "$libname_spec" | $SED "$delay_single_quote_subst"`' library_names_spec='`$ECHO "$library_names_spec" | $SED "$delay_single_quote_subst"`' soname_spec='`$ECHO "$soname_spec" | $SED "$delay_single_quote_subst"`' install_override_mode='`$ECHO "$install_override_mode" | $SED "$delay_single_quote_subst"`' postinstall_cmds='`$ECHO "$postinstall_cmds" | $SED "$delay_single_quote_subst"`' postuninstall_cmds='`$ECHO "$postuninstall_cmds" | $SED "$delay_single_quote_subst"`' finish_cmds='`$ECHO "$finish_cmds" | $SED "$delay_single_quote_subst"`' finish_eval='`$ECHO "$finish_eval" | $SED "$delay_single_quote_subst"`' hardcode_into_libs='`$ECHO "$hardcode_into_libs" | $SED "$delay_single_quote_subst"`' sys_lib_search_path_spec='`$ECHO "$sys_lib_search_path_spec" | $SED "$delay_single_quote_subst"`' sys_lib_dlsearch_path_spec='`$ECHO "$sys_lib_dlsearch_path_spec" | $SED "$delay_single_quote_subst"`' hardcode_action='`$ECHO "$hardcode_action" | $SED "$delay_single_quote_subst"`' enable_dlopen='`$ECHO "$enable_dlopen" | $SED "$delay_single_quote_subst"`' enable_dlopen_self='`$ECHO "$enable_dlopen_self" | $SED "$delay_single_quote_subst"`' enable_dlopen_self_static='`$ECHO "$enable_dlopen_self_static" | $SED "$delay_single_quote_subst"`' old_striplib='`$ECHO "$old_striplib" | $SED "$delay_single_quote_subst"`' striplib='`$ECHO "$striplib" | $SED "$delay_single_quote_subst"`' compiler_lib_search_dirs='`$ECHO "$compiler_lib_search_dirs" | $SED "$delay_single_quote_subst"`' predep_objects='`$ECHO "$predep_objects" | $SED "$delay_single_quote_subst"`' postdep_objects='`$ECHO "$postdep_objects" | $SED "$delay_single_quote_subst"`' predeps='`$ECHO "$predeps" | $SED "$delay_single_quote_subst"`' postdeps='`$ECHO "$postdeps" | $SED "$delay_single_quote_subst"`' compiler_lib_search_path='`$ECHO "$compiler_lib_search_path" | $SED "$delay_single_quote_subst"`' LD_CXX='`$ECHO "$LD_CXX" | $SED "$delay_single_quote_subst"`' reload_flag_CXX='`$ECHO "$reload_flag_CXX" | $SED "$delay_single_quote_subst"`' reload_cmds_CXX='`$ECHO "$reload_cmds_CXX" | $SED "$delay_single_quote_subst"`' old_archive_cmds_CXX='`$ECHO "$old_archive_cmds_CXX" | $SED "$delay_single_quote_subst"`' compiler_CXX='`$ECHO "$compiler_CXX" | $SED "$delay_single_quote_subst"`' GCC_CXX='`$ECHO "$GCC_CXX" | $SED "$delay_single_quote_subst"`' lt_prog_compiler_no_builtin_flag_CXX='`$ECHO "$lt_prog_compiler_no_builtin_flag_CXX" | $SED "$delay_single_quote_subst"`' lt_prog_compiler_pic_CXX='`$ECHO "$lt_prog_compiler_pic_CXX" | $SED "$delay_single_quote_subst"`' lt_prog_compiler_wl_CXX='`$ECHO "$lt_prog_compiler_wl_CXX" | $SED "$delay_single_quote_subst"`' lt_prog_compiler_static_CXX='`$ECHO "$lt_prog_compiler_static_CXX" | $SED "$delay_single_quote_subst"`' lt_cv_prog_compiler_c_o_CXX='`$ECHO "$lt_cv_prog_compiler_c_o_CXX" | $SED "$delay_single_quote_subst"`' archive_cmds_need_lc_CXX='`$ECHO "$archive_cmds_need_lc_CXX" | $SED "$delay_single_quote_subst"`' enable_shared_with_static_runtimes_CXX='`$ECHO "$enable_shared_with_static_runtimes_CXX" | $SED "$delay_single_quote_subst"`' export_dynamic_flag_spec_CXX='`$ECHO "$export_dynamic_flag_spec_CXX" | $SED "$delay_single_quote_subst"`' whole_archive_flag_spec_CXX='`$ECHO "$whole_archive_flag_spec_CXX" | $SED "$delay_single_quote_subst"`' compiler_needs_object_CXX='`$ECHO "$compiler_needs_object_CXX" | $SED "$delay_single_quote_subst"`' old_archive_from_new_cmds_CXX='`$ECHO "$old_archive_from_new_cmds_CXX" | $SED "$delay_single_quote_subst"`' old_archive_from_expsyms_cmds_CXX='`$ECHO "$old_archive_from_expsyms_cmds_CXX" | $SED "$delay_single_quote_subst"`' archive_cmds_CXX='`$ECHO "$archive_cmds_CXX" | $SED "$delay_single_quote_subst"`' archive_expsym_cmds_CXX='`$ECHO "$archive_expsym_cmds_CXX" | $SED "$delay_single_quote_subst"`' module_cmds_CXX='`$ECHO "$module_cmds_CXX" | $SED "$delay_single_quote_subst"`' module_expsym_cmds_CXX='`$ECHO "$module_expsym_cmds_CXX" | $SED "$delay_single_quote_subst"`' with_gnu_ld_CXX='`$ECHO "$with_gnu_ld_CXX" | $SED "$delay_single_quote_subst"`' allow_undefined_flag_CXX='`$ECHO "$allow_undefined_flag_CXX" | $SED "$delay_single_quote_subst"`' no_undefined_flag_CXX='`$ECHO "$no_undefined_flag_CXX" | $SED "$delay_single_quote_subst"`' hardcode_libdir_flag_spec_CXX='`$ECHO "$hardcode_libdir_flag_spec_CXX" | $SED "$delay_single_quote_subst"`' hardcode_libdir_separator_CXX='`$ECHO "$hardcode_libdir_separator_CXX" | $SED "$delay_single_quote_subst"`' hardcode_direct_CXX='`$ECHO "$hardcode_direct_CXX" | $SED "$delay_single_quote_subst"`' hardcode_direct_absolute_CXX='`$ECHO "$hardcode_direct_absolute_CXX" | $SED "$delay_single_quote_subst"`' hardcode_minus_L_CXX='`$ECHO "$hardcode_minus_L_CXX" | $SED "$delay_single_quote_subst"`' hardcode_shlibpath_var_CXX='`$ECHO "$hardcode_shlibpath_var_CXX" | $SED "$delay_single_quote_subst"`' hardcode_automatic_CXX='`$ECHO "$hardcode_automatic_CXX" | $SED "$delay_single_quote_subst"`' inherit_rpath_CXX='`$ECHO "$inherit_rpath_CXX" | $SED "$delay_single_quote_subst"`' link_all_deplibs_CXX='`$ECHO "$link_all_deplibs_CXX" | $SED "$delay_single_quote_subst"`' always_export_symbols_CXX='`$ECHO "$always_export_symbols_CXX" | $SED "$delay_single_quote_subst"`' export_symbols_cmds_CXX='`$ECHO "$export_symbols_cmds_CXX" | $SED "$delay_single_quote_subst"`' exclude_expsyms_CXX='`$ECHO "$exclude_expsyms_CXX" | $SED "$delay_single_quote_subst"`' include_expsyms_CXX='`$ECHO "$include_expsyms_CXX" | $SED "$delay_single_quote_subst"`' prelink_cmds_CXX='`$ECHO "$prelink_cmds_CXX" | $SED "$delay_single_quote_subst"`' postlink_cmds_CXX='`$ECHO "$postlink_cmds_CXX" | $SED "$delay_single_quote_subst"`' file_list_spec_CXX='`$ECHO "$file_list_spec_CXX" | $SED "$delay_single_quote_subst"`' hardcode_action_CXX='`$ECHO "$hardcode_action_CXX" | $SED "$delay_single_quote_subst"`' compiler_lib_search_dirs_CXX='`$ECHO "$compiler_lib_search_dirs_CXX" | $SED "$delay_single_quote_subst"`' predep_objects_CXX='`$ECHO "$predep_objects_CXX" | $SED "$delay_single_quote_subst"`' postdep_objects_CXX='`$ECHO "$postdep_objects_CXX" | $SED "$delay_single_quote_subst"`' predeps_CXX='`$ECHO "$predeps_CXX" | $SED "$delay_single_quote_subst"`' postdeps_CXX='`$ECHO "$postdeps_CXX" | $SED "$delay_single_quote_subst"`' compiler_lib_search_path_CXX='`$ECHO "$compiler_lib_search_path_CXX" | $SED "$delay_single_quote_subst"`' LTCC='$LTCC' LTCFLAGS='$LTCFLAGS' compiler='$compiler_DEFAULT' # A function that is used when there is no print builtin or printf. func_fallback_echo () { eval 'cat <<_LTECHO_EOF \$1 _LTECHO_EOF' } # Quote evaled strings. for var in AS \ DLLTOOL \ OBJDUMP \ SHELL \ ECHO \ PATH_SEPARATOR \ SED \ GREP \ EGREP \ FGREP \ LD \ NM \ LN_S \ lt_SP2NL \ lt_NL2SP \ reload_flag \ deplibs_check_method \ file_magic_cmd \ file_magic_glob \ want_nocaseglob \ sharedlib_from_linklib_cmd \ AR \ AR_FLAGS \ archiver_list_spec \ STRIP \ RANLIB \ CC \ CFLAGS \ compiler \ lt_cv_sys_global_symbol_pipe \ lt_cv_sys_global_symbol_to_cdecl \ lt_cv_sys_global_symbol_to_c_name_address \ lt_cv_sys_global_symbol_to_c_name_address_lib_prefix \ nm_file_list_spec \ lt_prog_compiler_no_builtin_flag \ lt_prog_compiler_pic \ lt_prog_compiler_wl \ lt_prog_compiler_static \ lt_cv_prog_compiler_c_o \ need_locks \ MANIFEST_TOOL \ DSYMUTIL \ NMEDIT \ LIPO \ OTOOL \ OTOOL64 \ shrext_cmds \ export_dynamic_flag_spec \ whole_archive_flag_spec \ compiler_needs_object \ with_gnu_ld \ allow_undefined_flag \ no_undefined_flag \ hardcode_libdir_flag_spec \ hardcode_libdir_separator \ exclude_expsyms \ include_expsyms \ file_list_spec \ variables_saved_for_relink \ libname_spec \ library_names_spec \ soname_spec \ install_override_mode \ finish_eval \ old_striplib \ striplib \ compiler_lib_search_dirs \ predep_objects \ postdep_objects \ predeps \ postdeps \ compiler_lib_search_path \ LD_CXX \ reload_flag_CXX \ compiler_CXX \ lt_prog_compiler_no_builtin_flag_CXX \ lt_prog_compiler_pic_CXX \ lt_prog_compiler_wl_CXX \ lt_prog_compiler_static_CXX \ lt_cv_prog_compiler_c_o_CXX \ export_dynamic_flag_spec_CXX \ whole_archive_flag_spec_CXX \ compiler_needs_object_CXX \ with_gnu_ld_CXX \ allow_undefined_flag_CXX \ no_undefined_flag_CXX \ hardcode_libdir_flag_spec_CXX \ hardcode_libdir_separator_CXX \ exclude_expsyms_CXX \ include_expsyms_CXX \ file_list_spec_CXX \ compiler_lib_search_dirs_CXX \ predep_objects_CXX \ postdep_objects_CXX \ predeps_CXX \ postdeps_CXX \ compiler_lib_search_path_CXX; do case \`eval \\\\\$ECHO \\\\""\\\\\$\$var"\\\\"\` in *[\\\\\\\`\\"\\\$]*) eval "lt_\$var=\\\\\\"\\\`\\\$ECHO \\"\\\$\$var\\" | \\\$SED \\"\\\$sed_quote_subst\\"\\\`\\\\\\"" ;; *) eval "lt_\$var=\\\\\\"\\\$\$var\\\\\\"" ;; esac done # Double-quote double-evaled strings. for var in reload_cmds \ old_postinstall_cmds \ old_postuninstall_cmds \ old_archive_cmds \ extract_expsyms_cmds \ old_archive_from_new_cmds \ old_archive_from_expsyms_cmds \ archive_cmds \ archive_expsym_cmds \ module_cmds \ module_expsym_cmds \ export_symbols_cmds \ prelink_cmds \ postlink_cmds \ postinstall_cmds \ postuninstall_cmds \ finish_cmds \ sys_lib_search_path_spec \ sys_lib_dlsearch_path_spec \ reload_cmds_CXX \ old_archive_cmds_CXX \ old_archive_from_new_cmds_CXX \ old_archive_from_expsyms_cmds_CXX \ archive_cmds_CXX \ archive_expsym_cmds_CXX \ module_cmds_CXX \ module_expsym_cmds_CXX \ export_symbols_cmds_CXX \ prelink_cmds_CXX \ postlink_cmds_CXX; do case \`eval \\\\\$ECHO \\\\""\\\\\$\$var"\\\\"\` in *[\\\\\\\`\\"\\\$]*) eval "lt_\$var=\\\\\\"\\\`\\\$ECHO \\"\\\$\$var\\" | \\\$SED -e \\"\\\$double_quote_subst\\" -e \\"\\\$sed_quote_subst\\" -e \\"\\\$delay_variable_subst\\"\\\`\\\\\\"" ;; *) eval "lt_\$var=\\\\\\"\\\$\$var\\\\\\"" ;; esac done ac_aux_dir='$ac_aux_dir' xsi_shell='$xsi_shell' lt_shell_append='$lt_shell_append' # See if we are running on zsh, and set the options which allow our # commands through without removal of \ escapes INIT. if test -n "\${ZSH_VERSION+set}" ; then setopt NO_GLOB_SUBST fi PACKAGE='$PACKAGE' VERSION='$VERSION' TIMESTAMP='$TIMESTAMP' RM='$RM' ofile='$ofile' _ACEOF cat >>$CONFIG_STATUS <<\_ACEOF || ac_write_fail=1 # Handling of arguments. for ac_config_target in $ac_config_targets do case $ac_config_target in "config.h") CONFIG_HEADERS="$CONFIG_HEADERS config.h" ;; "src/snappy/google-snappy/config.h") CONFIG_HEADERS="$CONFIG_HEADERS src/snappy/google-snappy/config.h" ;; "depfiles") CONFIG_COMMANDS="$CONFIG_COMMANDS depfiles" ;; "libtool") CONFIG_COMMANDS="$CONFIG_COMMANDS libtool" ;; "Makefile") CONFIG_FILES="$CONFIG_FILES Makefile" ;; "bin/couch-config.tpl") CONFIG_FILES="$CONFIG_FILES bin/couch-config.tpl" ;; "bin/couchdb.tpl") CONFIG_FILES="$CONFIG_FILES bin/couchdb.tpl" ;; "bin/couchdb.bat.tpl") CONFIG_FILES="$CONFIG_FILES bin/couchdb.bat.tpl" ;; "bin/Makefile") CONFIG_FILES="$CONFIG_FILES bin/Makefile" ;; "etc/couchdb/Makefile") CONFIG_FILES="$CONFIG_FILES etc/couchdb/Makefile" ;; "etc/couchdb/default.ini.tpl") CONFIG_FILES="$CONFIG_FILES etc/couchdb/default.ini.tpl" ;; "etc/default/Makefile") CONFIG_FILES="$CONFIG_FILES etc/default/Makefile" ;; "etc/init/couchdb.tpl") CONFIG_FILES="$CONFIG_FILES etc/init/couchdb.tpl" ;; "etc/init/Makefile") CONFIG_FILES="$CONFIG_FILES etc/init/Makefile" ;; "etc/launchd/org.apache.couchdb.plist.tpl") CONFIG_FILES="$CONFIG_FILES etc/launchd/org.apache.couchdb.plist.tpl" ;; "etc/launchd/Makefile") CONFIG_FILES="$CONFIG_FILES etc/launchd/Makefile" ;; "etc/logrotate.d/couchdb.tpl") CONFIG_FILES="$CONFIG_FILES etc/logrotate.d/couchdb.tpl" ;; "etc/logrotate.d/Makefile") CONFIG_FILES="$CONFIG_FILES etc/logrotate.d/Makefile" ;; "etc/windows/Makefile") CONFIG_FILES="$CONFIG_FILES etc/windows/Makefile" ;; "etc/Makefile") CONFIG_FILES="$CONFIG_FILES etc/Makefile" ;; "share/Makefile") CONFIG_FILES="$CONFIG_FILES share/Makefile" ;; "share/doc/Makefile") CONFIG_FILES="$CONFIG_FILES share/doc/Makefile" ;; "share/doc/build/Makefile") CONFIG_FILES="$CONFIG_FILES share/doc/build/Makefile" ;; "src/Makefile") CONFIG_FILES="$CONFIG_FILES src/Makefile" ;; "src/couch_dbupdates/Makefile") CONFIG_FILES="$CONFIG_FILES src/couch_dbupdates/Makefile" ;; "src/couch_index/Makefile") CONFIG_FILES="$CONFIG_FILES src/couch_index/Makefile" ;; "src/couch_mrview/Makefile") CONFIG_FILES="$CONFIG_FILES src/couch_mrview/Makefile" ;; "src/couch_plugins/Makefile") CONFIG_FILES="$CONFIG_FILES src/couch_plugins/Makefile" ;; "src/couch_replicator/Makefile") CONFIG_FILES="$CONFIG_FILES src/couch_replicator/Makefile" ;; "src/couchjs-node/Makefile") CONFIG_FILES="$CONFIG_FILES src/couchjs-node/Makefile" ;; "src/couchdb/couch.app.tpl") CONFIG_FILES="$CONFIG_FILES src/couchdb/couch.app.tpl" ;; "src/couchdb/Makefile") CONFIG_FILES="$CONFIG_FILES src/couchdb/Makefile" ;; "src/couchdb/priv/Makefile") CONFIG_FILES="$CONFIG_FILES src/couchdb/priv/Makefile" ;; "src/erlang-oauth/Makefile") CONFIG_FILES="$CONFIG_FILES src/erlang-oauth/Makefile" ;; "src/etap/Makefile") CONFIG_FILES="$CONFIG_FILES src/etap/Makefile" ;; "src/ibrowse/Makefile") CONFIG_FILES="$CONFIG_FILES src/ibrowse/Makefile" ;; "src/mochiweb/Makefile") CONFIG_FILES="$CONFIG_FILES src/mochiweb/Makefile" ;; "src/snappy/Makefile") CONFIG_FILES="$CONFIG_FILES src/snappy/Makefile" ;; "src/snappy/google-snappy/snappy-stubs-public.h") CONFIG_FILES="$CONFIG_FILES src/snappy/google-snappy/snappy-stubs-public.h" ;; "src/ejson/Makefile") CONFIG_FILES="$CONFIG_FILES src/ejson/Makefile" ;; "test/Makefile") CONFIG_FILES="$CONFIG_FILES test/Makefile" ;; "test/bench/Makefile") CONFIG_FILES="$CONFIG_FILES test/bench/Makefile" ;; "test/etap/Makefile") CONFIG_FILES="$CONFIG_FILES test/etap/Makefile" ;; "test/etap/test_util.erl") CONFIG_FILES="$CONFIG_FILES test/etap/test_util.erl" ;; "test/javascript/Makefile") CONFIG_FILES="$CONFIG_FILES test/javascript/Makefile" ;; "test/view_server/Makefile") CONFIG_FILES="$CONFIG_FILES test/view_server/Makefile" ;; "utils/Makefile") CONFIG_FILES="$CONFIG_FILES utils/Makefile" ;; "var/Makefile") CONFIG_FILES="$CONFIG_FILES var/Makefile" ;; *) as_fn_error $? "invalid argument: \`$ac_config_target'" "$LINENO" 5;; esac done # If the user did not use the arguments to specify the items to instantiate, # then the envvar interface is used. Set only those that are not. # We use the long form for the default assignment because of an extremely # bizarre bug on SunOS 4.1.3. if $ac_need_defaults; then test "${CONFIG_FILES+set}" = set || CONFIG_FILES=$config_files test "${CONFIG_HEADERS+set}" = set || CONFIG_HEADERS=$config_headers test "${CONFIG_COMMANDS+set}" = set || CONFIG_COMMANDS=$config_commands fi # Have a temporary directory for convenience. Make it in the build tree # simply because there is no reason against having it here, and in addition, # creating and moving files from /tmp can sometimes cause problems. # Hook for its removal unless debugging. # Note that there is a small window in which the directory will not be cleaned: # after its creation but before its name has been assigned to `$tmp'. $debug || { tmp= ac_tmp= trap 'exit_status=$? : "${ac_tmp:=$tmp}" { test ! -d "$ac_tmp" || rm -fr "$ac_tmp"; } && exit $exit_status ' 0 trap 'as_fn_exit 1' 1 2 13 15 } # Create a (secure) tmp directory for tmp files. { tmp=`(umask 077 && mktemp -d "./confXXXXXX") 2>/dev/null` && test -d "$tmp" } || { tmp=./conf$$-$RANDOM (umask 077 && mkdir "$tmp") } || as_fn_error $? "cannot create a temporary directory in ." "$LINENO" 5 ac_tmp=$tmp # Set up the scripts for CONFIG_FILES section. # No need to generate them if there are no CONFIG_FILES. # This happens for instance with `./config.status config.h'. if test -n "$CONFIG_FILES"; then ac_cr=`echo X | tr X '\015'` # On cygwin, bash can eat \r inside `` if the user requested igncr. # But we know of no other shell where ac_cr would be empty at this # point, so we can use a bashism as a fallback. if test "x$ac_cr" = x; then eval ac_cr=\$\'\\r\' fi ac_cs_awk_cr=`$AWK 'BEGIN { print "a\rb" }' /dev/null` if test "$ac_cs_awk_cr" = "a${ac_cr}b"; then ac_cs_awk_cr='\\r' else ac_cs_awk_cr=$ac_cr fi echo 'BEGIN {' >"$ac_tmp/subs1.awk" && _ACEOF { echo "cat >conf$$subs.awk <<_ACEOF" && echo "$ac_subst_vars" | sed 's/.*/&!$&$ac_delim/' && echo "_ACEOF" } >conf$$subs.sh || as_fn_error $? "could not make $CONFIG_STATUS" "$LINENO" 5 ac_delim_num=`echo "$ac_subst_vars" | grep -c '^'` ac_delim='%!_!# ' for ac_last_try in false false false false false :; do . ./conf$$subs.sh || as_fn_error $? "could not make $CONFIG_STATUS" "$LINENO" 5 ac_delim_n=`sed -n "s/.*$ac_delim\$/X/p" conf$$subs.awk | grep -c X` if test $ac_delim_n = $ac_delim_num; then break elif $ac_last_try; then as_fn_error $? "could not make $CONFIG_STATUS" "$LINENO" 5 else ac_delim="$ac_delim!$ac_delim _$ac_delim!! " fi done rm -f conf$$subs.sh cat >>$CONFIG_STATUS <<_ACEOF || ac_write_fail=1 cat >>"\$ac_tmp/subs1.awk" <<\\_ACAWK && _ACEOF sed -n ' h s/^/S["/; s/!.*/"]=/ p g s/^[^!]*!// :repl t repl s/'"$ac_delim"'$// t delim :nl h s/\(.\{148\}\)..*/\1/ t more1 s/["\\]/\\&/g; s/^/"/; s/$/\\n"\\/ p n b repl :more1 s/["\\]/\\&/g; s/^/"/; s/$/"\\/ p g s/.\{148\}// t nl :delim h s/\(.\{148\}\)..*/\1/ t more2 s/["\\]/\\&/g; s/^/"/; s/$/"/ p b :more2 s/["\\]/\\&/g; s/^/"/; s/$/"\\/ p g s/.\{148\}// t delim ' >$CONFIG_STATUS || ac_write_fail=1 rm -f conf$$subs.awk cat >>$CONFIG_STATUS <<_ACEOF || ac_write_fail=1 _ACAWK cat >>"\$ac_tmp/subs1.awk" <<_ACAWK && for (key in S) S_is_set[key] = 1 FS = "" } { line = $ 0 nfields = split(line, field, "@") substed = 0 len = length(field[1]) for (i = 2; i < nfields; i++) { key = field[i] keylen = length(key) if (S_is_set[key]) { value = S[key] line = substr(line, 1, len) "" value "" substr(line, len + keylen + 3) len += length(value) + length(field[++i]) substed = 1 } else len += 1 + keylen } print line } _ACAWK _ACEOF cat >>$CONFIG_STATUS <<\_ACEOF || ac_write_fail=1 if sed "s/$ac_cr//" < /dev/null > /dev/null 2>&1; then sed "s/$ac_cr\$//; s/$ac_cr/$ac_cs_awk_cr/g" else cat fi < "$ac_tmp/subs1.awk" > "$ac_tmp/subs.awk" \ || as_fn_error $? "could not setup config files machinery" "$LINENO" 5 _ACEOF # VPATH may cause trouble with some makes, so we remove sole $(srcdir), # ${srcdir} and @srcdir@ entries from VPATH if srcdir is ".", strip leading and # trailing colons and then remove the whole line if VPATH becomes empty # (actually we leave an empty line to preserve line numbers). if test "x$srcdir" = x.; then ac_vpsub='/^[ ]*VPATH[ ]*=[ ]*/{ h s/// s/^/:/ s/[ ]*$/:/ s/:\$(srcdir):/:/g s/:\${srcdir}:/:/g s/:@srcdir@:/:/g s/^:*// s/:*$// x s/\(=[ ]*\).*/\1/ G s/\n// s/^[^=]*=[ ]*$// }' fi cat >>$CONFIG_STATUS <<\_ACEOF || ac_write_fail=1 fi # test -n "$CONFIG_FILES" # Set up the scripts for CONFIG_HEADERS section. # No need to generate them if there are no CONFIG_HEADERS. # This happens for instance with `./config.status Makefile'. if test -n "$CONFIG_HEADERS"; then cat >"$ac_tmp/defines.awk" <<\_ACAWK || BEGIN { _ACEOF # Transform confdefs.h into an awk script `defines.awk', embedded as # here-document in config.status, that substitutes the proper values into # config.h.in to produce config.h. # Create a delimiter string that does not exist in confdefs.h, to ease # handling of long lines. ac_delim='%!_!# ' for ac_last_try in false false :; do ac_tt=`sed -n "/$ac_delim/p" confdefs.h` if test -z "$ac_tt"; then break elif $ac_last_try; then as_fn_error $? "could not make $CONFIG_HEADERS" "$LINENO" 5 else ac_delim="$ac_delim!$ac_delim _$ac_delim!! " fi done # For the awk script, D is an array of macro values keyed by name, # likewise P contains macro parameters if any. Preserve backslash # newline sequences. ac_word_re=[_$as_cr_Letters][_$as_cr_alnum]* sed -n ' s/.\{148\}/&'"$ac_delim"'/g t rset :rset s/^[ ]*#[ ]*define[ ][ ]*/ / t def d :def s/\\$// t bsnl s/["\\]/\\&/g s/^ \('"$ac_word_re"'\)\(([^()]*)\)[ ]*\(.*\)/P["\1"]="\2"\ D["\1"]=" \3"/p s/^ \('"$ac_word_re"'\)[ ]*\(.*\)/D["\1"]=" \2"/p d :bsnl s/["\\]/\\&/g s/^ \('"$ac_word_re"'\)\(([^()]*)\)[ ]*\(.*\)/P["\1"]="\2"\ D["\1"]=" \3\\\\\\n"\\/p t cont s/^ \('"$ac_word_re"'\)[ ]*\(.*\)/D["\1"]=" \2\\\\\\n"\\/p t cont d :cont n s/.\{148\}/&'"$ac_delim"'/g t clear :clear s/\\$// t bsnlc s/["\\]/\\&/g; s/^/"/; s/$/"/p d :bsnlc s/["\\]/\\&/g; s/^/"/; s/$/\\\\\\n"\\/p b cont ' >$CONFIG_STATUS || ac_write_fail=1 cat >>$CONFIG_STATUS <<_ACEOF || ac_write_fail=1 for (key in D) D_is_set[key] = 1 FS = "" } /^[\t ]*#[\t ]*(define|undef)[\t ]+$ac_word_re([\t (]|\$)/ { line = \$ 0 split(line, arg, " ") if (arg[1] == "#") { defundef = arg[2] mac1 = arg[3] } else { defundef = substr(arg[1], 2) mac1 = arg[2] } split(mac1, mac2, "(") #) macro = mac2[1] prefix = substr(line, 1, index(line, defundef) - 1) if (D_is_set[macro]) { # Preserve the white space surrounding the "#". print prefix "define", macro P[macro] D[macro] next } else { # Replace #undef with comments. This is necessary, for example, # in the case of _POSIX_SOURCE, which is predefined and required # on some systems where configure will not decide to define it. if (defundef == "undef") { print "/*", prefix defundef, macro, "*/" next } } } { print } _ACAWK _ACEOF cat >>$CONFIG_STATUS <<\_ACEOF || ac_write_fail=1 as_fn_error $? "could not setup config headers machinery" "$LINENO" 5 fi # test -n "$CONFIG_HEADERS" eval set X " :F $CONFIG_FILES :H $CONFIG_HEADERS :C $CONFIG_COMMANDS" shift for ac_tag do case $ac_tag in :[FHLC]) ac_mode=$ac_tag; continue;; esac case $ac_mode$ac_tag in :[FHL]*:*);; :L* | :C*:*) as_fn_error $? "invalid tag \`$ac_tag'" "$LINENO" 5;; :[FH]-) ac_tag=-:-;; :[FH]*) ac_tag=$ac_tag:$ac_tag.in;; esac ac_save_IFS=$IFS IFS=: set x $ac_tag IFS=$ac_save_IFS shift ac_file=$1 shift case $ac_mode in :L) ac_source=$1;; :[FH]) ac_file_inputs= for ac_f do case $ac_f in -) ac_f="$ac_tmp/stdin";; *) # Look for the file first in the build tree, then in the source tree # (if the path is not absolute). The absolute path cannot be DOS-style, # because $ac_f cannot contain `:'. test -f "$ac_f" || case $ac_f in [\\/$]*) false;; *) test -f "$srcdir/$ac_f" && ac_f="$srcdir/$ac_f";; esac || as_fn_error 1 "cannot find input file: \`$ac_f'" "$LINENO" 5;; esac case $ac_f in *\'*) ac_f=`$as_echo "$ac_f" | sed "s/'/'\\\\\\\\''/g"`;; esac as_fn_append ac_file_inputs " '$ac_f'" done # Let's still pretend it is `configure' which instantiates (i.e., don't # use $as_me), people would be surprised to read: # /* config.h. Generated by config.status. */ configure_input='Generated from '` $as_echo "$*" | sed 's|^[^:]*/||;s|:[^:]*/|, |g' `' by configure.' if test x"$ac_file" != x-; then configure_input="$ac_file. $configure_input" { $as_echo "$as_me:${as_lineno-$LINENO}: creating $ac_file" >&5 $as_echo "$as_me: creating $ac_file" >&6;} fi # Neutralize special characters interpreted by sed in replacement strings. case $configure_input in #( *\&* | *\|* | *\\* ) ac_sed_conf_input=`$as_echo "$configure_input" | sed 's/[\\\\&|]/\\\\&/g'`;; #( *) ac_sed_conf_input=$configure_input;; esac case $ac_tag in *:-:* | *:-) cat >"$ac_tmp/stdin" \ || as_fn_error $? "could not create $ac_file" "$LINENO" 5 ;; esac ;; esac ac_dir=`$as_dirname -- "$ac_file" || $as_expr X"$ac_file" : 'X\(.*[^/]\)//*[^/][^/]*/*$' \| \ X"$ac_file" : 'X\(//\)[^/]' \| \ X"$ac_file" : 'X\(//\)$' \| \ X"$ac_file" : 'X\(/\)' \| . 2>/dev/null || $as_echo X"$ac_file" | sed '/^X\(.*[^/]\)\/\/*[^/][^/]*\/*$/{ s//\1/ q } /^X\(\/\/\)[^/].*/{ s//\1/ q } /^X\(\/\/\)$/{ s//\1/ q } /^X\(\/\).*/{ s//\1/ q } s/.*/./; q'` as_dir="$ac_dir"; as_fn_mkdir_p ac_builddir=. case "$ac_dir" in .) ac_dir_suffix= ac_top_builddir_sub=. ac_top_build_prefix= ;; *) ac_dir_suffix=/`$as_echo "$ac_dir" | sed 's|^\.[\\/]||'` # A ".." for each directory in $ac_dir_suffix. ac_top_builddir_sub=`$as_echo "$ac_dir_suffix" | sed 's|/[^\\/]*|/..|g;s|/||'` case $ac_top_builddir_sub in "") ac_top_builddir_sub=. ac_top_build_prefix= ;; *) ac_top_build_prefix=$ac_top_builddir_sub/ ;; esac ;; esac ac_abs_top_builddir=$ac_pwd ac_abs_builddir=$ac_pwd$ac_dir_suffix # for backward compatibility: ac_top_builddir=$ac_top_build_prefix case $srcdir in .) # We are building in place. ac_srcdir=. ac_top_srcdir=$ac_top_builddir_sub ac_abs_top_srcdir=$ac_pwd ;; [\\/]* | ?:[\\/]* ) # Absolute name. ac_srcdir=$srcdir$ac_dir_suffix; ac_top_srcdir=$srcdir ac_abs_top_srcdir=$srcdir ;; *) # Relative name. ac_srcdir=$ac_top_build_prefix$srcdir$ac_dir_suffix ac_top_srcdir=$ac_top_build_prefix$srcdir ac_abs_top_srcdir=$ac_pwd/$srcdir ;; esac ac_abs_srcdir=$ac_abs_top_srcdir$ac_dir_suffix case $ac_mode in :F) # # CONFIG_FILE # case $INSTALL in [\\/$]* | ?:[\\/]* ) ac_INSTALL=$INSTALL ;; *) ac_INSTALL=$ac_top_build_prefix$INSTALL ;; esac ac_MKDIR_P=$MKDIR_P case $MKDIR_P in [\\/$]* | ?:[\\/]* ) ;; */*) ac_MKDIR_P=$ac_top_build_prefix$MKDIR_P ;; esac _ACEOF cat >>$CONFIG_STATUS <<\_ACEOF || ac_write_fail=1 # If the template does not know about datarootdir, expand it. # FIXME: This hack should be removed a few years after 2.60. ac_datarootdir_hack=; ac_datarootdir_seen= ac_sed_dataroot=' /datarootdir/ { p q } /@datadir@/p /@docdir@/p /@infodir@/p /@localedir@/p /@mandir@/p' case `eval "sed -n \"\$ac_sed_dataroot\" $ac_file_inputs"` in *datarootdir*) ac_datarootdir_seen=yes;; *@datadir@*|*@docdir@*|*@infodir@*|*@localedir@*|*@mandir@*) { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: $ac_file_inputs seems to ignore the --datarootdir setting" >&5 $as_echo "$as_me: WARNING: $ac_file_inputs seems to ignore the --datarootdir setting" >&2;} _ACEOF cat >>$CONFIG_STATUS <<_ACEOF || ac_write_fail=1 ac_datarootdir_hack=' s&@datadir@&$datadir&g s&@docdir@&$docdir&g s&@infodir@&$infodir&g s&@localedir@&$localedir&g s&@mandir@&$mandir&g s&\\\${datarootdir}&$datarootdir&g' ;; esac _ACEOF # Neutralize VPATH when `$srcdir' = `.'. # Shell code in configure.ac might set extrasub. # FIXME: do we really want to maintain this feature? cat >>$CONFIG_STATUS <<_ACEOF || ac_write_fail=1 ac_sed_extra="$ac_vpsub $extrasub _ACEOF cat >>$CONFIG_STATUS <<\_ACEOF || ac_write_fail=1 :t /@[a-zA-Z_][a-zA-Z_0-9]*@/!b s|@configure_input@|$ac_sed_conf_input|;t t s&@top_builddir@&$ac_top_builddir_sub&;t t s&@top_build_prefix@&$ac_top_build_prefix&;t t s&@srcdir@&$ac_srcdir&;t t s&@abs_srcdir@&$ac_abs_srcdir&;t t s&@top_srcdir@&$ac_top_srcdir&;t t s&@abs_top_srcdir@&$ac_abs_top_srcdir&;t t s&@builddir@&$ac_builddir&;t t s&@abs_builddir@&$ac_abs_builddir&;t t s&@abs_top_builddir@&$ac_abs_top_builddir&;t t s&@INSTALL@&$ac_INSTALL&;t t s&@MKDIR_P@&$ac_MKDIR_P&;t t $ac_datarootdir_hack " eval sed \"\$ac_sed_extra\" "$ac_file_inputs" | $AWK -f "$ac_tmp/subs.awk" \ >$ac_tmp/out || as_fn_error $? "could not create $ac_file" "$LINENO" 5 test -z "$ac_datarootdir_hack$ac_datarootdir_seen" && { ac_out=`sed -n '/\${datarootdir}/p' "$ac_tmp/out"`; test -n "$ac_out"; } && { ac_out=`sed -n '/^[ ]*datarootdir[ ]*:*=/p' \ "$ac_tmp/out"`; test -z "$ac_out"; } && { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: $ac_file contains a reference to the variable \`datarootdir' which seems to be undefined. Please make sure it is defined" >&5 $as_echo "$as_me: WARNING: $ac_file contains a reference to the variable \`datarootdir' which seems to be undefined. Please make sure it is defined" >&2;} rm -f "$ac_tmp/stdin" case $ac_file in -) cat "$ac_tmp/out" && rm -f "$ac_tmp/out";; *) rm -f "$ac_file" && mv "$ac_tmp/out" "$ac_file";; esac \ || as_fn_error $? "could not create $ac_file" "$LINENO" 5 ;; :H) # # CONFIG_HEADER # if test x"$ac_file" != x-; then { $as_echo "/* $configure_input */" \ && eval '$AWK -f "$ac_tmp/defines.awk"' "$ac_file_inputs" } >"$ac_tmp/config.h" \ || as_fn_error $? "could not create $ac_file" "$LINENO" 5 if diff "$ac_file" "$ac_tmp/config.h" >/dev/null 2>&1; then { $as_echo "$as_me:${as_lineno-$LINENO}: $ac_file is unchanged" >&5 $as_echo "$as_me: $ac_file is unchanged" >&6;} else rm -f "$ac_file" mv "$ac_tmp/config.h" "$ac_file" \ || as_fn_error $? "could not create $ac_file" "$LINENO" 5 fi else $as_echo "/* $configure_input */" \ && eval '$AWK -f "$ac_tmp/defines.awk"' "$ac_file_inputs" \ || as_fn_error $? "could not create -" "$LINENO" 5 fi # Compute "$ac_file"'s index in $config_headers. _am_arg="$ac_file" _am_stamp_count=1 for _am_header in $config_headers :; do case $_am_header in $_am_arg | $_am_arg:* ) break ;; * ) _am_stamp_count=`expr $_am_stamp_count + 1` ;; esac done echo "timestamp for $_am_arg" >`$as_dirname -- "$_am_arg" || $as_expr X"$_am_arg" : 'X\(.*[^/]\)//*[^/][^/]*/*$' \| \ X"$_am_arg" : 'X\(//\)[^/]' \| \ X"$_am_arg" : 'X\(//\)$' \| \ X"$_am_arg" : 'X\(/\)' \| . 2>/dev/null || $as_echo X"$_am_arg" | sed '/^X\(.*[^/]\)\/\/*[^/][^/]*\/*$/{ s//\1/ q } /^X\(\/\/\)[^/].*/{ s//\1/ q } /^X\(\/\/\)$/{ s//\1/ q } /^X\(\/\).*/{ s//\1/ q } s/.*/./; q'`/stamp-h$_am_stamp_count ;; :C) { $as_echo "$as_me:${as_lineno-$LINENO}: executing $ac_file commands" >&5 $as_echo "$as_me: executing $ac_file commands" >&6;} ;; esac case $ac_file$ac_mode in "depfiles":C) test x"$AMDEP_TRUE" != x"" || { # Autoconf 2.62 quotes --file arguments for eval, but not when files # are listed without --file. Let's play safe and only enable the eval # if we detect the quoting. case $CONFIG_FILES in *\'*) eval set x "$CONFIG_FILES" ;; *) set x $CONFIG_FILES ;; esac shift for mf do # Strip MF so we end up with the name of the file. mf=`echo "$mf" | sed -e 's/:.*$//'` # Check whether this is an Automake generated Makefile or not. # We used to match only the files named `Makefile.in', but # some people rename them; so instead we look at the file content. # Grep'ing the first line is not enough: some people post-process # each Makefile.in and add a new line on top of each file to say so. # Grep'ing the whole file is not good either: AIX grep has a line # limit of 2048, but all sed's we know have understand at least 4000. if sed -n 's,^#.*generated by automake.*,X,p' "$mf" | grep X >/dev/null 2>&1; then dirpart=`$as_dirname -- "$mf" || $as_expr X"$mf" : 'X\(.*[^/]\)//*[^/][^/]*/*$' \| \ X"$mf" : 'X\(//\)[^/]' \| \ X"$mf" : 'X\(//\)$' \| \ X"$mf" : 'X\(/\)' \| . 2>/dev/null || $as_echo X"$mf" | sed '/^X\(.*[^/]\)\/\/*[^/][^/]*\/*$/{ s//\1/ q } /^X\(\/\/\)[^/].*/{ s//\1/ q } /^X\(\/\/\)$/{ s//\1/ q } /^X\(\/\).*/{ s//\1/ q } s/.*/./; q'` else continue fi # Extract the definition of DEPDIR, am__include, and am__quote # from the Makefile without running `make'. DEPDIR=`sed -n 's/^DEPDIR = //p' < "$mf"` test -z "$DEPDIR" && continue am__include=`sed -n 's/^am__include = //p' < "$mf"` test -z "am__include" && continue am__quote=`sed -n 's/^am__quote = //p' < "$mf"` # When using ansi2knr, U may be empty or an underscore; expand it U=`sed -n 's/^U = //p' < "$mf"` # Find all dependency output files, they are included files with # $(DEPDIR) in their names. We invoke sed twice because it is the # simplest approach to changing $(DEPDIR) to its actual value in the # expansion. for file in `sed -n " s/^$am__include $am__quote\(.*(DEPDIR).*\)$am__quote"'$/\1/p' <"$mf" | \ sed -e 's/\$(DEPDIR)/'"$DEPDIR"'/g' -e 's/\$U/'"$U"'/g'`; do # Make sure the directory exists. test -f "$dirpart/$file" && continue fdir=`$as_dirname -- "$file" || $as_expr X"$file" : 'X\(.*[^/]\)//*[^/][^/]*/*$' \| \ X"$file" : 'X\(//\)[^/]' \| \ X"$file" : 'X\(//\)$' \| \ X"$file" : 'X\(/\)' \| . 2>/dev/null || $as_echo X"$file" | sed '/^X\(.*[^/]\)\/\/*[^/][^/]*\/*$/{ s//\1/ q } /^X\(\/\/\)[^/].*/{ s//\1/ q } /^X\(\/\/\)$/{ s//\1/ q } /^X\(\/\).*/{ s//\1/ q } s/.*/./; q'` as_dir=$dirpart/$fdir; as_fn_mkdir_p # echo "creating $dirpart/$file" echo '# dummy' > "$dirpart/$file" done done } ;; "libtool":C) # See if we are running on zsh, and set the options which allow our # commands through without removal of \ escapes. if test -n "${ZSH_VERSION+set}" ; then setopt NO_GLOB_SUBST fi cfgfile="${ofile}T" trap "$RM \"$cfgfile\"; exit 1" 1 2 15 $RM "$cfgfile" cat <<_LT_EOF >> "$cfgfile" #! $SHELL # `$ECHO "$ofile" | sed 's%^.*/%%'` - Provide generalized library-building support services. # Generated automatically by $as_me ($PACKAGE$TIMESTAMP) $VERSION # Libtool was configured on host `(hostname || uname -n) 2>/dev/null | sed 1q`: # NOTE: Changes made to this file will be lost: look at ltmain.sh. # # Copyright (C) 1996, 1997, 1998, 1999, 2000, 2001, 2003, 2004, 2005, # 2006, 2007, 2008, 2009, 2010, 2011 Free Software # Foundation, Inc. # Written by Gordon Matzigkeit, 1996 # # This file is part of GNU Libtool. # # GNU Libtool is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License as # published by the Free Software Foundation; either version 2 of # the License, or (at your option) any later version. # # As a special exception to the GNU General Public License, # if you distribute this file as part of a program or library that # is built using GNU Libtool, you may include this file under the # same distribution terms that you use for the rest of that program. # # GNU Libtool is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Libtool; see the file COPYING. If not, a copy # can be downloaded from http://www.gnu.org/licenses/gpl.html, or # obtained by writing to the Free Software Foundation, Inc., # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. # The names of the tagged configurations supported by this script. available_tags="CXX " # ### BEGIN LIBTOOL CONFIG # Whether or not to build shared libraries. build_libtool_libs=$enable_shared # Whether or not to build static libraries. build_old_libs=$enable_static # Which release of libtool.m4 was used? macro_version=$macro_version macro_revision=$macro_revision # Assembler program. AS=$lt_AS # DLL creation program. DLLTOOL=$lt_DLLTOOL # Object dumper program. OBJDUMP=$lt_OBJDUMP # What type of objects to build. pic_mode=$pic_mode # Whether or not to optimize for fast installation. fast_install=$enable_fast_install # Shell to use when invoking shell scripts. SHELL=$lt_SHELL # An echo program that protects backslashes. ECHO=$lt_ECHO # The PATH separator for the build system. PATH_SEPARATOR=$lt_PATH_SEPARATOR # The host system. host_alias=$host_alias host=$host host_os=$host_os # The build system. build_alias=$build_alias build=$build build_os=$build_os # A sed program that does not truncate output. SED=$lt_SED # Sed that helps us avoid accidentally triggering echo(1) options like -n. Xsed="\$SED -e 1s/^X//" # A grep program that handles long lines. GREP=$lt_GREP # An ERE matcher. EGREP=$lt_EGREP # A literal string matcher. FGREP=$lt_FGREP # A BSD- or MS-compatible name lister. NM=$lt_NM # Whether we need soft or hard links. LN_S=$lt_LN_S # What is the maximum length of a command? max_cmd_len=$max_cmd_len # Object file suffix (normally "o"). objext=$ac_objext # Executable file suffix (normally ""). exeext=$exeext # whether the shell understands "unset". lt_unset=$lt_unset # turn spaces into newlines. SP2NL=$lt_lt_SP2NL # turn newlines into spaces. NL2SP=$lt_lt_NL2SP # convert \$build file names to \$host format. to_host_file_cmd=$lt_cv_to_host_file_cmd # convert \$build files to toolchain format. to_tool_file_cmd=$lt_cv_to_tool_file_cmd # Method to check whether dependent libraries are shared objects. deplibs_check_method=$lt_deplibs_check_method # Command to use when deplibs_check_method = "file_magic". file_magic_cmd=$lt_file_magic_cmd # How to find potential files when deplibs_check_method = "file_magic". file_magic_glob=$lt_file_magic_glob # Find potential files using nocaseglob when deplibs_check_method = "file_magic". want_nocaseglob=$lt_want_nocaseglob # Command to associate shared and link libraries. sharedlib_from_linklib_cmd=$lt_sharedlib_from_linklib_cmd # The archiver. AR=$lt_AR # Flags to create an archive. AR_FLAGS=$lt_AR_FLAGS # How to feed a file listing to the archiver. archiver_list_spec=$lt_archiver_list_spec # A symbol stripping program. STRIP=$lt_STRIP # Commands used to install an old-style archive. RANLIB=$lt_RANLIB old_postinstall_cmds=$lt_old_postinstall_cmds old_postuninstall_cmds=$lt_old_postuninstall_cmds # Whether to use a lock for old archive extraction. lock_old_archive_extraction=$lock_old_archive_extraction # A C compiler. LTCC=$lt_CC # LTCC compiler flags. LTCFLAGS=$lt_CFLAGS # Take the output of nm and produce a listing of raw symbols and C names. global_symbol_pipe=$lt_lt_cv_sys_global_symbol_pipe # Transform the output of nm in a proper C declaration. global_symbol_to_cdecl=$lt_lt_cv_sys_global_symbol_to_cdecl # Transform the output of nm in a C name address pair. global_symbol_to_c_name_address=$lt_lt_cv_sys_global_symbol_to_c_name_address # Transform the output of nm in a C name address pair when lib prefix is needed. global_symbol_to_c_name_address_lib_prefix=$lt_lt_cv_sys_global_symbol_to_c_name_address_lib_prefix # Specify filename containing input files for \$NM. nm_file_list_spec=$lt_nm_file_list_spec # The root where to search for dependent libraries,and in which our libraries should be installed. lt_sysroot=$lt_sysroot # The name of the directory that contains temporary libtool files. objdir=$objdir # Used to examine libraries when file_magic_cmd begins with "file". MAGIC_CMD=$MAGIC_CMD # Must we lock files when doing compilation? need_locks=$lt_need_locks # Manifest tool. MANIFEST_TOOL=$lt_MANIFEST_TOOL # Tool to manipulate archived DWARF debug symbol files on Mac OS X. DSYMUTIL=$lt_DSYMUTIL # Tool to change global to local symbols on Mac OS X. NMEDIT=$lt_NMEDIT # Tool to manipulate fat objects and archives on Mac OS X. LIPO=$lt_LIPO # ldd/readelf like tool for Mach-O binaries on Mac OS X. OTOOL=$lt_OTOOL # ldd/readelf like tool for 64 bit Mach-O binaries on Mac OS X 10.4. OTOOL64=$lt_OTOOL64 # Old archive suffix (normally "a"). libext=$libext # Shared library suffix (normally ".so"). shrext_cmds=$lt_shrext_cmds # The commands to extract the exported symbol list from a shared archive. extract_expsyms_cmds=$lt_extract_expsyms_cmds # Variables whose values should be saved in libtool wrapper scripts and # restored at link time. variables_saved_for_relink=$lt_variables_saved_for_relink # Do we need the "lib" prefix for modules? need_lib_prefix=$need_lib_prefix # Do we need a version for libraries? need_version=$need_version # Library versioning type. version_type=$version_type # Shared library runtime path variable. runpath_var=$runpath_var # Shared library path variable. shlibpath_var=$shlibpath_var # Is shlibpath searched before the hard-coded library search path? shlibpath_overrides_runpath=$shlibpath_overrides_runpath # Format of library name prefix. libname_spec=$lt_libname_spec # List of archive names. First name is the real one, the rest are links. # The last name is the one that the linker finds with -lNAME library_names_spec=$lt_library_names_spec # The coded name of the library, if different from the real name. soname_spec=$lt_soname_spec # Permission mode override for installation of shared libraries. install_override_mode=$lt_install_override_mode # Command to use after installation of a shared archive. postinstall_cmds=$lt_postinstall_cmds # Command to use after uninstallation of a shared archive. postuninstall_cmds=$lt_postuninstall_cmds # Commands used to finish a libtool library installation in a directory. finish_cmds=$lt_finish_cmds # As "finish_cmds", except a single script fragment to be evaled but # not shown. finish_eval=$lt_finish_eval # Whether we should hardcode library paths into libraries. hardcode_into_libs=$hardcode_into_libs # Compile-time system search path for libraries. sys_lib_search_path_spec=$lt_sys_lib_search_path_spec # Run-time system search path for libraries. sys_lib_dlsearch_path_spec=$lt_sys_lib_dlsearch_path_spec # Whether dlopen is supported. dlopen_support=$enable_dlopen # Whether dlopen of programs is supported. dlopen_self=$enable_dlopen_self # Whether dlopen of statically linked programs is supported. dlopen_self_static=$enable_dlopen_self_static # Commands to strip libraries. old_striplib=$lt_old_striplib striplib=$lt_striplib # The linker used to build libraries. LD=$lt_LD # How to create reloadable object files. reload_flag=$lt_reload_flag reload_cmds=$lt_reload_cmds # Commands used to build an old-style archive. old_archive_cmds=$lt_old_archive_cmds # A language specific compiler. CC=$lt_compiler # Is the compiler the GNU compiler? with_gcc=$GCC # Compiler flag to turn off builtin functions. no_builtin_flag=$lt_lt_prog_compiler_no_builtin_flag # Additional compiler flags for building library objects. pic_flag=$lt_lt_prog_compiler_pic # How to pass a linker flag through the compiler. wl=$lt_lt_prog_compiler_wl # Compiler flag to prevent dynamic linking. link_static_flag=$lt_lt_prog_compiler_static # Does compiler simultaneously support -c and -o options? compiler_c_o=$lt_lt_cv_prog_compiler_c_o # Whether or not to add -lc for building shared libraries. build_libtool_need_lc=$archive_cmds_need_lc # Whether or not to disallow shared libs when runtime libs are static. allow_libtool_libs_with_static_runtimes=$enable_shared_with_static_runtimes # Compiler flag to allow reflexive dlopens. export_dynamic_flag_spec=$lt_export_dynamic_flag_spec # Compiler flag to generate shared objects directly from archives. whole_archive_flag_spec=$lt_whole_archive_flag_spec # Whether the compiler copes with passing no objects directly. compiler_needs_object=$lt_compiler_needs_object # Create an old-style archive from a shared archive. old_archive_from_new_cmds=$lt_old_archive_from_new_cmds # Create a temporary old-style archive to link instead of a shared archive. old_archive_from_expsyms_cmds=$lt_old_archive_from_expsyms_cmds # Commands used to build a shared archive. archive_cmds=$lt_archive_cmds archive_expsym_cmds=$lt_archive_expsym_cmds # Commands used to build a loadable module if different from building # a shared archive. module_cmds=$lt_module_cmds module_expsym_cmds=$lt_module_expsym_cmds # Whether we are building with GNU ld or not. with_gnu_ld=$lt_with_gnu_ld # Flag that allows shared libraries with undefined symbols to be built. allow_undefined_flag=$lt_allow_undefined_flag # Flag that enforces no undefined symbols. no_undefined_flag=$lt_no_undefined_flag # Flag to hardcode \$libdir into a binary during linking. # This must work even if \$libdir does not exist hardcode_libdir_flag_spec=$lt_hardcode_libdir_flag_spec # Whether we need a single "-rpath" flag with a separated argument. hardcode_libdir_separator=$lt_hardcode_libdir_separator # Set to "yes" if using DIR/libNAME\${shared_ext} during linking hardcodes # DIR into the resulting binary. hardcode_direct=$hardcode_direct # Set to "yes" if using DIR/libNAME\${shared_ext} during linking hardcodes # DIR into the resulting binary and the resulting library dependency is # "absolute",i.e impossible to change by setting \${shlibpath_var} if the # library is relocated. hardcode_direct_absolute=$hardcode_direct_absolute # Set to "yes" if using the -LDIR flag during linking hardcodes DIR # into the resulting binary. hardcode_minus_L=$hardcode_minus_L # Set to "yes" if using SHLIBPATH_VAR=DIR during linking hardcodes DIR # into the resulting binary. hardcode_shlibpath_var=$hardcode_shlibpath_var # Set to "yes" if building a shared library automatically hardcodes DIR # into the library and all subsequent libraries and executables linked # against it. hardcode_automatic=$hardcode_automatic # Set to yes if linker adds runtime paths of dependent libraries # to runtime path list. inherit_rpath=$inherit_rpath # Whether libtool must link a program against all its dependency libraries. link_all_deplibs=$link_all_deplibs # Set to "yes" if exported symbols are required. always_export_symbols=$always_export_symbols # The commands to list exported symbols. export_symbols_cmds=$lt_export_symbols_cmds # Symbols that should not be listed in the preloaded symbols. exclude_expsyms=$lt_exclude_expsyms # Symbols that must always be exported. include_expsyms=$lt_include_expsyms # Commands necessary for linking programs (against libraries) with templates. prelink_cmds=$lt_prelink_cmds # Commands necessary for finishing linking programs. postlink_cmds=$lt_postlink_cmds # Specify filename containing input files. file_list_spec=$lt_file_list_spec # How to hardcode a shared library path into an executable. hardcode_action=$hardcode_action # The directories searched by this compiler when creating a shared library. compiler_lib_search_dirs=$lt_compiler_lib_search_dirs # Dependencies to place before and after the objects being linked to # create a shared library. predep_objects=$lt_predep_objects postdep_objects=$lt_postdep_objects predeps=$lt_predeps postdeps=$lt_postdeps # The library search path used internally by the compiler when linking # a shared library. compiler_lib_search_path=$lt_compiler_lib_search_path # ### END LIBTOOL CONFIG _LT_EOF case $host_os in aix3*) cat <<\_LT_EOF >> "$cfgfile" # AIX sometimes has problems with the GCC collect2 program. For some # reason, if we set the COLLECT_NAMES environment variable, the problems # vanish in a puff of smoke. if test "X${COLLECT_NAMES+set}" != Xset; then COLLECT_NAMES= export COLLECT_NAMES fi _LT_EOF ;; esac ltmain="$ac_aux_dir/ltmain.sh" # We use sed instead of cat because bash on DJGPP gets confused if # if finds mixed CR/LF and LF-only lines. Since sed operates in # text mode, it properly converts lines to CR/LF. This bash problem # is reportedly fixed, but why not run on old versions too? sed '$q' "$ltmain" >> "$cfgfile" \ || (rm -f "$cfgfile"; exit 1) if test x"$xsi_shell" = xyes; then sed -e '/^func_dirname ()$/,/^} # func_dirname /c\ func_dirname ()\ {\ \ case ${1} in\ \ */*) func_dirname_result="${1%/*}${2}" ;;\ \ * ) func_dirname_result="${3}" ;;\ \ esac\ } # Extended-shell func_dirname implementation' "$cfgfile" > $cfgfile.tmp \ && mv -f "$cfgfile.tmp" "$cfgfile" \ || (rm -f "$cfgfile" && cp "$cfgfile.tmp" "$cfgfile" && rm -f "$cfgfile.tmp") test 0 -eq $? || _lt_function_replace_fail=: sed -e '/^func_basename ()$/,/^} # func_basename /c\ func_basename ()\ {\ \ func_basename_result="${1##*/}"\ } # Extended-shell func_basename implementation' "$cfgfile" > $cfgfile.tmp \ && mv -f "$cfgfile.tmp" "$cfgfile" \ || (rm -f "$cfgfile" && cp "$cfgfile.tmp" "$cfgfile" && rm -f "$cfgfile.tmp") test 0 -eq $? || _lt_function_replace_fail=: sed -e '/^func_dirname_and_basename ()$/,/^} # func_dirname_and_basename /c\ func_dirname_and_basename ()\ {\ \ case ${1} in\ \ */*) func_dirname_result="${1%/*}${2}" ;;\ \ * ) func_dirname_result="${3}" ;;\ \ esac\ \ func_basename_result="${1##*/}"\ } # Extended-shell func_dirname_and_basename implementation' "$cfgfile" > $cfgfile.tmp \ && mv -f "$cfgfile.tmp" "$cfgfile" \ || (rm -f "$cfgfile" && cp "$cfgfile.tmp" "$cfgfile" && rm -f "$cfgfile.tmp") test 0 -eq $? || _lt_function_replace_fail=: sed -e '/^func_stripname ()$/,/^} # func_stripname /c\ func_stripname ()\ {\ \ # pdksh 5.2.14 does not do ${X%$Y} correctly if both X and Y are\ \ # positional parameters, so assign one to ordinary parameter first.\ \ func_stripname_result=${3}\ \ func_stripname_result=${func_stripname_result#"${1}"}\ \ func_stripname_result=${func_stripname_result%"${2}"}\ } # Extended-shell func_stripname implementation' "$cfgfile" > $cfgfile.tmp \ && mv -f "$cfgfile.tmp" "$cfgfile" \ || (rm -f "$cfgfile" && cp "$cfgfile.tmp" "$cfgfile" && rm -f "$cfgfile.tmp") test 0 -eq $? || _lt_function_replace_fail=: sed -e '/^func_split_long_opt ()$/,/^} # func_split_long_opt /c\ func_split_long_opt ()\ {\ \ func_split_long_opt_name=${1%%=*}\ \ func_split_long_opt_arg=${1#*=}\ } # Extended-shell func_split_long_opt implementation' "$cfgfile" > $cfgfile.tmp \ && mv -f "$cfgfile.tmp" "$cfgfile" \ || (rm -f "$cfgfile" && cp "$cfgfile.tmp" "$cfgfile" && rm -f "$cfgfile.tmp") test 0 -eq $? || _lt_function_replace_fail=: sed -e '/^func_split_short_opt ()$/,/^} # func_split_short_opt /c\ func_split_short_opt ()\ {\ \ func_split_short_opt_arg=${1#??}\ \ func_split_short_opt_name=${1%"$func_split_short_opt_arg"}\ } # Extended-shell func_split_short_opt implementation' "$cfgfile" > $cfgfile.tmp \ && mv -f "$cfgfile.tmp" "$cfgfile" \ || (rm -f "$cfgfile" && cp "$cfgfile.tmp" "$cfgfile" && rm -f "$cfgfile.tmp") test 0 -eq $? || _lt_function_replace_fail=: sed -e '/^func_lo2o ()$/,/^} # func_lo2o /c\ func_lo2o ()\ {\ \ case ${1} in\ \ *.lo) func_lo2o_result=${1%.lo}.${objext} ;;\ \ *) func_lo2o_result=${1} ;;\ \ esac\ } # Extended-shell func_lo2o implementation' "$cfgfile" > $cfgfile.tmp \ && mv -f "$cfgfile.tmp" "$cfgfile" \ || (rm -f "$cfgfile" && cp "$cfgfile.tmp" "$cfgfile" && rm -f "$cfgfile.tmp") test 0 -eq $? || _lt_function_replace_fail=: sed -e '/^func_xform ()$/,/^} # func_xform /c\ func_xform ()\ {\ func_xform_result=${1%.*}.lo\ } # Extended-shell func_xform implementation' "$cfgfile" > $cfgfile.tmp \ && mv -f "$cfgfile.tmp" "$cfgfile" \ || (rm -f "$cfgfile" && cp "$cfgfile.tmp" "$cfgfile" && rm -f "$cfgfile.tmp") test 0 -eq $? || _lt_function_replace_fail=: sed -e '/^func_arith ()$/,/^} # func_arith /c\ func_arith ()\ {\ func_arith_result=$(( $* ))\ } # Extended-shell func_arith implementation' "$cfgfile" > $cfgfile.tmp \ && mv -f "$cfgfile.tmp" "$cfgfile" \ || (rm -f "$cfgfile" && cp "$cfgfile.tmp" "$cfgfile" && rm -f "$cfgfile.tmp") test 0 -eq $? || _lt_function_replace_fail=: sed -e '/^func_len ()$/,/^} # func_len /c\ func_len ()\ {\ func_len_result=${#1}\ } # Extended-shell func_len implementation' "$cfgfile" > $cfgfile.tmp \ && mv -f "$cfgfile.tmp" "$cfgfile" \ || (rm -f "$cfgfile" && cp "$cfgfile.tmp" "$cfgfile" && rm -f "$cfgfile.tmp") test 0 -eq $? || _lt_function_replace_fail=: fi if test x"$lt_shell_append" = xyes; then sed -e '/^func_append ()$/,/^} # func_append /c\ func_append ()\ {\ eval "${1}+=\\${2}"\ } # Extended-shell func_append implementation' "$cfgfile" > $cfgfile.tmp \ && mv -f "$cfgfile.tmp" "$cfgfile" \ || (rm -f "$cfgfile" && cp "$cfgfile.tmp" "$cfgfile" && rm -f "$cfgfile.tmp") test 0 -eq $? || _lt_function_replace_fail=: sed -e '/^func_append_quoted ()$/,/^} # func_append_quoted /c\ func_append_quoted ()\ {\ \ func_quote_for_eval "${2}"\ \ eval "${1}+=\\\\ \\$func_quote_for_eval_result"\ } # Extended-shell func_append_quoted implementation' "$cfgfile" > $cfgfile.tmp \ && mv -f "$cfgfile.tmp" "$cfgfile" \ || (rm -f "$cfgfile" && cp "$cfgfile.tmp" "$cfgfile" && rm -f "$cfgfile.tmp") test 0 -eq $? || _lt_function_replace_fail=: # Save a `func_append' function call where possible by direct use of '+=' sed -e 's%func_append \([a-zA-Z_]\{1,\}\) "%\1+="%g' $cfgfile > $cfgfile.tmp \ && mv -f "$cfgfile.tmp" "$cfgfile" \ || (rm -f "$cfgfile" && cp "$cfgfile.tmp" "$cfgfile" && rm -f "$cfgfile.tmp") test 0 -eq $? || _lt_function_replace_fail=: else # Save a `func_append' function call even when '+=' is not available sed -e 's%func_append \([a-zA-Z_]\{1,\}\) "%\1="$\1%g' $cfgfile > $cfgfile.tmp \ && mv -f "$cfgfile.tmp" "$cfgfile" \ || (rm -f "$cfgfile" && cp "$cfgfile.tmp" "$cfgfile" && rm -f "$cfgfile.tmp") test 0 -eq $? || _lt_function_replace_fail=: fi if test x"$_lt_function_replace_fail" = x":"; then { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: Unable to substitute extended shell functions in $ofile" >&5 $as_echo "$as_me: WARNING: Unable to substitute extended shell functions in $ofile" >&2;} fi mv -f "$cfgfile" "$ofile" || (rm -f "$ofile" && cp "$cfgfile" "$ofile" && rm -f "$cfgfile") chmod +x "$ofile" cat <<_LT_EOF >> "$ofile" # ### BEGIN LIBTOOL TAG CONFIG: CXX # The linker used to build libraries. LD=$lt_LD_CXX # How to create reloadable object files. reload_flag=$lt_reload_flag_CXX reload_cmds=$lt_reload_cmds_CXX # Commands used to build an old-style archive. old_archive_cmds=$lt_old_archive_cmds_CXX # A language specific compiler. CC=$lt_compiler_CXX # Is the compiler the GNU compiler? with_gcc=$GCC_CXX # Compiler flag to turn off builtin functions. no_builtin_flag=$lt_lt_prog_compiler_no_builtin_flag_CXX # Additional compiler flags for building library objects. pic_flag=$lt_lt_prog_compiler_pic_CXX # How to pass a linker flag through the compiler. wl=$lt_lt_prog_compiler_wl_CXX # Compiler flag to prevent dynamic linking. link_static_flag=$lt_lt_prog_compiler_static_CXX # Does compiler simultaneously support -c and -o options? compiler_c_o=$lt_lt_cv_prog_compiler_c_o_CXX # Whether or not to add -lc for building shared libraries. build_libtool_need_lc=$archive_cmds_need_lc_CXX # Whether or not to disallow shared libs when runtime libs are static. allow_libtool_libs_with_static_runtimes=$enable_shared_with_static_runtimes_CXX # Compiler flag to allow reflexive dlopens. export_dynamic_flag_spec=$lt_export_dynamic_flag_spec_CXX # Compiler flag to generate shared objects directly from archives. whole_archive_flag_spec=$lt_whole_archive_flag_spec_CXX # Whether the compiler copes with passing no objects directly. compiler_needs_object=$lt_compiler_needs_object_CXX # Create an old-style archive from a shared archive. old_archive_from_new_cmds=$lt_old_archive_from_new_cmds_CXX # Create a temporary old-style archive to link instead of a shared archive. old_archive_from_expsyms_cmds=$lt_old_archive_from_expsyms_cmds_CXX # Commands used to build a shared archive. archive_cmds=$lt_archive_cmds_CXX archive_expsym_cmds=$lt_archive_expsym_cmds_CXX # Commands used to build a loadable module if different from building # a shared archive. module_cmds=$lt_module_cmds_CXX module_expsym_cmds=$lt_module_expsym_cmds_CXX # Whether we are building with GNU ld or not. with_gnu_ld=$lt_with_gnu_ld_CXX # Flag that allows shared libraries with undefined symbols to be built. allow_undefined_flag=$lt_allow_undefined_flag_CXX # Flag that enforces no undefined symbols. no_undefined_flag=$lt_no_undefined_flag_CXX # Flag to hardcode \$libdir into a binary during linking. # This must work even if \$libdir does not exist hardcode_libdir_flag_spec=$lt_hardcode_libdir_flag_spec_CXX # Whether we need a single "-rpath" flag with a separated argument. hardcode_libdir_separator=$lt_hardcode_libdir_separator_CXX # Set to "yes" if using DIR/libNAME\${shared_ext} during linking hardcodes # DIR into the resulting binary. hardcode_direct=$hardcode_direct_CXX # Set to "yes" if using DIR/libNAME\${shared_ext} during linking hardcodes # DIR into the resulting binary and the resulting library dependency is # "absolute",i.e impossible to change by setting \${shlibpath_var} if the # library is relocated. hardcode_direct_absolute=$hardcode_direct_absolute_CXX # Set to "yes" if using the -LDIR flag during linking hardcodes DIR # into the resulting binary. hardcode_minus_L=$hardcode_minus_L_CXX # Set to "yes" if using SHLIBPATH_VAR=DIR during linking hardcodes DIR # into the resulting binary. hardcode_shlibpath_var=$hardcode_shlibpath_var_CXX # Set to "yes" if building a shared library automatically hardcodes DIR # into the library and all subsequent libraries and executables linked # against it. hardcode_automatic=$hardcode_automatic_CXX # Set to yes if linker adds runtime paths of dependent libraries # to runtime path list. inherit_rpath=$inherit_rpath_CXX # Whether libtool must link a program against all its dependency libraries. link_all_deplibs=$link_all_deplibs_CXX # Set to "yes" if exported symbols are required. always_export_symbols=$always_export_symbols_CXX # The commands to list exported symbols. export_symbols_cmds=$lt_export_symbols_cmds_CXX # Symbols that should not be listed in the preloaded symbols. exclude_expsyms=$lt_exclude_expsyms_CXX # Symbols that must always be exported. include_expsyms=$lt_include_expsyms_CXX # Commands necessary for linking programs (against libraries) with templates. prelink_cmds=$lt_prelink_cmds_CXX # Commands necessary for finishing linking programs. postlink_cmds=$lt_postlink_cmds_CXX # Specify filename containing input files. file_list_spec=$lt_file_list_spec_CXX # How to hardcode a shared library path into an executable. hardcode_action=$hardcode_action_CXX # The directories searched by this compiler when creating a shared library. compiler_lib_search_dirs=$lt_compiler_lib_search_dirs_CXX # Dependencies to place before and after the objects being linked to # create a shared library. predep_objects=$lt_predep_objects_CXX postdep_objects=$lt_postdep_objects_CXX predeps=$lt_predeps_CXX postdeps=$lt_postdeps_CXX # The library search path used internally by the compiler when linking # a shared library. compiler_lib_search_path=$lt_compiler_lib_search_path_CXX # ### END LIBTOOL TAG CONFIG: CXX _LT_EOF ;; esac done # for ac_tag as_fn_exit 0 _ACEOF ac_clean_files=$ac_clean_files_save test $ac_write_fail = 0 || as_fn_error $? "write failure creating $CONFIG_STATUS" "$LINENO" 5 # configure is writing to config.log, and then calls config.status. # config.status does its own redirection, appending to config.log. # Unfortunately, on DOS this fails, as config.log is still kept open # by configure, so config.status won't be able to write to it; its # output is simply discarded. So we exec the FD to /dev/null, # effectively closing config.log, so it can be properly (re)opened and # appended to by config.status. When coming back to configure, we # need to make the FD available again. if test "$no_create" != yes; then ac_cs_success=: ac_config_status_args= test "$silent" = yes && ac_config_status_args="$ac_config_status_args --quiet" exec 5>/dev/null $SHELL $CONFIG_STATUS $ac_config_status_args || ac_cs_success=false exec 5>>config.log # Use ||, not &&, to avoid exiting from the if with $? = 1, which # would make configure fail if this is the last instruction. $ac_cs_success || as_fn_exit 1 fi if test -n "$ac_unrecognized_opts" && test "$enable_option_checking" != no; then { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: unrecognized options: $ac_unrecognized_opts" >&5 $as_echo "$as_me: WARNING: unrecognized options: $ac_unrecognized_opts" >&2;} fi # Windows Erlang build tools wrap Microsoft's linker and compiler just enough # to be able to build Erlang/OTP successfully, but not enough for full # compatibility with GNU AutoTools. The MS VC compiler and linker are # hidden from autotools in Erlang's cc.sh and ld.sh wrappers. GNU autoconf # identifies this dastardly mix as a unix variant, and libtool kindly # passes incorrect flags and names through to the MS linker. The simplest fix # is to modify libtool via sed to remove those options. # # As this is only done once at first configure, and subsequent config or source # changes may trigger a silent reversion to the non-functioning original. # # Changes are; # # 1. replace LIB$name with $name in libname_spec (e.g. libicu -> icu) to ensure # correct windows versions of .lib and .dlls are found or generated. # 2. remove incompatible \w-link\w from archive_cmds # 3. remove GNU-style directives to be passed through to the linker # 4. swap GNU-style shared library flags with MS -dll variant # # This obscene hackery is tracked under COUCHDB-440 and COUCHDB-1197. if test x${IS_WINDOWS} = xTRUE; then mv libtool libtool.dist /bin/sed -E -e 's,^libname_spec="lib,libname_spec=",' \ -e 's,( -link ), ,' \ -e 's,-Xlinker --out-implib -Xlinker \\\$lib,,' \ -e 's,(-shared -nostdlib), -dll ,' \ < libtool.dist > libtool # probably would chmod +x if we weren't on windows... fi echo echo "You have configured Apache CouchDB, time to relax." echo echo "Run \`make && sudo make install' to install." apache-couchdb-1.5.0/configure.ac0000644000175000001440000005706312230722213013553 00000000000000dnl Licensed under the Apache License, Version 2.0 (the "License"); you may not dnl use this file except in compliance with the License. dnl You may obtain a dnl copy of the License at dnl dnl http://www.apache.org/licenses/LICENSE-2.0 dnl dnl Unless required by applicable law or agreed to in writing, software dnl distributed under the License is distributed on an "AS IS" BASIS, WITHOUT dnl WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the dnl License for the specific language governing permissions and limitations dnl under the License. AC_INIT( [LOCAL_PACKAGE_NAME], [LOCAL_VERSION], [LOCAL_BUG_URI], [LOCAL_PACKAGE_TARNAME]) AC_PREREQ([2.63]) AC_CONFIG_AUX_DIR([build-aux]) AC_CONFIG_MACRO_DIR([m4]) AC_CONFIG_HEADERS([config.h]) AC_CONFIG_HEADERS([src/snappy/google-snappy/config.h]) AM_INIT_AUTOMAKE([1.6.3 foreign]) AC_USE_SYSTEM_EXTENSIONS AC_ENABLE_SHARED AC_DISABLE_STATIC AC_PROG_CC LT_INIT([win32-dll]) LT_INIT AC_PROG_LN_S PKG_PROG_PKG_CONFIG dnl Config for google snappy m4_define([snappy_major], [1]) m4_define([snappy_minor], [0]) m4_define([snappy_patchlevel], [5]) AC_PROG_CXX AC_LANG([C++]) AC_LINK_IFELSE([AC_LANG_PROGRAM([], [])],, AC_MSG_ERROR([A C++ compiler is required.])) AC_C_BIGENDIAN AC_CHECK_HEADERS([stdint.h stddef.h sys/mman.h sys/resource.h]) AC_CHECK_FUNC([mmap]) AC_MSG_CHECKING([if the compiler supports __builtin_expect]) AC_COMPILE_IFELSE([AC_LANG_PROGRAM([[]], [[ return __builtin_expect(1, 1) ? 1 : 0 ]])],[ snappy_have_builtin_expect=yes AC_MSG_RESULT([yes]) ],[ snappy_have_builtin_expect=no AC_MSG_RESULT([no]) ]) if test x$snappy_have_builtin_expect = xyes ; then AC_DEFINE([HAVE_BUILTIN_EXPECT], [1], [Define to 1 if the compiler supports __builtin_expect.]) fi AC_MSG_CHECKING([if the compiler supports __builtin_ctzll]) AC_COMPILE_IFELSE([AC_LANG_PROGRAM([[]], [[ return (__builtin_ctzll(0x100000000LL) == 32) ? 1 : 0 ]])],[ snappy_have_builtin_ctz=yes AC_MSG_RESULT([yes]) ],[ snappy_have_builtin_ctz=no AC_MSG_RESULT([no]) ]) if test x$snappy_have_builtin_ctz = xyes ; then AC_DEFINE([HAVE_BUILTIN_CTZ], [1], [Define to 1 if the compiler supports __builtin_ctz and friends.]) fi if test "$ac_cv_header_stdint_h" = "yes"; then AC_SUBST([ac_cv_have_stdint_h], [1]) else AC_SUBST([ac_cv_have_stdint_h], [0]) fi if test "$ac_cv_header_stddef_h" = "yes"; then AC_SUBST([ac_cv_have_stddef_h], [1]) else AC_SUBST([ac_cv_have_stddef_h], [0]) fi SNAPPY_MAJOR="snappy_major" SNAPPY_MINOR="snappy_minor" SNAPPY_PATCHLEVEL="snappy_patchlevel" AC_SUBST([SNAPPY_MAJOR]) AC_SUBST([SNAPPY_MINOR]) AC_SUBST([SNAPPY_PATCHLEVEL]) AC_MSG_CHECKING([for pthread_create in -lpthread]) original_LIBS="$LIBS" LIBS="-lpthread $original_LIBS" AC_LINK_IFELSE([ AC_LANG_PROGRAM( [[#include]], [[pthread_create((void *)0, (void *)0, (void *)0, (void *)0)]])], [pthread=yes], [pthread=no]) if test x${pthread} = xyes; then AC_MSG_RESULT([yes]) else LIBS="$original_LIBS" AC_MSG_RESULT([no]) fi AC_PATH_PROG([ERL], [erl]) AC_PATH_PROG([ESCRIPT], [escript]) AS_IF([test x${ERL} = x], [ AC_MSG_ERROR([Could not find the `erl' executable. Is Erlang installed?]) ]) AC_ARG_WITH([erlang], [AS_HELP_STRING([--with-erlang=PATH], [set PATH to the Erlang include directory]) ], [ ERLANG_FLAGS="-I$withval" ], [ realerl=`readlink -f $ERL 2>/dev/null` AS_IF([test $? -eq 0], [ erlbase=`dirname $realerl` erlbase=`dirname $erlbase` ERLANG_FLAGS="-I${erlbase}/usr/include" ], [ # Failed to figure out where erl is installed.. # try to add some default directories to search ERLANG_FLAGS="-I${libdir}/erlang/usr/include" ERLANG_FLAGS="$ERLANG_FLAGS -I/usr/lib/erlang/usr/include" ERLANG_FLAGS="$ERLANG_FLAGS -I/usr/local/lib/erlang/usr/include" ERLANG_FLAGS="$ERLANG_FLAGS -I/opt/local/lib/erlang/usr/include" ]) ]) AC_SUBST(ERLANG_FLAGS) PKG_CHECK_MODULES([JS], [mozjs185], [ JS_LIB_DIR="$(${PKG_CONFIG} --variable=libdir mozjs185)" ], [ PKG_CHECK_MODULES([JS], [mozilla-js >= 1.7], [ JS_LIB_DIR="$(${PKG_CONFIG} --variable=sdkdir mozilla-js)/lib" ], [ JS_LIB_DIR="${libdir}" JS_CFLAGS="-I/usr/include" JS_CFLAGS="$JS_CFLAGS -I/usr/include/js" JS_CFLAGS="$JS_CFLAGS -I/usr/include/mozjs" JS_CFLAGS="$JS_CFLAGS -I/usr/local/include/js" JS_CFLAGS="$JS_CFLAGS -I/opt/local/include/js" ]) ]) AC_ARG_WITH([js-include], [AS_HELP_STRING([--with-js-include=PATH], [set PATH to the SpiderMonkey include directory]) ], [ JS_INCLUDE="$withval" JS_CFLAGS="-I$JS_INCLUDE" ], []) AC_ARG_WITH([js-lib], [AS_HELP_STRING([--with-js-lib=PATH], [set PATH to the SpiderMonkey library directory]) ], [ JS_LIB_DIR=$withval JS_LIBS="-L$withval" ], []) use_js_trunk=no AC_ARG_ENABLE([js-trunk], [AS_HELP_STRING([--enable-js-trunk], [allow use of SpiderMonkey versions newer than js185-1.0.0]) ], [ use_js_trunk=$enableval ], []) AC_ARG_VAR([ERLC_FLAGS], [general flags to prepend to ERLC_FLAGS]) AC_ARG_VAR([FLAGS], [general flags to prepend to LDFLAGS and CPPFLAGS]) AS_CASE([$(uname -s)], [CYGWIN*], [] , [*], [ CPPFLAGS="$CPPFLAGS -I/opt/local/include" CPPFLAGS="$CPPFLAGS -I/opt/local/include/js" CPPFLAGS="$CPPFLAGS -I/usr/local/include" CPPFLAGS="$CPPFLAGS -I/usr/local/include/js" CPPFLAGS="$CPPFLAGS -I/usr/include" CPPFLAGS="$CPPFLAGS -I/usr/include/js" LDFLAGS="$LDFLAGS -L/opt/local/lib" LDFLAGS="$LDFLAGS -L/usr/local/lib" ]) CPPFLAGS="$CPPFLAGS $FLAGS" LDFLAGS="$LDFLAGS $FLAGS" # The erlang cc.sh/ld.sh scripts will convert a -O option # into the same optimization flags erlang itself uses. CFLAGS="-O2 $CFLAGS" LIBS="$LIBS $LDFLAGS" AS_CASE([$(uname -s)], [CYGWIN*], [ JS_CFLAGS="-DXP_WIN $JS_CFLAGS" IS_WINDOWS="TRUE" ], [*], [ # XP_UNIX required for jsapi.h, tested on Linux and Darwin. JS_CFLAGS="-DXP_UNIX $JS_CFLAGS" ]) AM_CONDITIONAL([WINDOWS], [test x$IS_WINDOWS = xTRUE]) OLD_LIBS="$LIBS" LIBS="$JS_LIBS $LIBS" OLD_CPPFLAGS="$CPPFLAGS" CPPFLAGS="$JS_CFLAGS $CPPFLAGS" AC_CHECK_HEADER([jsapi.h], [], [ AC_CHECK_HEADER([js/jsapi.h], [ CPPFLAGS="$CPPFLAGS -I$JS_INCLUDE/js" ], [ AC_MSG_ERROR([Could not find the jsapi header. Are the Mozilla SpiderMonkey headers installed?]) ]) ]) AC_CHECK_LIB([mozjs185], [JS_NewContext], [JS_LIB_BASE=mozjs185], [ AC_CHECK_LIB([mozjs185-1.0], [JS_NewContext], [JS_LIB_BASE=mozjs185-1.0], [ AC_CHECK_LIB([mozjs], [JS_NewContext], [JS_LIB_BASE=mozjs], [ AC_CHECK_LIB([js], [JS_NewContext], [JS_LIB_BASE=js], [ AC_CHECK_LIB([js3250], [JS_NewContext], [JS_LIB_BASE=js3250], [ AC_CHECK_LIB([js32], [JS_NewContext], [JS_LIB_BASE=js32], [ AC_MSG_ERROR([Could not find the js library. Is the Mozilla SpiderMonkey library installed?]) ]) ]) ]) ]) ]) ]) # Figure out what version of SpiderMonkey to use AC_CHECK_LIB([$JS_LIB_BASE], [JS_NewCompartmentAndGlobalObject], # Prevent people from accidentally using SpiderMonkey's that are too new if test "$use_js_trunk" = "no"; then AC_CHECK_DECL([JSOPTION_ANONFUNFIX], [], [ AC_MSG_ERROR([Your SpiderMonkey library is too new. Versions of SpiderMonkey after the js185-1.0.0 release remove the optional enforcement of preventing anonymous functions in a statement context. This will most likely break your existing JavaScript code as well as render all example code invalid. If you wish to ignore this error pass --enable-js-trunk to ./configure.]) ], [ [#include ] ]) fi AC_DEFINE([SM185], [1], [Use SpiderMonkey 1.8.5]) ) AC_CHECK_LIB([$JS_LIB_BASE], [JS_ThrowStopIteration], AC_DEFINE([SM180], [1], [Use SpiderMonkey 1.8.0]) ) AC_CHECK_LIB([$JS_LIB_BASE], [JS_GetStringCharsAndLength], AC_DEFINE([HAVE_JS_GET_STRING_CHARS_AND_LENGTH], [1], [Use newer JS_GetCharsAndLength function.]) ) # Else, hope that 1.7.0 works # Deal with JSScript to JSObject to JSScript switcheroo AC_CHECK_TYPE([JSScript*], [AC_DEFINE([JSSCRIPT_TYPE], [JSScript*], [Use JSObject* for scripts])], [AC_DEFINE([JSSCRIPT_TYPE], [JSObject*], [Use JSScript* for scripts])], [[#include ]] ) AC_DEFINE([COUCHJS_NAME], ["couchjs"], ["CouchJS executable name."]) if test x${IS_WINDOWS} = xTRUE; then AC_DEFINE([COUCHJS_NAME], ["couchjs.exe"], ["CouchJS executable name."]) if test -f "$JS_LIB_DIR/$JS_LIB_BASE.dll"; then # seamonkey 1.7- build layout on Windows JS_LIB_BINARY="$JS_LIB_DIR/$JS_LIB_BASE.dll" else # seamonkey 1.8+ build layout on Windows if test -f "$JS_LIB_DIR/../bin/$JS_LIB_BASE.dll"; then JS_LIB_BINARY="$JS_LIB_DIR/../bin/$JS_LIB_BASE.dll" else AC_MSG_ERROR([Could not find $JS_LIB_BASE.dll.]) fi fi AC_SUBST(JS_LIB_BINARY) # On windows we need to know the path to the openssl binaries. AC_ARG_WITH([openssl-bin-dir], [AS_HELP_STRING([--with-openssl-bin-dir=PATH], [path to the open ssl binaries for distribution on Windows]) ], [ openssl_bin_dir=`cygpath -m "$withval"` AC_SUBST(openssl_bin_dir) ], []) # Windows uses Inno setup - look for its compiler. AC_PATH_PROG([INNO_COMPILER_EXECUTABLE], [iscc]) if test x${INNO_COMPILER_EXECUTABLE} = x; then AC_MSG_WARN([You will be unable to build the Windows installer.]) fi # We need the msvc redistributables for this platform too # (in theory we could just install the assembly locally - but # there are at least 4 directories with binaries, meaning 4 copies; # so using the redist .exe means it ends up installed globally...) AC_ARG_WITH([msvc-redist-dir], [AS_HELP_STRING([--with-msvc-redist-dir=PATH], [path to the msvc redistributables for the Windows platform]) ], [ msvc_redist_dir=`cygpath -m "$withval"` msvc_redist_name="vcredist_x86.exe" AC_SUBST(msvc_redist_dir) AC_SUBST(msvc_redist_name) ], []) if test ! -f ${msvc_redist_dir}/${msvc_redist_name}; then AC_MSG_WARN([Installer may fail due to missing MSVC redistributable.]) fi fi JS_LIBS="-l$JS_LIB_BASE -lm $JS_LIBS" AC_SUBST(JS_LIBS) LIBS="$OLD_LIBS" CPPFLAGS="$OLD_CPPFLAGS" %% auto detect "kegged" icu4c on Mac / Homebrew PATH="/usr/local/opt/icu4c/bin:$PATH" AC_ARG_WITH([win32-icu-binaries], [AS_HELP_STRING([--with-win32-icu-binaries=PATH], [set PATH to the Win32 native ICU binaries directory]) ], [ ICU_CPPFLAGS="-I$withval/include" ICU_LIBS="-L$withval/lib -licuuc -licudt -licuin" ICU_BIN=$withval/bin ], [ AX_CHECK_ICU([3.4.1]) ICU_BIN= ]) AC_SUBST(ICU_CFLAGS) AC_SUBST(ICU_CPPFLAGS) AC_SUBST(ICU_LIBS) AC_SUBST(ICU_BIN) use_curl=yes AC_ARG_WITH([win32-curl], [AS_HELP_STRING([--with-win32-curl=PATH], [set PATH to the Win32 native curl directory]) ], [ # default build on windows is a static lib, and that's what we want too CURL_CFLAGS="-I$withval/include -DCURL_STATICLIB" CURL_LIBS="-L$withval/lib -llibcurl -lWs2_32 -lkernel32 -luser32 -ladvapi32 -lWldap32" # OpenSSL libraries may be pulled in via libcurl if it was built with SSL # these are libeay32 ssleay32 instead of crypto ssl on unix ], [ AX_LIB_CURL([7.18.0],[ AC_DEFINE([HAVE_CURL], [1], ["Provide HTTP support to couchjs"]) ],[ AC_MSG_WARN([You will be unable to run some JavaScript unit tests.]) use_curl=no CURL_LIBS= ]) ]) AC_SUBST(CURL_CFLAGS) AC_SUBST(CURL_LIBS) case "$(uname -s)" in Linux) LIBS="$LIBS -lcrypt" CPPFLAGS="-D_XOPEN_SOURCE $CPPFLAGS" ;; FreeBSD) LIBS="$LIBS -lcrypt" ;; OpenBSD) LIBS="$LIBS -lcrypto" ;; esac { $as_echo "$as_me:${as_lineno-$LINENO}: checking Erlang version compatibility" >&5 $as_echo_n "checking Erlang version compatibility... " >&6; } erlang_version_error="The installed Erlang version must be >= R14B (erts-5.8.1) and xR13B03]) AM_CONDITIONAL([USE_EJSON_COMPARE_NIF], [test x$otp_release \> xR14B03]) has_crypto=`\ ${ERL} -eval "\ case application:load(crypto) of ok -> ok; _ -> exit(no_crypto) end. \ " -noshell -s init stop` if test -n "$has_crypto"; then AC_MSG_ERROR([Could not find the Erlang crypto library. Has Erlang been compiled with OpenSSL support?]) fi AC_PATH_PROG([ERLC], [erlc]) if test x${ERLC} = x; then AC_MSG_ERROR([Could not find the `erlc' executable. Is Erlang installed?]) fi OLD_CPPFLAGS="$CPPFLAGS" CPPFLAGS="$ERLANG_FLAGS $CPPFLAGS" AC_CHECK_HEADER([erl_driver.h], [], [ AC_MSG_ERROR([Could not find the `erl_driver.h' header. Are the Erlang headers installed? Use the `--with-erlang' option to specify the Erlang include directory.]) ]) CPPFLAGS="$OLD_CPPFLAGS" use_init=yes use_launchd=yes native_mochijson_enabled=no tests_enabled=yes docs_enabled=yes strictness_enabled=no AC_ARG_ENABLE([init], [AS_HELP_STRING([--disable-init], [don't install init script where applicable]) ], [ use_init=$enableval ], []) AC_ARG_ENABLE([launchd], [AS_HELP_STRING([--disable-launchd], [don't install launchd configuration where applicable]) ], [ use_launchd=$enableval ], []) AC_ARG_ENABLE([native-mochijson], [AS_HELP_STRING([--enable-native-mochijson], [compile mochijson to native code (EXPERIMENTAL)]) ], [ native_mochijson_enabled=$enableval ], []) AC_ARG_ENABLE([tests], [AS_HELP_STRING([--disable-tests], [skip tests during build]) ], [ tests_enabled=$enableval ], []) AC_ARG_ENABLE([docs], [AS_HELP_STRING([--disable-docs], [skip docs during build]) ], [ docs_enabled=$enableval ], []) AC_ARG_ENABLE([strictness], [AS_HELP_STRING([--enable-strictness], [exit when optional checks fail]) ], [ strictness_enabled=$enableval ], []) init_enabled=false launchd_enabled=false if test "$use_init" = "yes"; then AC_MSG_CHECKING(location of init directory) if test -d /etc/rc.d; then init_enabled=true AC_SUBST([initdir], ['${sysconfdir}/rc.d']) AC_MSG_RESULT(${initdir}) else if test -d /etc/init.d; then init_enabled=true AC_SUBST([initdir], ['${sysconfdir}/init.d']) AC_MSG_RESULT(${initdir}) else AC_MSG_RESULT(not found) fi fi fi if test "$use_launchd" = "yes"; then AC_MSG_CHECKING(location of launchd directory) if test -d /Library/LaunchDaemons; then init_enabled=false launchd_enabled=true AC_SUBST([launchddir], ['${prefix}/Library/LaunchDaemons']) AC_MSG_RESULT(${launchddir}) else AC_MSG_RESULT(not found) fi fi AC_CHECK_PROG([HAS_HELP2MAN], [help2man], [yes]) if test x${HAS_HELP2MAN} = x; then if test x${strictness_enabled} = xyes; then AC_MSG_ERROR([Could not find the `help2man' executable.]) else AC_MSG_WARN([You will be unable to regenerate man pages.]) fi fi AC_CHECK_PROG([HAS_PDFLATEX], [pdflatex], [yes]) if test x${HAS_PDFLATEX} = x; then if test x${strictness_enabled} = xyes; then AC_MSG_ERROR([Could not find the `pdflatex' executable. Is LaTeX installed?]) else AC_MSG_WARN([You will be unable to regenerate PDF documentation.]) fi fi AC_CHECK_PROG([HAS_MAKEINFO], [makeinfo], [yes]) if test x${HAS_MAKEINFO} = x; then if test x${strictness_enabled} = xyes; then AC_MSG_ERROR([Could not find the `makeinfo' executable. Is GNU Texinfo installed?]) else AC_MSG_WARN([You will be unable to regenerate info documentation.]) fi fi AC_CHECK_PROG([HAS_INSTALLINFO], [install-info], [yes]) if test x${HAS_INSTALLINFO} = x; then if test x${strictness_enabled} = xyes; then AC_MSG_ERROR([Could not find the `install-info' executable. Is GNU Texinfo installed?]) else AC_MSG_WARN([You will be unable to install info documentation.]) fi fi AC_CHECK_PROG([HAS_SPHINX_BUILD], [sphinx-build], [yes]) if test x${HAS_SPHINX_BUILD} = x; then if test x${strictness_enabled} = xyes; then AC_MSG_ERROR([Could not find the `sphinx-build' executable.]) else AC_MSG_WARN([You will be unable to regenerate documentation.]) fi fi if test x${docs_enabled} = xyes; then if test x${HAS_HELP2MAN} = xyes; then build_man=yes fi if test x${HAS_SPHINX_BUILD} = xyes; then build_html=yes if test x${HAS_MAKEINFO} = xyes; then build_info=yes fi if test x${HAS_PDFLATEX} = xyes; then build_pdf=yes fi fi fi if test x${strictness_enabled} = xyes; then AX_PYTHON_MODULE([pygments], [fatal]) else AX_PYTHON_MODULE([pygments]) fi AC_MSG_CHECKING(pygments version >= 1.5) python 2> /dev/null << EOF import sys import pygments if float(pygments.__version__) >= 1.5: sys.exit(0) else: sys.exit(1) EOF if test $? -eq 0; then AC_MSG_RESULT(yes) else AC_MSG_RESULT(no) if test x${strictness_enabled} = xyes; then AC_MSG_ERROR([Your copy of pygments is out of date.], 1) else AC_MSG_WARN([Syntax highlighting may not work.]) fi fi ERL_VERSION_COMMAND="${ESCRIPT} bin/erlang-version.escript" erlangversion=`${ERL_VERSION_COMMAND}` AC_ARG_VAR([ERL], [path to the `erl' executable]) AC_ARG_VAR([ERLC], [path to the `erlc' executable]) AM_CONDITIONAL([INIT], [test x${init_enabled} = xtrue]) AM_CONDITIONAL([LAUNCHD], [test x${launchd_enabled} = xtrue]) AM_CONDITIONAL([USE_NATIVE_MOCHIJSON], [test x${native_mochijson_enabled} = xyes]) AM_CONDITIONAL([USE_CURL], [test x${use_curl} = xyes]) AM_CONDITIONAL([BUILD_MAN], [test x${build_man} = xyes]) AM_CONDITIONAL([BUILD_INFO], [test x${build_info} = xyes]) AM_CONDITIONAL([BUILD_PDF], [test x${build_pdf} = xyes]) AM_CONDITIONAL([BUILD_HTML], [test x${build_html} = xyes]) AM_CONDITIONAL([TESTS], [test x${tests_enabled} = xyes]) AM_CONDITIONAL([STRICTNESS], [test x${strictness_enabled} = xyes]) AC_SUBST([package_author_name], ["LOCAL_PACKAGE_AUTHOR_NAME"]) AC_SUBST([package_author_address], ["LOCAL_PACKAGE_AUTHOR_ADDRESS"]) AC_SUBST([package_identifier], ["LOCAL_PACKAGE_IDENTIFIER"]) AC_SUBST([package_tarname], ["LOCAL_PACKAGE_TARNAME"]) AC_SUBST([package_name], ["LOCAL_PACKAGE_NAME"]) AC_SUBST([version], ["LOCAL_VERSION"]) AC_SUBST([version_major], ["LOCAL_VERSION_MAJOR"]) AC_SUBST([version_minor], ["LOCAL_VERSION_MINOR"]) AC_SUBST([version_revision], ["LOCAL_VERSION_REVISION"]) AC_SUBST([version_stage], ["LOCAL_VERSION_STAGE"]) AC_SUBST([version_release], ["LOCAL_VERSION_RELEASE"]) AC_SUBST([bug_uri], ["LOCAL_BUG_URI"]) AC_SUBST([localconfdir], [${sysconfdir}/${package_identifier}]) AC_SUBST([localdatadir], [${datadir}/${package_identifier}]) AC_SUBST([localdocdir], [${datadir}/doc/${package_identifier}]) AC_SUBST([locallibdir], [${libdir}/${package_identifier}]) AC_SUBST([localstatelibdir], [${localstatedir}/lib/${package_identifier}]) AC_SUBST([localstatelogdir], [${localstatedir}/log/${package_identifier}]) AC_SUBST([localstaterundir], [${localstatedir}/run/${package_identifier}]) AC_SUBST([erlangversion], [${erlangversion}]) AC_SUBST([erlangbin], [${ERL}]) # On Windows we install directly into our erlang distribution. if test x${IS_WINDOWS} = xTRUE; then AC_SUBST([locallibbindir], [${prefix}/bin]) AC_SUBST([localerlanglibdir], [${libdir}]) else AC_SUBST([locallibbindir], [${locallibdir}/bin]) AC_SUBST([localerlanglibdir], [${locallibdir}/erlang/lib]) fi # fix for older autotools that don't define "abs_top_YYY" by default AC_SUBST(abs_top_srcdir) AC_SUBST(abs_top_builddir) AC_REVISION([LOCAL_VERSION]) AC_CONFIG_FILES([Makefile]) AC_CONFIG_FILES([bin/couch-config.tpl]) AC_CONFIG_FILES([bin/couchdb.tpl]) AC_CONFIG_FILES([bin/couchdb.bat.tpl]) AC_CONFIG_FILES([bin/Makefile]) AC_CONFIG_FILES([etc/couchdb/Makefile]) AC_CONFIG_FILES([etc/couchdb/default.ini.tpl]) AC_CONFIG_FILES([etc/default/Makefile]) AC_CONFIG_FILES([etc/init/couchdb.tpl]) AC_CONFIG_FILES([etc/init/Makefile]) AC_CONFIG_FILES([etc/launchd/org.apache.couchdb.plist.tpl]) AC_CONFIG_FILES([etc/launchd/Makefile]) AC_CONFIG_FILES([etc/logrotate.d/couchdb.tpl]) AC_CONFIG_FILES([etc/logrotate.d/Makefile]) AC_CONFIG_FILES([etc/windows/Makefile]) AC_CONFIG_FILES([etc/Makefile]) AC_CONFIG_FILES([share/Makefile]) AC_CONFIG_FILES([share/doc/Makefile]) AC_CONFIG_FILES([share/doc/build/Makefile]) AC_CONFIG_FILES([src/Makefile]) AC_CONFIG_FILES([src/couch_dbupdates/Makefile]) AC_CONFIG_FILES([src/couch_index/Makefile]) AC_CONFIG_FILES([src/couch_mrview/Makefile]) AC_CONFIG_FILES([src/couch_plugins/Makefile]) AC_CONFIG_FILES([src/couch_replicator/Makefile]) AC_CONFIG_FILES([src/couchjs-node/Makefile]) AC_CONFIG_FILES([src/couchdb/couch.app.tpl]) AC_CONFIG_FILES([src/couchdb/Makefile]) AC_CONFIG_FILES([src/couchdb/priv/Makefile]) AC_CONFIG_FILES([src/erlang-oauth/Makefile]) AC_CONFIG_FILES([src/etap/Makefile]) AC_CONFIG_FILES([src/ibrowse/Makefile]) AC_CONFIG_FILES([src/mochiweb/Makefile]) AC_CONFIG_FILES([src/snappy/Makefile]) AC_CONFIG_FILES([src/snappy/google-snappy/snappy-stubs-public.h]) AC_CONFIG_FILES([src/ejson/Makefile]) AC_CONFIG_FILES([test/Makefile]) AC_CONFIG_FILES([test/bench/Makefile]) AC_CONFIG_FILES([test/etap/Makefile]) AC_CONFIG_FILES([test/etap/test_util.erl]) AC_CONFIG_FILES([test/javascript/Makefile]) AC_CONFIG_FILES([test/view_server/Makefile]) AC_CONFIG_FILES([utils/Makefile]) AC_CONFIG_FILES([var/Makefile]) AC_OUTPUT # Windows Erlang build tools wrap Microsoft's linker and compiler just enough # to be able to build Erlang/OTP successfully, but not enough for full # compatibility with GNU AutoTools. The MS VC compiler and linker are # hidden from autotools in Erlang's cc.sh and ld.sh wrappers. GNU autoconf # identifies this dastardly mix as a unix variant, and libtool kindly # passes incorrect flags and names through to the MS linker. The simplest fix # is to modify libtool via sed to remove those options. # # As this is only done once at first configure, and subsequent config or source # changes may trigger a silent reversion to the non-functioning original. # # Changes are; # # 1. replace LIB$name with $name in libname_spec (e.g. libicu -> icu) to ensure # correct windows versions of .lib and .dlls are found or generated. # 2. remove incompatible \w-link\w from archive_cmds # 3. remove GNU-style directives to be passed through to the linker # 4. swap GNU-style shared library flags with MS -dll variant # # This obscene hackery is tracked under COUCHDB-440 and COUCHDB-1197. if test x${IS_WINDOWS} = xTRUE; then mv libtool libtool.dist /bin/sed -E -e 's,^libname_spec="lib,libname_spec=",' \ -e 's,( -link ), ,' \ -e 's,-Xlinker --out-implib -Xlinker \\\$lib,,' \ -e 's,(-shared -nostdlib), -dll ,' \ < libtool.dist > libtool # probably would chmod +x if we weren't on windows... fi echo echo "You have configured Apache CouchDB, time to relax." echo echo "Run \`make && sudo make install' to install." apache-couchdb-1.5.0/Makefile.am0000644000175000001440000000731212230722214013312 00000000000000## 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. SUBDIRS = bin etc src share test var utils ACLOCAL_AMFLAGS = -I m4 localdoc_DATA = \ AUTHORS.gz \ BUGS.gz \ DEVELOPERS.gz \ INSTALL.gz \ INSTALL.Unix.gz \ INSTALL.Windows.gz \ LICENSE.gz \ NOTICE.gz \ README.gz \ THANKS.gz DISTCLEANFILES = $(localdoc_DATA) EXTRA_DIST = \ AUTHORS \ BUGS \ DEVELOPERS \ INSTALL \ INSTALL.Unix \ INSTALL.Windows \ LICENSE \ NOTICE \ README.rst \ THANKS \ build-aux/dist-error \ build-aux/sphinx-build \ build-aux/sphinx-touch \ license.skip AUTHORS.gz: AUTHORS gzip -9 < $< > $@ BUGS.gz: BUGS gzip -9 < $< > $@ DEVELOPERS.gz: DEVELOPERS gzip -9 < $< > $@ INSTALL.gz: INSTALL gzip -9 < $< > $@ INSTALL.Unix.gz: INSTALL.Unix gzip -9 < $< > $@ INSTALL.Windows.gz: INSTALL.Windows gzip -9 < $< > $@ LICENSE.gz: LICENSE gzip -9 < $< > $@ NOTICE.gz: NOTICE gzip -9 < $< > $@ README.gz: README.rst gzip -9 < $< > $@ THANKS.gz: THANKS gzip -9 < $< > $@ check: dev check-js if TESTS $(top_builddir)/test/etap/run $(top_srcdir)/test/etap endif check-js: dev if TESTS if USE_CURL MAKE=$(MAKE) $(top_builddir)/test/javascript/run endif endif check-etap: dev if TESTS $(top_builddir)/test/etap/run $(top_srcdir)/test/etap endif cover: dev if TESTS rm -f cover/*.coverdata COVER=1 COVER_BIN=./src/couchdb/ $(top_builddir)/test/etap/run SRC=./src/couchdb/ \ $(ERL) -noshell \ -pa src/etap \ -eval 'etap_report:create()' \ -s init stop > /dev/null 2>&1 endif dev: all if TESTS @echo "This command is intended for developers to use;" @echo "it creates development ini files as well as a" @echo "$(top_builddir)/tmp structure for development runtime files." @echo "Use ./utils/run to launch CouchDB from the source tree." mkdir -p $(top_builddir)/etc/couchdb/default.d mkdir -p $(top_builddir)/etc/couchdb/local.d mkdir -p $(top_builddir)/tmp/lib mkdir -p $(top_builddir)/tmp/log mkdir -p $(top_builddir)/tmp/run/couchdb mkdir -p $(top_builddir)/tmp/plugins endif install-data-hook: @echo @echo "You have installed Apache CouchDB, time to relax." distclean-local: rm -fr $(top_builddir)/etc/couchdb/default.d rm -fr $(top_builddir)/etc/couchdb/local.d rm -fr $(top_builddir)/tmp rm -f $(top_builddir)/couchdb.stdout rm -f $(top_builddir)/couchdb.stderr .PHONY: local-clean local-clean: maintainer-clean @echo "This command is intended for maintainers to use;" @echo "it deletes files that may need special tools to rebuild." rm -f $(top_srcdir)/INSTALL rm -f $(top_srcdir)/acinclude.m4 rm -f $(top_srcdir)/aclocal.m4 rm -f $(top_srcdir)/config.h.in rm -f $(top_srcdir)/configure rm -f $(top_srcdir)/test/etap/temp.* rm -f $(top_srcdir)/*.tar.gz rm -f $(top_srcdir)/*.tar.gz.* find $(top_srcdir) -name Makefile.in -exec rm -f {} \; dist-hook: find $(top_srcdir) -type f -name "._*" -exec rm -f {} \; find $(top_builddir) -type f -name "._*" -exec rm -f {} \; distcheck-hook: $(MAKE) -C bin distcheck-hook $(MAKE) -C src/couchdb/priv distcheck-hook $(MAKE) -C share/doc/build distcheck-hook grep -rL 'http://www.apache.org/licenses/LICENSE-2.0' * \ | grep --include= -vEf $(top_srcdir)/license.skip; \ test "$$?" -eq 1 apache-couchdb-1.5.0/Makefile.in0000644000175000001440000010016212230722245013324 00000000000000# Makefile.in generated by automake 1.11.6 from Makefile.am. # @configure_input@ # Copyright (C) 1994, 1995, 1996, 1997, 1998, 1999, 2000, 2001, 2002, # 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011 Free Software # Foundation, Inc. # This Makefile.in is free software; the Free Software Foundation # gives unlimited permission to copy and/or distribute it, # with or without modifications, as long as this notice is preserved. # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY, to the extent permitted by law; without # even the implied warranty of MERCHANTABILITY or FITNESS FOR A # PARTICULAR PURPOSE. @SET_MAKE@ VPATH = @srcdir@ am__make_dryrun = \ { \ am__dry=no; \ case $$MAKEFLAGS in \ *\\[\ \ ]*) \ echo 'am--echo: ; @echo "AM" OK' | $(MAKE) -f - 2>/dev/null \ | grep '^AM OK$$' >/dev/null || am__dry=yes;; \ *) \ for am__flg in $$MAKEFLAGS; do \ case $$am__flg in \ *=*|--*) ;; \ *n*) am__dry=yes; break;; \ esac; \ done;; \ esac; \ test $$am__dry = yes; \ } pkgdatadir = $(datadir)/@PACKAGE@ pkgincludedir = $(includedir)/@PACKAGE@ pkglibdir = $(libdir)/@PACKAGE@ pkglibexecdir = $(libexecdir)/@PACKAGE@ am__cd = CDPATH="$${ZSH_VERSION+.}$(PATH_SEPARATOR)" && cd install_sh_DATA = $(install_sh) -c -m 644 install_sh_PROGRAM = $(install_sh) -c install_sh_SCRIPT = $(install_sh) -c INSTALL_HEADER = $(INSTALL_DATA) transform = $(program_transform_name) NORMAL_INSTALL = : PRE_INSTALL = : POST_INSTALL = : NORMAL_UNINSTALL = : PRE_UNINSTALL = : POST_UNINSTALL = : build_triplet = @build@ host_triplet = @host@ subdir = . DIST_COMMON = $(am__configure_deps) $(srcdir)/Makefile.am \ $(srcdir)/Makefile.in $(srcdir)/config.h.in \ $(top_srcdir)/configure \ $(top_srcdir)/src/snappy/google-snappy/config.h.in \ $(top_srcdir)/src/snappy/google-snappy/snappy-stubs-public.h.in \ AUTHORS THANKS build-aux/config.guess build-aux/config.sub \ build-aux/depcomp build-aux/install-sh build-aux/ltmain.sh \ build-aux/missing ACLOCAL_M4 = $(top_srcdir)/aclocal.m4 am__aclocal_m4_deps = $(top_srcdir)/m4/libtool.m4 \ $(top_srcdir)/m4/ltoptions.m4 $(top_srcdir)/m4/ltsugar.m4 \ $(top_srcdir)/m4/ltversion.m4 $(top_srcdir)/m4/lt~obsolete.m4 \ $(top_srcdir)/acinclude.m4 $(top_srcdir)/configure.ac am__configure_deps = $(am__aclocal_m4_deps) $(CONFIGURE_DEPENDENCIES) \ $(ACLOCAL_M4) am__CONFIG_DISTCLEAN_FILES = config.status config.cache config.log \ configure.lineno config.status.lineno mkinstalldirs = $(install_sh) -d CONFIG_HEADER = config.h \ $(top_builddir)/src/snappy/google-snappy/config.h CONFIG_CLEAN_FILES = src/snappy/google-snappy/snappy-stubs-public.h CONFIG_CLEAN_VPATH_FILES = SOURCES = DIST_SOURCES = RECURSIVE_TARGETS = all-recursive check-recursive dvi-recursive \ html-recursive info-recursive install-data-recursive \ install-dvi-recursive install-exec-recursive \ install-html-recursive install-info-recursive \ install-pdf-recursive install-ps-recursive install-recursive \ installcheck-recursive installdirs-recursive pdf-recursive \ ps-recursive uninstall-recursive am__can_run_installinfo = \ case $$AM_UPDATE_INFO_DIR in \ n|no|NO) false;; \ *) (install-info --version) >/dev/null 2>&1;; \ esac am__vpath_adj_setup = srcdirstrip=`echo "$(srcdir)" | sed 's|.|.|g'`; am__vpath_adj = case $$p in \ $(srcdir)/*) f=`echo "$$p" | sed "s|^$$srcdirstrip/||"`;; \ *) f=$$p;; \ esac; am__strip_dir = f=`echo $$p | sed -e 's|^.*/||'`; am__install_max = 40 am__nobase_strip_setup = \ srcdirstrip=`echo "$(srcdir)" | sed 's/[].[^$$\\*|]/\\\\&/g'` am__nobase_strip = \ for p in $$list; do echo "$$p"; done | sed -e "s|$$srcdirstrip/||" am__nobase_list = $(am__nobase_strip_setup); \ for p in $$list; do echo "$$p $$p"; done | \ sed "s| $$srcdirstrip/| |;"' / .*\//!s/ .*/ ./; s,\( .*\)/[^/]*$$,\1,' | \ $(AWK) 'BEGIN { files["."] = "" } { files[$$2] = files[$$2] " " $$1; \ if (++n[$$2] == $(am__install_max)) \ { print $$2, files[$$2]; n[$$2] = 0; files[$$2] = "" } } \ END { for (dir in files) print dir, files[dir] }' am__base_list = \ sed '$$!N;$$!N;$$!N;$$!N;$$!N;$$!N;$$!N;s/\n/ /g' | \ sed '$$!N;$$!N;$$!N;$$!N;s/\n/ /g' am__uninstall_files_from_dir = { \ test -z "$$files" \ || { test ! -d "$$dir" && test ! -f "$$dir" && test ! -r "$$dir"; } \ || { echo " ( cd '$$dir' && rm -f" $$files ")"; \ $(am__cd) "$$dir" && rm -f $$files; }; \ } am__installdirs = "$(DESTDIR)$(localdocdir)" DATA = $(localdoc_DATA) RECURSIVE_CLEAN_TARGETS = mostlyclean-recursive clean-recursive \ distclean-recursive maintainer-clean-recursive AM_RECURSIVE_TARGETS = $(RECURSIVE_TARGETS:-recursive=) \ $(RECURSIVE_CLEAN_TARGETS:-recursive=) tags TAGS ctags CTAGS \ distdir dist dist-all distcheck ETAGS = etags CTAGS = ctags DIST_SUBDIRS = $(SUBDIRS) DISTFILES = $(DIST_COMMON) $(DIST_SOURCES) $(TEXINFOS) $(EXTRA_DIST) distdir = $(PACKAGE)-$(VERSION) top_distdir = $(distdir) am__remove_distdir = \ if test -d "$(distdir)"; then \ find "$(distdir)" -type d ! -perm -200 -exec chmod u+w {} ';' \ && rm -rf "$(distdir)" \ || { sleep 5 && rm -rf "$(distdir)"; }; \ else :; fi am__relativize = \ dir0=`pwd`; \ sed_first='s,^\([^/]*\)/.*$$,\1,'; \ sed_rest='s,^[^/]*/*,,'; \ sed_last='s,^.*/\([^/]*\)$$,\1,'; \ sed_butlast='s,/*[^/]*$$,,'; \ while test -n "$$dir1"; do \ first=`echo "$$dir1" | sed -e "$$sed_first"`; \ if test "$$first" != "."; then \ if test "$$first" = ".."; then \ dir2=`echo "$$dir0" | sed -e "$$sed_last"`/"$$dir2"; \ dir0=`echo "$$dir0" | sed -e "$$sed_butlast"`; \ else \ first2=`echo "$$dir2" | sed -e "$$sed_first"`; \ if test "$$first2" = "$$first"; then \ dir2=`echo "$$dir2" | sed -e "$$sed_rest"`; \ else \ dir2="../$$dir2"; \ fi; \ dir0="$$dir0"/"$$first"; \ fi; \ fi; \ dir1=`echo "$$dir1" | sed -e "$$sed_rest"`; \ done; \ reldir="$$dir2" DIST_ARCHIVES = $(distdir).tar.gz GZIP_ENV = --best distuninstallcheck_listfiles = find . -type f -print am__distuninstallcheck_listfiles = $(distuninstallcheck_listfiles) \ | sed 's|^\./|$(prefix)/|' | grep -v '$(infodir)/dir$$' distcleancheck_listfiles = find . -type f -print ACLOCAL = @ACLOCAL@ AMTAR = @AMTAR@ AR = @AR@ AS = @AS@ AUTOCONF = @AUTOCONF@ AUTOHEADER = @AUTOHEADER@ AUTOMAKE = @AUTOMAKE@ AWK = @AWK@ CC = @CC@ CCDEPMODE = @CCDEPMODE@ CFLAGS = @CFLAGS@ CPP = @CPP@ CPPFLAGS = @CPPFLAGS@ CURL_CFLAGS = @CURL_CFLAGS@ CURL_CONFIG = @CURL_CONFIG@ CURL_LIBS = @CURL_LIBS@ CXX = @CXX@ CXXCPP = @CXXCPP@ CXXDEPMODE = @CXXDEPMODE@ CXXFLAGS = @CXXFLAGS@ CYGPATH_W = @CYGPATH_W@ DEFS = @DEFS@ DEPDIR = @DEPDIR@ DLLTOOL = @DLLTOOL@ DSYMUTIL = @DSYMUTIL@ DUMPBIN = @DUMPBIN@ ECHO_C = @ECHO_C@ ECHO_N = @ECHO_N@ ECHO_T = @ECHO_T@ EGREP = @EGREP@ ERL = @ERL@ ERLANG_FLAGS = @ERLANG_FLAGS@ ERLC = @ERLC@ ERLC_FLAGS = @ERLC_FLAGS@ ESCRIPT = @ESCRIPT@ EXEEXT = @EXEEXT@ FGREP = @FGREP@ FLAGS = @FLAGS@ GREP = @GREP@ HAS_HELP2MAN = @HAS_HELP2MAN@ HAS_INSTALLINFO = @HAS_INSTALLINFO@ HAS_MAKEINFO = @HAS_MAKEINFO@ HAS_PDFLATEX = @HAS_PDFLATEX@ HAS_SPHINX_BUILD = @HAS_SPHINX_BUILD@ ICU_BIN = @ICU_BIN@ ICU_CFLAGS = @ICU_CFLAGS@ ICU_CONFIG = @ICU_CONFIG@ ICU_CPPFLAGS = @ICU_CPPFLAGS@ ICU_CXXFLAGS = @ICU_CXXFLAGS@ ICU_LIBS = @ICU_LIBS@ INNO_COMPILER_EXECUTABLE = @INNO_COMPILER_EXECUTABLE@ INSTALL = @INSTALL@ INSTALL_DATA = @INSTALL_DATA@ INSTALL_PROGRAM = @INSTALL_PROGRAM@ INSTALL_SCRIPT = @INSTALL_SCRIPT@ INSTALL_STRIP_PROGRAM = @INSTALL_STRIP_PROGRAM@ JS_CFLAGS = @JS_CFLAGS@ JS_LIBS = @JS_LIBS@ JS_LIB_BINARY = @JS_LIB_BINARY@ LD = @LD@ LDFLAGS = @LDFLAGS@ LIBOBJS = @LIBOBJS@ LIBS = @LIBS@ LIBTOOL = @LIBTOOL@ LIPO = @LIPO@ LN_S = @LN_S@ LTLIBOBJS = @LTLIBOBJS@ MAKEINFO = @MAKEINFO@ MANIFEST_TOOL = @MANIFEST_TOOL@ MKDIR_P = @MKDIR_P@ NM = @NM@ NMEDIT = @NMEDIT@ OBJDUMP = @OBJDUMP@ OBJEXT = @OBJEXT@ OTOOL = @OTOOL@ OTOOL64 = @OTOOL64@ PACKAGE = @PACKAGE@ PACKAGE_BUGREPORT = @PACKAGE_BUGREPORT@ PACKAGE_NAME = @PACKAGE_NAME@ PACKAGE_STRING = @PACKAGE_STRING@ PACKAGE_TARNAME = @PACKAGE_TARNAME@ PACKAGE_URL = @PACKAGE_URL@ PACKAGE_VERSION = @PACKAGE_VERSION@ PATH_SEPARATOR = @PATH_SEPARATOR@ PKG_CONFIG = @PKG_CONFIG@ PKG_CONFIG_LIBDIR = @PKG_CONFIG_LIBDIR@ PKG_CONFIG_PATH = @PKG_CONFIG_PATH@ RANLIB = @RANLIB@ SED = @SED@ SET_MAKE = @SET_MAKE@ SHELL = @SHELL@ SNAPPY_MAJOR = @SNAPPY_MAJOR@ SNAPPY_MINOR = @SNAPPY_MINOR@ SNAPPY_PATCHLEVEL = @SNAPPY_PATCHLEVEL@ STRIP = @STRIP@ VERSION = @VERSION@ abs_builddir = @abs_builddir@ abs_srcdir = @abs_srcdir@ abs_top_builddir = @abs_top_builddir@ abs_top_srcdir = @abs_top_srcdir@ ac_ct_AR = @ac_ct_AR@ ac_ct_CC = @ac_ct_CC@ ac_ct_CXX = @ac_ct_CXX@ ac_ct_DUMPBIN = @ac_ct_DUMPBIN@ ac_cv_have_stddef_h = @ac_cv_have_stddef_h@ ac_cv_have_stdint_h = @ac_cv_have_stdint_h@ am__include = @am__include@ am__leading_dot = @am__leading_dot@ am__quote = @am__quote@ am__tar = @am__tar@ am__untar = @am__untar@ bindir = @bindir@ bug_uri = @bug_uri@ build = @build@ build_alias = @build_alias@ build_cpu = @build_cpu@ build_os = @build_os@ build_vendor = @build_vendor@ builddir = @builddir@ datadir = @datadir@ datarootdir = @datarootdir@ docdir = @docdir@ dvidir = @dvidir@ erlangbin = @erlangbin@ erlangversion = @erlangversion@ exec_prefix = @exec_prefix@ host = @host@ host_alias = @host_alias@ host_cpu = @host_cpu@ host_os = @host_os@ host_vendor = @host_vendor@ htmldir = @htmldir@ includedir = @includedir@ infodir = @infodir@ initdir = @initdir@ install_sh = @install_sh@ launchddir = @launchddir@ libdir = @libdir@ libexecdir = @libexecdir@ localconfdir = @localconfdir@ localdatadir = @localdatadir@ localdocdir = @localdocdir@ localedir = @localedir@ localerlanglibdir = @localerlanglibdir@ locallibbindir = @locallibbindir@ locallibdir = @locallibdir@ localstatedir = @localstatedir@ localstatelibdir = @localstatelibdir@ localstatelogdir = @localstatelogdir@ localstaterundir = @localstaterundir@ mandir = @mandir@ mkdir_p = @mkdir_p@ msvc_redist_dir = @msvc_redist_dir@ msvc_redist_name = @msvc_redist_name@ oldincludedir = @oldincludedir@ openssl_bin_dir = @openssl_bin_dir@ otp_release = @otp_release@ package_author_address = @package_author_address@ package_author_name = @package_author_name@ package_identifier = @package_identifier@ package_name = @package_name@ package_tarname = @package_tarname@ pdfdir = @pdfdir@ prefix = @prefix@ program_transform_name = @program_transform_name@ psdir = @psdir@ sbindir = @sbindir@ sharedstatedir = @sharedstatedir@ srcdir = @srcdir@ sysconfdir = @sysconfdir@ target_alias = @target_alias@ top_build_prefix = @top_build_prefix@ top_builddir = @top_builddir@ top_srcdir = @top_srcdir@ version = @version@ version_major = @version_major@ version_minor = @version_minor@ version_release = @version_release@ version_revision = @version_revision@ version_stage = @version_stage@ SUBDIRS = bin etc src share test var utils ACLOCAL_AMFLAGS = -I m4 localdoc_DATA = \ AUTHORS.gz \ BUGS.gz \ DEVELOPERS.gz \ INSTALL.gz \ INSTALL.Unix.gz \ INSTALL.Windows.gz \ LICENSE.gz \ NOTICE.gz \ README.gz \ THANKS.gz DISTCLEANFILES = $(localdoc_DATA) EXTRA_DIST = \ AUTHORS \ BUGS \ DEVELOPERS \ INSTALL \ INSTALL.Unix \ INSTALL.Windows \ LICENSE \ NOTICE \ README.rst \ THANKS \ build-aux/dist-error \ build-aux/sphinx-build \ build-aux/sphinx-touch \ license.skip all: config.h $(MAKE) $(AM_MAKEFLAGS) all-recursive .SUFFIXES: am--refresh: Makefile @: $(srcdir)/Makefile.in: $(srcdir)/Makefile.am $(am__configure_deps) @for dep in $?; do \ case '$(am__configure_deps)' in \ *$$dep*) \ echo ' cd $(srcdir) && $(AUTOMAKE) --foreign'; \ $(am__cd) $(srcdir) && $(AUTOMAKE) --foreign \ && exit 0; \ exit 1;; \ esac; \ done; \ echo ' cd $(top_srcdir) && $(AUTOMAKE) --foreign Makefile'; \ $(am__cd) $(top_srcdir) && \ $(AUTOMAKE) --foreign Makefile .PRECIOUS: Makefile Makefile: $(srcdir)/Makefile.in $(top_builddir)/config.status @case '$?' in \ *config.status*) \ echo ' $(SHELL) ./config.status'; \ $(SHELL) ./config.status;; \ *) \ echo ' cd $(top_builddir) && $(SHELL) ./config.status $@ $(am__depfiles_maybe)'; \ cd $(top_builddir) && $(SHELL) ./config.status $@ $(am__depfiles_maybe);; \ esac; $(top_builddir)/config.status: $(top_srcdir)/configure $(CONFIG_STATUS_DEPENDENCIES) $(SHELL) ./config.status --recheck $(top_srcdir)/configure: $(am__configure_deps) $(am__cd) $(srcdir) && $(AUTOCONF) $(ACLOCAL_M4): $(am__aclocal_m4_deps) $(am__cd) $(srcdir) && $(ACLOCAL) $(ACLOCAL_AMFLAGS) $(am__aclocal_m4_deps): config.h: stamp-h1 @if test ! -f $@; then rm -f stamp-h1; else :; fi @if test ! -f $@; then $(MAKE) $(AM_MAKEFLAGS) stamp-h1; else :; fi stamp-h1: $(srcdir)/config.h.in $(top_builddir)/config.status @rm -f stamp-h1 cd $(top_builddir) && $(SHELL) ./config.status config.h $(srcdir)/config.h.in: $(am__configure_deps) ($(am__cd) $(top_srcdir) && $(AUTOHEADER)) rm -f stamp-h1 touch $@ src/snappy/google-snappy/config.h: src/snappy/google-snappy/stamp-h2 @if test ! -f $@; then rm -f src/snappy/google-snappy/stamp-h2; else :; fi @if test ! -f $@; then $(MAKE) $(AM_MAKEFLAGS) src/snappy/google-snappy/stamp-h2; else :; fi src/snappy/google-snappy/stamp-h2: $(top_srcdir)/src/snappy/google-snappy/config.h.in $(top_builddir)/config.status @rm -f src/snappy/google-snappy/stamp-h2 cd $(top_builddir) && $(SHELL) ./config.status src/snappy/google-snappy/config.h distclean-hdr: -rm -f config.h stamp-h1 src/snappy/google-snappy/config.h src/snappy/google-snappy/stamp-h2 src/snappy/google-snappy/snappy-stubs-public.h: $(top_builddir)/config.status $(top_srcdir)/src/snappy/google-snappy/snappy-stubs-public.h.in cd $(top_builddir) && $(SHELL) ./config.status $@ mostlyclean-libtool: -rm -f *.lo clean-libtool: -rm -rf .libs _libs distclean-libtool: -rm -f libtool config.lt install-localdocDATA: $(localdoc_DATA) @$(NORMAL_INSTALL) @list='$(localdoc_DATA)'; test -n "$(localdocdir)" || list=; \ if test -n "$$list"; then \ echo " $(MKDIR_P) '$(DESTDIR)$(localdocdir)'"; \ $(MKDIR_P) "$(DESTDIR)$(localdocdir)" || exit 1; \ fi; \ for p in $$list; do \ if test -f "$$p"; then d=; else d="$(srcdir)/"; fi; \ echo "$$d$$p"; \ done | $(am__base_list) | \ while read files; do \ echo " $(INSTALL_DATA) $$files '$(DESTDIR)$(localdocdir)'"; \ $(INSTALL_DATA) $$files "$(DESTDIR)$(localdocdir)" || exit $$?; \ done uninstall-localdocDATA: @$(NORMAL_UNINSTALL) @list='$(localdoc_DATA)'; test -n "$(localdocdir)" || list=; \ files=`for p in $$list; do echo $$p; done | sed -e 's|^.*/||'`; \ dir='$(DESTDIR)$(localdocdir)'; $(am__uninstall_files_from_dir) # This directory's subdirectories are mostly independent; you can cd # into them and run `make' without going through this Makefile. # To change the values of `make' variables: instead of editing Makefiles, # (1) if the variable is set in `config.status', edit `config.status' # (which will cause the Makefiles to be regenerated when you run `make'); # (2) otherwise, pass the desired values on the `make' command line. $(RECURSIVE_TARGETS): @fail= failcom='exit 1'; \ for f in x $$MAKEFLAGS; do \ case $$f in \ *=* | --[!k]*);; \ *k*) failcom='fail=yes';; \ esac; \ done; \ dot_seen=no; \ target=`echo $@ | sed s/-recursive//`; \ list='$(SUBDIRS)'; for subdir in $$list; do \ echo "Making $$target in $$subdir"; \ if test "$$subdir" = "."; then \ dot_seen=yes; \ local_target="$$target-am"; \ else \ local_target="$$target"; \ fi; \ ($(am__cd) $$subdir && $(MAKE) $(AM_MAKEFLAGS) $$local_target) \ || eval $$failcom; \ done; \ if test "$$dot_seen" = "no"; then \ $(MAKE) $(AM_MAKEFLAGS) "$$target-am" || exit 1; \ fi; test -z "$$fail" $(RECURSIVE_CLEAN_TARGETS): @fail= failcom='exit 1'; \ for f in x $$MAKEFLAGS; do \ case $$f in \ *=* | --[!k]*);; \ *k*) failcom='fail=yes';; \ esac; \ done; \ dot_seen=no; \ case "$@" in \ distclean-* | maintainer-clean-*) list='$(DIST_SUBDIRS)' ;; \ *) list='$(SUBDIRS)' ;; \ esac; \ rev=''; for subdir in $$list; do \ if test "$$subdir" = "."; then :; else \ rev="$$subdir $$rev"; \ fi; \ done; \ rev="$$rev ."; \ target=`echo $@ | sed s/-recursive//`; \ for subdir in $$rev; do \ echo "Making $$target in $$subdir"; \ if test "$$subdir" = "."; then \ local_target="$$target-am"; \ else \ local_target="$$target"; \ fi; \ ($(am__cd) $$subdir && $(MAKE) $(AM_MAKEFLAGS) $$local_target) \ || eval $$failcom; \ done && test -z "$$fail" tags-recursive: list='$(SUBDIRS)'; for subdir in $$list; do \ test "$$subdir" = . || ($(am__cd) $$subdir && $(MAKE) $(AM_MAKEFLAGS) tags); \ done ctags-recursive: list='$(SUBDIRS)'; for subdir in $$list; do \ test "$$subdir" = . || ($(am__cd) $$subdir && $(MAKE) $(AM_MAKEFLAGS) ctags); \ done ID: $(HEADERS) $(SOURCES) $(LISP) $(TAGS_FILES) list='$(SOURCES) $(HEADERS) $(LISP) $(TAGS_FILES)'; \ unique=`for i in $$list; do \ if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \ done | \ $(AWK) '{ files[$$0] = 1; nonempty = 1; } \ END { if (nonempty) { for (i in files) print i; }; }'`; \ mkid -fID $$unique tags: TAGS TAGS: tags-recursive $(HEADERS) $(SOURCES) config.h.in $(TAGS_DEPENDENCIES) \ $(TAGS_FILES) $(LISP) set x; \ here=`pwd`; \ if ($(ETAGS) --etags-include --version) >/dev/null 2>&1; then \ include_option=--etags-include; \ empty_fix=.; \ else \ include_option=--include; \ empty_fix=; \ fi; \ list='$(SUBDIRS)'; for subdir in $$list; do \ if test "$$subdir" = .; then :; else \ test ! -f $$subdir/TAGS || \ set "$$@" "$$include_option=$$here/$$subdir/TAGS"; \ fi; \ done; \ list='$(SOURCES) $(HEADERS) config.h.in $(LISP) $(TAGS_FILES)'; \ unique=`for i in $$list; do \ if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \ done | \ $(AWK) '{ files[$$0] = 1; nonempty = 1; } \ END { if (nonempty) { for (i in files) print i; }; }'`; \ shift; \ if test -z "$(ETAGS_ARGS)$$*$$unique"; then :; else \ test -n "$$unique" || unique=$$empty_fix; \ if test $$# -gt 0; then \ $(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \ "$$@" $$unique; \ else \ $(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \ $$unique; \ fi; \ fi ctags: CTAGS CTAGS: ctags-recursive $(HEADERS) $(SOURCES) config.h.in $(TAGS_DEPENDENCIES) \ $(TAGS_FILES) $(LISP) list='$(SOURCES) $(HEADERS) config.h.in $(LISP) $(TAGS_FILES)'; \ unique=`for i in $$list; do \ if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \ done | \ $(AWK) '{ files[$$0] = 1; nonempty = 1; } \ END { if (nonempty) { for (i in files) print i; }; }'`; \ test -z "$(CTAGS_ARGS)$$unique" \ || $(CTAGS) $(CTAGSFLAGS) $(AM_CTAGSFLAGS) $(CTAGS_ARGS) \ $$unique GTAGS: here=`$(am__cd) $(top_builddir) && pwd` \ && $(am__cd) $(top_srcdir) \ && gtags -i $(GTAGS_ARGS) "$$here" distclean-tags: -rm -f TAGS ID GTAGS GRTAGS GSYMS GPATH tags distdir: $(DISTFILES) $(am__remove_distdir) test -d "$(distdir)" || mkdir "$(distdir)" @srcdirstrip=`echo "$(srcdir)" | sed 's/[].[^$$\\*]/\\\\&/g'`; \ topsrcdirstrip=`echo "$(top_srcdir)" | sed 's/[].[^$$\\*]/\\\\&/g'`; \ list='$(DISTFILES)'; \ dist_files=`for file in $$list; do echo $$file; done | \ sed -e "s|^$$srcdirstrip/||;t" \ -e "s|^$$topsrcdirstrip/|$(top_builddir)/|;t"`; \ case $$dist_files in \ */*) $(MKDIR_P) `echo "$$dist_files" | \ sed '/\//!d;s|^|$(distdir)/|;s,/[^/]*$$,,' | \ sort -u` ;; \ esac; \ for file in $$dist_files; do \ if test -f $$file || test -d $$file; then d=.; else d=$(srcdir); fi; \ if test -d $$d/$$file; then \ dir=`echo "/$$file" | sed -e 's,/[^/]*$$,,'`; \ if test -d "$(distdir)/$$file"; then \ find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} \;; \ fi; \ if test -d $(srcdir)/$$file && test $$d != $(srcdir); then \ cp -fpR $(srcdir)/$$file "$(distdir)$$dir" || exit 1; \ find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} \;; \ fi; \ cp -fpR $$d/$$file "$(distdir)$$dir" || exit 1; \ else \ test -f "$(distdir)/$$file" \ || cp -p $$d/$$file "$(distdir)/$$file" \ || exit 1; \ fi; \ done @list='$(DIST_SUBDIRS)'; for subdir in $$list; do \ if test "$$subdir" = .; then :; else \ $(am__make_dryrun) \ || test -d "$(distdir)/$$subdir" \ || $(MKDIR_P) "$(distdir)/$$subdir" \ || exit 1; \ dir1=$$subdir; dir2="$(distdir)/$$subdir"; \ $(am__relativize); \ new_distdir=$$reldir; \ dir1=$$subdir; dir2="$(top_distdir)"; \ $(am__relativize); \ new_top_distdir=$$reldir; \ echo " (cd $$subdir && $(MAKE) $(AM_MAKEFLAGS) top_distdir="$$new_top_distdir" distdir="$$new_distdir" \\"; \ echo " am__remove_distdir=: am__skip_length_check=: am__skip_mode_fix=: distdir)"; \ ($(am__cd) $$subdir && \ $(MAKE) $(AM_MAKEFLAGS) \ top_distdir="$$new_top_distdir" \ distdir="$$new_distdir" \ am__remove_distdir=: \ am__skip_length_check=: \ am__skip_mode_fix=: \ distdir) \ || exit 1; \ fi; \ done $(MAKE) $(AM_MAKEFLAGS) \ top_distdir="$(top_distdir)" distdir="$(distdir)" \ dist-hook -test -n "$(am__skip_mode_fix)" \ || find "$(distdir)" -type d ! -perm -755 \ -exec chmod u+rwx,go+rx {} \; -o \ ! -type d ! -perm -444 -links 1 -exec chmod a+r {} \; -o \ ! -type d ! -perm -400 -exec chmod a+r {} \; -o \ ! -type d ! -perm -444 -exec $(install_sh) -c -m a+r {} {} \; \ || chmod -R a+r "$(distdir)" dist-gzip: distdir tardir=$(distdir) && $(am__tar) | GZIP=$(GZIP_ENV) gzip -c >$(distdir).tar.gz $(am__remove_distdir) dist-bzip2: distdir tardir=$(distdir) && $(am__tar) | BZIP2=$${BZIP2--9} bzip2 -c >$(distdir).tar.bz2 $(am__remove_distdir) dist-lzip: distdir tardir=$(distdir) && $(am__tar) | lzip -c $${LZIP_OPT--9} >$(distdir).tar.lz $(am__remove_distdir) dist-lzma: distdir tardir=$(distdir) && $(am__tar) | lzma -9 -c >$(distdir).tar.lzma $(am__remove_distdir) dist-xz: distdir tardir=$(distdir) && $(am__tar) | XZ_OPT=$${XZ_OPT--e} xz -c >$(distdir).tar.xz $(am__remove_distdir) dist-tarZ: distdir tardir=$(distdir) && $(am__tar) | compress -c >$(distdir).tar.Z $(am__remove_distdir) dist-shar: distdir shar $(distdir) | GZIP=$(GZIP_ENV) gzip -c >$(distdir).shar.gz $(am__remove_distdir) dist-zip: distdir -rm -f $(distdir).zip zip -rq $(distdir).zip $(distdir) $(am__remove_distdir) dist dist-all: distdir tardir=$(distdir) && $(am__tar) | GZIP=$(GZIP_ENV) gzip -c >$(distdir).tar.gz $(am__remove_distdir) # This target untars the dist file and tries a VPATH configuration. Then # it guarantees that the distribution is self-contained by making another # tarfile. distcheck: dist case '$(DIST_ARCHIVES)' in \ *.tar.gz*) \ GZIP=$(GZIP_ENV) gzip -dc $(distdir).tar.gz | $(am__untar) ;;\ *.tar.bz2*) \ bzip2 -dc $(distdir).tar.bz2 | $(am__untar) ;;\ *.tar.lzma*) \ lzma -dc $(distdir).tar.lzma | $(am__untar) ;;\ *.tar.lz*) \ lzip -dc $(distdir).tar.lz | $(am__untar) ;;\ *.tar.xz*) \ xz -dc $(distdir).tar.xz | $(am__untar) ;;\ *.tar.Z*) \ uncompress -c $(distdir).tar.Z | $(am__untar) ;;\ *.shar.gz*) \ GZIP=$(GZIP_ENV) gzip -dc $(distdir).shar.gz | unshar ;;\ *.zip*) \ unzip $(distdir).zip ;;\ esac chmod -R a-w $(distdir); chmod u+w $(distdir) mkdir $(distdir)/_build mkdir $(distdir)/_inst chmod a-w $(distdir) test -d $(distdir)/_build || exit 0; \ dc_install_base=`$(am__cd) $(distdir)/_inst && pwd | sed -e 's,^[^:\\/]:[\\/],/,'` \ && dc_destdir="$${TMPDIR-/tmp}/am-dc-$$$$/" \ && $(MAKE) $(AM_MAKEFLAGS) distcheck-hook \ && am__cwd=`pwd` \ && $(am__cd) $(distdir)/_build \ && ../configure --srcdir=.. --prefix="$$dc_install_base" \ $(AM_DISTCHECK_CONFIGURE_FLAGS) \ $(DISTCHECK_CONFIGURE_FLAGS) \ && $(MAKE) $(AM_MAKEFLAGS) \ && $(MAKE) $(AM_MAKEFLAGS) dvi \ && $(MAKE) $(AM_MAKEFLAGS) check \ && $(MAKE) $(AM_MAKEFLAGS) install \ && $(MAKE) $(AM_MAKEFLAGS) installcheck \ && $(MAKE) $(AM_MAKEFLAGS) uninstall \ && $(MAKE) $(AM_MAKEFLAGS) distuninstallcheck_dir="$$dc_install_base" \ distuninstallcheck \ && chmod -R a-w "$$dc_install_base" \ && ({ \ (cd ../.. && umask 077 && mkdir "$$dc_destdir") \ && $(MAKE) $(AM_MAKEFLAGS) DESTDIR="$$dc_destdir" install \ && $(MAKE) $(AM_MAKEFLAGS) DESTDIR="$$dc_destdir" uninstall \ && $(MAKE) $(AM_MAKEFLAGS) DESTDIR="$$dc_destdir" \ distuninstallcheck_dir="$$dc_destdir" distuninstallcheck; \ } || { rm -rf "$$dc_destdir"; exit 1; }) \ && rm -rf "$$dc_destdir" \ && $(MAKE) $(AM_MAKEFLAGS) dist \ && rm -rf $(DIST_ARCHIVES) \ && $(MAKE) $(AM_MAKEFLAGS) distcleancheck \ && cd "$$am__cwd" \ || exit 1 $(am__remove_distdir) @(echo "$(distdir) archives ready for distribution: "; \ list='$(DIST_ARCHIVES)'; for i in $$list; do echo $$i; done) | \ sed -e 1h -e 1s/./=/g -e 1p -e 1x -e '$$p' -e '$$x' distuninstallcheck: @test -n '$(distuninstallcheck_dir)' || { \ echo 'ERROR: trying to run $@ with an empty' \ '$$(distuninstallcheck_dir)' >&2; \ exit 1; \ }; \ $(am__cd) '$(distuninstallcheck_dir)' || { \ echo 'ERROR: cannot chdir into $(distuninstallcheck_dir)' >&2; \ exit 1; \ }; \ test `$(am__distuninstallcheck_listfiles) | wc -l` -eq 0 \ || { echo "ERROR: files left after uninstall:" ; \ if test -n "$(DESTDIR)"; then \ echo " (check DESTDIR support)"; \ fi ; \ $(distuninstallcheck_listfiles) ; \ exit 1; } >&2 distcleancheck: distclean @if test '$(srcdir)' = . ; then \ echo "ERROR: distcleancheck can only run from a VPATH build" ; \ exit 1 ; \ fi @test `$(distcleancheck_listfiles) | wc -l` -eq 0 \ || { echo "ERROR: files left in build directory after distclean:" ; \ $(distcleancheck_listfiles) ; \ exit 1; } >&2 check-am: all-am check: check-recursive all-am: Makefile $(DATA) config.h installdirs: installdirs-recursive installdirs-am: for dir in "$(DESTDIR)$(localdocdir)"; do \ test -z "$$dir" || $(MKDIR_P) "$$dir"; \ done install: install-recursive install-exec: install-exec-recursive install-data: install-data-recursive uninstall: uninstall-recursive install-am: all-am @$(MAKE) $(AM_MAKEFLAGS) install-exec-am install-data-am installcheck: installcheck-recursive install-strip: if test -z '$(STRIP)'; then \ $(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(INSTALL_STRIP_PROGRAM)" \ install_sh_PROGRAM="$(INSTALL_STRIP_PROGRAM)" INSTALL_STRIP_FLAG=-s \ install; \ else \ $(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(INSTALL_STRIP_PROGRAM)" \ install_sh_PROGRAM="$(INSTALL_STRIP_PROGRAM)" INSTALL_STRIP_FLAG=-s \ "INSTALL_PROGRAM_ENV=STRIPPROG='$(STRIP)'" install; \ fi mostlyclean-generic: clean-generic: distclean-generic: -test -z "$(CONFIG_CLEAN_FILES)" || rm -f $(CONFIG_CLEAN_FILES) -test . = "$(srcdir)" || test -z "$(CONFIG_CLEAN_VPATH_FILES)" || rm -f $(CONFIG_CLEAN_VPATH_FILES) -test -z "$(DISTCLEANFILES)" || rm -f $(DISTCLEANFILES) maintainer-clean-generic: @echo "This command is intended for maintainers to use" @echo "it deletes files that may require special tools to rebuild." clean: clean-recursive clean-am: clean-generic clean-libtool mostlyclean-am distclean: distclean-recursive -rm -f $(am__CONFIG_DISTCLEAN_FILES) -rm -f Makefile distclean-am: clean-am distclean-generic distclean-hdr \ distclean-libtool distclean-local distclean-tags dvi: dvi-recursive dvi-am: html: html-recursive html-am: info: info-recursive info-am: install-data-am: install-localdocDATA @$(NORMAL_INSTALL) $(MAKE) $(AM_MAKEFLAGS) install-data-hook install-dvi: install-dvi-recursive install-dvi-am: install-exec-am: install-html: install-html-recursive install-html-am: install-info: install-info-recursive install-info-am: install-man: install-pdf: install-pdf-recursive install-pdf-am: install-ps: install-ps-recursive install-ps-am: installcheck-am: maintainer-clean: maintainer-clean-recursive -rm -f $(am__CONFIG_DISTCLEAN_FILES) -rm -rf $(top_srcdir)/autom4te.cache -rm -f Makefile maintainer-clean-am: distclean-am maintainer-clean-generic mostlyclean: mostlyclean-recursive mostlyclean-am: mostlyclean-generic mostlyclean-libtool pdf: pdf-recursive pdf-am: ps: ps-recursive ps-am: uninstall-am: uninstall-localdocDATA .MAKE: $(RECURSIVE_CLEAN_TARGETS) $(RECURSIVE_TARGETS) all \ ctags-recursive install-am install-data-am install-strip \ tags-recursive .PHONY: $(RECURSIVE_CLEAN_TARGETS) $(RECURSIVE_TARGETS) CTAGS GTAGS \ all all-am am--refresh check check-am clean clean-generic \ clean-libtool ctags ctags-recursive dist dist-all dist-bzip2 \ dist-gzip dist-hook dist-lzip dist-lzma dist-shar dist-tarZ \ dist-xz dist-zip distcheck distclean distclean-generic \ distclean-hdr distclean-libtool distclean-local distclean-tags \ distcleancheck distdir distuninstallcheck dvi dvi-am html \ html-am info info-am install install-am install-data \ install-data-am install-data-hook install-dvi install-dvi-am \ install-exec install-exec-am install-html install-html-am \ install-info install-info-am install-localdocDATA install-man \ install-pdf install-pdf-am install-ps install-ps-am \ install-strip installcheck installcheck-am installdirs \ installdirs-am maintainer-clean maintainer-clean-generic \ mostlyclean mostlyclean-generic mostlyclean-libtool pdf pdf-am \ ps ps-am tags tags-recursive uninstall uninstall-am \ uninstall-localdocDATA AUTHORS.gz: AUTHORS gzip -9 < $< > $@ BUGS.gz: BUGS gzip -9 < $< > $@ DEVELOPERS.gz: DEVELOPERS gzip -9 < $< > $@ INSTALL.gz: INSTALL gzip -9 < $< > $@ INSTALL.Unix.gz: INSTALL.Unix gzip -9 < $< > $@ INSTALL.Windows.gz: INSTALL.Windows gzip -9 < $< > $@ LICENSE.gz: LICENSE gzip -9 < $< > $@ NOTICE.gz: NOTICE gzip -9 < $< > $@ README.gz: README.rst gzip -9 < $< > $@ THANKS.gz: THANKS gzip -9 < $< > $@ check: dev check-js @TESTS_TRUE@ $(top_builddir)/test/etap/run $(top_srcdir)/test/etap check-js: dev @TESTS_TRUE@@USE_CURL_TRUE@ MAKE=$(MAKE) $(top_builddir)/test/javascript/run check-etap: dev @TESTS_TRUE@ $(top_builddir)/test/etap/run $(top_srcdir)/test/etap cover: dev @TESTS_TRUE@ rm -f cover/*.coverdata @TESTS_TRUE@ COVER=1 COVER_BIN=./src/couchdb/ $(top_builddir)/test/etap/run @TESTS_TRUE@ SRC=./src/couchdb/ \ @TESTS_TRUE@ $(ERL) -noshell \ @TESTS_TRUE@ -pa src/etap \ @TESTS_TRUE@ -eval 'etap_report:create()' \ @TESTS_TRUE@ -s init stop > /dev/null 2>&1 dev: all @TESTS_TRUE@ @echo "This command is intended for developers to use;" @TESTS_TRUE@ @echo "it creates development ini files as well as a" @TESTS_TRUE@ @echo "$(top_builddir)/tmp structure for development runtime files." @TESTS_TRUE@ @echo "Use ./utils/run to launch CouchDB from the source tree." @TESTS_TRUE@ mkdir -p $(top_builddir)/etc/couchdb/default.d @TESTS_TRUE@ mkdir -p $(top_builddir)/etc/couchdb/local.d @TESTS_TRUE@ mkdir -p $(top_builddir)/tmp/lib @TESTS_TRUE@ mkdir -p $(top_builddir)/tmp/log @TESTS_TRUE@ mkdir -p $(top_builddir)/tmp/run/couchdb @TESTS_TRUE@ mkdir -p $(top_builddir)/tmp/plugins install-data-hook: @echo @echo "You have installed Apache CouchDB, time to relax." distclean-local: rm -fr $(top_builddir)/etc/couchdb/default.d rm -fr $(top_builddir)/etc/couchdb/local.d rm -fr $(top_builddir)/tmp rm -f $(top_builddir)/couchdb.stdout rm -f $(top_builddir)/couchdb.stderr .PHONY: local-clean local-clean: maintainer-clean @echo "This command is intended for maintainers to use;" @echo "it deletes files that may need special tools to rebuild." rm -f $(top_srcdir)/INSTALL rm -f $(top_srcdir)/acinclude.m4 rm -f $(top_srcdir)/aclocal.m4 rm -f $(top_srcdir)/config.h.in rm -f $(top_srcdir)/configure rm -f $(top_srcdir)/test/etap/temp.* rm -f $(top_srcdir)/*.tar.gz rm -f $(top_srcdir)/*.tar.gz.* find $(top_srcdir) -name Makefile.in -exec rm -f {} \; dist-hook: find $(top_srcdir) -type f -name "._*" -exec rm -f {} \; find $(top_builddir) -type f -name "._*" -exec rm -f {} \; distcheck-hook: $(MAKE) -C bin distcheck-hook $(MAKE) -C src/couchdb/priv distcheck-hook $(MAKE) -C share/doc/build distcheck-hook grep -rL 'http://www.apache.org/licenses/LICENSE-2.0' * \ | grep --include= -vEf $(top_srcdir)/license.skip; \ test "$$?" -eq 1 # Tell versions [3.59,3.63) of GNU make to not export all variables. # Otherwise a system limit (for SysV at least) may be exceeded. .NOEXPORT: apache-couchdb-1.5.0/config.h.in0000644000175000001440000000700012230722240013272 00000000000000/* config.h.in. Generated from configure.ac by autoheader. */ /* Define if building universal (internal helper macro) */ #undef AC_APPLE_UNIVERSAL_BUILD /* "CouchJS executable name." */ #undef COUCHJS_NAME /* Define to 1 if the compiler supports __builtin_ctz and friends. */ #undef HAVE_BUILTIN_CTZ /* Define to 1 if the compiler supports __builtin_expect. */ #undef HAVE_BUILTIN_EXPECT /* "Provide HTTP support to couchjs" */ #undef HAVE_CURL /* Define to 1 if you have the header file. */ #undef HAVE_DLFCN_H /* Define to 1 if you have the header file. */ #undef HAVE_INTTYPES_H /* Use newer JS_GetCharsAndLength function. */ #undef HAVE_JS_GET_STRING_CHARS_AND_LENGTH /* Define to 1 if you have the header file. */ #undef HAVE_MEMORY_H /* Define to 1 if you have the header file. */ #undef HAVE_STDDEF_H /* Define to 1 if you have the header file. */ #undef HAVE_STDINT_H /* Define to 1 if you have the header file. */ #undef HAVE_STDLIB_H /* Define to 1 if you have the header file. */ #undef HAVE_STRINGS_H /* Define to 1 if you have the header file. */ #undef HAVE_STRING_H /* Define to 1 if you have the header file. */ #undef HAVE_SYS_MMAN_H /* Define to 1 if you have the header file. */ #undef HAVE_SYS_RESOURCE_H /* Define to 1 if you have the header file. */ #undef HAVE_SYS_STAT_H /* Define to 1 if you have the header file. */ #undef HAVE_SYS_TYPES_H /* Define to 1 if you have the header file. */ #undef HAVE_UNISTD_H /* Use JSScript* for scripts */ #undef JSSCRIPT_TYPE /* Define to the sub-directory in which libtool stores uninstalled libraries. */ #undef LT_OBJDIR /* Name of package */ #undef PACKAGE /* Define to the address where bug reports for this package should be sent. */ #undef PACKAGE_BUGREPORT /* Define to the full name of this package. */ #undef PACKAGE_NAME /* Define to the full name and version of this package. */ #undef PACKAGE_STRING /* Define to the one symbol short name of this package. */ #undef PACKAGE_TARNAME /* Define to the home page for this package. */ #undef PACKAGE_URL /* Define to the version of this package. */ #undef PACKAGE_VERSION /* Use SpiderMonkey 1.8.0 */ #undef SM180 /* Use SpiderMonkey 1.8.5 */ #undef SM185 /* Define to 1 if you have the ANSI C header files. */ #undef STDC_HEADERS /* Enable extensions on AIX 3, Interix. */ #ifndef _ALL_SOURCE # undef _ALL_SOURCE #endif /* Enable GNU extensions on systems that have them. */ #ifndef _GNU_SOURCE # undef _GNU_SOURCE #endif /* Enable threading extensions on Solaris. */ #ifndef _POSIX_PTHREAD_SEMANTICS # undef _POSIX_PTHREAD_SEMANTICS #endif /* Enable extensions on HP NonStop. */ #ifndef _TANDEM_SOURCE # undef _TANDEM_SOURCE #endif /* Enable general extensions on Solaris. */ #ifndef __EXTENSIONS__ # undef __EXTENSIONS__ #endif /* Version number of package */ #undef VERSION /* Define WORDS_BIGENDIAN to 1 if your processor stores words with the most significant byte first (like Motorola and SPARC, unlike Intel). */ #if defined AC_APPLE_UNIVERSAL_BUILD # if defined __BIG_ENDIAN__ # define WORDS_BIGENDIAN 1 # endif #else # ifndef WORDS_BIGENDIAN # undef WORDS_BIGENDIAN # endif #endif /* Define to 1 if on MINIX. */ #undef _MINIX /* Define to 2 if the system does not provide POSIX.1 features except with this defined. */ #undef _POSIX_1_SOURCE /* Define to 1 if you need to in order for `stat' and other things to work. */ #undef _POSIX_SOURCE apache-couchdb-1.5.0/README.rst0000644000175000001440000000561212230722213012745 00000000000000Apache CouchDB README ===================== Installation ------------ For a low-level guide, see: INSTALL For a high-level guide to Unix-like systems, inc. Mac OS X and Ubuntu, see: INSTALL.Unix For a high-level guide to Microsoft Windows, see: INSTALL.Windows Follow the proper instructions to get CouchDB installed on your system. If you're having problems, skip to the next section. Documentation ------------- We have documentation: http://docs.couchdb.org/ They include a changelog: http://docs.couchdb.org/en/latest/changelog.html For troubleshooting, see: http://wiki.apache.org/couchdb/Troubleshooting If you're getting a cryptic error message, see: http://wiki.apache.org/couchdb/Error_messages For general help, see: http://couchdb.apache.org/#mailing-list We also have an IRC channel: http://webchat.freenode.net/?channels=couchdb The mailing lists provide a wealth of support and knowledge for you to tap into. Feel free to drop by with your questions or discussion. See the official CouchDB website for more information about our community resources. Running the Testsuite --------------------- Run the testsuite for couch.js and jquery.couch.js by browsing here: http://127.0.0.1:5984/_utils/spec/run.html It should work in at least Firefox >= 3.6 with Private Browsing mode enabled. Read more about JSpec here: https://github.com/liblime/jspec When you change the specs, but your changes have no effect, manually reload the changed spec file in the browser. When the spec that tests Erlang views fails, make sure you have enabled Erlang views as described here: http://wiki.apache.org/couchdb/EnableErlangViews Cryptographic Software Notice ----------------------------- This distribution includes cryptographic software. The country in which you currently reside may have restrictions on the import, possession, use, and/or re-export to another country, of encryption software. BEFORE using any encryption software, please check your country's laws, regulations and policies concerning the import, possession, or use, and re-export of encryption software, to see if this is permitted. See for more information. The U.S. Government Department of Commerce, Bureau of Industry and Security (BIS), has classified this software as Export Commodity Control Number (ECCN) 5D002.C.1, which includes information security software using or performing cryptographic functions with asymmetric algorithms. The form and manner of this Apache Software Foundation distribution makes it eligible for export under the License Exception ENC Technology Software Unrestricted (TSU) exception (see the BIS Export Administration Regulations, Section 740.13) for both object code and source code. The following provides more details on the included cryptographic software: CouchDB includes a HTTP client (ibrowse) with SSL functionality. apache-couchdb-1.5.0/INSTALL.Unix0000644000175000001440000002170012230722214013226 00000000000000Apache CouchDB README.Unix ========================== A high-level guide to Unix-like systems, inc. Mac OS X and Ubuntu. Community installation guides are available on the wiki: http://wiki.apache.org/couchdb/Installation This document is the canonical source of installation information. However, many systems have gotchas that you need to be aware of. In addition, dependencies frequently change as distributions update their archives. If you're running into trouble, be sure to check out the wiki. If you have any tips to share, please also update the wiki so that others can benefit from your experience. Troubleshooting --------------- There is a troubleshooting guide: http://wiki.apache.org/couchdb/Troubleshooting There is a wiki for general documentation: http://wiki.apache.org/couchdb/ There are collection of friendly mailing lists: http://couchdb.apache.org/community/lists.html Please work through these in order if you experience any problems. Dependencies ------------ You should have the following installed: * Erlang OTP (>=R13B04, =2.7) for docs (http://python.org/) * Python Sphinx (>=1.1.3) (http://pypi.python.org/pypi/Sphinx) It is recommended that you install Erlang OTP R13B-4 or above where possible. You will only need libcurl if you plan to run the JavaScript test suite. And help2man is only need if you plan on installing the CouchDB man pages. Python and Sphinx are only required for building the online documentation. Debian-based Systems ~~~~~~~~~~~~~~~~~~~~ You can install the dependencies by running: sudo apt-get install build-essential sudo apt-get install erlang-base-hipe sudo apt-get install erlang-dev sudo apt-get install erlang-manpages sudo apt-get install erlang-eunit sudo apt-get install erlang-nox sudo apt-get install libicu-dev sudo apt-get install libmozjs-dev sudo apt-get install libcurl4-openssl-dev sudo apt-get install pkg-config There are lots of Erlang packages. If there is a problem with your install, try a different mix. There is more information on the wiki. Additionally, you might want to install some of the optional Erlang tools which may also be useful. Be sure to update the version numbers to match your system's available packages. For up to date instructions, please see: http://wiki.apache.org/couchdb/Installing_on_Debian http://wiki.apache.org/couchdb/Installing_on_Ubuntu Unfortunately, it seems that installing dependencies on Ubuntu is troublesome. RedHat-based (Fedora, Centos, RHEL) Systems ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ You can install the dependencies by running: sudo yum groupinstall "Development Tools" sudo yum install autoconf sudo yum install autoconf-archive sudo yum install automake sudo yum install libtool sudo yum install perl-Test-Harness sudo yum install erlang-etap sudo yum install erlang-erts sudo yum install erlang-os_mon sudo yum install erlang-eunit sudo yum install libicu-devel sudo yum install js-devel sudo yum install curl-devel sudo yum install pkg-config While CouchDB builds against the default js-devel-1.7.0 included in some distributions, it's recommended to use a more recent js-devel-1.8.5. Mac OS X ~~~~~~~~ To build CouchDB from source on Mac OS X, you will need to install Xcode. You can install the other dependencies by running: brew install autoconf brew install autoconf-archive brew install automake brew install libtool brew install erlang brew install icu4c brew install spidermonkey brew install curl brew install pkg-config You will need Homebrew installed to use the `brew` command. Learn more about Homebrew at: http://mxcl.github.com/homebrew/ Some versions of Mac OS X ship a problematic OpenSSL library. If you're experiencing troubles with CouchDB crashing intermittently with a segmentation fault or a bus error, you will need to install your own version of OpenSSL. See the troubleshooting guide, mentioned above, for more information. Installing ---------- Once you have satisfied the dependencies you should run: ./configure This script will configure CouchDB to be installed into `/usr/local` by default. If you wish to customise the installation, pass `--help` to this script. If everything was successful you should see the following message: You have configured Apache CouchDB, time to relax. Relax. To install CouchDB you should run: make && sudo make install You only need to use `sudo` if you're installing into a system directory. Try `gmake` if `make` is giving you any problems. If everything was successful you should see the following message: You have installed Apache CouchDB, time to relax. Relax. First Run --------- You can start the CouchDB server by running: sudo -i -u couchdb couchdb This uses the `sudo` command to run the `couchdb` command as the `couchdb` user. When CouchDB starts it should eventually display the following message: Apache CouchDB has started, time to relax. Relax. To check that everything has worked, point your web browser to: http://127.0.0.1:5984/_utils/index.html From here you should run the test suite in Firefox. Security Considerations ----------------------- You should create a special `couchdb` user for CouchDB. On many Unix-like systems you can run: adduser --system \ --home /usr/local/var/lib/couchdb \ --no-create-home \ --shell /bin/bash \ --group --gecos \ "CouchDB Administrator" couchdb On Mac OS X you can use the Workgroup Manager to create users: http://www.apple.com/support/downloads/serveradmintools1047.html You must make sure that: * The user has a working POSIX shell * The user's home directory is `/usr/local/var/lib/couchdb` You can test this by: * Trying to log in as the `couchdb` user * Running `pwd` and checking the present working directory Change the ownership of the CouchDB directories by running: chown -R couchdb:couchdb /usr/local/etc/couchdb chown -R couchdb:couchdb /usr/local/var/lib/couchdb chown -R couchdb:couchdb /usr/local/var/log/couchdb chown -R couchdb:couchdb /usr/local/var/run/couchdb Change the permission of the CouchDB directories by running: chmod 0770 /usr/local/etc/couchdb chmod 0770 /usr/local/var/lib/couchdb chmod 0770 /usr/local/var/log/couchdb chmod 0770 /usr/local/var/run/couchdb Update the permissions for your `default.ini` file: chmod 0644 /usr/local/etc/couchdb/default.ini Running as a Daemon ------------------- SysV/BSD-style Systems ~~~~~~~~~~~~~~~~~~~~~~ You can use the `couchdb` init script to control the CouchDB daemon. On SysV-style systems, the init script will be installed into: /usr/local/etc/init.d On BSD-style systems, the init script will be installed into: /usr/local/etc/rc.d We use the `[init.d|rc.d]` notation to refer to both of these directories. You can control the CouchDB daemon by running: /usr/local/etc/[init.d|rc.d]/couchdb [start|stop|restart|status] If you wish to configure how the init script works, you can edit: /usr/local/etc/default/couchdb Comment out the `COUCHDB_USER` setting if you're running as a non-superuser. To start the daemon on boot, copy the init script to: /etc/[init.d|rc.d] You should then configure your system to run the init script automatically. You may be able to run: sudo update-rc.d couchdb defaults If this fails, consult your system documentation for more information. A `logrotate` configuration is installed into: /usr/local/etc/logrotate.d/couchdb Consult your `logrotate` documentation for more information. It is critical that the CouchDB logs are rotated so as not to fill your disk. Mac OS X ~~~~~~~~ You can use the `launchctl` command to control the CouchDB daemon. You can load the configuration by running: sudo launchctl load \ /usr/local/Library/LaunchDaemons/org.apache.couchdb.plist You can stop the CouchDB daemon by running: sudo launchctl unload \ /usr/local/Library/LaunchDaemons/org.apache.couchdb.plist You can start CouchDB by running: sudo launchctl start org.apache.couchdb You can restart CouchDB by running: sudo launchctl stop org.apache.couchdb You can edit the launchd configuration by running: open /usr/local/Library/LaunchDaemons/org.apache.couchdb.plist To start the daemon on boot, copy the configuration file to: /Library/LaunchDaemons Consult your system documentation for more information. apache-couchdb-1.5.0/acinclude.m40000644000175000001440000000257612230722214013456 00000000000000dnl Licensed under the Apache License, Version 2.0 (the "License"); you may not dnl use this file except in compliance with the License. dnl You may obtain a dnl copy of the License at dnl dnl http://www.apache.org/licenses/LICENSE-2.0 dnl dnl Unless required by applicable law or agreed to in writing, software dnl distributed under the License is distributed on an "AS IS" BASIS, WITHOUT dnl WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the dnl License for the specific language governing permissions and limitations dnl under the License. m4_define([LOCAL_PACKAGE_AUTHOR_NAME], [The Apache Software Foundation]) m4_define([LOCAL_PACKAGE_AUTHOR_ADDRESS], [dev@couchdb.apache.org]) m4_define([LOCAL_PACKAGE_IDENTIFIER], [couchdb]) m4_define([LOCAL_PACKAGE_TARNAME], [apache-couchdb]) m4_define([LOCAL_PACKAGE_NAME], [Apache CouchDB]) m4_define([LOCAL_BUG_URI], [https://issues.apache.org/jira/browse/COUCHDB]) m4_define([LOCAL_VERSION_MAJOR], [1]) m4_define([LOCAL_VERSION_MINOR], [5]) m4_define([LOCAL_VERSION_REVISION], [0]) m4_define([LOCAL_VERSION_STAGE], []) m4_define([LOCAL_VERSION_RELEASE], []) m4_define([LOCAL_VERSION_PRIMARY], [LOCAL_VERSION_MAJOR.LOCAL_VERSION_MINOR.LOCAL_VERSION_REVISION]) m4_define([LOCAL_VERSION_SECONDARY], [LOCAL_VERSION_STAGE[]LOCAL_VERSION_RELEASE]) m4_define([LOCAL_VERSION], [LOCAL_VERSION_PRIMARY[]LOCAL_VERSION_SECONDARY]) apache-couchdb-1.5.0/build-aux/0000755000175000001440000000000012230722301013222 500000000000000apache-couchdb-1.5.0/build-aux/depcomp0000755000175000001440000005064312021144127014531 00000000000000#! /bin/sh # depcomp - compile a program generating dependencies as side-effects scriptversion=2012-03-27.16; # UTC # Copyright (C) 1999, 2000, 2003, 2004, 2005, 2006, 2007, 2009, 2010, # 2011, 2012 Free Software Foundation, Inc. # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2, or (at your option) # any later version. # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # You should have received a copy of the GNU General Public License # along with this program. If not, see . # As a special exception to the GNU General Public License, if you # distribute this file as part of a program that contains a # configuration script generated by Autoconf, you may include it under # the same distribution terms that you use for the rest of that program. # Originally written by Alexandre Oliva . case $1 in '') echo "$0: No command. Try '$0 --help' for more information." 1>&2 exit 1; ;; -h | --h*) cat <<\EOF Usage: depcomp [--help] [--version] PROGRAM [ARGS] Run PROGRAMS ARGS to compile a file, generating dependencies as side-effects. Environment variables: depmode Dependency tracking mode. source Source file read by 'PROGRAMS ARGS'. object Object file output by 'PROGRAMS ARGS'. DEPDIR directory where to store dependencies. depfile Dependency file to output. tmpdepfile Temporary file to use when outputting dependencies. libtool Whether libtool is used (yes/no). Report bugs to . EOF exit $? ;; -v | --v*) echo "depcomp $scriptversion" exit $? ;; esac # A tabulation character. tab=' ' # A newline character. nl=' ' if test -z "$depmode" || test -z "$source" || test -z "$object"; then echo "depcomp: Variables source, object and depmode must be set" 1>&2 exit 1 fi # Dependencies for sub/bar.o or sub/bar.obj go into sub/.deps/bar.Po. depfile=${depfile-`echo "$object" | sed 's|[^\\/]*$|'${DEPDIR-.deps}'/&|;s|\.\([^.]*\)$|.P\1|;s|Pobj$|Po|'`} tmpdepfile=${tmpdepfile-`echo "$depfile" | sed 's/\.\([^.]*\)$/.T\1/'`} rm -f "$tmpdepfile" # Some modes work just like other modes, but use different flags. We # parameterize here, but still list the modes in the big case below, # to make depend.m4 easier to write. Note that we *cannot* use a case # here, because this file can only contain one case statement. if test "$depmode" = hp; then # HP compiler uses -M and no extra arg. gccflag=-M depmode=gcc fi if test "$depmode" = dashXmstdout; then # This is just like dashmstdout with a different argument. dashmflag=-xM depmode=dashmstdout fi cygpath_u="cygpath -u -f -" if test "$depmode" = msvcmsys; then # This is just like msvisualcpp but w/o cygpath translation. # Just convert the backslash-escaped backslashes to single forward # slashes to satisfy depend.m4 cygpath_u='sed s,\\\\,/,g' depmode=msvisualcpp fi if test "$depmode" = msvc7msys; then # This is just like msvc7 but w/o cygpath translation. # Just convert the backslash-escaped backslashes to single forward # slashes to satisfy depend.m4 cygpath_u='sed s,\\\\,/,g' depmode=msvc7 fi if test "$depmode" = xlc; then # IBM C/C++ Compilers xlc/xlC can output gcc-like dependency informations. gccflag=-qmakedep=gcc,-MF depmode=gcc fi case "$depmode" in gcc3) ## gcc 3 implements dependency tracking that does exactly what ## we want. Yay! Note: for some reason libtool 1.4 doesn't like ## it if -MD -MP comes after the -MF stuff. Hmm. ## Unfortunately, FreeBSD c89 acceptance of flags depends upon ## the command line argument order; so add the flags where they ## appear in depend2.am. Note that the slowdown incurred here ## affects only configure: in makefiles, %FASTDEP% shortcuts this. for arg do case $arg in -c) set fnord "$@" -MT "$object" -MD -MP -MF "$tmpdepfile" "$arg" ;; *) set fnord "$@" "$arg" ;; esac shift # fnord shift # $arg done "$@" stat=$? if test $stat -eq 0; then : else rm -f "$tmpdepfile" exit $stat fi mv "$tmpdepfile" "$depfile" ;; gcc) ## There are various ways to get dependency output from gcc. Here's ## why we pick this rather obscure method: ## - Don't want to use -MD because we'd like the dependencies to end ## up in a subdir. Having to rename by hand is ugly. ## (We might end up doing this anyway to support other compilers.) ## - The DEPENDENCIES_OUTPUT environment variable makes gcc act like ## -MM, not -M (despite what the docs say). ## - Using -M directly means running the compiler twice (even worse ## than renaming). if test -z "$gccflag"; then gccflag=-MD, fi "$@" -Wp,"$gccflag$tmpdepfile" stat=$? if test $stat -eq 0; then : else rm -f "$tmpdepfile" exit $stat fi rm -f "$depfile" echo "$object : \\" > "$depfile" alpha=ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz ## The second -e expression handles DOS-style file names with drive letters. sed -e 's/^[^:]*: / /' \ -e 's/^['$alpha']:\/[^:]*: / /' < "$tmpdepfile" >> "$depfile" ## This next piece of magic avoids the "deleted header file" problem. ## The problem is that when a header file which appears in a .P file ## is deleted, the dependency causes make to die (because there is ## typically no way to rebuild the header). We avoid this by adding ## dummy dependencies for each header file. Too bad gcc doesn't do ## this for us directly. tr ' ' "$nl" < "$tmpdepfile" | ## Some versions of gcc put a space before the ':'. On the theory ## that the space means something, we add a space to the output as ## well. hp depmode also adds that space, but also prefixes the VPATH ## to the object. Take care to not repeat it in the output. ## Some versions of the HPUX 10.20 sed can't process this invocation ## correctly. Breaking it into two sed invocations is a workaround. sed -e 's/^\\$//' -e '/^$/d' -e "s|.*$object$||" -e '/:$/d' \ | sed -e 's/$/ :/' >> "$depfile" rm -f "$tmpdepfile" ;; hp) # This case exists only to let depend.m4 do its work. It works by # looking at the text of this script. This case will never be run, # since it is checked for above. exit 1 ;; sgi) if test "$libtool" = yes; then "$@" "-Wp,-MDupdate,$tmpdepfile" else "$@" -MDupdate "$tmpdepfile" fi stat=$? if test $stat -eq 0; then : else rm -f "$tmpdepfile" exit $stat fi rm -f "$depfile" if test -f "$tmpdepfile"; then # yes, the sourcefile depend on other files echo "$object : \\" > "$depfile" # Clip off the initial element (the dependent). Don't try to be # clever and replace this with sed code, as IRIX sed won't handle # lines with more than a fixed number of characters (4096 in # IRIX 6.2 sed, 8192 in IRIX 6.5). We also remove comment lines; # the IRIX cc adds comments like '#:fec' to the end of the # dependency line. tr ' ' "$nl" < "$tmpdepfile" \ | sed -e 's/^.*\.o://' -e 's/#.*$//' -e '/^$/ d' | \ tr "$nl" ' ' >> "$depfile" echo >> "$depfile" # The second pass generates a dummy entry for each header file. tr ' ' "$nl" < "$tmpdepfile" \ | sed -e 's/^.*\.o://' -e 's/#.*$//' -e '/^$/ d' -e 's/$/:/' \ >> "$depfile" else # The sourcefile does not contain any dependencies, so just # store a dummy comment line, to avoid errors with the Makefile # "include basename.Plo" scheme. echo "#dummy" > "$depfile" fi rm -f "$tmpdepfile" ;; xlc) # This case exists only to let depend.m4 do its work. It works by # looking at the text of this script. This case will never be run, # since it is checked for above. exit 1 ;; aix) # The C for AIX Compiler uses -M and outputs the dependencies # in a .u file. In older versions, this file always lives in the # current directory. Also, the AIX compiler puts '$object:' at the # start of each line; $object doesn't have directory information. # Version 6 uses the directory in both cases. dir=`echo "$object" | sed -e 's|/[^/]*$|/|'` test "x$dir" = "x$object" && dir= base=`echo "$object" | sed -e 's|^.*/||' -e 's/\.o$//' -e 's/\.lo$//'` if test "$libtool" = yes; then tmpdepfile1=$dir$base.u tmpdepfile2=$base.u tmpdepfile3=$dir.libs/$base.u "$@" -Wc,-M else tmpdepfile1=$dir$base.u tmpdepfile2=$dir$base.u tmpdepfile3=$dir$base.u "$@" -M fi stat=$? if test $stat -eq 0; then : else rm -f "$tmpdepfile1" "$tmpdepfile2" "$tmpdepfile3" exit $stat fi for tmpdepfile in "$tmpdepfile1" "$tmpdepfile2" "$tmpdepfile3" do test -f "$tmpdepfile" && break done if test -f "$tmpdepfile"; then # Each line is of the form 'foo.o: dependent.h'. # Do two passes, one to just change these to # '$object: dependent.h' and one to simply 'dependent.h:'. sed -e "s,^.*\.[a-z]*:,$object:," < "$tmpdepfile" > "$depfile" sed -e 's,^.*\.[a-z]*:['"$tab"' ]*,,' -e 's,$,:,' < "$tmpdepfile" >> "$depfile" else # The sourcefile does not contain any dependencies, so just # store a dummy comment line, to avoid errors with the Makefile # "include basename.Plo" scheme. echo "#dummy" > "$depfile" fi rm -f "$tmpdepfile" ;; icc) # Intel's C compiler anf tcc (Tiny C Compiler) understand '-MD -MF file'. # However on # $CC -MD -MF foo.d -c -o sub/foo.o sub/foo.c # ICC 7.0 will fill foo.d with something like # foo.o: sub/foo.c # foo.o: sub/foo.h # which is wrong. We want # sub/foo.o: sub/foo.c # sub/foo.o: sub/foo.h # sub/foo.c: # sub/foo.h: # ICC 7.1 will output # foo.o: sub/foo.c sub/foo.h # and will wrap long lines using '\': # foo.o: sub/foo.c ... \ # sub/foo.h ... \ # ... # tcc 0.9.26 (FIXME still under development at the moment of writing) # will emit a similar output, but also prepend the continuation lines # with horizontal tabulation characters. "$@" -MD -MF "$tmpdepfile" stat=$? if test $stat -eq 0; then : else rm -f "$tmpdepfile" exit $stat fi rm -f "$depfile" # Each line is of the form 'foo.o: dependent.h', # or 'foo.o: dep1.h dep2.h \', or ' dep3.h dep4.h \'. # Do two passes, one to just change these to # '$object: dependent.h' and one to simply 'dependent.h:'. sed -e "s/^[ $tab][ $tab]*/ /" -e "s,^[^:]*:,$object :," \ < "$tmpdepfile" > "$depfile" sed ' s/[ '"$tab"'][ '"$tab"']*/ /g s/^ *// s/ *\\*$// s/^[^:]*: *// /^$/d /:$/d s/$/ :/ ' < "$tmpdepfile" >> "$depfile" rm -f "$tmpdepfile" ;; hp2) # The "hp" stanza above does not work with aCC (C++) and HP's ia64 # compilers, which have integrated preprocessors. The correct option # to use with these is +Maked; it writes dependencies to a file named # 'foo.d', which lands next to the object file, wherever that # happens to be. # Much of this is similar to the tru64 case; see comments there. dir=`echo "$object" | sed -e 's|/[^/]*$|/|'` test "x$dir" = "x$object" && dir= base=`echo "$object" | sed -e 's|^.*/||' -e 's/\.o$//' -e 's/\.lo$//'` if test "$libtool" = yes; then tmpdepfile1=$dir$base.d tmpdepfile2=$dir.libs/$base.d "$@" -Wc,+Maked else tmpdepfile1=$dir$base.d tmpdepfile2=$dir$base.d "$@" +Maked fi stat=$? if test $stat -eq 0; then : else rm -f "$tmpdepfile1" "$tmpdepfile2" exit $stat fi for tmpdepfile in "$tmpdepfile1" "$tmpdepfile2" do test -f "$tmpdepfile" && break done if test -f "$tmpdepfile"; then sed -e "s,^.*\.[a-z]*:,$object:," "$tmpdepfile" > "$depfile" # Add 'dependent.h:' lines. sed -ne '2,${ s/^ *// s/ \\*$// s/$/:/ p }' "$tmpdepfile" >> "$depfile" else echo "#dummy" > "$depfile" fi rm -f "$tmpdepfile" "$tmpdepfile2" ;; tru64) # The Tru64 compiler uses -MD to generate dependencies as a side # effect. 'cc -MD -o foo.o ...' puts the dependencies into 'foo.o.d'. # At least on Alpha/Redhat 6.1, Compaq CCC V6.2-504 seems to put # dependencies in 'foo.d' instead, so we check for that too. # Subdirectories are respected. dir=`echo "$object" | sed -e 's|/[^/]*$|/|'` test "x$dir" = "x$object" && dir= base=`echo "$object" | sed -e 's|^.*/||' -e 's/\.o$//' -e 's/\.lo$//'` if test "$libtool" = yes; then # With Tru64 cc, shared objects can also be used to make a # static library. This mechanism is used in libtool 1.4 series to # handle both shared and static libraries in a single compilation. # With libtool 1.4, dependencies were output in $dir.libs/$base.lo.d. # # With libtool 1.5 this exception was removed, and libtool now # generates 2 separate objects for the 2 libraries. These two # compilations output dependencies in $dir.libs/$base.o.d and # in $dir$base.o.d. We have to check for both files, because # one of the two compilations can be disabled. We should prefer # $dir$base.o.d over $dir.libs/$base.o.d because the latter is # automatically cleaned when .libs/ is deleted, while ignoring # the former would cause a distcleancheck panic. tmpdepfile1=$dir.libs/$base.lo.d # libtool 1.4 tmpdepfile2=$dir$base.o.d # libtool 1.5 tmpdepfile3=$dir.libs/$base.o.d # libtool 1.5 tmpdepfile4=$dir.libs/$base.d # Compaq CCC V6.2-504 "$@" -Wc,-MD else tmpdepfile1=$dir$base.o.d tmpdepfile2=$dir$base.d tmpdepfile3=$dir$base.d tmpdepfile4=$dir$base.d "$@" -MD fi stat=$? if test $stat -eq 0; then : else rm -f "$tmpdepfile1" "$tmpdepfile2" "$tmpdepfile3" "$tmpdepfile4" exit $stat fi for tmpdepfile in "$tmpdepfile1" "$tmpdepfile2" "$tmpdepfile3" "$tmpdepfile4" do test -f "$tmpdepfile" && break done if test -f "$tmpdepfile"; then sed -e "s,^.*\.[a-z]*:,$object:," < "$tmpdepfile" > "$depfile" sed -e 's,^.*\.[a-z]*:['"$tab"' ]*,,' -e 's,$,:,' < "$tmpdepfile" >> "$depfile" else echo "#dummy" > "$depfile" fi rm -f "$tmpdepfile" ;; msvc7) if test "$libtool" = yes; then showIncludes=-Wc,-showIncludes else showIncludes=-showIncludes fi "$@" $showIncludes > "$tmpdepfile" stat=$? grep -v '^Note: including file: ' "$tmpdepfile" if test "$stat" = 0; then : else rm -f "$tmpdepfile" exit $stat fi rm -f "$depfile" echo "$object : \\" > "$depfile" # The first sed program below extracts the file names and escapes # backslashes for cygpath. The second sed program outputs the file # name when reading, but also accumulates all include files in the # hold buffer in order to output them again at the end. This only # works with sed implementations that can handle large buffers. sed < "$tmpdepfile" -n ' /^Note: including file: *\(.*\)/ { s//\1/ s/\\/\\\\/g p }' | $cygpath_u | sort -u | sed -n ' s/ /\\ /g s/\(.*\)/'"$tab"'\1 \\/p s/.\(.*\) \\/\1:/ H $ { s/.*/'"$tab"'/ G p }' >> "$depfile" rm -f "$tmpdepfile" ;; msvc7msys) # This case exists only to let depend.m4 do its work. It works by # looking at the text of this script. This case will never be run, # since it is checked for above. exit 1 ;; #nosideeffect) # This comment above is used by automake to tell side-effect # dependency tracking mechanisms from slower ones. dashmstdout) # Important note: in order to support this mode, a compiler *must* # always write the preprocessed file to stdout, regardless of -o. "$@" || exit $? # Remove the call to Libtool. if test "$libtool" = yes; then while test "X$1" != 'X--mode=compile'; do shift done shift fi # Remove '-o $object'. IFS=" " for arg do case $arg in -o) shift ;; $object) shift ;; *) set fnord "$@" "$arg" shift # fnord shift # $arg ;; esac done test -z "$dashmflag" && dashmflag=-M # Require at least two characters before searching for ':' # in the target name. This is to cope with DOS-style filenames: # a dependency such as 'c:/foo/bar' could be seen as target 'c' otherwise. "$@" $dashmflag | sed 's:^['"$tab"' ]*[^:'"$tab"' ][^:][^:]*\:['"$tab"' ]*:'"$object"'\: :' > "$tmpdepfile" rm -f "$depfile" cat < "$tmpdepfile" > "$depfile" tr ' ' "$nl" < "$tmpdepfile" | \ ## Some versions of the HPUX 10.20 sed can't process this invocation ## correctly. Breaking it into two sed invocations is a workaround. sed -e 's/^\\$//' -e '/^$/d' -e '/:$/d' | sed -e 's/$/ :/' >> "$depfile" rm -f "$tmpdepfile" ;; dashXmstdout) # This case only exists to satisfy depend.m4. It is never actually # run, as this mode is specially recognized in the preamble. exit 1 ;; makedepend) "$@" || exit $? # Remove any Libtool call if test "$libtool" = yes; then while test "X$1" != 'X--mode=compile'; do shift done shift fi # X makedepend shift cleared=no eat=no for arg do case $cleared in no) set ""; shift cleared=yes ;; esac if test $eat = yes; then eat=no continue fi case "$arg" in -D*|-I*) set fnord "$@" "$arg"; shift ;; # Strip any option that makedepend may not understand. Remove # the object too, otherwise makedepend will parse it as a source file. -arch) eat=yes ;; -*|$object) ;; *) set fnord "$@" "$arg"; shift ;; esac done obj_suffix=`echo "$object" | sed 's/^.*\././'` touch "$tmpdepfile" ${MAKEDEPEND-makedepend} -o"$obj_suffix" -f"$tmpdepfile" "$@" rm -f "$depfile" # makedepend may prepend the VPATH from the source file name to the object. # No need to regex-escape $object, excess matching of '.' is harmless. sed "s|^.*\($object *:\)|\1|" "$tmpdepfile" > "$depfile" sed '1,2d' "$tmpdepfile" | tr ' ' "$nl" | \ ## Some versions of the HPUX 10.20 sed can't process this invocation ## correctly. Breaking it into two sed invocations is a workaround. sed -e 's/^\\$//' -e '/^$/d' -e '/:$/d' | sed -e 's/$/ :/' >> "$depfile" rm -f "$tmpdepfile" "$tmpdepfile".bak ;; cpp) # Important note: in order to support this mode, a compiler *must* # always write the preprocessed file to stdout. "$@" || exit $? # Remove the call to Libtool. if test "$libtool" = yes; then while test "X$1" != 'X--mode=compile'; do shift done shift fi # Remove '-o $object'. IFS=" " for arg do case $arg in -o) shift ;; $object) shift ;; *) set fnord "$@" "$arg" shift # fnord shift # $arg ;; esac done "$@" -E | sed -n -e '/^# [0-9][0-9]* "\([^"]*\)".*/ s:: \1 \\:p' \ -e '/^#line [0-9][0-9]* "\([^"]*\)".*/ s:: \1 \\:p' | sed '$ s: \\$::' > "$tmpdepfile" rm -f "$depfile" echo "$object : \\" > "$depfile" cat < "$tmpdepfile" >> "$depfile" sed < "$tmpdepfile" '/^$/d;s/^ //;s/ \\$//;s/$/ :/' >> "$depfile" rm -f "$tmpdepfile" ;; msvisualcpp) # Important note: in order to support this mode, a compiler *must* # always write the preprocessed file to stdout. "$@" || exit $? # Remove the call to Libtool. if test "$libtool" = yes; then while test "X$1" != 'X--mode=compile'; do shift done shift fi IFS=" " for arg do case "$arg" in -o) shift ;; $object) shift ;; "-Gm"|"/Gm"|"-Gi"|"/Gi"|"-ZI"|"/ZI") set fnord "$@" shift shift ;; *) set fnord "$@" "$arg" shift shift ;; esac done "$@" -E 2>/dev/null | sed -n '/^#line [0-9][0-9]* "\([^"]*\)"/ s::\1:p' | $cygpath_u | sort -u > "$tmpdepfile" rm -f "$depfile" echo "$object : \\" > "$depfile" sed < "$tmpdepfile" -n -e 's% %\\ %g' -e '/^\(.*\)$/ s::'"$tab"'\1 \\:p' >> "$depfile" echo "$tab" >> "$depfile" sed < "$tmpdepfile" -n -e 's% %\\ %g' -e '/^\(.*\)$/ s::\1\::p' >> "$depfile" rm -f "$tmpdepfile" ;; msvcmsys) # This case exists only to let depend.m4 do its work. It works by # looking at the text of this script. This case will never be run, # since it is checked for above. exit 1 ;; none) exec "$@" ;; *) echo "Unknown depmode $depmode" 1>&2 exit 1 ;; esac exit 0 # Local Variables: # mode: shell-script # sh-indentation: 2 # eval: (add-hook 'write-file-hooks 'time-stamp) # time-stamp-start: "scriptversion=" # time-stamp-format: "%:y-%02m-%02d.%02H" # time-stamp-time-zone: "UTC" # time-stamp-end: "; # UTC" # End: apache-couchdb-1.5.0/build-aux/ltmain.sh0000644000175000001440000105152212230722215014774 00000000000000 # libtool (GNU libtool) 2.4.2 # Written by Gordon Matzigkeit , 1996 # Copyright (C) 1996, 1997, 1998, 1999, 2000, 2001, 2003, 2004, 2005, 2006, # 2007, 2008, 2009, 2010, 2011 Free Software Foundation, Inc. # This is free software; see the source for copying conditions. There is NO # warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. # GNU Libtool is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # As a special exception to the GNU General Public License, # if you distribute this file as part of a program or library that # is built using GNU Libtool, you may include this file under the # same distribution terms that you use for the rest of that program. # # GNU Libtool is distributed in the hope that it will be useful, but # WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU # General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Libtool; see the file COPYING. If not, a copy # can be downloaded from http://www.gnu.org/licenses/gpl.html, # or obtained by writing to the Free Software Foundation, Inc., # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. # Usage: $progname [OPTION]... [MODE-ARG]... # # Provide generalized library-building support services. # # --config show all configuration variables # --debug enable verbose shell tracing # -n, --dry-run display commands without modifying any files # --features display basic configuration information and exit # --mode=MODE use operation mode MODE # --preserve-dup-deps don't remove duplicate dependency libraries # --quiet, --silent don't print informational messages # --no-quiet, --no-silent # print informational messages (default) # --no-warn don't display warning messages # --tag=TAG use configuration variables from tag TAG # -v, --verbose print more informational messages than default # --no-verbose don't print the extra informational messages # --version print version information # -h, --help, --help-all print short, long, or detailed help message # # MODE must be one of the following: # # clean remove files from the build directory # compile compile a source file into a libtool object # execute automatically set library path, then run a program # finish complete the installation of libtool libraries # install install libraries or executables # link create a library or an executable # uninstall remove libraries from an installed directory # # MODE-ARGS vary depending on the MODE. When passed as first option, # `--mode=MODE' may be abbreviated as `MODE' or a unique abbreviation of that. # Try `$progname --help --mode=MODE' for a more detailed description of MODE. # # When reporting a bug, please describe a test case to reproduce it and # include the following information: # # host-triplet: $host # shell: $SHELL # compiler: $LTCC # compiler flags: $LTCFLAGS # linker: $LD (gnu? $with_gnu_ld) # $progname: (GNU libtool) 2.4.2 # automake: $automake_version # autoconf: $autoconf_version # # Report bugs to . # GNU libtool home page: . # General help using GNU software: . PROGRAM=libtool PACKAGE=libtool VERSION=2.4.2 TIMESTAMP="" package_revision=1.3337 # Be Bourne compatible if test -n "${ZSH_VERSION+set}" && (emulate sh) >/dev/null 2>&1; then emulate sh NULLCMD=: # Zsh 3.x and 4.x performs word splitting on ${1+"$@"}, which # is contrary to our usage. Disable this feature. alias -g '${1+"$@"}'='"$@"' setopt NO_GLOB_SUBST else case `(set -o) 2>/dev/null` in *posix*) set -o posix;; esac fi BIN_SH=xpg4; export BIN_SH # for Tru64 DUALCASE=1; export DUALCASE # for MKS sh # A function that is used when there is no print builtin or printf. func_fallback_echo () { eval 'cat <<_LTECHO_EOF $1 _LTECHO_EOF' } # NLS nuisances: We save the old values to restore during execute mode. lt_user_locale= lt_safe_locale= for lt_var in LANG LANGUAGE LC_ALL LC_CTYPE LC_COLLATE LC_MESSAGES do eval "if test \"\${$lt_var+set}\" = set; then save_$lt_var=\$$lt_var $lt_var=C export $lt_var lt_user_locale=\"$lt_var=\\\$save_\$lt_var; \$lt_user_locale\" lt_safe_locale=\"$lt_var=C; \$lt_safe_locale\" fi" done LC_ALL=C LANGUAGE=C export LANGUAGE LC_ALL $lt_unset CDPATH # Work around backward compatibility issue on IRIX 6.5. On IRIX 6.4+, sh # is ksh but when the shell is invoked as "sh" and the current value of # the _XPG environment variable is not equal to 1 (one), the special # positional parameter $0, within a function call, is the name of the # function. progpath="$0" : ${CP="cp -f"} test "${ECHO+set}" = set || ECHO=${as_echo-'printf %s\n'} : ${MAKE="make"} : ${MKDIR="mkdir"} : ${MV="mv -f"} : ${RM="rm -f"} : ${SHELL="${CONFIG_SHELL-/bin/sh}"} : ${Xsed="$SED -e 1s/^X//"} # Global variables: EXIT_SUCCESS=0 EXIT_FAILURE=1 EXIT_MISMATCH=63 # $? = 63 is used to indicate version mismatch to missing. EXIT_SKIP=77 # $? = 77 is used to indicate a skipped test to automake. exit_status=$EXIT_SUCCESS # Make sure IFS has a sensible default lt_nl=' ' IFS=" $lt_nl" dirname="s,/[^/]*$,," basename="s,^.*/,," # func_dirname file append nondir_replacement # Compute the dirname of FILE. If nonempty, add APPEND to the result, # otherwise set result to NONDIR_REPLACEMENT. func_dirname () { func_dirname_result=`$ECHO "${1}" | $SED "$dirname"` if test "X$func_dirname_result" = "X${1}"; then func_dirname_result="${3}" else func_dirname_result="$func_dirname_result${2}" fi } # func_dirname may be replaced by extended shell implementation # func_basename file func_basename () { func_basename_result=`$ECHO "${1}" | $SED "$basename"` } # func_basename may be replaced by extended shell implementation # func_dirname_and_basename file append nondir_replacement # perform func_basename and func_dirname in a single function # call: # dirname: Compute the dirname of FILE. If nonempty, # add APPEND to the result, otherwise set result # to NONDIR_REPLACEMENT. # value returned in "$func_dirname_result" # basename: Compute filename of FILE. # value retuned in "$func_basename_result" # Implementation must be kept synchronized with func_dirname # and func_basename. For efficiency, we do not delegate to # those functions but instead duplicate the functionality here. func_dirname_and_basename () { # Extract subdirectory from the argument. func_dirname_result=`$ECHO "${1}" | $SED -e "$dirname"` if test "X$func_dirname_result" = "X${1}"; then func_dirname_result="${3}" else func_dirname_result="$func_dirname_result${2}" fi func_basename_result=`$ECHO "${1}" | $SED -e "$basename"` } # func_dirname_and_basename may be replaced by extended shell implementation # func_stripname prefix suffix name # strip PREFIX and SUFFIX off of NAME. # PREFIX and SUFFIX must not contain globbing or regex special # characters, hashes, percent signs, but SUFFIX may contain a leading # dot (in which case that matches only a dot). # func_strip_suffix prefix name func_stripname () { case ${2} in .*) func_stripname_result=`$ECHO "${3}" | $SED "s%^${1}%%; s%\\\\${2}\$%%"`;; *) func_stripname_result=`$ECHO "${3}" | $SED "s%^${1}%%; s%${2}\$%%"`;; esac } # func_stripname may be replaced by extended shell implementation # These SED scripts presuppose an absolute path with a trailing slash. pathcar='s,^/\([^/]*\).*$,\1,' pathcdr='s,^/[^/]*,,' removedotparts=':dotsl s@/\./@/@g t dotsl s,/\.$,/,' collapseslashes='s@/\{1,\}@/@g' finalslash='s,/*$,/,' # func_normal_abspath PATH # Remove doubled-up and trailing slashes, "." path components, # and cancel out any ".." path components in PATH after making # it an absolute path. # value returned in "$func_normal_abspath_result" func_normal_abspath () { # Start from root dir and reassemble the path. func_normal_abspath_result= func_normal_abspath_tpath=$1 func_normal_abspath_altnamespace= case $func_normal_abspath_tpath in "") # Empty path, that just means $cwd. func_stripname '' '/' "`pwd`" func_normal_abspath_result=$func_stripname_result return ;; # The next three entries are used to spot a run of precisely # two leading slashes without using negated character classes; # we take advantage of case's first-match behaviour. ///*) # Unusual form of absolute path, do nothing. ;; //*) # Not necessarily an ordinary path; POSIX reserves leading '//' # and for example Cygwin uses it to access remote file shares # over CIFS/SMB, so we conserve a leading double slash if found. func_normal_abspath_altnamespace=/ ;; /*) # Absolute path, do nothing. ;; *) # Relative path, prepend $cwd. func_normal_abspath_tpath=`pwd`/$func_normal_abspath_tpath ;; esac # Cancel out all the simple stuff to save iterations. We also want # the path to end with a slash for ease of parsing, so make sure # there is one (and only one) here. func_normal_abspath_tpath=`$ECHO "$func_normal_abspath_tpath" | $SED \ -e "$removedotparts" -e "$collapseslashes" -e "$finalslash"` while :; do # Processed it all yet? if test "$func_normal_abspath_tpath" = / ; then # If we ascended to the root using ".." the result may be empty now. if test -z "$func_normal_abspath_result" ; then func_normal_abspath_result=/ fi break fi func_normal_abspath_tcomponent=`$ECHO "$func_normal_abspath_tpath" | $SED \ -e "$pathcar"` func_normal_abspath_tpath=`$ECHO "$func_normal_abspath_tpath" | $SED \ -e "$pathcdr"` # Figure out what to do with it case $func_normal_abspath_tcomponent in "") # Trailing empty path component, ignore it. ;; ..) # Parent dir; strip last assembled component from result. func_dirname "$func_normal_abspath_result" func_normal_abspath_result=$func_dirname_result ;; *) # Actual path component, append it. func_normal_abspath_result=$func_normal_abspath_result/$func_normal_abspath_tcomponent ;; esac done # Restore leading double-slash if one was found on entry. func_normal_abspath_result=$func_normal_abspath_altnamespace$func_normal_abspath_result } # func_relative_path SRCDIR DSTDIR # generates a relative path from SRCDIR to DSTDIR, with a trailing # slash if non-empty, suitable for immediately appending a filename # without needing to append a separator. # value returned in "$func_relative_path_result" func_relative_path () { func_relative_path_result= func_normal_abspath "$1" func_relative_path_tlibdir=$func_normal_abspath_result func_normal_abspath "$2" func_relative_path_tbindir=$func_normal_abspath_result # Ascend the tree starting from libdir while :; do # check if we have found a prefix of bindir case $func_relative_path_tbindir in $func_relative_path_tlibdir) # found an exact match func_relative_path_tcancelled= break ;; $func_relative_path_tlibdir*) # found a matching prefix func_stripname "$func_relative_path_tlibdir" '' "$func_relative_path_tbindir" func_relative_path_tcancelled=$func_stripname_result if test -z "$func_relative_path_result"; then func_relative_path_result=. fi break ;; *) func_dirname $func_relative_path_tlibdir func_relative_path_tlibdir=${func_dirname_result} if test "x$func_relative_path_tlibdir" = x ; then # Have to descend all the way to the root! func_relative_path_result=../$func_relative_path_result func_relative_path_tcancelled=$func_relative_path_tbindir break fi func_relative_path_result=../$func_relative_path_result ;; esac done # Now calculate path; take care to avoid doubling-up slashes. func_stripname '' '/' "$func_relative_path_result" func_relative_path_result=$func_stripname_result func_stripname '/' '/' "$func_relative_path_tcancelled" if test "x$func_stripname_result" != x ; then func_relative_path_result=${func_relative_path_result}/${func_stripname_result} fi # Normalisation. If bindir is libdir, return empty string, # else relative path ending with a slash; either way, target # file name can be directly appended. if test ! -z "$func_relative_path_result"; then func_stripname './' '' "$func_relative_path_result/" func_relative_path_result=$func_stripname_result fi } # The name of this program: func_dirname_and_basename "$progpath" progname=$func_basename_result # Make sure we have an absolute path for reexecution: case $progpath in [\\/]*|[A-Za-z]:\\*) ;; *[\\/]*) progdir=$func_dirname_result progdir=`cd "$progdir" && pwd` progpath="$progdir/$progname" ;; *) save_IFS="$IFS" IFS=${PATH_SEPARATOR-:} for progdir in $PATH; do IFS="$save_IFS" test -x "$progdir/$progname" && break done IFS="$save_IFS" test -n "$progdir" || progdir=`pwd` progpath="$progdir/$progname" ;; esac # Sed substitution that helps us do robust quoting. It backslashifies # metacharacters that are still active within double-quoted strings. Xsed="${SED}"' -e 1s/^X//' sed_quote_subst='s/\([`"$\\]\)/\\\1/g' # Same as above, but do not quote variable references. double_quote_subst='s/\(["`\\]\)/\\\1/g' # Sed substitution that turns a string into a regex matching for the # string literally. sed_make_literal_regex='s,[].[^$\\*\/],\\&,g' # Sed substitution that converts a w32 file name or path # which contains forward slashes, into one that contains # (escaped) backslashes. A very naive implementation. lt_sed_naive_backslashify='s|\\\\*|\\|g;s|/|\\|g;s|\\|\\\\|g' # Re-`\' parameter expansions in output of double_quote_subst that were # `\'-ed in input to the same. If an odd number of `\' preceded a '$' # in input to double_quote_subst, that '$' was protected from expansion. # Since each input `\' is now two `\'s, look for any number of runs of # four `\'s followed by two `\'s and then a '$'. `\' that '$'. bs='\\' bs2='\\\\' bs4='\\\\\\\\' dollar='\$' sed_double_backslash="\ s/$bs4/&\\ /g s/^$bs2$dollar/$bs&/ s/\\([^$bs]\\)$bs2$dollar/\\1$bs2$bs$dollar/g s/\n//g" # Standard options: opt_dry_run=false opt_help=false opt_quiet=false opt_verbose=false opt_warning=: # func_echo arg... # Echo program name prefixed message, along with the current mode # name if it has been set yet. func_echo () { $ECHO "$progname: ${opt_mode+$opt_mode: }$*" } # func_verbose arg... # Echo program name prefixed message in verbose mode only. func_verbose () { $opt_verbose && func_echo ${1+"$@"} # A bug in bash halts the script if the last line of a function # fails when set -e is in force, so we need another command to # work around that: : } # func_echo_all arg... # Invoke $ECHO with all args, space-separated. func_echo_all () { $ECHO "$*" } # func_error arg... # Echo program name prefixed message to standard error. func_error () { $ECHO "$progname: ${opt_mode+$opt_mode: }"${1+"$@"} 1>&2 } # func_warning arg... # Echo program name prefixed warning message to standard error. func_warning () { $opt_warning && $ECHO "$progname: ${opt_mode+$opt_mode: }warning: "${1+"$@"} 1>&2 # bash bug again: : } # func_fatal_error arg... # Echo program name prefixed message to standard error, and exit. func_fatal_error () { func_error ${1+"$@"} exit $EXIT_FAILURE } # func_fatal_help arg... # Echo program name prefixed message to standard error, followed by # a help hint, and exit. func_fatal_help () { func_error ${1+"$@"} func_fatal_error "$help" } help="Try \`$progname --help' for more information." ## default # func_grep expression filename # Check whether EXPRESSION matches any line of FILENAME, without output. func_grep () { $GREP "$1" "$2" >/dev/null 2>&1 } # func_mkdir_p directory-path # Make sure the entire path to DIRECTORY-PATH is available. func_mkdir_p () { my_directory_path="$1" my_dir_list= if test -n "$my_directory_path" && test "$opt_dry_run" != ":"; then # Protect directory names starting with `-' case $my_directory_path in -*) my_directory_path="./$my_directory_path" ;; esac # While some portion of DIR does not yet exist... while test ! -d "$my_directory_path"; do # ...make a list in topmost first order. Use a colon delimited # list incase some portion of path contains whitespace. my_dir_list="$my_directory_path:$my_dir_list" # If the last portion added has no slash in it, the list is done case $my_directory_path in */*) ;; *) break ;; esac # ...otherwise throw away the child directory and loop my_directory_path=`$ECHO "$my_directory_path" | $SED -e "$dirname"` done my_dir_list=`$ECHO "$my_dir_list" | $SED 's,:*$,,'` save_mkdir_p_IFS="$IFS"; IFS=':' for my_dir in $my_dir_list; do IFS="$save_mkdir_p_IFS" # mkdir can fail with a `File exist' error if two processes # try to create one of the directories concurrently. Don't # stop in that case! $MKDIR "$my_dir" 2>/dev/null || : done IFS="$save_mkdir_p_IFS" # Bail out if we (or some other process) failed to create a directory. test -d "$my_directory_path" || \ func_fatal_error "Failed to create \`$1'" fi } # func_mktempdir [string] # Make a temporary directory that won't clash with other running # libtool processes, and avoids race conditions if possible. If # given, STRING is the basename for that directory. func_mktempdir () { my_template="${TMPDIR-/tmp}/${1-$progname}" if test "$opt_dry_run" = ":"; then # Return a directory name, but don't create it in dry-run mode my_tmpdir="${my_template}-$$" else # If mktemp works, use that first and foremost my_tmpdir=`mktemp -d "${my_template}-XXXXXXXX" 2>/dev/null` if test ! -d "$my_tmpdir"; then # Failing that, at least try and use $RANDOM to avoid a race my_tmpdir="${my_template}-${RANDOM-0}$$" save_mktempdir_umask=`umask` umask 0077 $MKDIR "$my_tmpdir" umask $save_mktempdir_umask fi # If we're not in dry-run mode, bomb out on failure test -d "$my_tmpdir" || \ func_fatal_error "cannot create temporary directory \`$my_tmpdir'" fi $ECHO "$my_tmpdir" } # func_quote_for_eval arg # Aesthetically quote ARG to be evaled later. # This function returns two values: FUNC_QUOTE_FOR_EVAL_RESULT # is double-quoted, suitable for a subsequent eval, whereas # FUNC_QUOTE_FOR_EVAL_UNQUOTED_RESULT has merely all characters # which are still active within double quotes backslashified. func_quote_for_eval () { case $1 in *[\\\`\"\$]*) func_quote_for_eval_unquoted_result=`$ECHO "$1" | $SED "$sed_quote_subst"` ;; *) func_quote_for_eval_unquoted_result="$1" ;; esac case $func_quote_for_eval_unquoted_result in # Double-quote args containing shell metacharacters to delay # word splitting, command substitution and and variable # expansion for a subsequent eval. # Many Bourne shells cannot handle close brackets correctly # in scan sets, so we specify it separately. *[\[\~\#\^\&\*\(\)\{\}\|\;\<\>\?\'\ \ ]*|*]*|"") func_quote_for_eval_result="\"$func_quote_for_eval_unquoted_result\"" ;; *) func_quote_for_eval_result="$func_quote_for_eval_unquoted_result" esac } # func_quote_for_expand arg # Aesthetically quote ARG to be evaled later; same as above, # but do not quote variable references. func_quote_for_expand () { case $1 in *[\\\`\"]*) my_arg=`$ECHO "$1" | $SED \ -e "$double_quote_subst" -e "$sed_double_backslash"` ;; *) my_arg="$1" ;; esac case $my_arg in # Double-quote args containing shell metacharacters to delay # word splitting and command substitution for a subsequent eval. # Many Bourne shells cannot handle close brackets correctly # in scan sets, so we specify it separately. *[\[\~\#\^\&\*\(\)\{\}\|\;\<\>\?\'\ \ ]*|*]*|"") my_arg="\"$my_arg\"" ;; esac func_quote_for_expand_result="$my_arg" } # func_show_eval cmd [fail_exp] # Unless opt_silent is true, then output CMD. Then, if opt_dryrun is # not true, evaluate CMD. If the evaluation of CMD fails, and FAIL_EXP # is given, then evaluate it. func_show_eval () { my_cmd="$1" my_fail_exp="${2-:}" ${opt_silent-false} || { func_quote_for_expand "$my_cmd" eval "func_echo $func_quote_for_expand_result" } if ${opt_dry_run-false}; then :; else eval "$my_cmd" my_status=$? if test "$my_status" -eq 0; then :; else eval "(exit $my_status); $my_fail_exp" fi fi } # func_show_eval_locale cmd [fail_exp] # Unless opt_silent is true, then output CMD. Then, if opt_dryrun is # not true, evaluate CMD. If the evaluation of CMD fails, and FAIL_EXP # is given, then evaluate it. Use the saved locale for evaluation. func_show_eval_locale () { my_cmd="$1" my_fail_exp="${2-:}" ${opt_silent-false} || { func_quote_for_expand "$my_cmd" eval "func_echo $func_quote_for_expand_result" } if ${opt_dry_run-false}; then :; else eval "$lt_user_locale $my_cmd" my_status=$? eval "$lt_safe_locale" if test "$my_status" -eq 0; then :; else eval "(exit $my_status); $my_fail_exp" fi fi } # func_tr_sh # Turn $1 into a string suitable for a shell variable name. # Result is stored in $func_tr_sh_result. All characters # not in the set a-zA-Z0-9_ are replaced with '_'. Further, # if $1 begins with a digit, a '_' is prepended as well. func_tr_sh () { case $1 in [0-9]* | *[!a-zA-Z0-9_]*) func_tr_sh_result=`$ECHO "$1" | $SED 's/^\([0-9]\)/_\1/; s/[^a-zA-Z0-9_]/_/g'` ;; * ) func_tr_sh_result=$1 ;; esac } # func_version # Echo version message to standard output and exit. func_version () { $opt_debug $SED -n '/(C)/!b go :more /\./!{ N s/\n# / / b more } :go /^# '$PROGRAM' (GNU /,/# warranty; / { s/^# // s/^# *$// s/\((C)\)[ 0-9,-]*\( [1-9][0-9]*\)/\1\2/ p }' < "$progpath" exit $? } # func_usage # Echo short help message to standard output and exit. func_usage () { $opt_debug $SED -n '/^# Usage:/,/^# *.*--help/ { s/^# // s/^# *$// s/\$progname/'$progname'/ p }' < "$progpath" echo $ECHO "run \`$progname --help | more' for full usage" exit $? } # func_help [NOEXIT] # Echo long help message to standard output and exit, # unless 'noexit' is passed as argument. func_help () { $opt_debug $SED -n '/^# Usage:/,/# Report bugs to/ { :print s/^# // s/^# *$// s*\$progname*'$progname'* s*\$host*'"$host"'* s*\$SHELL*'"$SHELL"'* s*\$LTCC*'"$LTCC"'* s*\$LTCFLAGS*'"$LTCFLAGS"'* s*\$LD*'"$LD"'* s/\$with_gnu_ld/'"$with_gnu_ld"'/ s/\$automake_version/'"`(${AUTOMAKE-automake} --version) 2>/dev/null |$SED 1q`"'/ s/\$autoconf_version/'"`(${AUTOCONF-autoconf} --version) 2>/dev/null |$SED 1q`"'/ p d } /^# .* home page:/b print /^# General help using/b print ' < "$progpath" ret=$? if test -z "$1"; then exit $ret fi } # func_missing_arg argname # Echo program name prefixed message to standard error and set global # exit_cmd. func_missing_arg () { $opt_debug func_error "missing argument for $1." exit_cmd=exit } # func_split_short_opt shortopt # Set func_split_short_opt_name and func_split_short_opt_arg shell # variables after splitting SHORTOPT after the 2nd character. func_split_short_opt () { my_sed_short_opt='1s/^\(..\).*$/\1/;q' my_sed_short_rest='1s/^..\(.*\)$/\1/;q' func_split_short_opt_name=`$ECHO "$1" | $SED "$my_sed_short_opt"` func_split_short_opt_arg=`$ECHO "$1" | $SED "$my_sed_short_rest"` } # func_split_short_opt may be replaced by extended shell implementation # func_split_long_opt longopt # Set func_split_long_opt_name and func_split_long_opt_arg shell # variables after splitting LONGOPT at the `=' sign. func_split_long_opt () { my_sed_long_opt='1s/^\(--[^=]*\)=.*/\1/;q' my_sed_long_arg='1s/^--[^=]*=//' func_split_long_opt_name=`$ECHO "$1" | $SED "$my_sed_long_opt"` func_split_long_opt_arg=`$ECHO "$1" | $SED "$my_sed_long_arg"` } # func_split_long_opt may be replaced by extended shell implementation exit_cmd=: magic="%%%MAGIC variable%%%" magic_exe="%%%MAGIC EXE variable%%%" # Global variables. nonopt= preserve_args= lo2o="s/\\.lo\$/.${objext}/" o2lo="s/\\.${objext}\$/.lo/" extracted_archives= extracted_serial=0 # If this variable is set in any of the actions, the command in it # will be execed at the end. This prevents here-documents from being # left over by shells. exec_cmd= # func_append var value # Append VALUE to the end of shell variable VAR. func_append () { eval "${1}=\$${1}\${2}" } # func_append may be replaced by extended shell implementation # func_append_quoted var value # Quote VALUE and append to the end of shell variable VAR, separated # by a space. func_append_quoted () { func_quote_for_eval "${2}" eval "${1}=\$${1}\\ \$func_quote_for_eval_result" } # func_append_quoted may be replaced by extended shell implementation # func_arith arithmetic-term... func_arith () { func_arith_result=`expr "${@}"` } # func_arith may be replaced by extended shell implementation # func_len string # STRING may not start with a hyphen. func_len () { func_len_result=`expr "${1}" : ".*" 2>/dev/null || echo $max_cmd_len` } # func_len may be replaced by extended shell implementation # func_lo2o object func_lo2o () { func_lo2o_result=`$ECHO "${1}" | $SED "$lo2o"` } # func_lo2o may be replaced by extended shell implementation # func_xform libobj-or-source func_xform () { func_xform_result=`$ECHO "${1}" | $SED 's/\.[^.]*$/.lo/'` } # func_xform may be replaced by extended shell implementation # func_fatal_configuration arg... # Echo program name prefixed message to standard error, followed by # a configuration failure hint, and exit. func_fatal_configuration () { func_error ${1+"$@"} func_error "See the $PACKAGE documentation for more information." func_fatal_error "Fatal configuration error." } # func_config # Display the configuration for all the tags in this script. func_config () { re_begincf='^# ### BEGIN LIBTOOL' re_endcf='^# ### END LIBTOOL' # Default configuration. $SED "1,/$re_begincf CONFIG/d;/$re_endcf CONFIG/,\$d" < "$progpath" # Now print the configurations for the tags. for tagname in $taglist; do $SED -n "/$re_begincf TAG CONFIG: $tagname\$/,/$re_endcf TAG CONFIG: $tagname\$/p" < "$progpath" done exit $? } # func_features # Display the features supported by this script. func_features () { echo "host: $host" if test "$build_libtool_libs" = yes; then echo "enable shared libraries" else echo "disable shared libraries" fi if test "$build_old_libs" = yes; then echo "enable static libraries" else echo "disable static libraries" fi exit $? } # func_enable_tag tagname # Verify that TAGNAME is valid, and either flag an error and exit, or # enable the TAGNAME tag. We also add TAGNAME to the global $taglist # variable here. func_enable_tag () { # Global variable: tagname="$1" re_begincf="^# ### BEGIN LIBTOOL TAG CONFIG: $tagname\$" re_endcf="^# ### END LIBTOOL TAG CONFIG: $tagname\$" sed_extractcf="/$re_begincf/,/$re_endcf/p" # Validate tagname. case $tagname in *[!-_A-Za-z0-9,/]*) func_fatal_error "invalid tag name: $tagname" ;; esac # Don't test for the "default" C tag, as we know it's # there but not specially marked. case $tagname in CC) ;; *) if $GREP "$re_begincf" "$progpath" >/dev/null 2>&1; then taglist="$taglist $tagname" # Evaluate the configuration. Be careful to quote the path # and the sed script, to avoid splitting on whitespace, but # also don't use non-portable quotes within backquotes within # quotes we have to do it in 2 steps: extractedcf=`$SED -n -e "$sed_extractcf" < "$progpath"` eval "$extractedcf" else func_error "ignoring unknown tag $tagname" fi ;; esac } # func_check_version_match # Ensure that we are using m4 macros, and libtool script from the same # release of libtool. func_check_version_match () { if test "$package_revision" != "$macro_revision"; then if test "$VERSION" != "$macro_version"; then if test -z "$macro_version"; then cat >&2 <<_LT_EOF $progname: Version mismatch error. This is $PACKAGE $VERSION, but the $progname: definition of this LT_INIT comes from an older release. $progname: You should recreate aclocal.m4 with macros from $PACKAGE $VERSION $progname: and run autoconf again. _LT_EOF else cat >&2 <<_LT_EOF $progname: Version mismatch error. This is $PACKAGE $VERSION, but the $progname: definition of this LT_INIT comes from $PACKAGE $macro_version. $progname: You should recreate aclocal.m4 with macros from $PACKAGE $VERSION $progname: and run autoconf again. _LT_EOF fi else cat >&2 <<_LT_EOF $progname: Version mismatch error. This is $PACKAGE $VERSION, revision $package_revision, $progname: but the definition of this LT_INIT comes from revision $macro_revision. $progname: You should recreate aclocal.m4 with macros from revision $package_revision $progname: of $PACKAGE $VERSION and run autoconf again. _LT_EOF fi exit $EXIT_MISMATCH fi } # Shorthand for --mode=foo, only valid as the first argument case $1 in clean|clea|cle|cl) shift; set dummy --mode clean ${1+"$@"}; shift ;; compile|compil|compi|comp|com|co|c) shift; set dummy --mode compile ${1+"$@"}; shift ;; execute|execut|execu|exec|exe|ex|e) shift; set dummy --mode execute ${1+"$@"}; shift ;; finish|finis|fini|fin|fi|f) shift; set dummy --mode finish ${1+"$@"}; shift ;; install|instal|insta|inst|ins|in|i) shift; set dummy --mode install ${1+"$@"}; shift ;; link|lin|li|l) shift; set dummy --mode link ${1+"$@"}; shift ;; uninstall|uninstal|uninsta|uninst|unins|unin|uni|un|u) shift; set dummy --mode uninstall ${1+"$@"}; shift ;; esac # Option defaults: opt_debug=: opt_dry_run=false opt_config=false opt_preserve_dup_deps=false opt_features=false opt_finish=false opt_help=false opt_help_all=false opt_silent=: opt_warning=: opt_verbose=: opt_silent=false opt_verbose=false # Parse options once, thoroughly. This comes as soon as possible in the # script to make things like `--version' happen as quickly as we can. { # this just eases exit handling while test $# -gt 0; do opt="$1" shift case $opt in --debug|-x) opt_debug='set -x' func_echo "enabling shell trace mode" $opt_debug ;; --dry-run|--dryrun|-n) opt_dry_run=: ;; --config) opt_config=: func_config ;; --dlopen|-dlopen) optarg="$1" opt_dlopen="${opt_dlopen+$opt_dlopen }$optarg" shift ;; --preserve-dup-deps) opt_preserve_dup_deps=: ;; --features) opt_features=: func_features ;; --finish) opt_finish=: set dummy --mode finish ${1+"$@"}; shift ;; --help) opt_help=: ;; --help-all) opt_help_all=: opt_help=': help-all' ;; --mode) test $# = 0 && func_missing_arg $opt && break optarg="$1" opt_mode="$optarg" case $optarg in # Valid mode arguments: clean|compile|execute|finish|install|link|relink|uninstall) ;; # Catch anything else as an error *) func_error "invalid argument for $opt" exit_cmd=exit break ;; esac shift ;; --no-silent|--no-quiet) opt_silent=false func_append preserve_args " $opt" ;; --no-warning|--no-warn) opt_warning=false func_append preserve_args " $opt" ;; --no-verbose) opt_verbose=false func_append preserve_args " $opt" ;; --silent|--quiet) opt_silent=: func_append preserve_args " $opt" opt_verbose=false ;; --verbose|-v) opt_verbose=: func_append preserve_args " $opt" opt_silent=false ;; --tag) test $# = 0 && func_missing_arg $opt && break optarg="$1" opt_tag="$optarg" func_append preserve_args " $opt $optarg" func_enable_tag "$optarg" shift ;; -\?|-h) func_usage ;; --help) func_help ;; --version) func_version ;; # Separate optargs to long options: --*=*) func_split_long_opt "$opt" set dummy "$func_split_long_opt_name" "$func_split_long_opt_arg" ${1+"$@"} shift ;; # Separate non-argument short options: -\?*|-h*|-n*|-v*) func_split_short_opt "$opt" set dummy "$func_split_short_opt_name" "-$func_split_short_opt_arg" ${1+"$@"} shift ;; --) break ;; -*) func_fatal_help "unrecognized option \`$opt'" ;; *) set dummy "$opt" ${1+"$@"}; shift; break ;; esac done # Validate options: # save first non-option argument if test "$#" -gt 0; then nonopt="$opt" shift fi # preserve --debug test "$opt_debug" = : || func_append preserve_args " --debug" case $host in *cygwin* | *mingw* | *pw32* | *cegcc*) # don't eliminate duplications in $postdeps and $predeps opt_duplicate_compiler_generated_deps=: ;; *) opt_duplicate_compiler_generated_deps=$opt_preserve_dup_deps ;; esac $opt_help || { # Sanity checks first: func_check_version_match if test "$build_libtool_libs" != yes && test "$build_old_libs" != yes; then func_fatal_configuration "not configured to build any kind of library" fi # Darwin sucks eval std_shrext=\"$shrext_cmds\" # Only execute mode is allowed to have -dlopen flags. if test -n "$opt_dlopen" && test "$opt_mode" != execute; then func_error "unrecognized option \`-dlopen'" $ECHO "$help" 1>&2 exit $EXIT_FAILURE fi # Change the help message to a mode-specific one. generic_help="$help" help="Try \`$progname --help --mode=$opt_mode' for more information." } # Bail if the options were screwed $exit_cmd $EXIT_FAILURE } ## ----------- ## ## Main. ## ## ----------- ## # func_lalib_p file # True iff FILE is a libtool `.la' library or `.lo' object file. # This function is only a basic sanity check; it will hardly flush out # determined imposters. func_lalib_p () { test -f "$1" && $SED -e 4q "$1" 2>/dev/null \ | $GREP "^# Generated by .*$PACKAGE" > /dev/null 2>&1 } # func_lalib_unsafe_p file # True iff FILE is a libtool `.la' library or `.lo' object file. # This function implements the same check as func_lalib_p without # resorting to external programs. To this end, it redirects stdin and # closes it afterwards, without saving the original file descriptor. # As a safety measure, use it only where a negative result would be # fatal anyway. Works if `file' does not exist. func_lalib_unsafe_p () { lalib_p=no if test -f "$1" && test -r "$1" && exec 5<&0 <"$1"; then for lalib_p_l in 1 2 3 4 do read lalib_p_line case "$lalib_p_line" in \#\ Generated\ by\ *$PACKAGE* ) lalib_p=yes; break;; esac done exec 0<&5 5<&- fi test "$lalib_p" = yes } # func_ltwrapper_script_p file # True iff FILE is a libtool wrapper script # This function is only a basic sanity check; it will hardly flush out # determined imposters. func_ltwrapper_script_p () { func_lalib_p "$1" } # func_ltwrapper_executable_p file # True iff FILE is a libtool wrapper executable # This function is only a basic sanity check; it will hardly flush out # determined imposters. func_ltwrapper_executable_p () { func_ltwrapper_exec_suffix= case $1 in *.exe) ;; *) func_ltwrapper_exec_suffix=.exe ;; esac $GREP "$magic_exe" "$1$func_ltwrapper_exec_suffix" >/dev/null 2>&1 } # func_ltwrapper_scriptname file # Assumes file is an ltwrapper_executable # uses $file to determine the appropriate filename for a # temporary ltwrapper_script. func_ltwrapper_scriptname () { func_dirname_and_basename "$1" "" "." func_stripname '' '.exe' "$func_basename_result" func_ltwrapper_scriptname_result="$func_dirname_result/$objdir/${func_stripname_result}_ltshwrapper" } # func_ltwrapper_p file # True iff FILE is a libtool wrapper script or wrapper executable # This function is only a basic sanity check; it will hardly flush out # determined imposters. func_ltwrapper_p () { func_ltwrapper_script_p "$1" || func_ltwrapper_executable_p "$1" } # func_execute_cmds commands fail_cmd # Execute tilde-delimited COMMANDS. # If FAIL_CMD is given, eval that upon failure. # FAIL_CMD may read-access the current command in variable CMD! func_execute_cmds () { $opt_debug save_ifs=$IFS; IFS='~' for cmd in $1; do IFS=$save_ifs eval cmd=\"$cmd\" func_show_eval "$cmd" "${2-:}" done IFS=$save_ifs } # func_source file # Source FILE, adding directory component if necessary. # Note that it is not necessary on cygwin/mingw to append a dot to # FILE even if both FILE and FILE.exe exist: automatic-append-.exe # behavior happens only for exec(3), not for open(2)! Also, sourcing # `FILE.' does not work on cygwin managed mounts. func_source () { $opt_debug case $1 in */* | *\\*) . "$1" ;; *) . "./$1" ;; esac } # func_resolve_sysroot PATH # Replace a leading = in PATH with a sysroot. Store the result into # func_resolve_sysroot_result func_resolve_sysroot () { func_resolve_sysroot_result=$1 case $func_resolve_sysroot_result in =*) func_stripname '=' '' "$func_resolve_sysroot_result" func_resolve_sysroot_result=$lt_sysroot$func_stripname_result ;; esac } # func_replace_sysroot PATH # If PATH begins with the sysroot, replace it with = and # store the result into func_replace_sysroot_result. func_replace_sysroot () { case "$lt_sysroot:$1" in ?*:"$lt_sysroot"*) func_stripname "$lt_sysroot" '' "$1" func_replace_sysroot_result="=$func_stripname_result" ;; *) # Including no sysroot. func_replace_sysroot_result=$1 ;; esac } # func_infer_tag arg # Infer tagged configuration to use if any are available and # if one wasn't chosen via the "--tag" command line option. # Only attempt this if the compiler in the base compile # command doesn't match the default compiler. # arg is usually of the form 'gcc ...' func_infer_tag () { $opt_debug if test -n "$available_tags" && test -z "$tagname"; then CC_quoted= for arg in $CC; do func_append_quoted CC_quoted "$arg" done CC_expanded=`func_echo_all $CC` CC_quoted_expanded=`func_echo_all $CC_quoted` case $@ in # Blanks in the command may have been stripped by the calling shell, # but not from the CC environment variable when configure was run. " $CC "* | "$CC "* | " $CC_expanded "* | "$CC_expanded "* | \ " $CC_quoted"* | "$CC_quoted "* | " $CC_quoted_expanded "* | "$CC_quoted_expanded "*) ;; # Blanks at the start of $base_compile will cause this to fail # if we don't check for them as well. *) for z in $available_tags; do if $GREP "^# ### BEGIN LIBTOOL TAG CONFIG: $z$" < "$progpath" > /dev/null; then # Evaluate the configuration. eval "`${SED} -n -e '/^# ### BEGIN LIBTOOL TAG CONFIG: '$z'$/,/^# ### END LIBTOOL TAG CONFIG: '$z'$/p' < $progpath`" CC_quoted= for arg in $CC; do # Double-quote args containing other shell metacharacters. func_append_quoted CC_quoted "$arg" done CC_expanded=`func_echo_all $CC` CC_quoted_expanded=`func_echo_all $CC_quoted` case "$@ " in " $CC "* | "$CC "* | " $CC_expanded "* | "$CC_expanded "* | \ " $CC_quoted"* | "$CC_quoted "* | " $CC_quoted_expanded "* | "$CC_quoted_expanded "*) # The compiler in the base compile command matches # the one in the tagged configuration. # Assume this is the tagged configuration we want. tagname=$z break ;; esac fi done # If $tagname still isn't set, then no tagged configuration # was found and let the user know that the "--tag" command # line option must be used. if test -z "$tagname"; then func_echo "unable to infer tagged configuration" func_fatal_error "specify a tag with \`--tag'" # else # func_verbose "using $tagname tagged configuration" fi ;; esac fi } # func_write_libtool_object output_name pic_name nonpic_name # Create a libtool object file (analogous to a ".la" file), # but don't create it if we're doing a dry run. func_write_libtool_object () { write_libobj=${1} if test "$build_libtool_libs" = yes; then write_lobj=\'${2}\' else write_lobj=none fi if test "$build_old_libs" = yes; then write_oldobj=\'${3}\' else write_oldobj=none fi $opt_dry_run || { cat >${write_libobj}T </dev/null` if test "$?" -eq 0 && test -n "${func_convert_core_file_wine_to_w32_tmp}"; then func_convert_core_file_wine_to_w32_result=`$ECHO "$func_convert_core_file_wine_to_w32_tmp" | $SED -e "$lt_sed_naive_backslashify"` else func_convert_core_file_wine_to_w32_result= fi fi } # end: func_convert_core_file_wine_to_w32 # func_convert_core_path_wine_to_w32 ARG # Helper function used by path conversion functions when $build is *nix, and # $host is mingw, cygwin, or some other w32 environment. Relies on a correctly # configured wine environment available, with the winepath program in $build's # $PATH. Assumes ARG has no leading or trailing path separator characters. # # ARG is path to be converted from $build format to win32. # Result is available in $func_convert_core_path_wine_to_w32_result. # Unconvertible file (directory) names in ARG are skipped; if no directory names # are convertible, then the result may be empty. func_convert_core_path_wine_to_w32 () { $opt_debug # unfortunately, winepath doesn't convert paths, only file names func_convert_core_path_wine_to_w32_result="" if test -n "$1"; then oldIFS=$IFS IFS=: for func_convert_core_path_wine_to_w32_f in $1; do IFS=$oldIFS func_convert_core_file_wine_to_w32 "$func_convert_core_path_wine_to_w32_f" if test -n "$func_convert_core_file_wine_to_w32_result" ; then if test -z "$func_convert_core_path_wine_to_w32_result"; then func_convert_core_path_wine_to_w32_result="$func_convert_core_file_wine_to_w32_result" else func_append func_convert_core_path_wine_to_w32_result ";$func_convert_core_file_wine_to_w32_result" fi fi done IFS=$oldIFS fi } # end: func_convert_core_path_wine_to_w32 # func_cygpath ARGS... # Wrapper around calling the cygpath program via LT_CYGPATH. This is used when # when (1) $build is *nix and Cygwin is hosted via a wine environment; or (2) # $build is MSYS and $host is Cygwin, or (3) $build is Cygwin. In case (1) or # (2), returns the Cygwin file name or path in func_cygpath_result (input # file name or path is assumed to be in w32 format, as previously converted # from $build's *nix or MSYS format). In case (3), returns the w32 file name # or path in func_cygpath_result (input file name or path is assumed to be in # Cygwin format). Returns an empty string on error. # # ARGS are passed to cygpath, with the last one being the file name or path to # be converted. # # Specify the absolute *nix (or w32) name to cygpath in the LT_CYGPATH # environment variable; do not put it in $PATH. func_cygpath () { $opt_debug if test -n "$LT_CYGPATH" && test -f "$LT_CYGPATH"; then func_cygpath_result=`$LT_CYGPATH "$@" 2>/dev/null` if test "$?" -ne 0; then # on failure, ensure result is empty func_cygpath_result= fi else func_cygpath_result= func_error "LT_CYGPATH is empty or specifies non-existent file: \`$LT_CYGPATH'" fi } #end: func_cygpath # func_convert_core_msys_to_w32 ARG # Convert file name or path ARG from MSYS format to w32 format. Return # result in func_convert_core_msys_to_w32_result. func_convert_core_msys_to_w32 () { $opt_debug # awkward: cmd appends spaces to result func_convert_core_msys_to_w32_result=`( cmd //c echo "$1" ) 2>/dev/null | $SED -e 's/[ ]*$//' -e "$lt_sed_naive_backslashify"` } #end: func_convert_core_msys_to_w32 # func_convert_file_check ARG1 ARG2 # Verify that ARG1 (a file name in $build format) was converted to $host # format in ARG2. Otherwise, emit an error message, but continue (resetting # func_to_host_file_result to ARG1). func_convert_file_check () { $opt_debug if test -z "$2" && test -n "$1" ; then func_error "Could not determine host file name corresponding to" func_error " \`$1'" func_error "Continuing, but uninstalled executables may not work." # Fallback: func_to_host_file_result="$1" fi } # end func_convert_file_check # func_convert_path_check FROM_PATHSEP TO_PATHSEP FROM_PATH TO_PATH # Verify that FROM_PATH (a path in $build format) was converted to $host # format in TO_PATH. Otherwise, emit an error message, but continue, resetting # func_to_host_file_result to a simplistic fallback value (see below). func_convert_path_check () { $opt_debug if test -z "$4" && test -n "$3"; then func_error "Could not determine the host path corresponding to" func_error " \`$3'" func_error "Continuing, but uninstalled executables may not work." # Fallback. This is a deliberately simplistic "conversion" and # should not be "improved". See libtool.info. if test "x$1" != "x$2"; then lt_replace_pathsep_chars="s|$1|$2|g" func_to_host_path_result=`echo "$3" | $SED -e "$lt_replace_pathsep_chars"` else func_to_host_path_result="$3" fi fi } # end func_convert_path_check # func_convert_path_front_back_pathsep FRONTPAT BACKPAT REPL ORIG # Modifies func_to_host_path_result by prepending REPL if ORIG matches FRONTPAT # and appending REPL if ORIG matches BACKPAT. func_convert_path_front_back_pathsep () { $opt_debug case $4 in $1 ) func_to_host_path_result="$3$func_to_host_path_result" ;; esac case $4 in $2 ) func_append func_to_host_path_result "$3" ;; esac } # end func_convert_path_front_back_pathsep ################################################## # $build to $host FILE NAME CONVERSION FUNCTIONS # ################################################## # invoked via `$to_host_file_cmd ARG' # # In each case, ARG is the path to be converted from $build to $host format. # Result will be available in $func_to_host_file_result. # func_to_host_file ARG # Converts the file name ARG from $build format to $host format. Return result # in func_to_host_file_result. func_to_host_file () { $opt_debug $to_host_file_cmd "$1" } # end func_to_host_file # func_to_tool_file ARG LAZY # converts the file name ARG from $build format to toolchain format. Return # result in func_to_tool_file_result. If the conversion in use is listed # in (the comma separated) LAZY, no conversion takes place. func_to_tool_file () { $opt_debug case ,$2, in *,"$to_tool_file_cmd",*) func_to_tool_file_result=$1 ;; *) $to_tool_file_cmd "$1" func_to_tool_file_result=$func_to_host_file_result ;; esac } # end func_to_tool_file # func_convert_file_noop ARG # Copy ARG to func_to_host_file_result. func_convert_file_noop () { func_to_host_file_result="$1" } # end func_convert_file_noop # func_convert_file_msys_to_w32 ARG # Convert file name ARG from (mingw) MSYS to (mingw) w32 format; automatic # conversion to w32 is not available inside the cwrapper. Returns result in # func_to_host_file_result. func_convert_file_msys_to_w32 () { $opt_debug func_to_host_file_result="$1" if test -n "$1"; then func_convert_core_msys_to_w32 "$1" func_to_host_file_result="$func_convert_core_msys_to_w32_result" fi func_convert_file_check "$1" "$func_to_host_file_result" } # end func_convert_file_msys_to_w32 # func_convert_file_cygwin_to_w32 ARG # Convert file name ARG from Cygwin to w32 format. Returns result in # func_to_host_file_result. func_convert_file_cygwin_to_w32 () { $opt_debug func_to_host_file_result="$1" if test -n "$1"; then # because $build is cygwin, we call "the" cygpath in $PATH; no need to use # LT_CYGPATH in this case. func_to_host_file_result=`cygpath -m "$1"` fi func_convert_file_check "$1" "$func_to_host_file_result" } # end func_convert_file_cygwin_to_w32 # func_convert_file_nix_to_w32 ARG # Convert file name ARG from *nix to w32 format. Requires a wine environment # and a working winepath. Returns result in func_to_host_file_result. func_convert_file_nix_to_w32 () { $opt_debug func_to_host_file_result="$1" if test -n "$1"; then func_convert_core_file_wine_to_w32 "$1" func_to_host_file_result="$func_convert_core_file_wine_to_w32_result" fi func_convert_file_check "$1" "$func_to_host_file_result" } # end func_convert_file_nix_to_w32 # func_convert_file_msys_to_cygwin ARG # Convert file name ARG from MSYS to Cygwin format. Requires LT_CYGPATH set. # Returns result in func_to_host_file_result. func_convert_file_msys_to_cygwin () { $opt_debug func_to_host_file_result="$1" if test -n "$1"; then func_convert_core_msys_to_w32 "$1" func_cygpath -u "$func_convert_core_msys_to_w32_result" func_to_host_file_result="$func_cygpath_result" fi func_convert_file_check "$1" "$func_to_host_file_result" } # end func_convert_file_msys_to_cygwin # func_convert_file_nix_to_cygwin ARG # Convert file name ARG from *nix to Cygwin format. Requires Cygwin installed # in a wine environment, working winepath, and LT_CYGPATH set. Returns result # in func_to_host_file_result. func_convert_file_nix_to_cygwin () { $opt_debug func_to_host_file_result="$1" if test -n "$1"; then # convert from *nix to w32, then use cygpath to convert from w32 to cygwin. func_convert_core_file_wine_to_w32 "$1" func_cygpath -u "$func_convert_core_file_wine_to_w32_result" func_to_host_file_result="$func_cygpath_result" fi func_convert_file_check "$1" "$func_to_host_file_result" } # end func_convert_file_nix_to_cygwin ############################################# # $build to $host PATH CONVERSION FUNCTIONS # ############################################# # invoked via `$to_host_path_cmd ARG' # # In each case, ARG is the path to be converted from $build to $host format. # The result will be available in $func_to_host_path_result. # # Path separators are also converted from $build format to $host format. If # ARG begins or ends with a path separator character, it is preserved (but # converted to $host format) on output. # # All path conversion functions are named using the following convention: # file name conversion function : func_convert_file_X_to_Y () # path conversion function : func_convert_path_X_to_Y () # where, for any given $build/$host combination the 'X_to_Y' value is the # same. If conversion functions are added for new $build/$host combinations, # the two new functions must follow this pattern, or func_init_to_host_path_cmd # will break. # func_init_to_host_path_cmd # Ensures that function "pointer" variable $to_host_path_cmd is set to the # appropriate value, based on the value of $to_host_file_cmd. to_host_path_cmd= func_init_to_host_path_cmd () { $opt_debug if test -z "$to_host_path_cmd"; then func_stripname 'func_convert_file_' '' "$to_host_file_cmd" to_host_path_cmd="func_convert_path_${func_stripname_result}" fi } # func_to_host_path ARG # Converts the path ARG from $build format to $host format. Return result # in func_to_host_path_result. func_to_host_path () { $opt_debug func_init_to_host_path_cmd $to_host_path_cmd "$1" } # end func_to_host_path # func_convert_path_noop ARG # Copy ARG to func_to_host_path_result. func_convert_path_noop () { func_to_host_path_result="$1" } # end func_convert_path_noop # func_convert_path_msys_to_w32 ARG # Convert path ARG from (mingw) MSYS to (mingw) w32 format; automatic # conversion to w32 is not available inside the cwrapper. Returns result in # func_to_host_path_result. func_convert_path_msys_to_w32 () { $opt_debug func_to_host_path_result="$1" if test -n "$1"; then # Remove leading and trailing path separator characters from ARG. MSYS # behavior is inconsistent here; cygpath turns them into '.;' and ';.'; # and winepath ignores them completely. func_stripname : : "$1" func_to_host_path_tmp1=$func_stripname_result func_convert_core_msys_to_w32 "$func_to_host_path_tmp1" func_to_host_path_result="$func_convert_core_msys_to_w32_result" func_convert_path_check : ";" \ "$func_to_host_path_tmp1" "$func_to_host_path_result" func_convert_path_front_back_pathsep ":*" "*:" ";" "$1" fi } # end func_convert_path_msys_to_w32 # func_convert_path_cygwin_to_w32 ARG # Convert path ARG from Cygwin to w32 format. Returns result in # func_to_host_file_result. func_convert_path_cygwin_to_w32 () { $opt_debug func_to_host_path_result="$1" if test -n "$1"; then # See func_convert_path_msys_to_w32: func_stripname : : "$1" func_to_host_path_tmp1=$func_stripname_result func_to_host_path_result=`cygpath -m -p "$func_to_host_path_tmp1"` func_convert_path_check : ";" \ "$func_to_host_path_tmp1" "$func_to_host_path_result" func_convert_path_front_back_pathsep ":*" "*:" ";" "$1" fi } # end func_convert_path_cygwin_to_w32 # func_convert_path_nix_to_w32 ARG # Convert path ARG from *nix to w32 format. Requires a wine environment and # a working winepath. Returns result in func_to_host_file_result. func_convert_path_nix_to_w32 () { $opt_debug func_to_host_path_result="$1" if test -n "$1"; then # See func_convert_path_msys_to_w32: func_stripname : : "$1" func_to_host_path_tmp1=$func_stripname_result func_convert_core_path_wine_to_w32 "$func_to_host_path_tmp1" func_to_host_path_result="$func_convert_core_path_wine_to_w32_result" func_convert_path_check : ";" \ "$func_to_host_path_tmp1" "$func_to_host_path_result" func_convert_path_front_back_pathsep ":*" "*:" ";" "$1" fi } # end func_convert_path_nix_to_w32 # func_convert_path_msys_to_cygwin ARG # Convert path ARG from MSYS to Cygwin format. Requires LT_CYGPATH set. # Returns result in func_to_host_file_result. func_convert_path_msys_to_cygwin () { $opt_debug func_to_host_path_result="$1" if test -n "$1"; then # See func_convert_path_msys_to_w32: func_stripname : : "$1" func_to_host_path_tmp1=$func_stripname_result func_convert_core_msys_to_w32 "$func_to_host_path_tmp1" func_cygpath -u -p "$func_convert_core_msys_to_w32_result" func_to_host_path_result="$func_cygpath_result" func_convert_path_check : : \ "$func_to_host_path_tmp1" "$func_to_host_path_result" func_convert_path_front_back_pathsep ":*" "*:" : "$1" fi } # end func_convert_path_msys_to_cygwin # func_convert_path_nix_to_cygwin ARG # Convert path ARG from *nix to Cygwin format. Requires Cygwin installed in a # a wine environment, working winepath, and LT_CYGPATH set. Returns result in # func_to_host_file_result. func_convert_path_nix_to_cygwin () { $opt_debug func_to_host_path_result="$1" if test -n "$1"; then # Remove leading and trailing path separator characters from # ARG. msys behavior is inconsistent here, cygpath turns them # into '.;' and ';.', and winepath ignores them completely. func_stripname : : "$1" func_to_host_path_tmp1=$func_stripname_result func_convert_core_path_wine_to_w32 "$func_to_host_path_tmp1" func_cygpath -u -p "$func_convert_core_path_wine_to_w32_result" func_to_host_path_result="$func_cygpath_result" func_convert_path_check : : \ "$func_to_host_path_tmp1" "$func_to_host_path_result" func_convert_path_front_back_pathsep ":*" "*:" : "$1" fi } # end func_convert_path_nix_to_cygwin # func_mode_compile arg... func_mode_compile () { $opt_debug # Get the compilation command and the source file. base_compile= srcfile="$nonopt" # always keep a non-empty value in "srcfile" suppress_opt=yes suppress_output= arg_mode=normal libobj= later= pie_flag= for arg do case $arg_mode in arg ) # do not "continue". Instead, add this to base_compile lastarg="$arg" arg_mode=normal ;; target ) libobj="$arg" arg_mode=normal continue ;; normal ) # Accept any command-line options. case $arg in -o) test -n "$libobj" && \ func_fatal_error "you cannot specify \`-o' more than once" arg_mode=target continue ;; -pie | -fpie | -fPIE) func_append pie_flag " $arg" continue ;; -shared | -static | -prefer-pic | -prefer-non-pic) func_append later " $arg" continue ;; -no-suppress) suppress_opt=no continue ;; -Xcompiler) arg_mode=arg # the next one goes into the "base_compile" arg list continue # The current "srcfile" will either be retained or ;; # replaced later. I would guess that would be a bug. -Wc,*) func_stripname '-Wc,' '' "$arg" args=$func_stripname_result lastarg= save_ifs="$IFS"; IFS=',' for arg in $args; do IFS="$save_ifs" func_append_quoted lastarg "$arg" done IFS="$save_ifs" func_stripname ' ' '' "$lastarg" lastarg=$func_stripname_result # Add the arguments to base_compile. func_append base_compile " $lastarg" continue ;; *) # Accept the current argument as the source file. # The previous "srcfile" becomes the current argument. # lastarg="$srcfile" srcfile="$arg" ;; esac # case $arg ;; esac # case $arg_mode # Aesthetically quote the previous argument. func_append_quoted base_compile "$lastarg" done # for arg case $arg_mode in arg) func_fatal_error "you must specify an argument for -Xcompile" ;; target) func_fatal_error "you must specify a target with \`-o'" ;; *) # Get the name of the library object. test -z "$libobj" && { func_basename "$srcfile" libobj="$func_basename_result" } ;; esac # Recognize several different file suffixes. # If the user specifies -o file.o, it is replaced with file.lo case $libobj in *.[cCFSifmso] | \ *.ada | *.adb | *.ads | *.asm | \ *.c++ | *.cc | *.ii | *.class | *.cpp | *.cxx | \ *.[fF][09]? | *.for | *.java | *.go | *.obj | *.sx | *.cu | *.cup) func_xform "$libobj" libobj=$func_xform_result ;; esac case $libobj in *.lo) func_lo2o "$libobj"; obj=$func_lo2o_result ;; *) func_fatal_error "cannot determine name of library object from \`$libobj'" ;; esac func_infer_tag $base_compile for arg in $later; do case $arg in -shared) test "$build_libtool_libs" != yes && \ func_fatal_configuration "can not build a shared library" build_old_libs=no continue ;; -static) build_libtool_libs=no build_old_libs=yes continue ;; -prefer-pic) pic_mode=yes continue ;; -prefer-non-pic) pic_mode=no continue ;; esac done func_quote_for_eval "$libobj" test "X$libobj" != "X$func_quote_for_eval_result" \ && $ECHO "X$libobj" | $GREP '[]~#^*{};<>?"'"'"' &()|`$[]' \ && func_warning "libobj name \`$libobj' may not contain shell special characters." func_dirname_and_basename "$obj" "/" "" objname="$func_basename_result" xdir="$func_dirname_result" lobj=${xdir}$objdir/$objname test -z "$base_compile" && \ func_fatal_help "you must specify a compilation command" # Delete any leftover library objects. if test "$build_old_libs" = yes; then removelist="$obj $lobj $libobj ${libobj}T" else removelist="$lobj $libobj ${libobj}T" fi # On Cygwin there's no "real" PIC flag so we must build both object types case $host_os in cygwin* | mingw* | pw32* | os2* | cegcc*) pic_mode=default ;; esac if test "$pic_mode" = no && test "$deplibs_check_method" != pass_all; then # non-PIC code in shared libraries is not supported pic_mode=default fi # Calculate the filename of the output object if compiler does # not support -o with -c if test "$compiler_c_o" = no; then output_obj=`$ECHO "$srcfile" | $SED 's%^.*/%%; s%\.[^.]*$%%'`.${objext} lockfile="$output_obj.lock" else output_obj= need_locks=no lockfile= fi # Lock this critical section if it is needed # We use this script file to make the link, it avoids creating a new file if test "$need_locks" = yes; then until $opt_dry_run || ln "$progpath" "$lockfile" 2>/dev/null; do func_echo "Waiting for $lockfile to be removed" sleep 2 done elif test "$need_locks" = warn; then if test -f "$lockfile"; then $ECHO "\ *** ERROR, $lockfile exists and contains: `cat $lockfile 2>/dev/null` This indicates that another process is trying to use the same temporary object file, and libtool could not work around it because your compiler does not support \`-c' and \`-o' together. If you repeat this compilation, it may succeed, by chance, but you had better avoid parallel builds (make -j) in this platform, or get a better compiler." $opt_dry_run || $RM $removelist exit $EXIT_FAILURE fi func_append removelist " $output_obj" $ECHO "$srcfile" > "$lockfile" fi $opt_dry_run || $RM $removelist func_append removelist " $lockfile" trap '$opt_dry_run || $RM $removelist; exit $EXIT_FAILURE' 1 2 15 func_to_tool_file "$srcfile" func_convert_file_msys_to_w32 srcfile=$func_to_tool_file_result func_quote_for_eval "$srcfile" qsrcfile=$func_quote_for_eval_result # Only build a PIC object if we are building libtool libraries. if test "$build_libtool_libs" = yes; then # Without this assignment, base_compile gets emptied. fbsd_hideous_sh_bug=$base_compile if test "$pic_mode" != no; then command="$base_compile $qsrcfile $pic_flag" else # Don't build PIC code command="$base_compile $qsrcfile" fi func_mkdir_p "$xdir$objdir" if test -z "$output_obj"; then # Place PIC objects in $objdir func_append command " -o $lobj" fi func_show_eval_locale "$command" \ 'test -n "$output_obj" && $RM $removelist; exit $EXIT_FAILURE' if test "$need_locks" = warn && test "X`cat $lockfile 2>/dev/null`" != "X$srcfile"; then $ECHO "\ *** ERROR, $lockfile contains: `cat $lockfile 2>/dev/null` but it should contain: $srcfile This indicates that another process is trying to use the same temporary object file, and libtool could not work around it because your compiler does not support \`-c' and \`-o' together. If you repeat this compilation, it may succeed, by chance, but you had better avoid parallel builds (make -j) in this platform, or get a better compiler." $opt_dry_run || $RM $removelist exit $EXIT_FAILURE fi # Just move the object if needed, then go on to compile the next one if test -n "$output_obj" && test "X$output_obj" != "X$lobj"; then func_show_eval '$MV "$output_obj" "$lobj"' \ 'error=$?; $opt_dry_run || $RM $removelist; exit $error' fi # Allow error messages only from the first compilation. if test "$suppress_opt" = yes; then suppress_output=' >/dev/null 2>&1' fi fi # Only build a position-dependent object if we build old libraries. if test "$build_old_libs" = yes; then if test "$pic_mode" != yes; then # Don't build PIC code command="$base_compile $qsrcfile$pie_flag" else command="$base_compile $qsrcfile $pic_flag" fi if test "$compiler_c_o" = yes; then func_append command " -o $obj" fi # Suppress compiler output if we already did a PIC compilation. func_append command "$suppress_output" func_show_eval_locale "$command" \ '$opt_dry_run || $RM $removelist; exit $EXIT_FAILURE' if test "$need_locks" = warn && test "X`cat $lockfile 2>/dev/null`" != "X$srcfile"; then $ECHO "\ *** ERROR, $lockfile contains: `cat $lockfile 2>/dev/null` but it should contain: $srcfile This indicates that another process is trying to use the same temporary object file, and libtool could not work around it because your compiler does not support \`-c' and \`-o' together. If you repeat this compilation, it may succeed, by chance, but you had better avoid parallel builds (make -j) in this platform, or get a better compiler." $opt_dry_run || $RM $removelist exit $EXIT_FAILURE fi # Just move the object if needed if test -n "$output_obj" && test "X$output_obj" != "X$obj"; then func_show_eval '$MV "$output_obj" "$obj"' \ 'error=$?; $opt_dry_run || $RM $removelist; exit $error' fi fi $opt_dry_run || { func_write_libtool_object "$libobj" "$objdir/$objname" "$objname" # Unlock the critical section if it was locked if test "$need_locks" != no; then removelist=$lockfile $RM "$lockfile" fi } exit $EXIT_SUCCESS } $opt_help || { test "$opt_mode" = compile && func_mode_compile ${1+"$@"} } func_mode_help () { # We need to display help for each of the modes. case $opt_mode in "") # Generic help is extracted from the usage comments # at the start of this file. func_help ;; clean) $ECHO \ "Usage: $progname [OPTION]... --mode=clean RM [RM-OPTION]... FILE... Remove files from the build directory. RM is the name of the program to use to delete files associated with each FILE (typically \`/bin/rm'). RM-OPTIONS are options (such as \`-f') to be passed to RM. If FILE is a libtool library, object or program, all the files associated with it are deleted. Otherwise, only FILE itself is deleted using RM." ;; compile) $ECHO \ "Usage: $progname [OPTION]... --mode=compile COMPILE-COMMAND... SOURCEFILE Compile a source file into a libtool library object. This mode accepts the following additional options: -o OUTPUT-FILE set the output file name to OUTPUT-FILE -no-suppress do not suppress compiler output for multiple passes -prefer-pic try to build PIC objects only -prefer-non-pic try to build non-PIC objects only -shared do not build a \`.o' file suitable for static linking -static only build a \`.o' file suitable for static linking -Wc,FLAG pass FLAG directly to the compiler COMPILE-COMMAND is a command to be used in creating a \`standard' object file from the given SOURCEFILE. The output file name is determined by removing the directory component from SOURCEFILE, then substituting the C source code suffix \`.c' with the library object suffix, \`.lo'." ;; execute) $ECHO \ "Usage: $progname [OPTION]... --mode=execute COMMAND [ARGS]... Automatically set library path, then run a program. This mode accepts the following additional options: -dlopen FILE add the directory containing FILE to the library path This mode sets the library path environment variable according to \`-dlopen' flags. If any of the ARGS are libtool executable wrappers, then they are translated into their corresponding uninstalled binary, and any of their required library directories are added to the library path. Then, COMMAND is executed, with ARGS as arguments." ;; finish) $ECHO \ "Usage: $progname [OPTION]... --mode=finish [LIBDIR]... Complete the installation of libtool libraries. Each LIBDIR is a directory that contains libtool libraries. The commands that this mode executes may require superuser privileges. Use the \`--dry-run' option if you just want to see what would be executed." ;; install) $ECHO \ "Usage: $progname [OPTION]... --mode=install INSTALL-COMMAND... Install executables or libraries. INSTALL-COMMAND is the installation command. The first component should be either the \`install' or \`cp' program. The following components of INSTALL-COMMAND are treated specially: -inst-prefix-dir PREFIX-DIR Use PREFIX-DIR as a staging area for installation The rest of the components are interpreted as arguments to that command (only BSD-compatible install options are recognized)." ;; link) $ECHO \ "Usage: $progname [OPTION]... --mode=link LINK-COMMAND... Link object files or libraries together to form another library, or to create an executable program. LINK-COMMAND is a command using the C compiler that you would use to create a program from several object files. The following components of LINK-COMMAND are treated specially: -all-static do not do any dynamic linking at all -avoid-version do not add a version suffix if possible -bindir BINDIR specify path to binaries directory (for systems where libraries must be found in the PATH setting at runtime) -dlopen FILE \`-dlpreopen' FILE if it cannot be dlopened at runtime -dlpreopen FILE link in FILE and add its symbols to lt_preloaded_symbols -export-dynamic allow symbols from OUTPUT-FILE to be resolved with dlsym(3) -export-symbols SYMFILE try to export only the symbols listed in SYMFILE -export-symbols-regex REGEX try to export only the symbols matching REGEX -LLIBDIR search LIBDIR for required installed libraries -lNAME OUTPUT-FILE requires the installed library libNAME -module build a library that can dlopened -no-fast-install disable the fast-install mode -no-install link a not-installable executable -no-undefined declare that a library does not refer to external symbols -o OUTPUT-FILE create OUTPUT-FILE from the specified objects -objectlist FILE Use a list of object files found in FILE to specify objects -precious-files-regex REGEX don't remove output files matching REGEX -release RELEASE specify package release information -rpath LIBDIR the created library will eventually be installed in LIBDIR -R[ ]LIBDIR add LIBDIR to the runtime path of programs and libraries -shared only do dynamic linking of libtool libraries -shrext SUFFIX override the standard shared library file extension -static do not do any dynamic linking of uninstalled libtool libraries -static-libtool-libs do not do any dynamic linking of libtool libraries -version-info CURRENT[:REVISION[:AGE]] specify library version info [each variable defaults to 0] -weak LIBNAME declare that the target provides the LIBNAME interface -Wc,FLAG -Xcompiler FLAG pass linker-specific FLAG directly to the compiler -Wl,FLAG -Xlinker FLAG pass linker-specific FLAG directly to the linker -XCClinker FLAG pass link-specific FLAG to the compiler driver (CC) All other options (arguments beginning with \`-') are ignored. Every other argument is treated as a filename. Files ending in \`.la' are treated as uninstalled libtool libraries, other files are standard or library object files. If the OUTPUT-FILE ends in \`.la', then a libtool library is created, only library objects (\`.lo' files) may be specified, and \`-rpath' is required, except when creating a convenience library. If OUTPUT-FILE ends in \`.a' or \`.lib', then a standard library is created using \`ar' and \`ranlib', or on Windows using \`lib'. If OUTPUT-FILE ends in \`.lo' or \`.${objext}', then a reloadable object file is created, otherwise an executable program is created." ;; uninstall) $ECHO \ "Usage: $progname [OPTION]... --mode=uninstall RM [RM-OPTION]... FILE... Remove libraries from an installation directory. RM is the name of the program to use to delete files associated with each FILE (typically \`/bin/rm'). RM-OPTIONS are options (such as \`-f') to be passed to RM. If FILE is a libtool library, all the files associated with it are deleted. Otherwise, only FILE itself is deleted using RM." ;; *) func_fatal_help "invalid operation mode \`$opt_mode'" ;; esac echo $ECHO "Try \`$progname --help' for more information about other modes." } # Now that we've collected a possible --mode arg, show help if necessary if $opt_help; then if test "$opt_help" = :; then func_mode_help else { func_help noexit for opt_mode in compile link execute install finish uninstall clean; do func_mode_help done } | sed -n '1p; 2,$s/^Usage:/ or: /p' { func_help noexit for opt_mode in compile link execute install finish uninstall clean; do echo func_mode_help done } | sed '1d /^When reporting/,/^Report/{ H d } $x /information about other modes/d /more detailed .*MODE/d s/^Usage:.*--mode=\([^ ]*\) .*/Description of \1 mode:/' fi exit $? fi # func_mode_execute arg... func_mode_execute () { $opt_debug # The first argument is the command name. cmd="$nonopt" test -z "$cmd" && \ func_fatal_help "you must specify a COMMAND" # Handle -dlopen flags immediately. for file in $opt_dlopen; do test -f "$file" \ || func_fatal_help "\`$file' is not a file" dir= case $file in *.la) func_resolve_sysroot "$file" file=$func_resolve_sysroot_result # Check to see that this really is a libtool archive. func_lalib_unsafe_p "$file" \ || func_fatal_help "\`$lib' is not a valid libtool archive" # Read the libtool library. dlname= library_names= func_source "$file" # Skip this library if it cannot be dlopened. if test -z "$dlname"; then # Warn if it was a shared library. test -n "$library_names" && \ func_warning "\`$file' was not linked with \`-export-dynamic'" continue fi func_dirname "$file" "" "." dir="$func_dirname_result" if test -f "$dir/$objdir/$dlname"; then func_append dir "/$objdir" else if test ! -f "$dir/$dlname"; then func_fatal_error "cannot find \`$dlname' in \`$dir' or \`$dir/$objdir'" fi fi ;; *.lo) # Just add the directory containing the .lo file. func_dirname "$file" "" "." dir="$func_dirname_result" ;; *) func_warning "\`-dlopen' is ignored for non-libtool libraries and objects" continue ;; esac # Get the absolute pathname. absdir=`cd "$dir" && pwd` test -n "$absdir" && dir="$absdir" # Now add the directory to shlibpath_var. if eval "test -z \"\$$shlibpath_var\""; then eval "$shlibpath_var=\"\$dir\"" else eval "$shlibpath_var=\"\$dir:\$$shlibpath_var\"" fi done # This variable tells wrapper scripts just to set shlibpath_var # rather than running their programs. libtool_execute_magic="$magic" # Check if any of the arguments is a wrapper script. args= for file do case $file in -* | *.la | *.lo ) ;; *) # Do a test to see if this is really a libtool program. if func_ltwrapper_script_p "$file"; then func_source "$file" # Transform arg to wrapped name. file="$progdir/$program" elif func_ltwrapper_executable_p "$file"; then func_ltwrapper_scriptname "$file" func_source "$func_ltwrapper_scriptname_result" # Transform arg to wrapped name. file="$progdir/$program" fi ;; esac # Quote arguments (to preserve shell metacharacters). func_append_quoted args "$file" done if test "X$opt_dry_run" = Xfalse; then if test -n "$shlibpath_var"; then # Export the shlibpath_var. eval "export $shlibpath_var" fi # Restore saved environment variables for lt_var in LANG LANGUAGE LC_ALL LC_CTYPE LC_COLLATE LC_MESSAGES do eval "if test \"\${save_$lt_var+set}\" = set; then $lt_var=\$save_$lt_var; export $lt_var else $lt_unset $lt_var fi" done # Now prepare to actually exec the command. exec_cmd="\$cmd$args" else # Display what would be done. if test -n "$shlibpath_var"; then eval "\$ECHO \"\$shlibpath_var=\$$shlibpath_var\"" echo "export $shlibpath_var" fi $ECHO "$cmd$args" exit $EXIT_SUCCESS fi } test "$opt_mode" = execute && func_mode_execute ${1+"$@"} # func_mode_finish arg... func_mode_finish () { $opt_debug libs= libdirs= admincmds= for opt in "$nonopt" ${1+"$@"} do if test -d "$opt"; then func_append libdirs " $opt" elif test -f "$opt"; then if func_lalib_unsafe_p "$opt"; then func_append libs " $opt" else func_warning "\`$opt' is not a valid libtool archive" fi else func_fatal_error "invalid argument \`$opt'" fi done if test -n "$libs"; then if test -n "$lt_sysroot"; then sysroot_regex=`$ECHO "$lt_sysroot" | $SED "$sed_make_literal_regex"` sysroot_cmd="s/\([ ']\)$sysroot_regex/\1/g;" else sysroot_cmd= fi # Remove sysroot references if $opt_dry_run; then for lib in $libs; do echo "removing references to $lt_sysroot and \`=' prefixes from $lib" done else tmpdir=`func_mktempdir` for lib in $libs; do sed -e "${sysroot_cmd} s/\([ ']-[LR]\)=/\1/g; s/\([ ']\)=/\1/g" $lib \ > $tmpdir/tmp-la mv -f $tmpdir/tmp-la $lib done ${RM}r "$tmpdir" fi fi if test -n "$finish_cmds$finish_eval" && test -n "$libdirs"; then for libdir in $libdirs; do if test -n "$finish_cmds"; then # Do each command in the finish commands. func_execute_cmds "$finish_cmds" 'admincmds="$admincmds '"$cmd"'"' fi if test -n "$finish_eval"; then # Do the single finish_eval. eval cmds=\"$finish_eval\" $opt_dry_run || eval "$cmds" || func_append admincmds " $cmds" fi done fi # Exit here if they wanted silent mode. $opt_silent && exit $EXIT_SUCCESS if test -n "$finish_cmds$finish_eval" && test -n "$libdirs"; then echo "----------------------------------------------------------------------" echo "Libraries have been installed in:" for libdir in $libdirs; do $ECHO " $libdir" done echo echo "If you ever happen to want to link against installed libraries" echo "in a given directory, LIBDIR, you must either use libtool, and" echo "specify the full pathname of the library, or use the \`-LLIBDIR'" echo "flag during linking and do at least one of the following:" if test -n "$shlibpath_var"; then echo " - add LIBDIR to the \`$shlibpath_var' environment variable" echo " during execution" fi if test -n "$runpath_var"; then echo " - add LIBDIR to the \`$runpath_var' environment variable" echo " during linking" fi if test -n "$hardcode_libdir_flag_spec"; then libdir=LIBDIR eval flag=\"$hardcode_libdir_flag_spec\" $ECHO " - use the \`$flag' linker flag" fi if test -n "$admincmds"; then $ECHO " - have your system administrator run these commands:$admincmds" fi if test -f /etc/ld.so.conf; then echo " - have your system administrator add LIBDIR to \`/etc/ld.so.conf'" fi echo echo "See any operating system documentation about shared libraries for" case $host in solaris2.[6789]|solaris2.1[0-9]) echo "more information, such as the ld(1), crle(1) and ld.so(8) manual" echo "pages." ;; *) echo "more information, such as the ld(1) and ld.so(8) manual pages." ;; esac echo "----------------------------------------------------------------------" fi exit $EXIT_SUCCESS } test "$opt_mode" = finish && func_mode_finish ${1+"$@"} # func_mode_install arg... func_mode_install () { $opt_debug # There may be an optional sh(1) argument at the beginning of # install_prog (especially on Windows NT). if test "$nonopt" = "$SHELL" || test "$nonopt" = /bin/sh || # Allow the use of GNU shtool's install command. case $nonopt in *shtool*) :;; *) false;; esac; then # Aesthetically quote it. func_quote_for_eval "$nonopt" install_prog="$func_quote_for_eval_result " arg=$1 shift else install_prog= arg=$nonopt fi # The real first argument should be the name of the installation program. # Aesthetically quote it. func_quote_for_eval "$arg" func_append install_prog "$func_quote_for_eval_result" install_shared_prog=$install_prog case " $install_prog " in *[\\\ /]cp\ *) install_cp=: ;; *) install_cp=false ;; esac # We need to accept at least all the BSD install flags. dest= files= opts= prev= install_type= isdir=no stripme= no_mode=: for arg do arg2= if test -n "$dest"; then func_append files " $dest" dest=$arg continue fi case $arg in -d) isdir=yes ;; -f) if $install_cp; then :; else prev=$arg fi ;; -g | -m | -o) prev=$arg ;; -s) stripme=" -s" continue ;; -*) ;; *) # If the previous option needed an argument, then skip it. if test -n "$prev"; then if test "x$prev" = x-m && test -n "$install_override_mode"; then arg2=$install_override_mode no_mode=false fi prev= else dest=$arg continue fi ;; esac # Aesthetically quote the argument. func_quote_for_eval "$arg" func_append install_prog " $func_quote_for_eval_result" if test -n "$arg2"; then func_quote_for_eval "$arg2" fi func_append install_shared_prog " $func_quote_for_eval_result" done test -z "$install_prog" && \ func_fatal_help "you must specify an install program" test -n "$prev" && \ func_fatal_help "the \`$prev' option requires an argument" if test -n "$install_override_mode" && $no_mode; then if $install_cp; then :; else func_quote_for_eval "$install_override_mode" func_append install_shared_prog " -m $func_quote_for_eval_result" fi fi if test -z "$files"; then if test -z "$dest"; then func_fatal_help "no file or destination specified" else func_fatal_help "you must specify a destination" fi fi # Strip any trailing slash from the destination. func_stripname '' '/' "$dest" dest=$func_stripname_result # Check to see that the destination is a directory. test -d "$dest" && isdir=yes if test "$isdir" = yes; then destdir="$dest" destname= else func_dirname_and_basename "$dest" "" "." destdir="$func_dirname_result" destname="$func_basename_result" # Not a directory, so check to see that there is only one file specified. set dummy $files; shift test "$#" -gt 1 && \ func_fatal_help "\`$dest' is not a directory" fi case $destdir in [\\/]* | [A-Za-z]:[\\/]*) ;; *) for file in $files; do case $file in *.lo) ;; *) func_fatal_help "\`$destdir' must be an absolute directory name" ;; esac done ;; esac # This variable tells wrapper scripts just to set variables rather # than running their programs. libtool_install_magic="$magic" staticlibs= future_libdirs= current_libdirs= for file in $files; do # Do each installation. case $file in *.$libext) # Do the static libraries later. func_append staticlibs " $file" ;; *.la) func_resolve_sysroot "$file" file=$func_resolve_sysroot_result # Check to see that this really is a libtool archive. func_lalib_unsafe_p "$file" \ || func_fatal_help "\`$file' is not a valid libtool archive" library_names= old_library= relink_command= func_source "$file" # Add the libdir to current_libdirs if it is the destination. if test "X$destdir" = "X$libdir"; then case "$current_libdirs " in *" $libdir "*) ;; *) func_append current_libdirs " $libdir" ;; esac else # Note the libdir as a future libdir. case "$future_libdirs " in *" $libdir "*) ;; *) func_append future_libdirs " $libdir" ;; esac fi func_dirname "$file" "/" "" dir="$func_dirname_result" func_append dir "$objdir" if test -n "$relink_command"; then # Determine the prefix the user has applied to our future dir. inst_prefix_dir=`$ECHO "$destdir" | $SED -e "s%$libdir\$%%"` # Don't allow the user to place us outside of our expected # location b/c this prevents finding dependent libraries that # are installed to the same prefix. # At present, this check doesn't affect windows .dll's that # are installed into $libdir/../bin (currently, that works fine) # but it's something to keep an eye on. test "$inst_prefix_dir" = "$destdir" && \ func_fatal_error "error: cannot install \`$file' to a directory not ending in $libdir" if test -n "$inst_prefix_dir"; then # Stick the inst_prefix_dir data into the link command. relink_command=`$ECHO "$relink_command" | $SED "s%@inst_prefix_dir@%-inst-prefix-dir $inst_prefix_dir%"` else relink_command=`$ECHO "$relink_command" | $SED "s%@inst_prefix_dir@%%"` fi func_warning "relinking \`$file'" func_show_eval "$relink_command" \ 'func_fatal_error "error: relink \`$file'\'' with the above command before installing it"' fi # See the names of the shared library. set dummy $library_names; shift if test -n "$1"; then realname="$1" shift srcname="$realname" test -n "$relink_command" && srcname="$realname"T # Install the shared library and build the symlinks. func_show_eval "$install_shared_prog $dir/$srcname $destdir/$realname" \ 'exit $?' tstripme="$stripme" case $host_os in cygwin* | mingw* | pw32* | cegcc*) case $realname in *.dll.a) tstripme="" ;; esac ;; esac if test -n "$tstripme" && test -n "$striplib"; then func_show_eval "$striplib $destdir/$realname" 'exit $?' fi if test "$#" -gt 0; then # Delete the old symlinks, and create new ones. # Try `ln -sf' first, because the `ln' binary might depend on # the symlink we replace! Solaris /bin/ln does not understand -f, # so we also need to try rm && ln -s. for linkname do test "$linkname" != "$realname" \ && func_show_eval "(cd $destdir && { $LN_S -f $realname $linkname || { $RM $linkname && $LN_S $realname $linkname; }; })" done fi # Do each command in the postinstall commands. lib="$destdir/$realname" func_execute_cmds "$postinstall_cmds" 'exit $?' fi # Install the pseudo-library for information purposes. func_basename "$file" name="$func_basename_result" instname="$dir/$name"i func_show_eval "$install_prog $instname $destdir/$name" 'exit $?' # Maybe install the static library, too. test -n "$old_library" && func_append staticlibs " $dir/$old_library" ;; *.lo) # Install (i.e. copy) a libtool object. # Figure out destination file name, if it wasn't already specified. if test -n "$destname"; then destfile="$destdir/$destname" else func_basename "$file" destfile="$func_basename_result" destfile="$destdir/$destfile" fi # Deduce the name of the destination old-style object file. case $destfile in *.lo) func_lo2o "$destfile" staticdest=$func_lo2o_result ;; *.$objext) staticdest="$destfile" destfile= ;; *) func_fatal_help "cannot copy a libtool object to \`$destfile'" ;; esac # Install the libtool object if requested. test -n "$destfile" && \ func_show_eval "$install_prog $file $destfile" 'exit $?' # Install the old object if enabled. if test "$build_old_libs" = yes; then # Deduce the name of the old-style object file. func_lo2o "$file" staticobj=$func_lo2o_result func_show_eval "$install_prog \$staticobj \$staticdest" 'exit $?' fi exit $EXIT_SUCCESS ;; *) # Figure out destination file name, if it wasn't already specified. if test -n "$destname"; then destfile="$destdir/$destname" else func_basename "$file" destfile="$func_basename_result" destfile="$destdir/$destfile" fi # If the file is missing, and there is a .exe on the end, strip it # because it is most likely a libtool script we actually want to # install stripped_ext="" case $file in *.exe) if test ! -f "$file"; then func_stripname '' '.exe' "$file" file=$func_stripname_result stripped_ext=".exe" fi ;; esac # Do a test to see if this is really a libtool program. case $host in *cygwin* | *mingw*) if func_ltwrapper_executable_p "$file"; then func_ltwrapper_scriptname "$file" wrapper=$func_ltwrapper_scriptname_result else func_stripname '' '.exe' "$file" wrapper=$func_stripname_result fi ;; *) wrapper=$file ;; esac if func_ltwrapper_script_p "$wrapper"; then notinst_deplibs= relink_command= func_source "$wrapper" # Check the variables that should have been set. test -z "$generated_by_libtool_version" && \ func_fatal_error "invalid libtool wrapper script \`$wrapper'" finalize=yes for lib in $notinst_deplibs; do # Check to see that each library is installed. libdir= if test -f "$lib"; then func_source "$lib" fi libfile="$libdir/"`$ECHO "$lib" | $SED 's%^.*/%%g'` ### testsuite: skip nested quoting test if test -n "$libdir" && test ! -f "$libfile"; then func_warning "\`$lib' has not been installed in \`$libdir'" finalize=no fi done relink_command= func_source "$wrapper" outputname= if test "$fast_install" = no && test -n "$relink_command"; then $opt_dry_run || { if test "$finalize" = yes; then tmpdir=`func_mktempdir` func_basename "$file$stripped_ext" file="$func_basename_result" outputname="$tmpdir/$file" # Replace the output file specification. relink_command=`$ECHO "$relink_command" | $SED 's%@OUTPUT@%'"$outputname"'%g'` $opt_silent || { func_quote_for_expand "$relink_command" eval "func_echo $func_quote_for_expand_result" } if eval "$relink_command"; then : else func_error "error: relink \`$file' with the above command before installing it" $opt_dry_run || ${RM}r "$tmpdir" continue fi file="$outputname" else func_warning "cannot relink \`$file'" fi } else # Install the binary that we compiled earlier. file=`$ECHO "$file$stripped_ext" | $SED "s%\([^/]*\)$%$objdir/\1%"` fi fi # remove .exe since cygwin /usr/bin/install will append another # one anyway case $install_prog,$host in */usr/bin/install*,*cygwin*) case $file:$destfile in *.exe:*.exe) # this is ok ;; *.exe:*) destfile=$destfile.exe ;; *:*.exe) func_stripname '' '.exe' "$destfile" destfile=$func_stripname_result ;; esac ;; esac func_show_eval "$install_prog\$stripme \$file \$destfile" 'exit $?' $opt_dry_run || if test -n "$outputname"; then ${RM}r "$tmpdir" fi ;; esac done for file in $staticlibs; do func_basename "$file" name="$func_basename_result" # Set up the ranlib parameters. oldlib="$destdir/$name" func_to_tool_file "$oldlib" func_convert_file_msys_to_w32 tool_oldlib=$func_to_tool_file_result func_show_eval "$install_prog \$file \$oldlib" 'exit $?' if test -n "$stripme" && test -n "$old_striplib"; then func_show_eval "$old_striplib $tool_oldlib" 'exit $?' fi # Do each command in the postinstall commands. func_execute_cmds "$old_postinstall_cmds" 'exit $?' done test -n "$future_libdirs" && \ func_warning "remember to run \`$progname --finish$future_libdirs'" if test -n "$current_libdirs"; then # Maybe just do a dry run. $opt_dry_run && current_libdirs=" -n$current_libdirs" exec_cmd='$SHELL $progpath $preserve_args --finish$current_libdirs' else exit $EXIT_SUCCESS fi } test "$opt_mode" = install && func_mode_install ${1+"$@"} # func_generate_dlsyms outputname originator pic_p # Extract symbols from dlprefiles and create ${outputname}S.o with # a dlpreopen symbol table. func_generate_dlsyms () { $opt_debug my_outputname="$1" my_originator="$2" my_pic_p="${3-no}" my_prefix=`$ECHO "$my_originator" | sed 's%[^a-zA-Z0-9]%_%g'` my_dlsyms= if test -n "$dlfiles$dlprefiles" || test "$dlself" != no; then if test -n "$NM" && test -n "$global_symbol_pipe"; then my_dlsyms="${my_outputname}S.c" else func_error "not configured to extract global symbols from dlpreopened files" fi fi if test -n "$my_dlsyms"; then case $my_dlsyms in "") ;; *.c) # Discover the nlist of each of the dlfiles. nlist="$output_objdir/${my_outputname}.nm" func_show_eval "$RM $nlist ${nlist}S ${nlist}T" # Parse the name list into a source file. func_verbose "creating $output_objdir/$my_dlsyms" $opt_dry_run || $ECHO > "$output_objdir/$my_dlsyms" "\ /* $my_dlsyms - symbol resolution table for \`$my_outputname' dlsym emulation. */ /* Generated by $PROGRAM (GNU $PACKAGE$TIMESTAMP) $VERSION */ #ifdef __cplusplus extern \"C\" { #endif #if defined(__GNUC__) && (((__GNUC__ == 4) && (__GNUC_MINOR__ >= 4)) || (__GNUC__ > 4)) #pragma GCC diagnostic ignored \"-Wstrict-prototypes\" #endif /* Keep this code in sync between libtool.m4, ltmain, lt_system.h, and tests. */ #if defined(_WIN32) || defined(__CYGWIN__) || defined(_WIN32_WCE) /* DATA imports from DLLs on WIN32 con't be const, because runtime relocations are performed -- see ld's documentation on pseudo-relocs. */ # define LT_DLSYM_CONST #elif defined(__osf__) /* This system does not cope well with relocations in const data. */ # define LT_DLSYM_CONST #else # define LT_DLSYM_CONST const #endif /* External symbol declarations for the compiler. */\ " if test "$dlself" = yes; then func_verbose "generating symbol list for \`$output'" $opt_dry_run || echo ': @PROGRAM@ ' > "$nlist" # Add our own program objects to the symbol list. progfiles=`$ECHO "$objs$old_deplibs" | $SP2NL | $SED "$lo2o" | $NL2SP` for progfile in $progfiles; do func_to_tool_file "$progfile" func_convert_file_msys_to_w32 func_verbose "extracting global C symbols from \`$func_to_tool_file_result'" $opt_dry_run || eval "$NM $func_to_tool_file_result | $global_symbol_pipe >> '$nlist'" done if test -n "$exclude_expsyms"; then $opt_dry_run || { eval '$EGREP -v " ($exclude_expsyms)$" "$nlist" > "$nlist"T' eval '$MV "$nlist"T "$nlist"' } fi if test -n "$export_symbols_regex"; then $opt_dry_run || { eval '$EGREP -e "$export_symbols_regex" "$nlist" > "$nlist"T' eval '$MV "$nlist"T "$nlist"' } fi # Prepare the list of exported symbols if test -z "$export_symbols"; then export_symbols="$output_objdir/$outputname.exp" $opt_dry_run || { $RM $export_symbols eval "${SED} -n -e '/^: @PROGRAM@ $/d' -e 's/^.* \(.*\)$/\1/p' "'< "$nlist" > "$export_symbols"' case $host in *cygwin* | *mingw* | *cegcc* ) eval "echo EXPORTS "'> "$output_objdir/$outputname.def"' eval 'cat "$export_symbols" >> "$output_objdir/$outputname.def"' ;; esac } else $opt_dry_run || { eval "${SED} -e 's/\([].[*^$]\)/\\\\\1/g' -e 's/^/ /' -e 's/$/$/'"' < "$export_symbols" > "$output_objdir/$outputname.exp"' eval '$GREP -f "$output_objdir/$outputname.exp" < "$nlist" > "$nlist"T' eval '$MV "$nlist"T "$nlist"' case $host in *cygwin* | *mingw* | *cegcc* ) eval "echo EXPORTS "'> "$output_objdir/$outputname.def"' eval 'cat "$nlist" >> "$output_objdir/$outputname.def"' ;; esac } fi fi for dlprefile in $dlprefiles; do func_verbose "extracting global C symbols from \`$dlprefile'" func_basename "$dlprefile" name="$func_basename_result" case $host in *cygwin* | *mingw* | *cegcc* ) # if an import library, we need to obtain dlname if func_win32_import_lib_p "$dlprefile"; then func_tr_sh "$dlprefile" eval "curr_lafile=\$libfile_$func_tr_sh_result" dlprefile_dlbasename="" if test -n "$curr_lafile" && func_lalib_p "$curr_lafile"; then # Use subshell, to avoid clobbering current variable values dlprefile_dlname=`source "$curr_lafile" && echo "$dlname"` if test -n "$dlprefile_dlname" ; then func_basename "$dlprefile_dlname" dlprefile_dlbasename="$func_basename_result" else # no lafile. user explicitly requested -dlpreopen . $sharedlib_from_linklib_cmd "$dlprefile" dlprefile_dlbasename=$sharedlib_from_linklib_result fi fi $opt_dry_run || { if test -n "$dlprefile_dlbasename" ; then eval '$ECHO ": $dlprefile_dlbasename" >> "$nlist"' else func_warning "Could not compute DLL name from $name" eval '$ECHO ": $name " >> "$nlist"' fi func_to_tool_file "$dlprefile" func_convert_file_msys_to_w32 eval "$NM \"$func_to_tool_file_result\" 2>/dev/null | $global_symbol_pipe | $SED -e '/I __imp/d' -e 's/I __nm_/D /;s/_nm__//' >> '$nlist'" } else # not an import lib $opt_dry_run || { eval '$ECHO ": $name " >> "$nlist"' func_to_tool_file "$dlprefile" func_convert_file_msys_to_w32 eval "$NM \"$func_to_tool_file_result\" 2>/dev/null | $global_symbol_pipe >> '$nlist'" } fi ;; *) $opt_dry_run || { eval '$ECHO ": $name " >> "$nlist"' func_to_tool_file "$dlprefile" func_convert_file_msys_to_w32 eval "$NM \"$func_to_tool_file_result\" 2>/dev/null | $global_symbol_pipe >> '$nlist'" } ;; esac done $opt_dry_run || { # Make sure we have at least an empty file. test -f "$nlist" || : > "$nlist" if test -n "$exclude_expsyms"; then $EGREP -v " ($exclude_expsyms)$" "$nlist" > "$nlist"T $MV "$nlist"T "$nlist" fi # Try sorting and uniquifying the output. if $GREP -v "^: " < "$nlist" | if sort -k 3 /dev/null 2>&1; then sort -k 3 else sort +2 fi | uniq > "$nlist"S; then : else $GREP -v "^: " < "$nlist" > "$nlist"S fi if test -f "$nlist"S; then eval "$global_symbol_to_cdecl"' < "$nlist"S >> "$output_objdir/$my_dlsyms"' else echo '/* NONE */' >> "$output_objdir/$my_dlsyms" fi echo >> "$output_objdir/$my_dlsyms" "\ /* The mapping between symbol names and symbols. */ typedef struct { const char *name; void *address; } lt_dlsymlist; extern LT_DLSYM_CONST lt_dlsymlist lt_${my_prefix}_LTX_preloaded_symbols[]; LT_DLSYM_CONST lt_dlsymlist lt_${my_prefix}_LTX_preloaded_symbols[] = {\ { \"$my_originator\", (void *) 0 }," case $need_lib_prefix in no) eval "$global_symbol_to_c_name_address" < "$nlist" >> "$output_objdir/$my_dlsyms" ;; *) eval "$global_symbol_to_c_name_address_lib_prefix" < "$nlist" >> "$output_objdir/$my_dlsyms" ;; esac echo >> "$output_objdir/$my_dlsyms" "\ {0, (void *) 0} }; /* This works around a problem in FreeBSD linker */ #ifdef FREEBSD_WORKAROUND static const void *lt_preloaded_setup() { return lt_${my_prefix}_LTX_preloaded_symbols; } #endif #ifdef __cplusplus } #endif\ " } # !$opt_dry_run pic_flag_for_symtable= case "$compile_command " in *" -static "*) ;; *) case $host in # compiling the symbol table file with pic_flag works around # a FreeBSD bug that causes programs to crash when -lm is # linked before any other PIC object. But we must not use # pic_flag when linking with -static. The problem exists in # FreeBSD 2.2.6 and is fixed in FreeBSD 3.1. *-*-freebsd2.*|*-*-freebsd3.0*|*-*-freebsdelf3.0*) pic_flag_for_symtable=" $pic_flag -DFREEBSD_WORKAROUND" ;; *-*-hpux*) pic_flag_for_symtable=" $pic_flag" ;; *) if test "X$my_pic_p" != Xno; then pic_flag_for_symtable=" $pic_flag" fi ;; esac ;; esac symtab_cflags= for arg in $LTCFLAGS; do case $arg in -pie | -fpie | -fPIE) ;; *) func_append symtab_cflags " $arg" ;; esac done # Now compile the dynamic symbol file. func_show_eval '(cd $output_objdir && $LTCC$symtab_cflags -c$no_builtin_flag$pic_flag_for_symtable "$my_dlsyms")' 'exit $?' # Clean up the generated files. func_show_eval '$RM "$output_objdir/$my_dlsyms" "$nlist" "${nlist}S" "${nlist}T"' # Transform the symbol file into the correct name. symfileobj="$output_objdir/${my_outputname}S.$objext" case $host in *cygwin* | *mingw* | *cegcc* ) if test -f "$output_objdir/$my_outputname.def"; then compile_command=`$ECHO "$compile_command" | $SED "s%@SYMFILE@%$output_objdir/$my_outputname.def $symfileobj%"` finalize_command=`$ECHO "$finalize_command" | $SED "s%@SYMFILE@%$output_objdir/$my_outputname.def $symfileobj%"` else compile_command=`$ECHO "$compile_command" | $SED "s%@SYMFILE@%$symfileobj%"` finalize_command=`$ECHO "$finalize_command" | $SED "s%@SYMFILE@%$symfileobj%"` fi ;; *) compile_command=`$ECHO "$compile_command" | $SED "s%@SYMFILE@%$symfileobj%"` finalize_command=`$ECHO "$finalize_command" | $SED "s%@SYMFILE@%$symfileobj%"` ;; esac ;; *) func_fatal_error "unknown suffix for \`$my_dlsyms'" ;; esac else # We keep going just in case the user didn't refer to # lt_preloaded_symbols. The linker will fail if global_symbol_pipe # really was required. # Nullify the symbol file. compile_command=`$ECHO "$compile_command" | $SED "s% @SYMFILE@%%"` finalize_command=`$ECHO "$finalize_command" | $SED "s% @SYMFILE@%%"` fi } # func_win32_libid arg # return the library type of file 'arg' # # Need a lot of goo to handle *both* DLLs and import libs # Has to be a shell function in order to 'eat' the argument # that is supplied when $file_magic_command is called. # Despite the name, also deal with 64 bit binaries. func_win32_libid () { $opt_debug win32_libid_type="unknown" win32_fileres=`file -L $1 2>/dev/null` case $win32_fileres in *ar\ archive\ import\ library*) # definitely import win32_libid_type="x86 archive import" ;; *ar\ archive*) # could be an import, or static # Keep the egrep pattern in sync with the one in _LT_CHECK_MAGIC_METHOD. if eval $OBJDUMP -f $1 | $SED -e '10q' 2>/dev/null | $EGREP 'file format (pei*-i386(.*architecture: i386)?|pe-arm-wince|pe-x86-64)' >/dev/null; then func_to_tool_file "$1" func_convert_file_msys_to_w32 win32_nmres=`eval $NM -f posix -A \"$func_to_tool_file_result\" | $SED -n -e ' 1,100{ / I /{ s,.*,import, p q } }'` case $win32_nmres in import*) win32_libid_type="x86 archive import";; *) win32_libid_type="x86 archive static";; esac fi ;; *DLL*) win32_libid_type="x86 DLL" ;; *executable*) # but shell scripts are "executable" too... case $win32_fileres in *MS\ Windows\ PE\ Intel*) win32_libid_type="x86 DLL" ;; esac ;; esac $ECHO "$win32_libid_type" } # func_cygming_dll_for_implib ARG # # Platform-specific function to extract the # name of the DLL associated with the specified # import library ARG. # Invoked by eval'ing the libtool variable # $sharedlib_from_linklib_cmd # Result is available in the variable # $sharedlib_from_linklib_result func_cygming_dll_for_implib () { $opt_debug sharedlib_from_linklib_result=`$DLLTOOL --identify-strict --identify "$1"` } # func_cygming_dll_for_implib_fallback_core SECTION_NAME LIBNAMEs # # The is the core of a fallback implementation of a # platform-specific function to extract the name of the # DLL associated with the specified import library LIBNAME. # # SECTION_NAME is either .idata$6 or .idata$7, depending # on the platform and compiler that created the implib. # # Echos the name of the DLL associated with the # specified import library. func_cygming_dll_for_implib_fallback_core () { $opt_debug match_literal=`$ECHO "$1" | $SED "$sed_make_literal_regex"` $OBJDUMP -s --section "$1" "$2" 2>/dev/null | $SED '/^Contents of section '"$match_literal"':/{ # Place marker at beginning of archive member dllname section s/.*/====MARK====/ p d } # These lines can sometimes be longer than 43 characters, but # are always uninteresting /:[ ]*file format pe[i]\{,1\}-/d /^In archive [^:]*:/d # Ensure marker is printed /^====MARK====/p # Remove all lines with less than 43 characters /^.\{43\}/!d # From remaining lines, remove first 43 characters s/^.\{43\}//' | $SED -n ' # Join marker and all lines until next marker into a single line /^====MARK====/ b para H $ b para b :para x s/\n//g # Remove the marker s/^====MARK====// # Remove trailing dots and whitespace s/[\. \t]*$// # Print /./p' | # we now have a list, one entry per line, of the stringified # contents of the appropriate section of all members of the # archive which possess that section. Heuristic: eliminate # all those which have a first or second character that is # a '.' (that is, objdump's representation of an unprintable # character.) This should work for all archives with less than # 0x302f exports -- but will fail for DLLs whose name actually # begins with a literal '.' or a single character followed by # a '.'. # # Of those that remain, print the first one. $SED -e '/^\./d;/^.\./d;q' } # func_cygming_gnu_implib_p ARG # This predicate returns with zero status (TRUE) if # ARG is a GNU/binutils-style import library. Returns # with nonzero status (FALSE) otherwise. func_cygming_gnu_implib_p () { $opt_debug func_to_tool_file "$1" func_convert_file_msys_to_w32 func_cygming_gnu_implib_tmp=`$NM "$func_to_tool_file_result" | eval "$global_symbol_pipe" | $EGREP ' (_head_[A-Za-z0-9_]+_[ad]l*|[A-Za-z0-9_]+_[ad]l*_iname)$'` test -n "$func_cygming_gnu_implib_tmp" } # func_cygming_ms_implib_p ARG # This predicate returns with zero status (TRUE) if # ARG is an MS-style import library. Returns # with nonzero status (FALSE) otherwise. func_cygming_ms_implib_p () { $opt_debug func_to_tool_file "$1" func_convert_file_msys_to_w32 func_cygming_ms_implib_tmp=`$NM "$func_to_tool_file_result" | eval "$global_symbol_pipe" | $GREP '_NULL_IMPORT_DESCRIPTOR'` test -n "$func_cygming_ms_implib_tmp" } # func_cygming_dll_for_implib_fallback ARG # Platform-specific function to extract the # name of the DLL associated with the specified # import library ARG. # # This fallback implementation is for use when $DLLTOOL # does not support the --identify-strict option. # Invoked by eval'ing the libtool variable # $sharedlib_from_linklib_cmd # Result is available in the variable # $sharedlib_from_linklib_result func_cygming_dll_for_implib_fallback () { $opt_debug if func_cygming_gnu_implib_p "$1" ; then # binutils import library sharedlib_from_linklib_result=`func_cygming_dll_for_implib_fallback_core '.idata$7' "$1"` elif func_cygming_ms_implib_p "$1" ; then # ms-generated import library sharedlib_from_linklib_result=`func_cygming_dll_for_implib_fallback_core '.idata$6' "$1"` else # unknown sharedlib_from_linklib_result="" fi } # func_extract_an_archive dir oldlib func_extract_an_archive () { $opt_debug f_ex_an_ar_dir="$1"; shift f_ex_an_ar_oldlib="$1" if test "$lock_old_archive_extraction" = yes; then lockfile=$f_ex_an_ar_oldlib.lock until $opt_dry_run || ln "$progpath" "$lockfile" 2>/dev/null; do func_echo "Waiting for $lockfile to be removed" sleep 2 done fi func_show_eval "(cd \$f_ex_an_ar_dir && $AR x \"\$f_ex_an_ar_oldlib\")" \ 'stat=$?; rm -f "$lockfile"; exit $stat' if test "$lock_old_archive_extraction" = yes; then $opt_dry_run || rm -f "$lockfile" fi if ($AR t "$f_ex_an_ar_oldlib" | sort | sort -uc >/dev/null 2>&1); then : else func_fatal_error "object name conflicts in archive: $f_ex_an_ar_dir/$f_ex_an_ar_oldlib" fi } # func_extract_archives gentop oldlib ... func_extract_archives () { $opt_debug my_gentop="$1"; shift my_oldlibs=${1+"$@"} my_oldobjs="" my_xlib="" my_xabs="" my_xdir="" for my_xlib in $my_oldlibs; do # Extract the objects. case $my_xlib in [\\/]* | [A-Za-z]:[\\/]*) my_xabs="$my_xlib" ;; *) my_xabs=`pwd`"/$my_xlib" ;; esac func_basename "$my_xlib" my_xlib="$func_basename_result" my_xlib_u=$my_xlib while :; do case " $extracted_archives " in *" $my_xlib_u "*) func_arith $extracted_serial + 1 extracted_serial=$func_arith_result my_xlib_u=lt$extracted_serial-$my_xlib ;; *) break ;; esac done extracted_archives="$extracted_archives $my_xlib_u" my_xdir="$my_gentop/$my_xlib_u" func_mkdir_p "$my_xdir" case $host in *-darwin*) func_verbose "Extracting $my_xabs" # Do not bother doing anything if just a dry run $opt_dry_run || { darwin_orig_dir=`pwd` cd $my_xdir || exit $? darwin_archive=$my_xabs darwin_curdir=`pwd` darwin_base_archive=`basename "$darwin_archive"` darwin_arches=`$LIPO -info "$darwin_archive" 2>/dev/null | $GREP Architectures 2>/dev/null || true` if test -n "$darwin_arches"; then darwin_arches=`$ECHO "$darwin_arches" | $SED -e 's/.*are://'` darwin_arch= func_verbose "$darwin_base_archive has multiple architectures $darwin_arches" for darwin_arch in $darwin_arches ; do func_mkdir_p "unfat-$$/${darwin_base_archive}-${darwin_arch}" $LIPO -thin $darwin_arch -output "unfat-$$/${darwin_base_archive}-${darwin_arch}/${darwin_base_archive}" "${darwin_archive}" cd "unfat-$$/${darwin_base_archive}-${darwin_arch}" func_extract_an_archive "`pwd`" "${darwin_base_archive}" cd "$darwin_curdir" $RM "unfat-$$/${darwin_base_archive}-${darwin_arch}/${darwin_base_archive}" done # $darwin_arches ## Okay now we've a bunch of thin objects, gotta fatten them up :) darwin_filelist=`find unfat-$$ -type f -name \*.o -print -o -name \*.lo -print | $SED -e "$basename" | sort -u` darwin_file= darwin_files= for darwin_file in $darwin_filelist; do darwin_files=`find unfat-$$ -name $darwin_file -print | sort | $NL2SP` $LIPO -create -output "$darwin_file" $darwin_files done # $darwin_filelist $RM -rf unfat-$$ cd "$darwin_orig_dir" else cd $darwin_orig_dir func_extract_an_archive "$my_xdir" "$my_xabs" fi # $darwin_arches } # !$opt_dry_run ;; *) func_extract_an_archive "$my_xdir" "$my_xabs" ;; esac my_oldobjs="$my_oldobjs "`find $my_xdir -name \*.$objext -print -o -name \*.lo -print | sort | $NL2SP` done func_extract_archives_result="$my_oldobjs" } # func_emit_wrapper [arg=no] # # Emit a libtool wrapper script on stdout. # Don't directly open a file because we may want to # incorporate the script contents within a cygwin/mingw # wrapper executable. Must ONLY be called from within # func_mode_link because it depends on a number of variables # set therein. # # ARG is the value that the WRAPPER_SCRIPT_BELONGS_IN_OBJDIR # variable will take. If 'yes', then the emitted script # will assume that the directory in which it is stored is # the $objdir directory. This is a cygwin/mingw-specific # behavior. func_emit_wrapper () { func_emit_wrapper_arg1=${1-no} $ECHO "\ #! $SHELL # $output - temporary wrapper script for $objdir/$outputname # Generated by $PROGRAM (GNU $PACKAGE$TIMESTAMP) $VERSION # # The $output program cannot be directly executed until all the libtool # libraries that it depends on are installed. # # This wrapper script should never be moved out of the build directory. # If it is, it will not operate correctly. # Sed substitution that helps us do robust quoting. It backslashifies # metacharacters that are still active within double-quoted strings. sed_quote_subst='$sed_quote_subst' # Be Bourne compatible if test -n \"\${ZSH_VERSION+set}\" && (emulate sh) >/dev/null 2>&1; then emulate sh NULLCMD=: # Zsh 3.x and 4.x performs word splitting on \${1+\"\$@\"}, which # is contrary to our usage. Disable this feature. alias -g '\${1+\"\$@\"}'='\"\$@\"' setopt NO_GLOB_SUBST else case \`(set -o) 2>/dev/null\` in *posix*) set -o posix;; esac fi BIN_SH=xpg4; export BIN_SH # for Tru64 DUALCASE=1; export DUALCASE # for MKS sh # The HP-UX ksh and POSIX shell print the target directory to stdout # if CDPATH is set. (unset CDPATH) >/dev/null 2>&1 && unset CDPATH relink_command=\"$relink_command\" # This environment variable determines our operation mode. if test \"\$libtool_install_magic\" = \"$magic\"; then # install mode needs the following variables: generated_by_libtool_version='$macro_version' notinst_deplibs='$notinst_deplibs' else # When we are sourced in execute mode, \$file and \$ECHO are already set. if test \"\$libtool_execute_magic\" != \"$magic\"; then file=\"\$0\"" qECHO=`$ECHO "$ECHO" | $SED "$sed_quote_subst"` $ECHO "\ # A function that is used when there is no print builtin or printf. func_fallback_echo () { eval 'cat <<_LTECHO_EOF \$1 _LTECHO_EOF' } ECHO=\"$qECHO\" fi # Very basic option parsing. These options are (a) specific to # the libtool wrapper, (b) are identical between the wrapper # /script/ and the wrapper /executable/ which is used only on # windows platforms, and (c) all begin with the string "--lt-" # (application programs are unlikely to have options which match # this pattern). # # There are only two supported options: --lt-debug and # --lt-dump-script. There is, deliberately, no --lt-help. # # The first argument to this parsing function should be the # script's $0 value, followed by "$@". lt_option_debug= func_parse_lt_options () { lt_script_arg0=\$0 shift for lt_opt do case \"\$lt_opt\" in --lt-debug) lt_option_debug=1 ;; --lt-dump-script) lt_dump_D=\`\$ECHO \"X\$lt_script_arg0\" | $SED -e 's/^X//' -e 's%/[^/]*$%%'\` test \"X\$lt_dump_D\" = \"X\$lt_script_arg0\" && lt_dump_D=. lt_dump_F=\`\$ECHO \"X\$lt_script_arg0\" | $SED -e 's/^X//' -e 's%^.*/%%'\` cat \"\$lt_dump_D/\$lt_dump_F\" exit 0 ;; --lt-*) \$ECHO \"Unrecognized --lt- option: '\$lt_opt'\" 1>&2 exit 1 ;; esac done # Print the debug banner immediately: if test -n \"\$lt_option_debug\"; then echo \"${outputname}:${output}:\${LINENO}: libtool wrapper (GNU $PACKAGE$TIMESTAMP) $VERSION\" 1>&2 fi } # Used when --lt-debug. Prints its arguments to stdout # (redirection is the responsibility of the caller) func_lt_dump_args () { lt_dump_args_N=1; for lt_arg do \$ECHO \"${outputname}:${output}:\${LINENO}: newargv[\$lt_dump_args_N]: \$lt_arg\" lt_dump_args_N=\`expr \$lt_dump_args_N + 1\` done } # Core function for launching the target application func_exec_program_core () { " case $host in # Backslashes separate directories on plain windows *-*-mingw | *-*-os2* | *-cegcc*) $ECHO "\ if test -n \"\$lt_option_debug\"; then \$ECHO \"${outputname}:${output}:\${LINENO}: newargv[0]: \$progdir\\\\\$program\" 1>&2 func_lt_dump_args \${1+\"\$@\"} 1>&2 fi exec \"\$progdir\\\\\$program\" \${1+\"\$@\"} " ;; *) $ECHO "\ if test -n \"\$lt_option_debug\"; then \$ECHO \"${outputname}:${output}:\${LINENO}: newargv[0]: \$progdir/\$program\" 1>&2 func_lt_dump_args \${1+\"\$@\"} 1>&2 fi exec \"\$progdir/\$program\" \${1+\"\$@\"} " ;; esac $ECHO "\ \$ECHO \"\$0: cannot exec \$program \$*\" 1>&2 exit 1 } # A function to encapsulate launching the target application # Strips options in the --lt-* namespace from \$@ and # launches target application with the remaining arguments. func_exec_program () { case \" \$* \" in *\\ --lt-*) for lt_wr_arg do case \$lt_wr_arg in --lt-*) ;; *) set x \"\$@\" \"\$lt_wr_arg\"; shift;; esac shift done ;; esac func_exec_program_core \${1+\"\$@\"} } # Parse options func_parse_lt_options \"\$0\" \${1+\"\$@\"} # Find the directory that this script lives in. thisdir=\`\$ECHO \"\$file\" | $SED 's%/[^/]*$%%'\` test \"x\$thisdir\" = \"x\$file\" && thisdir=. # Follow symbolic links until we get to the real thisdir. file=\`ls -ld \"\$file\" | $SED -n 's/.*-> //p'\` while test -n \"\$file\"; do destdir=\`\$ECHO \"\$file\" | $SED 's%/[^/]*\$%%'\` # If there was a directory component, then change thisdir. if test \"x\$destdir\" != \"x\$file\"; then case \"\$destdir\" in [\\\\/]* | [A-Za-z]:[\\\\/]*) thisdir=\"\$destdir\" ;; *) thisdir=\"\$thisdir/\$destdir\" ;; esac fi file=\`\$ECHO \"\$file\" | $SED 's%^.*/%%'\` file=\`ls -ld \"\$thisdir/\$file\" | $SED -n 's/.*-> //p'\` done # Usually 'no', except on cygwin/mingw when embedded into # the cwrapper. WRAPPER_SCRIPT_BELONGS_IN_OBJDIR=$func_emit_wrapper_arg1 if test \"\$WRAPPER_SCRIPT_BELONGS_IN_OBJDIR\" = \"yes\"; then # special case for '.' if test \"\$thisdir\" = \".\"; then thisdir=\`pwd\` fi # remove .libs from thisdir case \"\$thisdir\" in *[\\\\/]$objdir ) thisdir=\`\$ECHO \"\$thisdir\" | $SED 's%[\\\\/][^\\\\/]*$%%'\` ;; $objdir ) thisdir=. ;; esac fi # Try to get the absolute directory name. absdir=\`cd \"\$thisdir\" && pwd\` test -n \"\$absdir\" && thisdir=\"\$absdir\" " if test "$fast_install" = yes; then $ECHO "\ program=lt-'$outputname'$exeext progdir=\"\$thisdir/$objdir\" if test ! -f \"\$progdir/\$program\" || { file=\`ls -1dt \"\$progdir/\$program\" \"\$progdir/../\$program\" 2>/dev/null | ${SED} 1q\`; \\ test \"X\$file\" != \"X\$progdir/\$program\"; }; then file=\"\$\$-\$program\" if test ! -d \"\$progdir\"; then $MKDIR \"\$progdir\" else $RM \"\$progdir/\$file\" fi" $ECHO "\ # relink executable if necessary if test -n \"\$relink_command\"; then if relink_command_output=\`eval \$relink_command 2>&1\`; then : else $ECHO \"\$relink_command_output\" >&2 $RM \"\$progdir/\$file\" exit 1 fi fi $MV \"\$progdir/\$file\" \"\$progdir/\$program\" 2>/dev/null || { $RM \"\$progdir/\$program\"; $MV \"\$progdir/\$file\" \"\$progdir/\$program\"; } $RM \"\$progdir/\$file\" fi" else $ECHO "\ program='$outputname' progdir=\"\$thisdir/$objdir\" " fi $ECHO "\ if test -f \"\$progdir/\$program\"; then" # fixup the dll searchpath if we need to. # # Fix the DLL searchpath if we need to. Do this before prepending # to shlibpath, because on Windows, both are PATH and uninstalled # libraries must come first. if test -n "$dllsearchpath"; then $ECHO "\ # Add the dll search path components to the executable PATH PATH=$dllsearchpath:\$PATH " fi # Export our shlibpath_var if we have one. if test "$shlibpath_overrides_runpath" = yes && test -n "$shlibpath_var" && test -n "$temp_rpath"; then $ECHO "\ # Add our own library path to $shlibpath_var $shlibpath_var=\"$temp_rpath\$$shlibpath_var\" # Some systems cannot cope with colon-terminated $shlibpath_var # The second colon is a workaround for a bug in BeOS R4 sed $shlibpath_var=\`\$ECHO \"\$$shlibpath_var\" | $SED 's/::*\$//'\` export $shlibpath_var " fi $ECHO "\ if test \"\$libtool_execute_magic\" != \"$magic\"; then # Run the actual program with our arguments. func_exec_program \${1+\"\$@\"} fi else # The program doesn't exist. \$ECHO \"\$0: error: \\\`\$progdir/\$program' does not exist\" 1>&2 \$ECHO \"This script is just a wrapper for \$program.\" 1>&2 \$ECHO \"See the $PACKAGE documentation for more information.\" 1>&2 exit 1 fi fi\ " } # func_emit_cwrapperexe_src # emit the source code for a wrapper executable on stdout # Must ONLY be called from within func_mode_link because # it depends on a number of variable set therein. func_emit_cwrapperexe_src () { cat < #include #ifdef _MSC_VER # include # include # include #else # include # include # ifdef __CYGWIN__ # include # endif #endif #include #include #include #include #include #include #include #include /* declarations of non-ANSI functions */ #if defined(__MINGW32__) # ifdef __STRICT_ANSI__ int _putenv (const char *); # endif #elif defined(__CYGWIN__) # ifdef __STRICT_ANSI__ char *realpath (const char *, char *); int putenv (char *); int setenv (const char *, const char *, int); # endif /* #elif defined (other platforms) ... */ #endif /* portability defines, excluding path handling macros */ #if defined(_MSC_VER) # define setmode _setmode # define stat _stat # define chmod _chmod # define getcwd _getcwd # define putenv _putenv # define S_IXUSR _S_IEXEC # ifndef _INTPTR_T_DEFINED # define _INTPTR_T_DEFINED # define intptr_t int # endif #elif defined(__MINGW32__) # define setmode _setmode # define stat _stat # define chmod _chmod # define getcwd _getcwd # define putenv _putenv #elif defined(__CYGWIN__) # define HAVE_SETENV # define FOPEN_WB "wb" /* #elif defined (other platforms) ... */ #endif #if defined(PATH_MAX) # define LT_PATHMAX PATH_MAX #elif defined(MAXPATHLEN) # define LT_PATHMAX MAXPATHLEN #else # define LT_PATHMAX 1024 #endif #ifndef S_IXOTH # define S_IXOTH 0 #endif #ifndef S_IXGRP # define S_IXGRP 0 #endif /* path handling portability macros */ #ifndef DIR_SEPARATOR # define DIR_SEPARATOR '/' # define PATH_SEPARATOR ':' #endif #if defined (_WIN32) || defined (__MSDOS__) || defined (__DJGPP__) || \ defined (__OS2__) # define HAVE_DOS_BASED_FILE_SYSTEM # define FOPEN_WB "wb" # ifndef DIR_SEPARATOR_2 # define DIR_SEPARATOR_2 '\\' # endif # ifndef PATH_SEPARATOR_2 # define PATH_SEPARATOR_2 ';' # endif #endif #ifndef DIR_SEPARATOR_2 # define IS_DIR_SEPARATOR(ch) ((ch) == DIR_SEPARATOR) #else /* DIR_SEPARATOR_2 */ # define IS_DIR_SEPARATOR(ch) \ (((ch) == DIR_SEPARATOR) || ((ch) == DIR_SEPARATOR_2)) #endif /* DIR_SEPARATOR_2 */ #ifndef PATH_SEPARATOR_2 # define IS_PATH_SEPARATOR(ch) ((ch) == PATH_SEPARATOR) #else /* PATH_SEPARATOR_2 */ # define IS_PATH_SEPARATOR(ch) ((ch) == PATH_SEPARATOR_2) #endif /* PATH_SEPARATOR_2 */ #ifndef FOPEN_WB # define FOPEN_WB "w" #endif #ifndef _O_BINARY # define _O_BINARY 0 #endif #define XMALLOC(type, num) ((type *) xmalloc ((num) * sizeof(type))) #define XFREE(stale) do { \ if (stale) { free ((void *) stale); stale = 0; } \ } while (0) #if defined(LT_DEBUGWRAPPER) static int lt_debug = 1; #else static int lt_debug = 0; #endif const char *program_name = "libtool-wrapper"; /* in case xstrdup fails */ void *xmalloc (size_t num); char *xstrdup (const char *string); const char *base_name (const char *name); char *find_executable (const char *wrapper); char *chase_symlinks (const char *pathspec); int make_executable (const char *path); int check_executable (const char *path); char *strendzap (char *str, const char *pat); void lt_debugprintf (const char *file, int line, const char *fmt, ...); void lt_fatal (const char *file, int line, const char *message, ...); static const char *nonnull (const char *s); static const char *nonempty (const char *s); void lt_setenv (const char *name, const char *value); char *lt_extend_str (const char *orig_value, const char *add, int to_end); void lt_update_exe_path (const char *name, const char *value); void lt_update_lib_path (const char *name, const char *value); char **prepare_spawn (char **argv); void lt_dump_script (FILE *f); EOF cat <= 0) && (st.st_mode & (S_IXUSR | S_IXGRP | S_IXOTH))) return 1; else return 0; } int make_executable (const char *path) { int rval = 0; struct stat st; lt_debugprintf (__FILE__, __LINE__, "(make_executable): %s\n", nonempty (path)); if ((!path) || (!*path)) return 0; if (stat (path, &st) >= 0) { rval = chmod (path, st.st_mode | S_IXOTH | S_IXGRP | S_IXUSR); } return rval; } /* Searches for the full path of the wrapper. Returns newly allocated full path name if found, NULL otherwise Does not chase symlinks, even on platforms that support them. */ char * find_executable (const char *wrapper) { int has_slash = 0; const char *p; const char *p_next; /* static buffer for getcwd */ char tmp[LT_PATHMAX + 1]; int tmp_len; char *concat_name; lt_debugprintf (__FILE__, __LINE__, "(find_executable): %s\n", nonempty (wrapper)); if ((wrapper == NULL) || (*wrapper == '\0')) return NULL; /* Absolute path? */ #if defined (HAVE_DOS_BASED_FILE_SYSTEM) if (isalpha ((unsigned char) wrapper[0]) && wrapper[1] == ':') { concat_name = xstrdup (wrapper); if (check_executable (concat_name)) return concat_name; XFREE (concat_name); } else { #endif if (IS_DIR_SEPARATOR (wrapper[0])) { concat_name = xstrdup (wrapper); if (check_executable (concat_name)) return concat_name; XFREE (concat_name); } #if defined (HAVE_DOS_BASED_FILE_SYSTEM) } #endif for (p = wrapper; *p; p++) if (*p == '/') { has_slash = 1; break; } if (!has_slash) { /* no slashes; search PATH */ const char *path = getenv ("PATH"); if (path != NULL) { for (p = path; *p; p = p_next) { const char *q; size_t p_len; for (q = p; *q; q++) if (IS_PATH_SEPARATOR (*q)) break; p_len = q - p; p_next = (*q == '\0' ? q : q + 1); if (p_len == 0) { /* empty path: current directory */ if (getcwd (tmp, LT_PATHMAX) == NULL) lt_fatal (__FILE__, __LINE__, "getcwd failed: %s", nonnull (strerror (errno))); tmp_len = strlen (tmp); concat_name = XMALLOC (char, tmp_len + 1 + strlen (wrapper) + 1); memcpy (concat_name, tmp, tmp_len); concat_name[tmp_len] = '/'; strcpy (concat_name + tmp_len + 1, wrapper); } else { concat_name = XMALLOC (char, p_len + 1 + strlen (wrapper) + 1); memcpy (concat_name, p, p_len); concat_name[p_len] = '/'; strcpy (concat_name + p_len + 1, wrapper); } if (check_executable (concat_name)) return concat_name; XFREE (concat_name); } } /* not found in PATH; assume curdir */ } /* Relative path | not found in path: prepend cwd */ if (getcwd (tmp, LT_PATHMAX) == NULL) lt_fatal (__FILE__, __LINE__, "getcwd failed: %s", nonnull (strerror (errno))); tmp_len = strlen (tmp); concat_name = XMALLOC (char, tmp_len + 1 + strlen (wrapper) + 1); memcpy (concat_name, tmp, tmp_len); concat_name[tmp_len] = '/'; strcpy (concat_name + tmp_len + 1, wrapper); if (check_executable (concat_name)) return concat_name; XFREE (concat_name); return NULL; } char * chase_symlinks (const char *pathspec) { #ifndef S_ISLNK return xstrdup (pathspec); #else char buf[LT_PATHMAX]; struct stat s; char *tmp_pathspec = xstrdup (pathspec); char *p; int has_symlinks = 0; while (strlen (tmp_pathspec) && !has_symlinks) { lt_debugprintf (__FILE__, __LINE__, "checking path component for symlinks: %s\n", tmp_pathspec); if (lstat (tmp_pathspec, &s) == 0) { if (S_ISLNK (s.st_mode) != 0) { has_symlinks = 1; break; } /* search backwards for last DIR_SEPARATOR */ p = tmp_pathspec + strlen (tmp_pathspec) - 1; while ((p > tmp_pathspec) && (!IS_DIR_SEPARATOR (*p))) p--; if ((p == tmp_pathspec) && (!IS_DIR_SEPARATOR (*p))) { /* no more DIR_SEPARATORS left */ break; } *p = '\0'; } else { lt_fatal (__FILE__, __LINE__, "error accessing file \"%s\": %s", tmp_pathspec, nonnull (strerror (errno))); } } XFREE (tmp_pathspec); if (!has_symlinks) { return xstrdup (pathspec); } tmp_pathspec = realpath (pathspec, buf); if (tmp_pathspec == 0) { lt_fatal (__FILE__, __LINE__, "could not follow symlinks for %s", pathspec); } return xstrdup (tmp_pathspec); #endif } char * strendzap (char *str, const char *pat) { size_t len, patlen; assert (str != NULL); assert (pat != NULL); len = strlen (str); patlen = strlen (pat); if (patlen <= len) { str += len - patlen; if (strcmp (str, pat) == 0) *str = '\0'; } return str; } void lt_debugprintf (const char *file, int line, const char *fmt, ...) { va_list args; if (lt_debug) { (void) fprintf (stderr, "%s:%s:%d: ", program_name, file, line); va_start (args, fmt); (void) vfprintf (stderr, fmt, args); va_end (args); } } static void lt_error_core (int exit_status, const char *file, int line, const char *mode, const char *message, va_list ap) { fprintf (stderr, "%s:%s:%d: %s: ", program_name, file, line, mode); vfprintf (stderr, message, ap); fprintf (stderr, ".\n"); if (exit_status >= 0) exit (exit_status); } void lt_fatal (const char *file, int line, const char *message, ...) { va_list ap; va_start (ap, message); lt_error_core (EXIT_FAILURE, file, line, "FATAL", message, ap); va_end (ap); } static const char * nonnull (const char *s) { return s ? s : "(null)"; } static const char * nonempty (const char *s) { return (s && !*s) ? "(empty)" : nonnull (s); } void lt_setenv (const char *name, const char *value) { lt_debugprintf (__FILE__, __LINE__, "(lt_setenv) setting '%s' to '%s'\n", nonnull (name), nonnull (value)); { #ifdef HAVE_SETENV /* always make a copy, for consistency with !HAVE_SETENV */ char *str = xstrdup (value); setenv (name, str, 1); #else int len = strlen (name) + 1 + strlen (value) + 1; char *str = XMALLOC (char, len); sprintf (str, "%s=%s", name, value); if (putenv (str) != EXIT_SUCCESS) { XFREE (str); } #endif } } char * lt_extend_str (const char *orig_value, const char *add, int to_end) { char *new_value; if (orig_value && *orig_value) { int orig_value_len = strlen (orig_value); int add_len = strlen (add); new_value = XMALLOC (char, add_len + orig_value_len + 1); if (to_end) { strcpy (new_value, orig_value); strcpy (new_value + orig_value_len, add); } else { strcpy (new_value, add); strcpy (new_value + add_len, orig_value); } } else { new_value = xstrdup (add); } return new_value; } void lt_update_exe_path (const char *name, const char *value) { lt_debugprintf (__FILE__, __LINE__, "(lt_update_exe_path) modifying '%s' by prepending '%s'\n", nonnull (name), nonnull (value)); if (name && *name && value && *value) { char *new_value = lt_extend_str (getenv (name), value, 0); /* some systems can't cope with a ':'-terminated path #' */ int len = strlen (new_value); while (((len = strlen (new_value)) > 0) && IS_PATH_SEPARATOR (new_value[len-1])) { new_value[len-1] = '\0'; } lt_setenv (name, new_value); XFREE (new_value); } } void lt_update_lib_path (const char *name, const char *value) { lt_debugprintf (__FILE__, __LINE__, "(lt_update_lib_path) modifying '%s' by prepending '%s'\n", nonnull (name), nonnull (value)); if (name && *name && value && *value) { char *new_value = lt_extend_str (getenv (name), value, 0); lt_setenv (name, new_value); XFREE (new_value); } } EOF case $host_os in mingw*) cat <<"EOF" /* Prepares an argument vector before calling spawn(). Note that spawn() does not by itself call the command interpreter (getenv ("COMSPEC") != NULL ? getenv ("COMSPEC") : ({ OSVERSIONINFO v; v.dwOSVersionInfoSize = sizeof(OSVERSIONINFO); GetVersionEx(&v); v.dwPlatformId == VER_PLATFORM_WIN32_NT; }) ? "cmd.exe" : "command.com"). Instead it simply concatenates the arguments, separated by ' ', and calls CreateProcess(). We must quote the arguments since Win32 CreateProcess() interprets characters like ' ', '\t', '\\', '"' (but not '<' and '>') in a special way: - Space and tab are interpreted as delimiters. They are not treated as delimiters if they are surrounded by double quotes: "...". - Unescaped double quotes are removed from the input. Their only effect is that within double quotes, space and tab are treated like normal characters. - Backslashes not followed by double quotes are not special. - But 2*n+1 backslashes followed by a double quote become n backslashes followed by a double quote (n >= 0): \" -> " \\\" -> \" \\\\\" -> \\" */ #define SHELL_SPECIAL_CHARS "\"\\ \001\002\003\004\005\006\007\010\011\012\013\014\015\016\017\020\021\022\023\024\025\026\027\030\031\032\033\034\035\036\037" #define SHELL_SPACE_CHARS " \001\002\003\004\005\006\007\010\011\012\013\014\015\016\017\020\021\022\023\024\025\026\027\030\031\032\033\034\035\036\037" char ** prepare_spawn (char **argv) { size_t argc; char **new_argv; size_t i; /* Count number of arguments. */ for (argc = 0; argv[argc] != NULL; argc++) ; /* Allocate new argument vector. */ new_argv = XMALLOC (char *, argc + 1); /* Put quoted arguments into the new argument vector. */ for (i = 0; i < argc; i++) { const char *string = argv[i]; if (string[0] == '\0') new_argv[i] = xstrdup ("\"\""); else if (strpbrk (string, SHELL_SPECIAL_CHARS) != NULL) { int quote_around = (strpbrk (string, SHELL_SPACE_CHARS) != NULL); size_t length; unsigned int backslashes; const char *s; char *quoted_string; char *p; length = 0; backslashes = 0; if (quote_around) length++; for (s = string; *s != '\0'; s++) { char c = *s; if (c == '"') length += backslashes + 1; length++; if (c == '\\') backslashes++; else backslashes = 0; } if (quote_around) length += backslashes + 1; quoted_string = XMALLOC (char, length + 1); p = quoted_string; backslashes = 0; if (quote_around) *p++ = '"'; for (s = string; *s != '\0'; s++) { char c = *s; if (c == '"') { unsigned int j; for (j = backslashes + 1; j > 0; j--) *p++ = '\\'; } *p++ = c; if (c == '\\') backslashes++; else backslashes = 0; } if (quote_around) { unsigned int j; for (j = backslashes; j > 0; j--) *p++ = '\\'; *p++ = '"'; } *p = '\0'; new_argv[i] = quoted_string; } else new_argv[i] = (char *) string; } new_argv[argc] = NULL; return new_argv; } EOF ;; esac cat <<"EOF" void lt_dump_script (FILE* f) { EOF func_emit_wrapper yes | $SED -n -e ' s/^\(.\{79\}\)\(..*\)/\1\ \2/ h s/\([\\"]\)/\\\1/g s/$/\\n/ s/\([^\n]*\).*/ fputs ("\1", f);/p g D' cat <<"EOF" } EOF } # end: func_emit_cwrapperexe_src # func_win32_import_lib_p ARG # True if ARG is an import lib, as indicated by $file_magic_cmd func_win32_import_lib_p () { $opt_debug case `eval $file_magic_cmd \"\$1\" 2>/dev/null | $SED -e 10q` in *import*) : ;; *) false ;; esac } # func_mode_link arg... func_mode_link () { $opt_debug case $host in *-*-cygwin* | *-*-mingw* | *-*-pw32* | *-*-os2* | *-cegcc*) # It is impossible to link a dll without this setting, and # we shouldn't force the makefile maintainer to figure out # which system we are compiling for in order to pass an extra # flag for every libtool invocation. # allow_undefined=no # FIXME: Unfortunately, there are problems with the above when trying # to make a dll which has undefined symbols, in which case not # even a static library is built. For now, we need to specify # -no-undefined on the libtool link line when we can be certain # that all symbols are satisfied, otherwise we get a static library. allow_undefined=yes ;; *) allow_undefined=yes ;; esac libtool_args=$nonopt base_compile="$nonopt $@" compile_command=$nonopt finalize_command=$nonopt compile_rpath= finalize_rpath= compile_shlibpath= finalize_shlibpath= convenience= old_convenience= deplibs= old_deplibs= compiler_flags= linker_flags= dllsearchpath= lib_search_path=`pwd` inst_prefix_dir= new_inherited_linker_flags= avoid_version=no bindir= dlfiles= dlprefiles= dlself=no export_dynamic=no export_symbols= export_symbols_regex= generated= libobjs= ltlibs= module=no no_install=no objs= non_pic_objects= precious_files_regex= prefer_static_libs=no preload=no prev= prevarg= release= rpath= xrpath= perm_rpath= temp_rpath= thread_safe=no vinfo= vinfo_number=no weak_libs= single_module="${wl}-single_module" func_infer_tag $base_compile # We need to know -static, to get the right output filenames. for arg do case $arg in -shared) test "$build_libtool_libs" != yes && \ func_fatal_configuration "can not build a shared library" build_old_libs=no break ;; -all-static | -static | -static-libtool-libs) case $arg in -all-static) if test "$build_libtool_libs" = yes && test -z "$link_static_flag"; then func_warning "complete static linking is impossible in this configuration" fi if test -n "$link_static_flag"; then dlopen_self=$dlopen_self_static fi prefer_static_libs=yes ;; -static) if test -z "$pic_flag" && test -n "$link_static_flag"; then dlopen_self=$dlopen_self_static fi prefer_static_libs=built ;; -static-libtool-libs) if test -z "$pic_flag" && test -n "$link_static_flag"; then dlopen_self=$dlopen_self_static fi prefer_static_libs=yes ;; esac build_libtool_libs=no build_old_libs=yes break ;; esac done # See if our shared archives depend on static archives. test -n "$old_archive_from_new_cmds" && build_old_libs=yes # Go through the arguments, transforming them on the way. while test "$#" -gt 0; do arg="$1" shift func_quote_for_eval "$arg" qarg=$func_quote_for_eval_unquoted_result func_append libtool_args " $func_quote_for_eval_result" # If the previous option needs an argument, assign it. if test -n "$prev"; then case $prev in output) func_append compile_command " @OUTPUT@" func_append finalize_command " @OUTPUT@" ;; esac case $prev in bindir) bindir="$arg" prev= continue ;; dlfiles|dlprefiles) if test "$preload" = no; then # Add the symbol object into the linking commands. func_append compile_command " @SYMFILE@" func_append finalize_command " @SYMFILE@" preload=yes fi case $arg in *.la | *.lo) ;; # We handle these cases below. force) if test "$dlself" = no; then dlself=needless export_dynamic=yes fi prev= continue ;; self) if test "$prev" = dlprefiles; then dlself=yes elif test "$prev" = dlfiles && test "$dlopen_self" != yes; then dlself=yes else dlself=needless export_dynamic=yes fi prev= continue ;; *) if test "$prev" = dlfiles; then func_append dlfiles " $arg" else func_append dlprefiles " $arg" fi prev= continue ;; esac ;; expsyms) export_symbols="$arg" test -f "$arg" \ || func_fatal_error "symbol file \`$arg' does not exist" prev= continue ;; expsyms_regex) export_symbols_regex="$arg" prev= continue ;; framework) case $host in *-*-darwin*) case "$deplibs " in *" $qarg.ltframework "*) ;; *) func_append deplibs " $qarg.ltframework" # this is fixed later ;; esac ;; esac prev= continue ;; inst_prefix) inst_prefix_dir="$arg" prev= continue ;; objectlist) if test -f "$arg"; then save_arg=$arg moreargs= for fil in `cat "$save_arg"` do # func_append moreargs " $fil" arg=$fil # A libtool-controlled object. # Check to see that this really is a libtool object. if func_lalib_unsafe_p "$arg"; then pic_object= non_pic_object= # Read the .lo file func_source "$arg" if test -z "$pic_object" || test -z "$non_pic_object" || test "$pic_object" = none && test "$non_pic_object" = none; then func_fatal_error "cannot find name of object for \`$arg'" fi # Extract subdirectory from the argument. func_dirname "$arg" "/" "" xdir="$func_dirname_result" if test "$pic_object" != none; then # Prepend the subdirectory the object is found in. pic_object="$xdir$pic_object" if test "$prev" = dlfiles; then if test "$build_libtool_libs" = yes && test "$dlopen_support" = yes; then func_append dlfiles " $pic_object" prev= continue else # If libtool objects are unsupported, then we need to preload. prev=dlprefiles fi fi # CHECK ME: I think I busted this. -Ossama if test "$prev" = dlprefiles; then # Preload the old-style object. func_append dlprefiles " $pic_object" prev= fi # A PIC object. func_append libobjs " $pic_object" arg="$pic_object" fi # Non-PIC object. if test "$non_pic_object" != none; then # Prepend the subdirectory the object is found in. non_pic_object="$xdir$non_pic_object" # A standard non-PIC object func_append non_pic_objects " $non_pic_object" if test -z "$pic_object" || test "$pic_object" = none ; then arg="$non_pic_object" fi else # If the PIC object exists, use it instead. # $xdir was prepended to $pic_object above. non_pic_object="$pic_object" func_append non_pic_objects " $non_pic_object" fi else # Only an error if not doing a dry-run. if $opt_dry_run; then # Extract subdirectory from the argument. func_dirname "$arg" "/" "" xdir="$func_dirname_result" func_lo2o "$arg" pic_object=$xdir$objdir/$func_lo2o_result non_pic_object=$xdir$func_lo2o_result func_append libobjs " $pic_object" func_append non_pic_objects " $non_pic_object" else func_fatal_error "\`$arg' is not a valid libtool object" fi fi done else func_fatal_error "link input file \`$arg' does not exist" fi arg=$save_arg prev= continue ;; precious_regex) precious_files_regex="$arg" prev= continue ;; release) release="-$arg" prev= continue ;; rpath | xrpath) # We need an absolute path. case $arg in [\\/]* | [A-Za-z]:[\\/]*) ;; *) func_fatal_error "only absolute run-paths are allowed" ;; esac if test "$prev" = rpath; then case "$rpath " in *" $arg "*) ;; *) func_append rpath " $arg" ;; esac else case "$xrpath " in *" $arg "*) ;; *) func_append xrpath " $arg" ;; esac fi prev= continue ;; shrext) shrext_cmds="$arg" prev= continue ;; weak) func_append weak_libs " $arg" prev= continue ;; xcclinker) func_append linker_flags " $qarg" func_append compiler_flags " $qarg" prev= func_append compile_command " $qarg" func_append finalize_command " $qarg" continue ;; xcompiler) func_append compiler_flags " $qarg" prev= func_append compile_command " $qarg" func_append finalize_command " $qarg" continue ;; xlinker) func_append linker_flags " $qarg" func_append compiler_flags " $wl$qarg" prev= func_append compile_command " $wl$qarg" func_append finalize_command " $wl$qarg" continue ;; *) eval "$prev=\"\$arg\"" prev= continue ;; esac fi # test -n "$prev" prevarg="$arg" case $arg in -all-static) if test -n "$link_static_flag"; then # See comment for -static flag below, for more details. func_append compile_command " $link_static_flag" func_append finalize_command " $link_static_flag" fi continue ;; -allow-undefined) # FIXME: remove this flag sometime in the future. func_fatal_error "\`-allow-undefined' must not be used because it is the default" ;; -avoid-version) avoid_version=yes continue ;; -bindir) prev=bindir continue ;; -dlopen) prev=dlfiles continue ;; -dlpreopen) prev=dlprefiles continue ;; -export-dynamic) export_dynamic=yes continue ;; -export-symbols | -export-symbols-regex) if test -n "$export_symbols" || test -n "$export_symbols_regex"; then func_fatal_error "more than one -exported-symbols argument is not allowed" fi if test "X$arg" = "X-export-symbols"; then prev=expsyms else prev=expsyms_regex fi continue ;; -framework) prev=framework continue ;; -inst-prefix-dir) prev=inst_prefix continue ;; # The native IRIX linker understands -LANG:*, -LIST:* and -LNO:* # so, if we see these flags be careful not to treat them like -L -L[A-Z][A-Z]*:*) case $with_gcc/$host in no/*-*-irix* | /*-*-irix*) func_append compile_command " $arg" func_append finalize_command " $arg" ;; esac continue ;; -L*) func_stripname "-L" '' "$arg" if test -z "$func_stripname_result"; then if test "$#" -gt 0; then func_fatal_error "require no space between \`-L' and \`$1'" else func_fatal_error "need path for \`-L' option" fi fi func_resolve_sysroot "$func_stripname_result" dir=$func_resolve_sysroot_result # We need an absolute path. case $dir in [\\/]* | [A-Za-z]:[\\/]*) ;; *) absdir=`cd "$dir" && pwd` test -z "$absdir" && \ func_fatal_error "cannot determine absolute directory name of \`$dir'" dir="$absdir" ;; esac case "$deplibs " in *" -L$dir "* | *" $arg "*) # Will only happen for absolute or sysroot arguments ;; *) # Preserve sysroot, but never include relative directories case $dir in [\\/]* | [A-Za-z]:[\\/]* | =*) func_append deplibs " $arg" ;; *) func_append deplibs " -L$dir" ;; esac func_append lib_search_path " $dir" ;; esac case $host in *-*-cygwin* | *-*-mingw* | *-*-pw32* | *-*-os2* | *-cegcc*) testbindir=`$ECHO "$dir" | $SED 's*/lib$*/bin*'` case :$dllsearchpath: in *":$dir:"*) ;; ::) dllsearchpath=$dir;; *) func_append dllsearchpath ":$dir";; esac case :$dllsearchpath: in *":$testbindir:"*) ;; ::) dllsearchpath=$testbindir;; *) func_append dllsearchpath ":$testbindir";; esac ;; esac continue ;; -l*) if test "X$arg" = "X-lc" || test "X$arg" = "X-lm"; then case $host in *-*-cygwin* | *-*-mingw* | *-*-pw32* | *-*-beos* | *-cegcc* | *-*-haiku*) # These systems don't actually have a C or math library (as such) continue ;; *-*-os2*) # These systems don't actually have a C library (as such) test "X$arg" = "X-lc" && continue ;; *-*-openbsd* | *-*-freebsd* | *-*-dragonfly*) # Do not include libc due to us having libc/libc_r. test "X$arg" = "X-lc" && continue ;; *-*-rhapsody* | *-*-darwin1.[012]) # Rhapsody C and math libraries are in the System framework func_append deplibs " System.ltframework" continue ;; *-*-sco3.2v5* | *-*-sco5v6*) # Causes problems with __ctype test "X$arg" = "X-lc" && continue ;; *-*-sysv4.2uw2* | *-*-sysv5* | *-*-unixware* | *-*-OpenUNIX*) # Compiler inserts libc in the correct place for threads to work test "X$arg" = "X-lc" && continue ;; esac elif test "X$arg" = "X-lc_r"; then case $host in *-*-openbsd* | *-*-freebsd* | *-*-dragonfly*) # Do not include libc_r directly, use -pthread flag. continue ;; esac fi func_append deplibs " $arg" continue ;; -module) module=yes continue ;; # Tru64 UNIX uses -model [arg] to determine the layout of C++ # classes, name mangling, and exception handling. # Darwin uses the -arch flag to determine output architecture. -model|-arch|-isysroot|--sysroot) func_append compiler_flags " $arg" func_append compile_command " $arg" func_append finalize_command " $arg" prev=xcompiler continue ;; -mt|-mthreads|-kthread|-Kthread|-pthread|-pthreads|--thread-safe \ |-threads|-fopenmp|-openmp|-mp|-xopenmp|-omp|-qsmp=*) func_append compiler_flags " $arg" func_append compile_command " $arg" func_append finalize_command " $arg" case "$new_inherited_linker_flags " in *" $arg "*) ;; * ) func_append new_inherited_linker_flags " $arg" ;; esac continue ;; -multi_module) single_module="${wl}-multi_module" continue ;; -no-fast-install) fast_install=no continue ;; -no-install) case $host in *-*-cygwin* | *-*-mingw* | *-*-pw32* | *-*-os2* | *-*-darwin* | *-cegcc*) # The PATH hackery in wrapper scripts is required on Windows # and Darwin in order for the loader to find any dlls it needs. func_warning "\`-no-install' is ignored for $host" func_warning "assuming \`-no-fast-install' instead" fast_install=no ;; *) no_install=yes ;; esac continue ;; -no-undefined) allow_undefined=no continue ;; -objectlist) prev=objectlist continue ;; -o) prev=output ;; -precious-files-regex) prev=precious_regex continue ;; -release) prev=release continue ;; -rpath) prev=rpath continue ;; -R) prev=xrpath continue ;; -R*) func_stripname '-R' '' "$arg" dir=$func_stripname_result # We need an absolute path. case $dir in [\\/]* | [A-Za-z]:[\\/]*) ;; =*) func_stripname '=' '' "$dir" dir=$lt_sysroot$func_stripname_result ;; *) func_fatal_error "only absolute run-paths are allowed" ;; esac case "$xrpath " in *" $dir "*) ;; *) func_append xrpath " $dir" ;; esac continue ;; -shared) # The effects of -shared are defined in a previous loop. continue ;; -shrext) prev=shrext continue ;; -static | -static-libtool-libs) # The effects of -static are defined in a previous loop. # We used to do the same as -all-static on platforms that # didn't have a PIC flag, but the assumption that the effects # would be equivalent was wrong. It would break on at least # Digital Unix and AIX. continue ;; -thread-safe) thread_safe=yes continue ;; -version-info) prev=vinfo continue ;; -version-number) prev=vinfo vinfo_number=yes continue ;; -weak) prev=weak continue ;; -Wc,*) func_stripname '-Wc,' '' "$arg" args=$func_stripname_result arg= save_ifs="$IFS"; IFS=',' for flag in $args; do IFS="$save_ifs" func_quote_for_eval "$flag" func_append arg " $func_quote_for_eval_result" func_append compiler_flags " $func_quote_for_eval_result" done IFS="$save_ifs" func_stripname ' ' '' "$arg" arg=$func_stripname_result ;; -Wl,*) func_stripname '-Wl,' '' "$arg" args=$func_stripname_result arg= save_ifs="$IFS"; IFS=',' for flag in $args; do IFS="$save_ifs" func_quote_for_eval "$flag" func_append arg " $wl$func_quote_for_eval_result" func_append compiler_flags " $wl$func_quote_for_eval_result" func_append linker_flags " $func_quote_for_eval_result" done IFS="$save_ifs" func_stripname ' ' '' "$arg" arg=$func_stripname_result ;; -Xcompiler) prev=xcompiler continue ;; -Xlinker) prev=xlinker continue ;; -XCClinker) prev=xcclinker continue ;; # -msg_* for osf cc -msg_*) func_quote_for_eval "$arg" arg="$func_quote_for_eval_result" ;; # Flags to be passed through unchanged, with rationale: # -64, -mips[0-9] enable 64-bit mode for the SGI compiler # -r[0-9][0-9]* specify processor for the SGI compiler # -xarch=*, -xtarget=* enable 64-bit mode for the Sun compiler # +DA*, +DD* enable 64-bit mode for the HP compiler # -q* compiler args for the IBM compiler # -m*, -t[45]*, -txscale* architecture-specific flags for GCC # -F/path path to uninstalled frameworks, gcc on darwin # -p, -pg, --coverage, -fprofile-* profiling flags for GCC # @file GCC response files # -tp=* Portland pgcc target processor selection # --sysroot=* for sysroot support # -O*, -flto*, -fwhopr*, -fuse-linker-plugin GCC link-time optimization -64|-mips[0-9]|-r[0-9][0-9]*|-xarch=*|-xtarget=*|+DA*|+DD*|-q*|-m*| \ -t[45]*|-txscale*|-p|-pg|--coverage|-fprofile-*|-F*|@*|-tp=*|--sysroot=*| \ -O*|-flto*|-fwhopr*|-fuse-linker-plugin) func_quote_for_eval "$arg" arg="$func_quote_for_eval_result" func_append compile_command " $arg" func_append finalize_command " $arg" func_append compiler_flags " $arg" continue ;; # Some other compiler flag. -* | +*) func_quote_for_eval "$arg" arg="$func_quote_for_eval_result" ;; *.$objext) # A standard object. func_append objs " $arg" ;; *.lo) # A libtool-controlled object. # Check to see that this really is a libtool object. if func_lalib_unsafe_p "$arg"; then pic_object= non_pic_object= # Read the .lo file func_source "$arg" if test -z "$pic_object" || test -z "$non_pic_object" || test "$pic_object" = none && test "$non_pic_object" = none; then func_fatal_error "cannot find name of object for \`$arg'" fi # Extract subdirectory from the argument. func_dirname "$arg" "/" "" xdir="$func_dirname_result" if test "$pic_object" != none; then # Prepend the subdirectory the object is found in. pic_object="$xdir$pic_object" if test "$prev" = dlfiles; then if test "$build_libtool_libs" = yes && test "$dlopen_support" = yes; then func_append dlfiles " $pic_object" prev= continue else # If libtool objects are unsupported, then we need to preload. prev=dlprefiles fi fi # CHECK ME: I think I busted this. -Ossama if test "$prev" = dlprefiles; then # Preload the old-style object. func_append dlprefiles " $pic_object" prev= fi # A PIC object. func_append libobjs " $pic_object" arg="$pic_object" fi # Non-PIC object. if test "$non_pic_object" != none; then # Prepend the subdirectory the object is found in. non_pic_object="$xdir$non_pic_object" # A standard non-PIC object func_append non_pic_objects " $non_pic_object" if test -z "$pic_object" || test "$pic_object" = none ; then arg="$non_pic_object" fi else # If the PIC object exists, use it instead. # $xdir was prepended to $pic_object above. non_pic_object="$pic_object" func_append non_pic_objects " $non_pic_object" fi else # Only an error if not doing a dry-run. if $opt_dry_run; then # Extract subdirectory from the argument. func_dirname "$arg" "/" "" xdir="$func_dirname_result" func_lo2o "$arg" pic_object=$xdir$objdir/$func_lo2o_result non_pic_object=$xdir$func_lo2o_result func_append libobjs " $pic_object" func_append non_pic_objects " $non_pic_object" else func_fatal_error "\`$arg' is not a valid libtool object" fi fi ;; *.$libext) # An archive. func_append deplibs " $arg" func_append old_deplibs " $arg" continue ;; *.la) # A libtool-controlled library. func_resolve_sysroot "$arg" if test "$prev" = dlfiles; then # This library was specified with -dlopen. func_append dlfiles " $func_resolve_sysroot_result" prev= elif test "$prev" = dlprefiles; then # The library was specified with -dlpreopen. func_append dlprefiles " $func_resolve_sysroot_result" prev= else func_append deplibs " $func_resolve_sysroot_result" fi continue ;; # Some other compiler argument. *) # Unknown arguments in both finalize_command and compile_command need # to be aesthetically quoted because they are evaled later. func_quote_for_eval "$arg" arg="$func_quote_for_eval_result" ;; esac # arg # Now actually substitute the argument into the commands. if test -n "$arg"; then func_append compile_command " $arg" func_append finalize_command " $arg" fi done # argument parsing loop test -n "$prev" && \ func_fatal_help "the \`$prevarg' option requires an argument" if test "$export_dynamic" = yes && test -n "$export_dynamic_flag_spec"; then eval arg=\"$export_dynamic_flag_spec\" func_append compile_command " $arg" func_append finalize_command " $arg" fi oldlibs= # calculate the name of the file, without its directory func_basename "$output" outputname="$func_basename_result" libobjs_save="$libobjs" if test -n "$shlibpath_var"; then # get the directories listed in $shlibpath_var eval shlib_search_path=\`\$ECHO \"\${$shlibpath_var}\" \| \$SED \'s/:/ /g\'\` else shlib_search_path= fi eval sys_lib_search_path=\"$sys_lib_search_path_spec\" eval sys_lib_dlsearch_path=\"$sys_lib_dlsearch_path_spec\" func_dirname "$output" "/" "" output_objdir="$func_dirname_result$objdir" func_to_tool_file "$output_objdir/" tool_output_objdir=$func_to_tool_file_result # Create the object directory. func_mkdir_p "$output_objdir" # Determine the type of output case $output in "") func_fatal_help "you must specify an output file" ;; *.$libext) linkmode=oldlib ;; *.lo | *.$objext) linkmode=obj ;; *.la) linkmode=lib ;; *) linkmode=prog ;; # Anything else should be a program. esac specialdeplibs= libs= # Find all interdependent deplibs by searching for libraries # that are linked more than once (e.g. -la -lb -la) for deplib in $deplibs; do if $opt_preserve_dup_deps ; then case "$libs " in *" $deplib "*) func_append specialdeplibs " $deplib" ;; esac fi func_append libs " $deplib" done if test "$linkmode" = lib; then libs="$predeps $libs $compiler_lib_search_path $postdeps" # Compute libraries that are listed more than once in $predeps # $postdeps and mark them as special (i.e., whose duplicates are # not to be eliminated). pre_post_deps= if $opt_duplicate_compiler_generated_deps; then for pre_post_dep in $predeps $postdeps; do case "$pre_post_deps " in *" $pre_post_dep "*) func_append specialdeplibs " $pre_post_deps" ;; esac func_append pre_post_deps " $pre_post_dep" done fi pre_post_deps= fi deplibs= newdependency_libs= newlib_search_path= need_relink=no # whether we're linking any uninstalled libtool libraries notinst_deplibs= # not-installed libtool libraries notinst_path= # paths that contain not-installed libtool libraries case $linkmode in lib) passes="conv dlpreopen link" for file in $dlfiles $dlprefiles; do case $file in *.la) ;; *) func_fatal_help "libraries can \`-dlopen' only libtool libraries: $file" ;; esac done ;; prog) compile_deplibs= finalize_deplibs= alldeplibs=no newdlfiles= newdlprefiles= passes="conv scan dlopen dlpreopen link" ;; *) passes="conv" ;; esac for pass in $passes; do # The preopen pass in lib mode reverses $deplibs; put it back here # so that -L comes before libs that need it for instance... if test "$linkmode,$pass" = "lib,link"; then ## FIXME: Find the place where the list is rebuilt in the wrong ## order, and fix it there properly tmp_deplibs= for deplib in $deplibs; do tmp_deplibs="$deplib $tmp_deplibs" done deplibs="$tmp_deplibs" fi if test "$linkmode,$pass" = "lib,link" || test "$linkmode,$pass" = "prog,scan"; then libs="$deplibs" deplibs= fi if test "$linkmode" = prog; then case $pass in dlopen) libs="$dlfiles" ;; dlpreopen) libs="$dlprefiles" ;; link) libs="$deplibs %DEPLIBS% $dependency_libs" ;; esac fi if test "$linkmode,$pass" = "lib,dlpreopen"; then # Collect and forward deplibs of preopened libtool libs for lib in $dlprefiles; do # Ignore non-libtool-libs dependency_libs= func_resolve_sysroot "$lib" case $lib in *.la) func_source "$func_resolve_sysroot_result" ;; esac # Collect preopened libtool deplibs, except any this library # has declared as weak libs for deplib in $dependency_libs; do func_basename "$deplib" deplib_base=$func_basename_result case " $weak_libs " in *" $deplib_base "*) ;; *) func_append deplibs " $deplib" ;; esac done done libs="$dlprefiles" fi if test "$pass" = dlopen; then # Collect dlpreopened libraries save_deplibs="$deplibs" deplibs= fi for deplib in $libs; do lib= found=no case $deplib in -mt|-mthreads|-kthread|-Kthread|-pthread|-pthreads|--thread-safe \ |-threads|-fopenmp|-openmp|-mp|-xopenmp|-omp|-qsmp=*) if test "$linkmode,$pass" = "prog,link"; then compile_deplibs="$deplib $compile_deplibs" finalize_deplibs="$deplib $finalize_deplibs" else func_append compiler_flags " $deplib" if test "$linkmode" = lib ; then case "$new_inherited_linker_flags " in *" $deplib "*) ;; * ) func_append new_inherited_linker_flags " $deplib" ;; esac fi fi continue ;; -l*) if test "$linkmode" != lib && test "$linkmode" != prog; then func_warning "\`-l' is ignored for archives/objects" continue fi func_stripname '-l' '' "$deplib" name=$func_stripname_result if test "$linkmode" = lib; then searchdirs="$newlib_search_path $lib_search_path $compiler_lib_search_dirs $sys_lib_search_path $shlib_search_path" else searchdirs="$newlib_search_path $lib_search_path $sys_lib_search_path $shlib_search_path" fi for searchdir in $searchdirs; do for search_ext in .la $std_shrext .so .a; do # Search the libtool library lib="$searchdir/lib${name}${search_ext}" if test -f "$lib"; then if test "$search_ext" = ".la"; then found=yes else found=no fi break 2 fi done done if test "$found" != yes; then # deplib doesn't seem to be a libtool library if test "$linkmode,$pass" = "prog,link"; then compile_deplibs="$deplib $compile_deplibs" finalize_deplibs="$deplib $finalize_deplibs" else deplibs="$deplib $deplibs" test "$linkmode" = lib && newdependency_libs="$deplib $newdependency_libs" fi continue else # deplib is a libtool library # If $allow_libtool_libs_with_static_runtimes && $deplib is a stdlib, # We need to do some special things here, and not later. if test "X$allow_libtool_libs_with_static_runtimes" = "Xyes" ; then case " $predeps $postdeps " in *" $deplib "*) if func_lalib_p "$lib"; then library_names= old_library= func_source "$lib" for l in $old_library $library_names; do ll="$l" done if test "X$ll" = "X$old_library" ; then # only static version available found=no func_dirname "$lib" "" "." ladir="$func_dirname_result" lib=$ladir/$old_library if test "$linkmode,$pass" = "prog,link"; then compile_deplibs="$deplib $compile_deplibs" finalize_deplibs="$deplib $finalize_deplibs" else deplibs="$deplib $deplibs" test "$linkmode" = lib && newdependency_libs="$deplib $newdependency_libs" fi continue fi fi ;; *) ;; esac fi fi ;; # -l *.ltframework) if test "$linkmode,$pass" = "prog,link"; then compile_deplibs="$deplib $compile_deplibs" finalize_deplibs="$deplib $finalize_deplibs" else deplibs="$deplib $deplibs" if test "$linkmode" = lib ; then case "$new_inherited_linker_flags " in *" $deplib "*) ;; * ) func_append new_inherited_linker_flags " $deplib" ;; esac fi fi continue ;; -L*) case $linkmode in lib) deplibs="$deplib $deplibs" test "$pass" = conv && continue newdependency_libs="$deplib $newdependency_libs" func_stripname '-L' '' "$deplib" func_resolve_sysroot "$func_stripname_result" func_append newlib_search_path " $func_resolve_sysroot_result" ;; prog) if test "$pass" = conv; then deplibs="$deplib $deplibs" continue fi if test "$pass" = scan; then deplibs="$deplib $deplibs" else compile_deplibs="$deplib $compile_deplibs" finalize_deplibs="$deplib $finalize_deplibs" fi func_stripname '-L' '' "$deplib" func_resolve_sysroot "$func_stripname_result" func_append newlib_search_path " $func_resolve_sysroot_result" ;; *) func_warning "\`-L' is ignored for archives/objects" ;; esac # linkmode continue ;; # -L -R*) if test "$pass" = link; then func_stripname '-R' '' "$deplib" func_resolve_sysroot "$func_stripname_result" dir=$func_resolve_sysroot_result # Make sure the xrpath contains only unique directories. case "$xrpath " in *" $dir "*) ;; *) func_append xrpath " $dir" ;; esac fi deplibs="$deplib $deplibs" continue ;; *.la) func_resolve_sysroot "$deplib" lib=$func_resolve_sysroot_result ;; *.$libext) if test "$pass" = conv; then deplibs="$deplib $deplibs" continue fi case $linkmode in lib) # Linking convenience modules into shared libraries is allowed, # but linking other static libraries is non-portable. case " $dlpreconveniencelibs " in *" $deplib "*) ;; *) valid_a_lib=no case $deplibs_check_method in match_pattern*) set dummy $deplibs_check_method; shift match_pattern_regex=`expr "$deplibs_check_method" : "$1 \(.*\)"` if eval "\$ECHO \"$deplib\"" 2>/dev/null | $SED 10q \ | $EGREP "$match_pattern_regex" > /dev/null; then valid_a_lib=yes fi ;; pass_all) valid_a_lib=yes ;; esac if test "$valid_a_lib" != yes; then echo $ECHO "*** Warning: Trying to link with static lib archive $deplib." echo "*** I have the capability to make that library automatically link in when" echo "*** you link to this library. But I can only do this if you have a" echo "*** shared version of the library, which you do not appear to have" echo "*** because the file extensions .$libext of this argument makes me believe" echo "*** that it is just a static archive that I should not use here." else echo $ECHO "*** Warning: Linking the shared library $output against the" $ECHO "*** static library $deplib is not portable!" deplibs="$deplib $deplibs" fi ;; esac continue ;; prog) if test "$pass" != link; then deplibs="$deplib $deplibs" else compile_deplibs="$deplib $compile_deplibs" finalize_deplibs="$deplib $finalize_deplibs" fi continue ;; esac # linkmode ;; # *.$libext *.lo | *.$objext) if test "$pass" = conv; then deplibs="$deplib $deplibs" elif test "$linkmode" = prog; then if test "$pass" = dlpreopen || test "$dlopen_support" != yes || test "$build_libtool_libs" = no; then # If there is no dlopen support or we're linking statically, # we need to preload. func_append newdlprefiles " $deplib" compile_deplibs="$deplib $compile_deplibs" finalize_deplibs="$deplib $finalize_deplibs" else func_append newdlfiles " $deplib" fi fi continue ;; %DEPLIBS%) alldeplibs=yes continue ;; esac # case $deplib if test "$found" = yes || test -f "$lib"; then : else func_fatal_error "cannot find the library \`$lib' or unhandled argument \`$deplib'" fi # Check to see that this really is a libtool archive. func_lalib_unsafe_p "$lib" \ || func_fatal_error "\`$lib' is not a valid libtool archive" func_dirname "$lib" "" "." ladir="$func_dirname_result" dlname= dlopen= dlpreopen= libdir= library_names= old_library= inherited_linker_flags= # If the library was installed with an old release of libtool, # it will not redefine variables installed, or shouldnotlink installed=yes shouldnotlink=no avoidtemprpath= # Read the .la file func_source "$lib" # Convert "-framework foo" to "foo.ltframework" if test -n "$inherited_linker_flags"; then tmp_inherited_linker_flags=`$ECHO "$inherited_linker_flags" | $SED 's/-framework \([^ $]*\)/\1.ltframework/g'` for tmp_inherited_linker_flag in $tmp_inherited_linker_flags; do case " $new_inherited_linker_flags " in *" $tmp_inherited_linker_flag "*) ;; *) func_append new_inherited_linker_flags " $tmp_inherited_linker_flag";; esac done fi dependency_libs=`$ECHO " $dependency_libs" | $SED 's% \([^ $]*\).ltframework% -framework \1%g'` if test "$linkmode,$pass" = "lib,link" || test "$linkmode,$pass" = "prog,scan" || { test "$linkmode" != prog && test "$linkmode" != lib; }; then test -n "$dlopen" && func_append dlfiles " $dlopen" test -n "$dlpreopen" && func_append dlprefiles " $dlpreopen" fi if test "$pass" = conv; then # Only check for convenience libraries deplibs="$lib $deplibs" if test -z "$libdir"; then if test -z "$old_library"; then func_fatal_error "cannot find name of link library for \`$lib'" fi # It is a libtool convenience library, so add in its objects. func_append convenience " $ladir/$objdir/$old_library" func_append old_convenience " $ladir/$objdir/$old_library" elif test "$linkmode" != prog && test "$linkmode" != lib; then func_fatal_error "\`$lib' is not a convenience library" fi tmp_libs= for deplib in $dependency_libs; do deplibs="$deplib $deplibs" if $opt_preserve_dup_deps ; then case "$tmp_libs " in *" $deplib "*) func_append specialdeplibs " $deplib" ;; esac fi func_append tmp_libs " $deplib" done continue fi # $pass = conv # Get the name of the library we link against. linklib= if test -n "$old_library" && { test "$prefer_static_libs" = yes || test "$prefer_static_libs,$installed" = "built,no"; }; then linklib=$old_library else for l in $old_library $library_names; do linklib="$l" done fi if test -z "$linklib"; then func_fatal_error "cannot find name of link library for \`$lib'" fi # This library was specified with -dlopen. if test "$pass" = dlopen; then if test -z "$libdir"; then func_fatal_error "cannot -dlopen a convenience library: \`$lib'" fi if test -z "$dlname" || test "$dlopen_support" != yes || test "$build_libtool_libs" = no; then # If there is no dlname, no dlopen support or we're linking # statically, we need to preload. We also need to preload any # dependent libraries so libltdl's deplib preloader doesn't # bomb out in the load deplibs phase. func_append dlprefiles " $lib $dependency_libs" else func_append newdlfiles " $lib" fi continue fi # $pass = dlopen # We need an absolute path. case $ladir in [\\/]* | [A-Za-z]:[\\/]*) abs_ladir="$ladir" ;; *) abs_ladir=`cd "$ladir" && pwd` if test -z "$abs_ladir"; then func_warning "cannot determine absolute directory name of \`$ladir'" func_warning "passing it literally to the linker, although it might fail" abs_ladir="$ladir" fi ;; esac func_basename "$lib" laname="$func_basename_result" # Find the relevant object directory and library name. if test "X$installed" = Xyes; then if test ! -f "$lt_sysroot$libdir/$linklib" && test -f "$abs_ladir/$linklib"; then func_warning "library \`$lib' was moved." dir="$ladir" absdir="$abs_ladir" libdir="$abs_ladir" else dir="$lt_sysroot$libdir" absdir="$lt_sysroot$libdir" fi test "X$hardcode_automatic" = Xyes && avoidtemprpath=yes else if test ! -f "$ladir/$objdir/$linklib" && test -f "$abs_ladir/$linklib"; then dir="$ladir" absdir="$abs_ladir" # Remove this search path later func_append notinst_path " $abs_ladir" else dir="$ladir/$objdir" absdir="$abs_ladir/$objdir" # Remove this search path later func_append notinst_path " $abs_ladir" fi fi # $installed = yes func_stripname 'lib' '.la' "$laname" name=$func_stripname_result # This library was specified with -dlpreopen. if test "$pass" = dlpreopen; then if test -z "$libdir" && test "$linkmode" = prog; then func_fatal_error "only libraries may -dlpreopen a convenience library: \`$lib'" fi case "$host" in # special handling for platforms with PE-DLLs. *cygwin* | *mingw* | *cegcc* ) # Linker will automatically link against shared library if both # static and shared are present. Therefore, ensure we extract # symbols from the import library if a shared library is present # (otherwise, the dlopen module name will be incorrect). We do # this by putting the import library name into $newdlprefiles. # We recover the dlopen module name by 'saving' the la file # name in a special purpose variable, and (later) extracting the # dlname from the la file. if test -n "$dlname"; then func_tr_sh "$dir/$linklib" eval "libfile_$func_tr_sh_result=\$abs_ladir/\$laname" func_append newdlprefiles " $dir/$linklib" else func_append newdlprefiles " $dir/$old_library" # Keep a list of preopened convenience libraries to check # that they are being used correctly in the link pass. test -z "$libdir" && \ func_append dlpreconveniencelibs " $dir/$old_library" fi ;; * ) # Prefer using a static library (so that no silly _DYNAMIC symbols # are required to link). if test -n "$old_library"; then func_append newdlprefiles " $dir/$old_library" # Keep a list of preopened convenience libraries to check # that they are being used correctly in the link pass. test -z "$libdir" && \ func_append dlpreconveniencelibs " $dir/$old_library" # Otherwise, use the dlname, so that lt_dlopen finds it. elif test -n "$dlname"; then func_append newdlprefiles " $dir/$dlname" else func_append newdlprefiles " $dir/$linklib" fi ;; esac fi # $pass = dlpreopen if test -z "$libdir"; then # Link the convenience library if test "$linkmode" = lib; then deplibs="$dir/$old_library $deplibs" elif test "$linkmode,$pass" = "prog,link"; then compile_deplibs="$dir/$old_library $compile_deplibs" finalize_deplibs="$dir/$old_library $finalize_deplibs" else deplibs="$lib $deplibs" # used for prog,scan pass fi continue fi if test "$linkmode" = prog && test "$pass" != link; then func_append newlib_search_path " $ladir" deplibs="$lib $deplibs" linkalldeplibs=no if test "$link_all_deplibs" != no || test -z "$library_names" || test "$build_libtool_libs" = no; then linkalldeplibs=yes fi tmp_libs= for deplib in $dependency_libs; do case $deplib in -L*) func_stripname '-L' '' "$deplib" func_resolve_sysroot "$func_stripname_result" func_append newlib_search_path " $func_resolve_sysroot_result" ;; esac # Need to link against all dependency_libs? if test "$linkalldeplibs" = yes; then deplibs="$deplib $deplibs" else # Need to hardcode shared library paths # or/and link against static libraries newdependency_libs="$deplib $newdependency_libs" fi if $opt_preserve_dup_deps ; then case "$tmp_libs " in *" $deplib "*) func_append specialdeplibs " $deplib" ;; esac fi func_append tmp_libs " $deplib" done # for deplib continue fi # $linkmode = prog... if test "$linkmode,$pass" = "prog,link"; then if test -n "$library_names" && { { test "$prefer_static_libs" = no || test "$prefer_static_libs,$installed" = "built,yes"; } || test -z "$old_library"; }; then # We need to hardcode the library path if test -n "$shlibpath_var" && test -z "$avoidtemprpath" ; then # Make sure the rpath contains only unique directories. case "$temp_rpath:" in *"$absdir:"*) ;; *) func_append temp_rpath "$absdir:" ;; esac fi # Hardcode the library path. # Skip directories that are in the system default run-time # search path. case " $sys_lib_dlsearch_path " in *" $absdir "*) ;; *) case "$compile_rpath " in *" $absdir "*) ;; *) func_append compile_rpath " $absdir" ;; esac ;; esac case " $sys_lib_dlsearch_path " in *" $libdir "*) ;; *) case "$finalize_rpath " in *" $libdir "*) ;; *) func_append finalize_rpath " $libdir" ;; esac ;; esac fi # $linkmode,$pass = prog,link... if test "$alldeplibs" = yes && { test "$deplibs_check_method" = pass_all || { test "$build_libtool_libs" = yes && test -n "$library_names"; }; }; then # We only need to search for static libraries continue fi fi link_static=no # Whether the deplib will be linked statically use_static_libs=$prefer_static_libs if test "$use_static_libs" = built && test "$installed" = yes; then use_static_libs=no fi if test -n "$library_names" && { test "$use_static_libs" = no || test -z "$old_library"; }; then case $host in *cygwin* | *mingw* | *cegcc*) # No point in relinking DLLs because paths are not encoded func_append notinst_deplibs " $lib" need_relink=no ;; *) if test "$installed" = no; then func_append notinst_deplibs " $lib" need_relink=yes fi ;; esac # This is a shared library # Warn about portability, can't link against -module's on some # systems (darwin). Don't bleat about dlopened modules though! dlopenmodule="" for dlpremoduletest in $dlprefiles; do if test "X$dlpremoduletest" = "X$lib"; then dlopenmodule="$dlpremoduletest" break fi done if test -z "$dlopenmodule" && test "$shouldnotlink" = yes && test "$pass" = link; then echo if test "$linkmode" = prog; then $ECHO "*** Warning: Linking the executable $output against the loadable module" else $ECHO "*** Warning: Linking the shared library $output against the loadable module" fi $ECHO "*** $linklib is not portable!" fi if test "$linkmode" = lib && test "$hardcode_into_libs" = yes; then # Hardcode the library path. # Skip directories that are in the system default run-time # search path. case " $sys_lib_dlsearch_path " in *" $absdir "*) ;; *) case "$compile_rpath " in *" $absdir "*) ;; *) func_append compile_rpath " $absdir" ;; esac ;; esac case " $sys_lib_dlsearch_path " in *" $libdir "*) ;; *) case "$finalize_rpath " in *" $libdir "*) ;; *) func_append finalize_rpath " $libdir" ;; esac ;; esac fi if test -n "$old_archive_from_expsyms_cmds"; then # figure out the soname set dummy $library_names shift realname="$1" shift libname=`eval "\\$ECHO \"$libname_spec\""` # use dlname if we got it. it's perfectly good, no? if test -n "$dlname"; then soname="$dlname" elif test -n "$soname_spec"; then # bleh windows case $host in *cygwin* | mingw* | *cegcc*) func_arith $current - $age major=$func_arith_result versuffix="-$major" ;; esac eval soname=\"$soname_spec\" else soname="$realname" fi # Make a new name for the extract_expsyms_cmds to use soroot="$soname" func_basename "$soroot" soname="$func_basename_result" func_stripname 'lib' '.dll' "$soname" newlib=libimp-$func_stripname_result.a # If the library has no export list, then create one now if test -f "$output_objdir/$soname-def"; then : else func_verbose "extracting exported symbol list from \`$soname'" func_execute_cmds "$extract_expsyms_cmds" 'exit $?' fi # Create $newlib if test -f "$output_objdir/$newlib"; then :; else func_verbose "generating import library for \`$soname'" func_execute_cmds "$old_archive_from_expsyms_cmds" 'exit $?' fi # make sure the library variables are pointing to the new library dir=$output_objdir linklib=$newlib fi # test -n "$old_archive_from_expsyms_cmds" if test "$linkmode" = prog || test "$opt_mode" != relink; then add_shlibpath= add_dir= add= lib_linked=yes case $hardcode_action in immediate | unsupported) if test "$hardcode_direct" = no; then add="$dir/$linklib" case $host in *-*-sco3.2v5.0.[024]*) add_dir="-L$dir" ;; *-*-sysv4*uw2*) add_dir="-L$dir" ;; *-*-sysv5OpenUNIX* | *-*-sysv5UnixWare7.[01].[10]* | \ *-*-unixware7*) add_dir="-L$dir" ;; *-*-darwin* ) # if the lib is a (non-dlopened) module then we can not # link against it, someone is ignoring the earlier warnings if /usr/bin/file -L $add 2> /dev/null | $GREP ": [^:]* bundle" >/dev/null ; then if test "X$dlopenmodule" != "X$lib"; then $ECHO "*** Warning: lib $linklib is a module, not a shared library" if test -z "$old_library" ; then echo echo "*** And there doesn't seem to be a static archive available" echo "*** The link will probably fail, sorry" else add="$dir/$old_library" fi elif test -n "$old_library"; then add="$dir/$old_library" fi fi esac elif test "$hardcode_minus_L" = no; then case $host in *-*-sunos*) add_shlibpath="$dir" ;; esac add_dir="-L$dir" add="-l$name" elif test "$hardcode_shlibpath_var" = no; then add_shlibpath="$dir" add="-l$name" else lib_linked=no fi ;; relink) if test "$hardcode_direct" = yes && test "$hardcode_direct_absolute" = no; then add="$dir/$linklib" elif test "$hardcode_minus_L" = yes; then add_dir="-L$absdir" # Try looking first in the location we're being installed to. if test -n "$inst_prefix_dir"; then case $libdir in [\\/]*) func_append add_dir " -L$inst_prefix_dir$libdir" ;; esac fi add="-l$name" elif test "$hardcode_shlibpath_var" = yes; then add_shlibpath="$dir" add="-l$name" else lib_linked=no fi ;; *) lib_linked=no ;; esac if test "$lib_linked" != yes; then func_fatal_configuration "unsupported hardcode properties" fi if test -n "$add_shlibpath"; then case :$compile_shlibpath: in *":$add_shlibpath:"*) ;; *) func_append compile_shlibpath "$add_shlibpath:" ;; esac fi if test "$linkmode" = prog; then test -n "$add_dir" && compile_deplibs="$add_dir $compile_deplibs" test -n "$add" && compile_deplibs="$add $compile_deplibs" else test -n "$add_dir" && deplibs="$add_dir $deplibs" test -n "$add" && deplibs="$add $deplibs" if test "$hardcode_direct" != yes && test "$hardcode_minus_L" != yes && test "$hardcode_shlibpath_var" = yes; then case :$finalize_shlibpath: in *":$libdir:"*) ;; *) func_append finalize_shlibpath "$libdir:" ;; esac fi fi fi if test "$linkmode" = prog || test "$opt_mode" = relink; then add_shlibpath= add_dir= add= # Finalize command for both is simple: just hardcode it. if test "$hardcode_direct" = yes && test "$hardcode_direct_absolute" = no; then add="$libdir/$linklib" elif test "$hardcode_minus_L" = yes; then add_dir="-L$libdir" add="-l$name" elif test "$hardcode_shlibpath_var" = yes; then case :$finalize_shlibpath: in *":$libdir:"*) ;; *) func_append finalize_shlibpath "$libdir:" ;; esac add="-l$name" elif test "$hardcode_automatic" = yes; then if test -n "$inst_prefix_dir" && test -f "$inst_prefix_dir$libdir/$linklib" ; then add="$inst_prefix_dir$libdir/$linklib" else add="$libdir/$linklib" fi else # We cannot seem to hardcode it, guess we'll fake it. add_dir="-L$libdir" # Try looking first in the location we're being installed to. if test -n "$inst_prefix_dir"; then case $libdir in [\\/]*) func_append add_dir " -L$inst_prefix_dir$libdir" ;; esac fi add="-l$name" fi if test "$linkmode" = prog; then test -n "$add_dir" && finalize_deplibs="$add_dir $finalize_deplibs" test -n "$add" && finalize_deplibs="$add $finalize_deplibs" else test -n "$add_dir" && deplibs="$add_dir $deplibs" test -n "$add" && deplibs="$add $deplibs" fi fi elif test "$linkmode" = prog; then # Here we assume that one of hardcode_direct or hardcode_minus_L # is not unsupported. This is valid on all known static and # shared platforms. if test "$hardcode_direct" != unsupported; then test -n "$old_library" && linklib="$old_library" compile_deplibs="$dir/$linklib $compile_deplibs" finalize_deplibs="$dir/$linklib $finalize_deplibs" else compile_deplibs="-l$name -L$dir $compile_deplibs" finalize_deplibs="-l$name -L$dir $finalize_deplibs" fi elif test "$build_libtool_libs" = yes; then # Not a shared library if test "$deplibs_check_method" != pass_all; then # We're trying link a shared library against a static one # but the system doesn't support it. # Just print a warning and add the library to dependency_libs so # that the program can be linked against the static library. echo $ECHO "*** Warning: This system can not link to static lib archive $lib." echo "*** I have the capability to make that library automatically link in when" echo "*** you link to this library. But I can only do this if you have a" echo "*** shared version of the library, which you do not appear to have." if test "$module" = yes; then echo "*** But as you try to build a module library, libtool will still create " echo "*** a static module, that should work as long as the dlopening application" echo "*** is linked with the -dlopen flag to resolve symbols at runtime." if test -z "$global_symbol_pipe"; then echo echo "*** However, this would only work if libtool was able to extract symbol" echo "*** lists from a program, using \`nm' or equivalent, but libtool could" echo "*** not find such a program. So, this module is probably useless." echo "*** \`nm' from GNU binutils and a full rebuild may help." fi if test "$build_old_libs" = no; then build_libtool_libs=module build_old_libs=yes else build_libtool_libs=no fi fi else deplibs="$dir/$old_library $deplibs" link_static=yes fi fi # link shared/static library? if test "$linkmode" = lib; then if test -n "$dependency_libs" && { test "$hardcode_into_libs" != yes || test "$build_old_libs" = yes || test "$link_static" = yes; }; then # Extract -R from dependency_libs temp_deplibs= for libdir in $dependency_libs; do case $libdir in -R*) func_stripname '-R' '' "$libdir" temp_xrpath=$func_stripname_result case " $xrpath " in *" $temp_xrpath "*) ;; *) func_append xrpath " $temp_xrpath";; esac;; *) func_append temp_deplibs " $libdir";; esac done dependency_libs="$temp_deplibs" fi func_append newlib_search_path " $absdir" # Link against this library test "$link_static" = no && newdependency_libs="$abs_ladir/$laname $newdependency_libs" # ... and its dependency_libs tmp_libs= for deplib in $dependency_libs; do newdependency_libs="$deplib $newdependency_libs" case $deplib in -L*) func_stripname '-L' '' "$deplib" func_resolve_sysroot "$func_stripname_result";; *) func_resolve_sysroot "$deplib" ;; esac if $opt_preserve_dup_deps ; then case "$tmp_libs " in *" $func_resolve_sysroot_result "*) func_append specialdeplibs " $func_resolve_sysroot_result" ;; esac fi func_append tmp_libs " $func_resolve_sysroot_result" done if test "$link_all_deplibs" != no; then # Add the search paths of all dependency libraries for deplib in $dependency_libs; do path= case $deplib in -L*) path="$deplib" ;; *.la) func_resolve_sysroot "$deplib" deplib=$func_resolve_sysroot_result func_dirname "$deplib" "" "." dir=$func_dirname_result # We need an absolute path. case $dir in [\\/]* | [A-Za-z]:[\\/]*) absdir="$dir" ;; *) absdir=`cd "$dir" && pwd` if test -z "$absdir"; then func_warning "cannot determine absolute directory name of \`$dir'" absdir="$dir" fi ;; esac if $GREP "^installed=no" $deplib > /dev/null; then case $host in *-*-darwin*) depdepl= eval deplibrary_names=`${SED} -n -e 's/^library_names=\(.*\)$/\1/p' $deplib` if test -n "$deplibrary_names" ; then for tmp in $deplibrary_names ; do depdepl=$tmp done if test -f "$absdir/$objdir/$depdepl" ; then depdepl="$absdir/$objdir/$depdepl" darwin_install_name=`${OTOOL} -L $depdepl | awk '{if (NR == 2) {print $1;exit}}'` if test -z "$darwin_install_name"; then darwin_install_name=`${OTOOL64} -L $depdepl | awk '{if (NR == 2) {print $1;exit}}'` fi func_append compiler_flags " ${wl}-dylib_file ${wl}${darwin_install_name}:${depdepl}" func_append linker_flags " -dylib_file ${darwin_install_name}:${depdepl}" path= fi fi ;; *) path="-L$absdir/$objdir" ;; esac else eval libdir=`${SED} -n -e 's/^libdir=\(.*\)$/\1/p' $deplib` test -z "$libdir" && \ func_fatal_error "\`$deplib' is not a valid libtool archive" test "$absdir" != "$libdir" && \ func_warning "\`$deplib' seems to be moved" path="-L$absdir" fi ;; esac case " $deplibs " in *" $path "*) ;; *) deplibs="$path $deplibs" ;; esac done fi # link_all_deplibs != no fi # linkmode = lib done # for deplib in $libs if test "$pass" = link; then if test "$linkmode" = "prog"; then compile_deplibs="$new_inherited_linker_flags $compile_deplibs" finalize_deplibs="$new_inherited_linker_flags $finalize_deplibs" else compiler_flags="$compiler_flags "`$ECHO " $new_inherited_linker_flags" | $SED 's% \([^ $]*\).ltframework% -framework \1%g'` fi fi dependency_libs="$newdependency_libs" if test "$pass" = dlpreopen; then # Link the dlpreopened libraries before other libraries for deplib in $save_deplibs; do deplibs="$deplib $deplibs" done fi if test "$pass" != dlopen; then if test "$pass" != conv; then # Make sure lib_search_path contains only unique directories. lib_search_path= for dir in $newlib_search_path; do case "$lib_search_path " in *" $dir "*) ;; *) func_append lib_search_path " $dir" ;; esac done newlib_search_path= fi if test "$linkmode,$pass" != "prog,link"; then vars="deplibs" else vars="compile_deplibs finalize_deplibs" fi for var in $vars dependency_libs; do # Add libraries to $var in reverse order eval tmp_libs=\"\$$var\" new_libs= for deplib in $tmp_libs; do # FIXME: Pedantically, this is the right thing to do, so # that some nasty dependency loop isn't accidentally # broken: #new_libs="$deplib $new_libs" # Pragmatically, this seems to cause very few problems in # practice: case $deplib in -L*) new_libs="$deplib $new_libs" ;; -R*) ;; *) # And here is the reason: when a library appears more # than once as an explicit dependence of a library, or # is implicitly linked in more than once by the # compiler, it is considered special, and multiple # occurrences thereof are not removed. Compare this # with having the same library being listed as a # dependency of multiple other libraries: in this case, # we know (pedantically, we assume) the library does not # need to be listed more than once, so we keep only the # last copy. This is not always right, but it is rare # enough that we require users that really mean to play # such unportable linking tricks to link the library # using -Wl,-lname, so that libtool does not consider it # for duplicate removal. case " $specialdeplibs " in *" $deplib "*) new_libs="$deplib $new_libs" ;; *) case " $new_libs " in *" $deplib "*) ;; *) new_libs="$deplib $new_libs" ;; esac ;; esac ;; esac done tmp_libs= for deplib in $new_libs; do case $deplib in -L*) case " $tmp_libs " in *" $deplib "*) ;; *) func_append tmp_libs " $deplib" ;; esac ;; *) func_append tmp_libs " $deplib" ;; esac done eval $var=\"$tmp_libs\" done # for var fi # Last step: remove runtime libs from dependency_libs # (they stay in deplibs) tmp_libs= for i in $dependency_libs ; do case " $predeps $postdeps $compiler_lib_search_path " in *" $i "*) i="" ;; esac if test -n "$i" ; then func_append tmp_libs " $i" fi done dependency_libs=$tmp_libs done # for pass if test "$linkmode" = prog; then dlfiles="$newdlfiles" fi if test "$linkmode" = prog || test "$linkmode" = lib; then dlprefiles="$newdlprefiles" fi case $linkmode in oldlib) if test -n "$dlfiles$dlprefiles" || test "$dlself" != no; then func_warning "\`-dlopen' is ignored for archives" fi case " $deplibs" in *\ -l* | *\ -L*) func_warning "\`-l' and \`-L' are ignored for archives" ;; esac test -n "$rpath" && \ func_warning "\`-rpath' is ignored for archives" test -n "$xrpath" && \ func_warning "\`-R' is ignored for archives" test -n "$vinfo" && \ func_warning "\`-version-info/-version-number' is ignored for archives" test -n "$release" && \ func_warning "\`-release' is ignored for archives" test -n "$export_symbols$export_symbols_regex" && \ func_warning "\`-export-symbols' is ignored for archives" # Now set the variables for building old libraries. build_libtool_libs=no oldlibs="$output" func_append objs "$old_deplibs" ;; lib) # Make sure we only generate libraries of the form `libNAME.la'. case $outputname in lib*) func_stripname 'lib' '.la' "$outputname" name=$func_stripname_result eval shared_ext=\"$shrext_cmds\" eval libname=\"$libname_spec\" ;; *) test "$module" = no && \ func_fatal_help "libtool library \`$output' must begin with \`lib'" if test "$need_lib_prefix" != no; then # Add the "lib" prefix for modules if required func_stripname '' '.la' "$outputname" name=$func_stripname_result eval shared_ext=\"$shrext_cmds\" eval libname=\"$libname_spec\" else func_stripname '' '.la' "$outputname" libname=$func_stripname_result fi ;; esac if test -n "$objs"; then if test "$deplibs_check_method" != pass_all; then func_fatal_error "cannot build libtool library \`$output' from non-libtool objects on this host:$objs" else echo $ECHO "*** Warning: Linking the shared library $output against the non-libtool" $ECHO "*** objects $objs is not portable!" func_append libobjs " $objs" fi fi test "$dlself" != no && \ func_warning "\`-dlopen self' is ignored for libtool libraries" set dummy $rpath shift test "$#" -gt 1 && \ func_warning "ignoring multiple \`-rpath's for a libtool library" install_libdir="$1" oldlibs= if test -z "$rpath"; then if test "$build_libtool_libs" = yes; then # Building a libtool convenience library. # Some compilers have problems with a `.al' extension so # convenience libraries should have the same extension an # archive normally would. oldlibs="$output_objdir/$libname.$libext $oldlibs" build_libtool_libs=convenience build_old_libs=yes fi test -n "$vinfo" && \ func_warning "\`-version-info/-version-number' is ignored for convenience libraries" test -n "$release" && \ func_warning "\`-release' is ignored for convenience libraries" else # Parse the version information argument. save_ifs="$IFS"; IFS=':' set dummy $vinfo 0 0 0 shift IFS="$save_ifs" test -n "$7" && \ func_fatal_help "too many parameters to \`-version-info'" # convert absolute version numbers to libtool ages # this retains compatibility with .la files and attempts # to make the code below a bit more comprehensible case $vinfo_number in yes) number_major="$1" number_minor="$2" number_revision="$3" # # There are really only two kinds -- those that # use the current revision as the major version # and those that subtract age and use age as # a minor version. But, then there is irix # which has an extra 1 added just for fun # case $version_type in # correct linux to gnu/linux during the next big refactor darwin|linux|osf|windows|none) func_arith $number_major + $number_minor current=$func_arith_result age="$number_minor" revision="$number_revision" ;; freebsd-aout|freebsd-elf|qnx|sunos) current="$number_major" revision="$number_minor" age="0" ;; irix|nonstopux) func_arith $number_major + $number_minor current=$func_arith_result age="$number_minor" revision="$number_minor" lt_irix_increment=no ;; esac ;; no) current="$1" revision="$2" age="$3" ;; esac # Check that each of the things are valid numbers. case $current in 0|[1-9]|[1-9][0-9]|[1-9][0-9][0-9]|[1-9][0-9][0-9][0-9]|[1-9][0-9][0-9][0-9][0-9]) ;; *) func_error "CURRENT \`$current' must be a nonnegative integer" func_fatal_error "\`$vinfo' is not valid version information" ;; esac case $revision in 0|[1-9]|[1-9][0-9]|[1-9][0-9][0-9]|[1-9][0-9][0-9][0-9]|[1-9][0-9][0-9][0-9][0-9]) ;; *) func_error "REVISION \`$revision' must be a nonnegative integer" func_fatal_error "\`$vinfo' is not valid version information" ;; esac case $age in 0|[1-9]|[1-9][0-9]|[1-9][0-9][0-9]|[1-9][0-9][0-9][0-9]|[1-9][0-9][0-9][0-9][0-9]) ;; *) func_error "AGE \`$age' must be a nonnegative integer" func_fatal_error "\`$vinfo' is not valid version information" ;; esac if test "$age" -gt "$current"; then func_error "AGE \`$age' is greater than the current interface number \`$current'" func_fatal_error "\`$vinfo' is not valid version information" fi # Calculate the version variables. major= versuffix= verstring= case $version_type in none) ;; darwin) # Like Linux, but with the current version available in # verstring for coding it into the library header func_arith $current - $age major=.$func_arith_result versuffix="$major.$age.$revision" # Darwin ld doesn't like 0 for these options... func_arith $current + 1 minor_current=$func_arith_result xlcverstring="${wl}-compatibility_version ${wl}$minor_current ${wl}-current_version ${wl}$minor_current.$revision" verstring="-compatibility_version $minor_current -current_version $minor_current.$revision" ;; freebsd-aout) major=".$current" versuffix=".$current.$revision"; ;; freebsd-elf) major=".$current" versuffix=".$current" ;; irix | nonstopux) if test "X$lt_irix_increment" = "Xno"; then func_arith $current - $age else func_arith $current - $age + 1 fi major=$func_arith_result case $version_type in nonstopux) verstring_prefix=nonstopux ;; *) verstring_prefix=sgi ;; esac verstring="$verstring_prefix$major.$revision" # Add in all the interfaces that we are compatible with. loop=$revision while test "$loop" -ne 0; do func_arith $revision - $loop iface=$func_arith_result func_arith $loop - 1 loop=$func_arith_result verstring="$verstring_prefix$major.$iface:$verstring" done # Before this point, $major must not contain `.'. major=.$major versuffix="$major.$revision" ;; linux) # correct to gnu/linux during the next big refactor func_arith $current - $age major=.$func_arith_result versuffix="$major.$age.$revision" ;; osf) func_arith $current - $age major=.$func_arith_result versuffix=".$current.$age.$revision" verstring="$current.$age.$revision" # Add in all the interfaces that we are compatible with. loop=$age while test "$loop" -ne 0; do func_arith $current - $loop iface=$func_arith_result func_arith $loop - 1 loop=$func_arith_result verstring="$verstring:${iface}.0" done # Make executables depend on our current version. func_append verstring ":${current}.0" ;; qnx) major=".$current" versuffix=".$current" ;; sunos) major=".$current" versuffix=".$current.$revision" ;; windows) # Use '-' rather than '.', since we only want one # extension on DOS 8.3 filesystems. func_arith $current - $age major=$func_arith_result versuffix="-$major" ;; *) func_fatal_configuration "unknown library version type \`$version_type'" ;; esac # Clear the version info if we defaulted, and they specified a release. if test -z "$vinfo" && test -n "$release"; then major= case $version_type in darwin) # we can't check for "0.0" in archive_cmds due to quoting # problems, so we reset it completely verstring= ;; *) verstring="0.0" ;; esac if test "$need_version" = no; then versuffix= else versuffix=".0.0" fi fi # Remove version info from name if versioning should be avoided if test "$avoid_version" = yes && test "$need_version" = no; then major= versuffix= verstring="" fi # Check to see if the archive will have undefined symbols. if test "$allow_undefined" = yes; then if test "$allow_undefined_flag" = unsupported; then func_warning "undefined symbols not allowed in $host shared libraries" build_libtool_libs=no build_old_libs=yes fi else # Don't allow undefined symbols. allow_undefined_flag="$no_undefined_flag" fi fi func_generate_dlsyms "$libname" "$libname" "yes" func_append libobjs " $symfileobj" test "X$libobjs" = "X " && libobjs= if test "$opt_mode" != relink; then # Remove our outputs, but don't remove object files since they # may have been created when compiling PIC objects. removelist= tempremovelist=`$ECHO "$output_objdir/*"` for p in $tempremovelist; do case $p in *.$objext | *.gcno) ;; $output_objdir/$outputname | $output_objdir/$libname.* | $output_objdir/${libname}${release}.*) if test "X$precious_files_regex" != "X"; then if $ECHO "$p" | $EGREP -e "$precious_files_regex" >/dev/null 2>&1 then continue fi fi func_append removelist " $p" ;; *) ;; esac done test -n "$removelist" && \ func_show_eval "${RM}r \$removelist" fi # Now set the variables for building old libraries. if test "$build_old_libs" = yes && test "$build_libtool_libs" != convenience ; then func_append oldlibs " $output_objdir/$libname.$libext" # Transform .lo files to .o files. oldobjs="$objs "`$ECHO "$libobjs" | $SP2NL | $SED "/\.${libext}$/d; $lo2o" | $NL2SP` fi # Eliminate all temporary directories. #for path in $notinst_path; do # lib_search_path=`$ECHO "$lib_search_path " | $SED "s% $path % %g"` # deplibs=`$ECHO "$deplibs " | $SED "s% -L$path % %g"` # dependency_libs=`$ECHO "$dependency_libs " | $SED "s% -L$path % %g"` #done if test -n "$xrpath"; then # If the user specified any rpath flags, then add them. temp_xrpath= for libdir in $xrpath; do func_replace_sysroot "$libdir" func_append temp_xrpath " -R$func_replace_sysroot_result" case "$finalize_rpath " in *" $libdir "*) ;; *) func_append finalize_rpath " $libdir" ;; esac done if test "$hardcode_into_libs" != yes || test "$build_old_libs" = yes; then dependency_libs="$temp_xrpath $dependency_libs" fi fi # Make sure dlfiles contains only unique files that won't be dlpreopened old_dlfiles="$dlfiles" dlfiles= for lib in $old_dlfiles; do case " $dlprefiles $dlfiles " in *" $lib "*) ;; *) func_append dlfiles " $lib" ;; esac done # Make sure dlprefiles contains only unique files old_dlprefiles="$dlprefiles" dlprefiles= for lib in $old_dlprefiles; do case "$dlprefiles " in *" $lib "*) ;; *) func_append dlprefiles " $lib" ;; esac done if test "$build_libtool_libs" = yes; then if test -n "$rpath"; then case $host in *-*-cygwin* | *-*-mingw* | *-*-pw32* | *-*-os2* | *-*-beos* | *-cegcc* | *-*-haiku*) # these systems don't actually have a c library (as such)! ;; *-*-rhapsody* | *-*-darwin1.[012]) # Rhapsody C library is in the System framework func_append deplibs " System.ltframework" ;; *-*-netbsd*) # Don't link with libc until the a.out ld.so is fixed. ;; *-*-openbsd* | *-*-freebsd* | *-*-dragonfly*) # Do not include libc due to us having libc/libc_r. ;; *-*-sco3.2v5* | *-*-sco5v6*) # Causes problems with __ctype ;; *-*-sysv4.2uw2* | *-*-sysv5* | *-*-unixware* | *-*-OpenUNIX*) # Compiler inserts libc in the correct place for threads to work ;; *) # Add libc to deplibs on all other systems if necessary. if test "$build_libtool_need_lc" = "yes"; then func_append deplibs " -lc" fi ;; esac fi # Transform deplibs into only deplibs that can be linked in shared. name_save=$name libname_save=$libname release_save=$release versuffix_save=$versuffix major_save=$major # I'm not sure if I'm treating the release correctly. I think # release should show up in the -l (ie -lgmp5) so we don't want to # add it in twice. Is that correct? release="" versuffix="" major="" newdeplibs= droppeddeps=no case $deplibs_check_method in pass_all) # Don't check for shared/static. Everything works. # This might be a little naive. We might want to check # whether the library exists or not. But this is on # osf3 & osf4 and I'm not really sure... Just # implementing what was already the behavior. newdeplibs=$deplibs ;; test_compile) # This code stresses the "libraries are programs" paradigm to its # limits. Maybe even breaks it. We compile a program, linking it # against the deplibs as a proxy for the library. Then we can check # whether they linked in statically or dynamically with ldd. $opt_dry_run || $RM conftest.c cat > conftest.c </dev/null` $nocaseglob else potential_libs=`ls $i/$libnameglob[.-]* 2>/dev/null` fi for potent_lib in $potential_libs; do # Follow soft links. if ls -lLd "$potent_lib" 2>/dev/null | $GREP " -> " >/dev/null; then continue fi # The statement above tries to avoid entering an # endless loop below, in case of cyclic links. # We might still enter an endless loop, since a link # loop can be closed while we follow links, # but so what? potlib="$potent_lib" while test -h "$potlib" 2>/dev/null; do potliblink=`ls -ld $potlib | ${SED} 's/.* -> //'` case $potliblink in [\\/]* | [A-Za-z]:[\\/]*) potlib="$potliblink";; *) potlib=`$ECHO "$potlib" | $SED 's,[^/]*$,,'`"$potliblink";; esac done if eval $file_magic_cmd \"\$potlib\" 2>/dev/null | $SED -e 10q | $EGREP "$file_magic_regex" > /dev/null; then func_append newdeplibs " $a_deplib" a_deplib="" break 2 fi done done fi if test -n "$a_deplib" ; then droppeddeps=yes echo $ECHO "*** Warning: linker path does not have real file for library $a_deplib." echo "*** I have the capability to make that library automatically link in when" echo "*** you link to this library. But I can only do this if you have a" echo "*** shared version of the library, which you do not appear to have" echo "*** because I did check the linker path looking for a file starting" if test -z "$potlib" ; then $ECHO "*** with $libname but no candidates were found. (...for file magic test)" else $ECHO "*** with $libname and none of the candidates passed a file format test" $ECHO "*** using a file magic. Last file checked: $potlib" fi fi ;; *) # Add a -L argument. func_append newdeplibs " $a_deplib" ;; esac done # Gone through all deplibs. ;; match_pattern*) set dummy $deplibs_check_method; shift match_pattern_regex=`expr "$deplibs_check_method" : "$1 \(.*\)"` for a_deplib in $deplibs; do case $a_deplib in -l*) func_stripname -l '' "$a_deplib" name=$func_stripname_result if test "X$allow_libtool_libs_with_static_runtimes" = "Xyes" ; then case " $predeps $postdeps " in *" $a_deplib "*) func_append newdeplibs " $a_deplib" a_deplib="" ;; esac fi if test -n "$a_deplib" ; then libname=`eval "\\$ECHO \"$libname_spec\""` for i in $lib_search_path $sys_lib_search_path $shlib_search_path; do potential_libs=`ls $i/$libname[.-]* 2>/dev/null` for potent_lib in $potential_libs; do potlib="$potent_lib" # see symlink-check above in file_magic test if eval "\$ECHO \"$potent_lib\"" 2>/dev/null | $SED 10q | \ $EGREP "$match_pattern_regex" > /dev/null; then func_append newdeplibs " $a_deplib" a_deplib="" break 2 fi done done fi if test -n "$a_deplib" ; then droppeddeps=yes echo $ECHO "*** Warning: linker path does not have real file for library $a_deplib." echo "*** I have the capability to make that library automatically link in when" echo "*** you link to this library. But I can only do this if you have a" echo "*** shared version of the library, which you do not appear to have" echo "*** because I did check the linker path looking for a file starting" if test -z "$potlib" ; then $ECHO "*** with $libname but no candidates were found. (...for regex pattern test)" else $ECHO "*** with $libname and none of the candidates passed a file format test" $ECHO "*** using a regex pattern. Last file checked: $potlib" fi fi ;; *) # Add a -L argument. func_append newdeplibs " $a_deplib" ;; esac done # Gone through all deplibs. ;; none | unknown | *) newdeplibs="" tmp_deplibs=`$ECHO " $deplibs" | $SED 's/ -lc$//; s/ -[LR][^ ]*//g'` if test "X$allow_libtool_libs_with_static_runtimes" = "Xyes" ; then for i in $predeps $postdeps ; do # can't use Xsed below, because $i might contain '/' tmp_deplibs=`$ECHO " $tmp_deplibs" | $SED "s,$i,,"` done fi case $tmp_deplibs in *[!\ \ ]*) echo if test "X$deplibs_check_method" = "Xnone"; then echo "*** Warning: inter-library dependencies are not supported in this platform." else echo "*** Warning: inter-library dependencies are not known to be supported." fi echo "*** All declared inter-library dependencies are being dropped." droppeddeps=yes ;; esac ;; esac versuffix=$versuffix_save major=$major_save release=$release_save libname=$libname_save name=$name_save case $host in *-*-rhapsody* | *-*-darwin1.[012]) # On Rhapsody replace the C library with the System framework newdeplibs=`$ECHO " $newdeplibs" | $SED 's/ -lc / System.ltframework /'` ;; esac if test "$droppeddeps" = yes; then if test "$module" = yes; then echo echo "*** Warning: libtool could not satisfy all declared inter-library" $ECHO "*** dependencies of module $libname. Therefore, libtool will create" echo "*** a static module, that should work as long as the dlopening" echo "*** application is linked with the -dlopen flag." if test -z "$global_symbol_pipe"; then echo echo "*** However, this would only work if libtool was able to extract symbol" echo "*** lists from a program, using \`nm' or equivalent, but libtool could" echo "*** not find such a program. So, this module is probably useless." echo "*** \`nm' from GNU binutils and a full rebuild may help." fi if test "$build_old_libs" = no; then oldlibs="$output_objdir/$libname.$libext" build_libtool_libs=module build_old_libs=yes else build_libtool_libs=no fi else echo "*** The inter-library dependencies that have been dropped here will be" echo "*** automatically added whenever a program is linked with this library" echo "*** or is declared to -dlopen it." if test "$allow_undefined" = no; then echo echo "*** Since this library must not contain undefined symbols," echo "*** because either the platform does not support them or" echo "*** it was explicitly requested with -no-undefined," echo "*** libtool will only create a static version of it." if test "$build_old_libs" = no; then oldlibs="$output_objdir/$libname.$libext" build_libtool_libs=module build_old_libs=yes else build_libtool_libs=no fi fi fi fi # Done checking deplibs! deplibs=$newdeplibs fi # Time to change all our "foo.ltframework" stuff back to "-framework foo" case $host in *-*-darwin*) newdeplibs=`$ECHO " $newdeplibs" | $SED 's% \([^ $]*\).ltframework% -framework \1%g'` new_inherited_linker_flags=`$ECHO " $new_inherited_linker_flags" | $SED 's% \([^ $]*\).ltframework% -framework \1%g'` deplibs=`$ECHO " $deplibs" | $SED 's% \([^ $]*\).ltframework% -framework \1%g'` ;; esac # move library search paths that coincide with paths to not yet # installed libraries to the beginning of the library search list new_libs= for path in $notinst_path; do case " $new_libs " in *" -L$path/$objdir "*) ;; *) case " $deplibs " in *" -L$path/$objdir "*) func_append new_libs " -L$path/$objdir" ;; esac ;; esac done for deplib in $deplibs; do case $deplib in -L*) case " $new_libs " in *" $deplib "*) ;; *) func_append new_libs " $deplib" ;; esac ;; *) func_append new_libs " $deplib" ;; esac done deplibs="$new_libs" # All the library-specific variables (install_libdir is set above). library_names= old_library= dlname= # Test again, we may have decided not to build it any more if test "$build_libtool_libs" = yes; then # Remove ${wl} instances when linking with ld. # FIXME: should test the right _cmds variable. case $archive_cmds in *\$LD\ *) wl= ;; esac if test "$hardcode_into_libs" = yes; then # Hardcode the library paths hardcode_libdirs= dep_rpath= rpath="$finalize_rpath" test "$opt_mode" != relink && rpath="$compile_rpath$rpath" for libdir in $rpath; do if test -n "$hardcode_libdir_flag_spec"; then if test -n "$hardcode_libdir_separator"; then func_replace_sysroot "$libdir" libdir=$func_replace_sysroot_result if test -z "$hardcode_libdirs"; then hardcode_libdirs="$libdir" else # Just accumulate the unique libdirs. case $hardcode_libdir_separator$hardcode_libdirs$hardcode_libdir_separator in *"$hardcode_libdir_separator$libdir$hardcode_libdir_separator"*) ;; *) func_append hardcode_libdirs "$hardcode_libdir_separator$libdir" ;; esac fi else eval flag=\"$hardcode_libdir_flag_spec\" func_append dep_rpath " $flag" fi elif test -n "$runpath_var"; then case "$perm_rpath " in *" $libdir "*) ;; *) func_append perm_rpath " $libdir" ;; esac fi done # Substitute the hardcoded libdirs into the rpath. if test -n "$hardcode_libdir_separator" && test -n "$hardcode_libdirs"; then libdir="$hardcode_libdirs" eval "dep_rpath=\"$hardcode_libdir_flag_spec\"" fi if test -n "$runpath_var" && test -n "$perm_rpath"; then # We should set the runpath_var. rpath= for dir in $perm_rpath; do func_append rpath "$dir:" done eval "$runpath_var='$rpath\$$runpath_var'; export $runpath_var" fi test -n "$dep_rpath" && deplibs="$dep_rpath $deplibs" fi shlibpath="$finalize_shlibpath" test "$opt_mode" != relink && shlibpath="$compile_shlibpath$shlibpath" if test -n "$shlibpath"; then eval "$shlibpath_var='$shlibpath\$$shlibpath_var'; export $shlibpath_var" fi # Get the real and link names of the library. eval shared_ext=\"$shrext_cmds\" eval library_names=\"$library_names_spec\" set dummy $library_names shift realname="$1" shift if test -n "$soname_spec"; then eval soname=\"$soname_spec\" else soname="$realname" fi if test -z "$dlname"; then dlname=$soname fi lib="$output_objdir/$realname" linknames= for link do func_append linknames " $link" done # Use standard objects if they are pic test -z "$pic_flag" && libobjs=`$ECHO "$libobjs" | $SP2NL | $SED "$lo2o" | $NL2SP` test "X$libobjs" = "X " && libobjs= delfiles= if test -n "$export_symbols" && test -n "$include_expsyms"; then $opt_dry_run || cp "$export_symbols" "$output_objdir/$libname.uexp" export_symbols="$output_objdir/$libname.uexp" func_append delfiles " $export_symbols" fi orig_export_symbols= case $host_os in cygwin* | mingw* | cegcc*) if test -n "$export_symbols" && test -z "$export_symbols_regex"; then # exporting using user supplied symfile if test "x`$SED 1q $export_symbols`" != xEXPORTS; then # and it's NOT already a .def file. Must figure out # which of the given symbols are data symbols and tag # them as such. So, trigger use of export_symbols_cmds. # export_symbols gets reassigned inside the "prepare # the list of exported symbols" if statement, so the # include_expsyms logic still works. orig_export_symbols="$export_symbols" export_symbols= always_export_symbols=yes fi fi ;; esac # Prepare the list of exported symbols if test -z "$export_symbols"; then if test "$always_export_symbols" = yes || test -n "$export_symbols_regex"; then func_verbose "generating symbol list for \`$libname.la'" export_symbols="$output_objdir/$libname.exp" $opt_dry_run || $RM $export_symbols cmds=$export_symbols_cmds save_ifs="$IFS"; IFS='~' for cmd1 in $cmds; do IFS="$save_ifs" # Take the normal branch if the nm_file_list_spec branch # doesn't work or if tool conversion is not needed. case $nm_file_list_spec~$to_tool_file_cmd in *~func_convert_file_noop | *~func_convert_file_msys_to_w32 | ~*) try_normal_branch=yes eval cmd=\"$cmd1\" func_len " $cmd" len=$func_len_result ;; *) try_normal_branch=no ;; esac if test "$try_normal_branch" = yes \ && { test "$len" -lt "$max_cmd_len" \ || test "$max_cmd_len" -le -1; } then func_show_eval "$cmd" 'exit $?' skipped_export=false elif test -n "$nm_file_list_spec"; then func_basename "$output" output_la=$func_basename_result save_libobjs=$libobjs save_output=$output output=${output_objdir}/${output_la}.nm func_to_tool_file "$output" libobjs=$nm_file_list_spec$func_to_tool_file_result func_append delfiles " $output" func_verbose "creating $NM input file list: $output" for obj in $save_libobjs; do func_to_tool_file "$obj" $ECHO "$func_to_tool_file_result" done > "$output" eval cmd=\"$cmd1\" func_show_eval "$cmd" 'exit $?' output=$save_output libobjs=$save_libobjs skipped_export=false else # The command line is too long to execute in one step. func_verbose "using reloadable object file for export list..." skipped_export=: # Break out early, otherwise skipped_export may be # set to false by a later but shorter cmd. break fi done IFS="$save_ifs" if test -n "$export_symbols_regex" && test "X$skipped_export" != "X:"; then func_show_eval '$EGREP -e "$export_symbols_regex" "$export_symbols" > "${export_symbols}T"' func_show_eval '$MV "${export_symbols}T" "$export_symbols"' fi fi fi if test -n "$export_symbols" && test -n "$include_expsyms"; then tmp_export_symbols="$export_symbols" test -n "$orig_export_symbols" && tmp_export_symbols="$orig_export_symbols" $opt_dry_run || eval '$ECHO "$include_expsyms" | $SP2NL >> "$tmp_export_symbols"' fi if test "X$skipped_export" != "X:" && test -n "$orig_export_symbols"; then # The given exports_symbols file has to be filtered, so filter it. func_verbose "filter symbol list for \`$libname.la' to tag DATA exports" # FIXME: $output_objdir/$libname.filter potentially contains lots of # 's' commands which not all seds can handle. GNU sed should be fine # though. Also, the filter scales superlinearly with the number of # global variables. join(1) would be nice here, but unfortunately # isn't a blessed tool. $opt_dry_run || $SED -e '/[ ,]DATA/!d;s,\(.*\)\([ \,].*\),s|^\1$|\1\2|,' < $export_symbols > $output_objdir/$libname.filter func_append delfiles " $export_symbols $output_objdir/$libname.filter" export_symbols=$output_objdir/$libname.def $opt_dry_run || $SED -f $output_objdir/$libname.filter < $orig_export_symbols > $export_symbols fi tmp_deplibs= for test_deplib in $deplibs; do case " $convenience " in *" $test_deplib "*) ;; *) func_append tmp_deplibs " $test_deplib" ;; esac done deplibs="$tmp_deplibs" if test -n "$convenience"; then if test -n "$whole_archive_flag_spec" && test "$compiler_needs_object" = yes && test -z "$libobjs"; then # extract the archives, so we have objects to list. # TODO: could optimize this to just extract one archive. whole_archive_flag_spec= fi if test -n "$whole_archive_flag_spec"; then save_libobjs=$libobjs eval libobjs=\"\$libobjs $whole_archive_flag_spec\" test "X$libobjs" = "X " && libobjs= else gentop="$output_objdir/${outputname}x" func_append generated " $gentop" func_extract_archives $gentop $convenience func_append libobjs " $func_extract_archives_result" test "X$libobjs" = "X " && libobjs= fi fi if test "$thread_safe" = yes && test -n "$thread_safe_flag_spec"; then eval flag=\"$thread_safe_flag_spec\" func_append linker_flags " $flag" fi # Make a backup of the uninstalled library when relinking if test "$opt_mode" = relink; then $opt_dry_run || eval '(cd $output_objdir && $RM ${realname}U && $MV $realname ${realname}U)' || exit $? fi # Do each of the archive commands. if test "$module" = yes && test -n "$module_cmds" ; then if test -n "$export_symbols" && test -n "$module_expsym_cmds"; then eval test_cmds=\"$module_expsym_cmds\" cmds=$module_expsym_cmds else eval test_cmds=\"$module_cmds\" cmds=$module_cmds fi else if test -n "$export_symbols" && test -n "$archive_expsym_cmds"; then eval test_cmds=\"$archive_expsym_cmds\" cmds=$archive_expsym_cmds else eval test_cmds=\"$archive_cmds\" cmds=$archive_cmds fi fi if test "X$skipped_export" != "X:" && func_len " $test_cmds" && len=$func_len_result && test "$len" -lt "$max_cmd_len" || test "$max_cmd_len" -le -1; then : else # The command line is too long to link in one step, link piecewise # or, if using GNU ld and skipped_export is not :, use a linker # script. # Save the value of $output and $libobjs because we want to # use them later. If we have whole_archive_flag_spec, we # want to use save_libobjs as it was before # whole_archive_flag_spec was expanded, because we can't # assume the linker understands whole_archive_flag_spec. # This may have to be revisited, in case too many # convenience libraries get linked in and end up exceeding # the spec. if test -z "$convenience" || test -z "$whole_archive_flag_spec"; then save_libobjs=$libobjs fi save_output=$output func_basename "$output" output_la=$func_basename_result # Clear the reloadable object creation command queue and # initialize k to one. test_cmds= concat_cmds= objlist= last_robj= k=1 if test -n "$save_libobjs" && test "X$skipped_export" != "X:" && test "$with_gnu_ld" = yes; then output=${output_objdir}/${output_la}.lnkscript func_verbose "creating GNU ld script: $output" echo 'INPUT (' > $output for obj in $save_libobjs do func_to_tool_file "$obj" $ECHO "$func_to_tool_file_result" >> $output done echo ')' >> $output func_append delfiles " $output" func_to_tool_file "$output" output=$func_to_tool_file_result elif test -n "$save_libobjs" && test "X$skipped_export" != "X:" && test "X$file_list_spec" != X; then output=${output_objdir}/${output_la}.lnk func_verbose "creating linker input file list: $output" : > $output set x $save_libobjs shift firstobj= if test "$compiler_needs_object" = yes; then firstobj="$1 " shift fi for obj do func_to_tool_file "$obj" $ECHO "$func_to_tool_file_result" >> $output done func_append delfiles " $output" func_to_tool_file "$output" output=$firstobj\"$file_list_spec$func_to_tool_file_result\" else if test -n "$save_libobjs"; then func_verbose "creating reloadable object files..." output=$output_objdir/$output_la-${k}.$objext eval test_cmds=\"$reload_cmds\" func_len " $test_cmds" len0=$func_len_result len=$len0 # Loop over the list of objects to be linked. for obj in $save_libobjs do func_len " $obj" func_arith $len + $func_len_result len=$func_arith_result if test "X$objlist" = X || test "$len" -lt "$max_cmd_len"; then func_append objlist " $obj" else # The command $test_cmds is almost too long, add a # command to the queue. if test "$k" -eq 1 ; then # The first file doesn't have a previous command to add. reload_objs=$objlist eval concat_cmds=\"$reload_cmds\" else # All subsequent reloadable object files will link in # the last one created. reload_objs="$objlist $last_robj" eval concat_cmds=\"\$concat_cmds~$reload_cmds~\$RM $last_robj\" fi last_robj=$output_objdir/$output_la-${k}.$objext func_arith $k + 1 k=$func_arith_result output=$output_objdir/$output_la-${k}.$objext objlist=" $obj" func_len " $last_robj" func_arith $len0 + $func_len_result len=$func_arith_result fi done # Handle the remaining objects by creating one last # reloadable object file. All subsequent reloadable object # files will link in the last one created. test -z "$concat_cmds" || concat_cmds=$concat_cmds~ reload_objs="$objlist $last_robj" eval concat_cmds=\"\${concat_cmds}$reload_cmds\" if test -n "$last_robj"; then eval concat_cmds=\"\${concat_cmds}~\$RM $last_robj\" fi func_append delfiles " $output" else output= fi if ${skipped_export-false}; then func_verbose "generating symbol list for \`$libname.la'" export_symbols="$output_objdir/$libname.exp" $opt_dry_run || $RM $export_symbols libobjs=$output # Append the command to create the export file. test -z "$concat_cmds" || concat_cmds=$concat_cmds~ eval concat_cmds=\"\$concat_cmds$export_symbols_cmds\" if test -n "$last_robj"; then eval concat_cmds=\"\$concat_cmds~\$RM $last_robj\" fi fi test -n "$save_libobjs" && func_verbose "creating a temporary reloadable object file: $output" # Loop through the commands generated above and execute them. save_ifs="$IFS"; IFS='~' for cmd in $concat_cmds; do IFS="$save_ifs" $opt_silent || { func_quote_for_expand "$cmd" eval "func_echo $func_quote_for_expand_result" } $opt_dry_run || eval "$cmd" || { lt_exit=$? # Restore the uninstalled library and exit if test "$opt_mode" = relink; then ( cd "$output_objdir" && \ $RM "${realname}T" && \ $MV "${realname}U" "$realname" ) fi exit $lt_exit } done IFS="$save_ifs" if test -n "$export_symbols_regex" && ${skipped_export-false}; then func_show_eval '$EGREP -e "$export_symbols_regex" "$export_symbols" > "${export_symbols}T"' func_show_eval '$MV "${export_symbols}T" "$export_symbols"' fi fi if ${skipped_export-false}; then if test -n "$export_symbols" && test -n "$include_expsyms"; then tmp_export_symbols="$export_symbols" test -n "$orig_export_symbols" && tmp_export_symbols="$orig_export_symbols" $opt_dry_run || eval '$ECHO "$include_expsyms" | $SP2NL >> "$tmp_export_symbols"' fi if test -n "$orig_export_symbols"; then # The given exports_symbols file has to be filtered, so filter it. func_verbose "filter symbol list for \`$libname.la' to tag DATA exports" # FIXME: $output_objdir/$libname.filter potentially contains lots of # 's' commands which not all seds can handle. GNU sed should be fine # though. Also, the filter scales superlinearly with the number of # global variables. join(1) would be nice here, but unfortunately # isn't a blessed tool. $opt_dry_run || $SED -e '/[ ,]DATA/!d;s,\(.*\)\([ \,].*\),s|^\1$|\1\2|,' < $export_symbols > $output_objdir/$libname.filter func_append delfiles " $export_symbols $output_objdir/$libname.filter" export_symbols=$output_objdir/$libname.def $opt_dry_run || $SED -f $output_objdir/$libname.filter < $orig_export_symbols > $export_symbols fi fi libobjs=$output # Restore the value of output. output=$save_output if test -n "$convenience" && test -n "$whole_archive_flag_spec"; then eval libobjs=\"\$libobjs $whole_archive_flag_spec\" test "X$libobjs" = "X " && libobjs= fi # Expand the library linking commands again to reset the # value of $libobjs for piecewise linking. # Do each of the archive commands. if test "$module" = yes && test -n "$module_cmds" ; then if test -n "$export_symbols" && test -n "$module_expsym_cmds"; then cmds=$module_expsym_cmds else cmds=$module_cmds fi else if test -n "$export_symbols" && test -n "$archive_expsym_cmds"; then cmds=$archive_expsym_cmds else cmds=$archive_cmds fi fi fi if test -n "$delfiles"; then # Append the command to remove temporary files to $cmds. eval cmds=\"\$cmds~\$RM $delfiles\" fi # Add any objects from preloaded convenience libraries if test -n "$dlprefiles"; then gentop="$output_objdir/${outputname}x" func_append generated " $gentop" func_extract_archives $gentop $dlprefiles func_append libobjs " $func_extract_archives_result" test "X$libobjs" = "X " && libobjs= fi save_ifs="$IFS"; IFS='~' for cmd in $cmds; do IFS="$save_ifs" eval cmd=\"$cmd\" $opt_silent || { func_quote_for_expand "$cmd" eval "func_echo $func_quote_for_expand_result" } $opt_dry_run || eval "$cmd" || { lt_exit=$? # Restore the uninstalled library and exit if test "$opt_mode" = relink; then ( cd "$output_objdir" && \ $RM "${realname}T" && \ $MV "${realname}U" "$realname" ) fi exit $lt_exit } done IFS="$save_ifs" # Restore the uninstalled library and exit if test "$opt_mode" = relink; then $opt_dry_run || eval '(cd $output_objdir && $RM ${realname}T && $MV $realname ${realname}T && $MV ${realname}U $realname)' || exit $? if test -n "$convenience"; then if test -z "$whole_archive_flag_spec"; then func_show_eval '${RM}r "$gentop"' fi fi exit $EXIT_SUCCESS fi # Create links to the real library. for linkname in $linknames; do if test "$realname" != "$linkname"; then func_show_eval '(cd "$output_objdir" && $RM "$linkname" && $LN_S "$realname" "$linkname")' 'exit $?' fi done # If -module or -export-dynamic was specified, set the dlname. if test "$module" = yes || test "$export_dynamic" = yes; then # On all known operating systems, these are identical. dlname="$soname" fi fi ;; obj) if test -n "$dlfiles$dlprefiles" || test "$dlself" != no; then func_warning "\`-dlopen' is ignored for objects" fi case " $deplibs" in *\ -l* | *\ -L*) func_warning "\`-l' and \`-L' are ignored for objects" ;; esac test -n "$rpath" && \ func_warning "\`-rpath' is ignored for objects" test -n "$xrpath" && \ func_warning "\`-R' is ignored for objects" test -n "$vinfo" && \ func_warning "\`-version-info' is ignored for objects" test -n "$release" && \ func_warning "\`-release' is ignored for objects" case $output in *.lo) test -n "$objs$old_deplibs" && \ func_fatal_error "cannot build library object \`$output' from non-libtool objects" libobj=$output func_lo2o "$libobj" obj=$func_lo2o_result ;; *) libobj= obj="$output" ;; esac # Delete the old objects. $opt_dry_run || $RM $obj $libobj # Objects from convenience libraries. This assumes # single-version convenience libraries. Whenever we create # different ones for PIC/non-PIC, this we'll have to duplicate # the extraction. reload_conv_objs= gentop= # reload_cmds runs $LD directly, so let us get rid of # -Wl from whole_archive_flag_spec and hope we can get by with # turning comma into space.. wl= if test -n "$convenience"; then if test -n "$whole_archive_flag_spec"; then eval tmp_whole_archive_flags=\"$whole_archive_flag_spec\" reload_conv_objs=$reload_objs\ `$ECHO "$tmp_whole_archive_flags" | $SED 's|,| |g'` else gentop="$output_objdir/${obj}x" func_append generated " $gentop" func_extract_archives $gentop $convenience reload_conv_objs="$reload_objs $func_extract_archives_result" fi fi # If we're not building shared, we need to use non_pic_objs test "$build_libtool_libs" != yes && libobjs="$non_pic_objects" # Create the old-style object. reload_objs="$objs$old_deplibs "`$ECHO "$libobjs" | $SP2NL | $SED "/\.${libext}$/d; /\.lib$/d; $lo2o" | $NL2SP`" $reload_conv_objs" ### testsuite: skip nested quoting test output="$obj" func_execute_cmds "$reload_cmds" 'exit $?' # Exit if we aren't doing a library object file. if test -z "$libobj"; then if test -n "$gentop"; then func_show_eval '${RM}r "$gentop"' fi exit $EXIT_SUCCESS fi if test "$build_libtool_libs" != yes; then if test -n "$gentop"; then func_show_eval '${RM}r "$gentop"' fi # Create an invalid libtool object if no PIC, so that we don't # accidentally link it into a program. # $show "echo timestamp > $libobj" # $opt_dry_run || eval "echo timestamp > $libobj" || exit $? exit $EXIT_SUCCESS fi if test -n "$pic_flag" || test "$pic_mode" != default; then # Only do commands if we really have different PIC objects. reload_objs="$libobjs $reload_conv_objs" output="$libobj" func_execute_cmds "$reload_cmds" 'exit $?' fi if test -n "$gentop"; then func_show_eval '${RM}r "$gentop"' fi exit $EXIT_SUCCESS ;; prog) case $host in *cygwin*) func_stripname '' '.exe' "$output" output=$func_stripname_result.exe;; esac test -n "$vinfo" && \ func_warning "\`-version-info' is ignored for programs" test -n "$release" && \ func_warning "\`-release' is ignored for programs" test "$preload" = yes \ && test "$dlopen_support" = unknown \ && test "$dlopen_self" = unknown \ && test "$dlopen_self_static" = unknown && \ func_warning "\`LT_INIT([dlopen])' not used. Assuming no dlopen support." case $host in *-*-rhapsody* | *-*-darwin1.[012]) # On Rhapsody replace the C library is the System framework compile_deplibs=`$ECHO " $compile_deplibs" | $SED 's/ -lc / System.ltframework /'` finalize_deplibs=`$ECHO " $finalize_deplibs" | $SED 's/ -lc / System.ltframework /'` ;; esac case $host in *-*-darwin*) # Don't allow lazy linking, it breaks C++ global constructors # But is supposedly fixed on 10.4 or later (yay!). if test "$tagname" = CXX ; then case ${MACOSX_DEPLOYMENT_TARGET-10.0} in 10.[0123]) func_append compile_command " ${wl}-bind_at_load" func_append finalize_command " ${wl}-bind_at_load" ;; esac fi # Time to change all our "foo.ltframework" stuff back to "-framework foo" compile_deplibs=`$ECHO " $compile_deplibs" | $SED 's% \([^ $]*\).ltframework% -framework \1%g'` finalize_deplibs=`$ECHO " $finalize_deplibs" | $SED 's% \([^ $]*\).ltframework% -framework \1%g'` ;; esac # move library search paths that coincide with paths to not yet # installed libraries to the beginning of the library search list new_libs= for path in $notinst_path; do case " $new_libs " in *" -L$path/$objdir "*) ;; *) case " $compile_deplibs " in *" -L$path/$objdir "*) func_append new_libs " -L$path/$objdir" ;; esac ;; esac done for deplib in $compile_deplibs; do case $deplib in -L*) case " $new_libs " in *" $deplib "*) ;; *) func_append new_libs " $deplib" ;; esac ;; *) func_append new_libs " $deplib" ;; esac done compile_deplibs="$new_libs" func_append compile_command " $compile_deplibs" func_append finalize_command " $finalize_deplibs" if test -n "$rpath$xrpath"; then # If the user specified any rpath flags, then add them. for libdir in $rpath $xrpath; do # This is the magic to use -rpath. case "$finalize_rpath " in *" $libdir "*) ;; *) func_append finalize_rpath " $libdir" ;; esac done fi # Now hardcode the library paths rpath= hardcode_libdirs= for libdir in $compile_rpath $finalize_rpath; do if test -n "$hardcode_libdir_flag_spec"; then if test -n "$hardcode_libdir_separator"; then if test -z "$hardcode_libdirs"; then hardcode_libdirs="$libdir" else # Just accumulate the unique libdirs. case $hardcode_libdir_separator$hardcode_libdirs$hardcode_libdir_separator in *"$hardcode_libdir_separator$libdir$hardcode_libdir_separator"*) ;; *) func_append hardcode_libdirs "$hardcode_libdir_separator$libdir" ;; esac fi else eval flag=\"$hardcode_libdir_flag_spec\" func_append rpath " $flag" fi elif test -n "$runpath_var"; then case "$perm_rpath " in *" $libdir "*) ;; *) func_append perm_rpath " $libdir" ;; esac fi case $host in *-*-cygwin* | *-*-mingw* | *-*-pw32* | *-*-os2* | *-cegcc*) testbindir=`${ECHO} "$libdir" | ${SED} -e 's*/lib$*/bin*'` case :$dllsearchpath: in *":$libdir:"*) ;; ::) dllsearchpath=$libdir;; *) func_append dllsearchpath ":$libdir";; esac case :$dllsearchpath: in *":$testbindir:"*) ;; ::) dllsearchpath=$testbindir;; *) func_append dllsearchpath ":$testbindir";; esac ;; esac done # Substitute the hardcoded libdirs into the rpath. if test -n "$hardcode_libdir_separator" && test -n "$hardcode_libdirs"; then libdir="$hardcode_libdirs" eval rpath=\" $hardcode_libdir_flag_spec\" fi compile_rpath="$rpath" rpath= hardcode_libdirs= for libdir in $finalize_rpath; do if test -n "$hardcode_libdir_flag_spec"; then if test -n "$hardcode_libdir_separator"; then if test -z "$hardcode_libdirs"; then hardcode_libdirs="$libdir" else # Just accumulate the unique libdirs. case $hardcode_libdir_separator$hardcode_libdirs$hardcode_libdir_separator in *"$hardcode_libdir_separator$libdir$hardcode_libdir_separator"*) ;; *) func_append hardcode_libdirs "$hardcode_libdir_separator$libdir" ;; esac fi else eval flag=\"$hardcode_libdir_flag_spec\" func_append rpath " $flag" fi elif test -n "$runpath_var"; then case "$finalize_perm_rpath " in *" $libdir "*) ;; *) func_append finalize_perm_rpath " $libdir" ;; esac fi done # Substitute the hardcoded libdirs into the rpath. if test -n "$hardcode_libdir_separator" && test -n "$hardcode_libdirs"; then libdir="$hardcode_libdirs" eval rpath=\" $hardcode_libdir_flag_spec\" fi finalize_rpath="$rpath" if test -n "$libobjs" && test "$build_old_libs" = yes; then # Transform all the library objects into standard objects. compile_command=`$ECHO "$compile_command" | $SP2NL | $SED "$lo2o" | $NL2SP` finalize_command=`$ECHO "$finalize_command" | $SP2NL | $SED "$lo2o" | $NL2SP` fi func_generate_dlsyms "$outputname" "@PROGRAM@" "no" # template prelinking step if test -n "$prelink_cmds"; then func_execute_cmds "$prelink_cmds" 'exit $?' fi wrappers_required=yes case $host in *cegcc* | *mingw32ce*) # Disable wrappers for cegcc and mingw32ce hosts, we are cross compiling anyway. wrappers_required=no ;; *cygwin* | *mingw* ) if test "$build_libtool_libs" != yes; then wrappers_required=no fi ;; *) if test "$need_relink" = no || test "$build_libtool_libs" != yes; then wrappers_required=no fi ;; esac if test "$wrappers_required" = no; then # Replace the output file specification. compile_command=`$ECHO "$compile_command" | $SED 's%@OUTPUT@%'"$output"'%g'` link_command="$compile_command$compile_rpath" # We have no uninstalled library dependencies, so finalize right now. exit_status=0 func_show_eval "$link_command" 'exit_status=$?' if test -n "$postlink_cmds"; then func_to_tool_file "$output" postlink_cmds=`func_echo_all "$postlink_cmds" | $SED -e 's%@OUTPUT@%'"$output"'%g' -e 's%@TOOL_OUTPUT@%'"$func_to_tool_file_result"'%g'` func_execute_cmds "$postlink_cmds" 'exit $?' fi # Delete the generated files. if test -f "$output_objdir/${outputname}S.${objext}"; then func_show_eval '$RM "$output_objdir/${outputname}S.${objext}"' fi exit $exit_status fi if test -n "$compile_shlibpath$finalize_shlibpath"; then compile_command="$shlibpath_var=\"$compile_shlibpath$finalize_shlibpath\$$shlibpath_var\" $compile_command" fi if test -n "$finalize_shlibpath"; then finalize_command="$shlibpath_var=\"$finalize_shlibpath\$$shlibpath_var\" $finalize_command" fi compile_var= finalize_var= if test -n "$runpath_var"; then if test -n "$perm_rpath"; then # We should set the runpath_var. rpath= for dir in $perm_rpath; do func_append rpath "$dir:" done compile_var="$runpath_var=\"$rpath\$$runpath_var\" " fi if test -n "$finalize_perm_rpath"; then # We should set the runpath_var. rpath= for dir in $finalize_perm_rpath; do func_append rpath "$dir:" done finalize_var="$runpath_var=\"$rpath\$$runpath_var\" " fi fi if test "$no_install" = yes; then # We don't need to create a wrapper script. link_command="$compile_var$compile_command$compile_rpath" # Replace the output file specification. link_command=`$ECHO "$link_command" | $SED 's%@OUTPUT@%'"$output"'%g'` # Delete the old output file. $opt_dry_run || $RM $output # Link the executable and exit func_show_eval "$link_command" 'exit $?' if test -n "$postlink_cmds"; then func_to_tool_file "$output" postlink_cmds=`func_echo_all "$postlink_cmds" | $SED -e 's%@OUTPUT@%'"$output"'%g' -e 's%@TOOL_OUTPUT@%'"$func_to_tool_file_result"'%g'` func_execute_cmds "$postlink_cmds" 'exit $?' fi exit $EXIT_SUCCESS fi if test "$hardcode_action" = relink; then # Fast installation is not supported link_command="$compile_var$compile_command$compile_rpath" relink_command="$finalize_var$finalize_command$finalize_rpath" func_warning "this platform does not like uninstalled shared libraries" func_warning "\`$output' will be relinked during installation" else if test "$fast_install" != no; then link_command="$finalize_var$compile_command$finalize_rpath" if test "$fast_install" = yes; then relink_command=`$ECHO "$compile_var$compile_command$compile_rpath" | $SED 's%@OUTPUT@%\$progdir/\$file%g'` else # fast_install is set to needless relink_command= fi else link_command="$compile_var$compile_command$compile_rpath" relink_command="$finalize_var$finalize_command$finalize_rpath" fi fi # Replace the output file specification. link_command=`$ECHO "$link_command" | $SED 's%@OUTPUT@%'"$output_objdir/$outputname"'%g'` # Delete the old output files. $opt_dry_run || $RM $output $output_objdir/$outputname $output_objdir/lt-$outputname func_show_eval "$link_command" 'exit $?' if test -n "$postlink_cmds"; then func_to_tool_file "$output_objdir/$outputname" postlink_cmds=`func_echo_all "$postlink_cmds" | $SED -e 's%@OUTPUT@%'"$output_objdir/$outputname"'%g' -e 's%@TOOL_OUTPUT@%'"$func_to_tool_file_result"'%g'` func_execute_cmds "$postlink_cmds" 'exit $?' fi # Now create the wrapper script. func_verbose "creating $output" # Quote the relink command for shipping. if test -n "$relink_command"; then # Preserve any variables that may affect compiler behavior for var in $variables_saved_for_relink; do if eval test -z \"\${$var+set}\"; then relink_command="{ test -z \"\${$var+set}\" || $lt_unset $var || { $var=; export $var; }; }; $relink_command" elif eval var_value=\$$var; test -z "$var_value"; then relink_command="$var=; export $var; $relink_command" else func_quote_for_eval "$var_value" relink_command="$var=$func_quote_for_eval_result; export $var; $relink_command" fi done relink_command="(cd `pwd`; $relink_command)" relink_command=`$ECHO "$relink_command" | $SED "$sed_quote_subst"` fi # Only actually do things if not in dry run mode. $opt_dry_run || { # win32 will think the script is a binary if it has # a .exe suffix, so we strip it off here. case $output in *.exe) func_stripname '' '.exe' "$output" output=$func_stripname_result ;; esac # test for cygwin because mv fails w/o .exe extensions case $host in *cygwin*) exeext=.exe func_stripname '' '.exe' "$outputname" outputname=$func_stripname_result ;; *) exeext= ;; esac case $host in *cygwin* | *mingw* ) func_dirname_and_basename "$output" "" "." output_name=$func_basename_result output_path=$func_dirname_result cwrappersource="$output_path/$objdir/lt-$output_name.c" cwrapper="$output_path/$output_name.exe" $RM $cwrappersource $cwrapper trap "$RM $cwrappersource $cwrapper; exit $EXIT_FAILURE" 1 2 15 func_emit_cwrapperexe_src > $cwrappersource # The wrapper executable is built using the $host compiler, # because it contains $host paths and files. If cross- # compiling, it, like the target executable, must be # executed on the $host or under an emulation environment. $opt_dry_run || { $LTCC $LTCFLAGS -o $cwrapper $cwrappersource $STRIP $cwrapper } # Now, create the wrapper script for func_source use: func_ltwrapper_scriptname $cwrapper $RM $func_ltwrapper_scriptname_result trap "$RM $func_ltwrapper_scriptname_result; exit $EXIT_FAILURE" 1 2 15 $opt_dry_run || { # note: this script will not be executed, so do not chmod. if test "x$build" = "x$host" ; then $cwrapper --lt-dump-script > $func_ltwrapper_scriptname_result else func_emit_wrapper no > $func_ltwrapper_scriptname_result fi } ;; * ) $RM $output trap "$RM $output; exit $EXIT_FAILURE" 1 2 15 func_emit_wrapper no > $output chmod +x $output ;; esac } exit $EXIT_SUCCESS ;; esac # See if we need to build an old-fashioned archive. for oldlib in $oldlibs; do if test "$build_libtool_libs" = convenience; then oldobjs="$libobjs_save $symfileobj" addlibs="$convenience" build_libtool_libs=no else if test "$build_libtool_libs" = module; then oldobjs="$libobjs_save" build_libtool_libs=no else oldobjs="$old_deplibs $non_pic_objects" if test "$preload" = yes && test -f "$symfileobj"; then func_append oldobjs " $symfileobj" fi fi addlibs="$old_convenience" fi if test -n "$addlibs"; then gentop="$output_objdir/${outputname}x" func_append generated " $gentop" func_extract_archives $gentop $addlibs func_append oldobjs " $func_extract_archives_result" fi # Do each command in the archive commands. if test -n "$old_archive_from_new_cmds" && test "$build_libtool_libs" = yes; then cmds=$old_archive_from_new_cmds else # Add any objects from preloaded convenience libraries if test -n "$dlprefiles"; then gentop="$output_objdir/${outputname}x" func_append generated " $gentop" func_extract_archives $gentop $dlprefiles func_append oldobjs " $func_extract_archives_result" fi # POSIX demands no paths to be encoded in archives. We have # to avoid creating archives with duplicate basenames if we # might have to extract them afterwards, e.g., when creating a # static archive out of a convenience library, or when linking # the entirety of a libtool archive into another (currently # not supported by libtool). if (for obj in $oldobjs do func_basename "$obj" $ECHO "$func_basename_result" done | sort | sort -uc >/dev/null 2>&1); then : else echo "copying selected object files to avoid basename conflicts..." gentop="$output_objdir/${outputname}x" func_append generated " $gentop" func_mkdir_p "$gentop" save_oldobjs=$oldobjs oldobjs= counter=1 for obj in $save_oldobjs do func_basename "$obj" objbase="$func_basename_result" case " $oldobjs " in " ") oldobjs=$obj ;; *[\ /]"$objbase "*) while :; do # Make sure we don't pick an alternate name that also # overlaps. newobj=lt$counter-$objbase func_arith $counter + 1 counter=$func_arith_result case " $oldobjs " in *[\ /]"$newobj "*) ;; *) if test ! -f "$gentop/$newobj"; then break; fi ;; esac done func_show_eval "ln $obj $gentop/$newobj || cp $obj $gentop/$newobj" func_append oldobjs " $gentop/$newobj" ;; *) func_append oldobjs " $obj" ;; esac done fi func_to_tool_file "$oldlib" func_convert_file_msys_to_w32 tool_oldlib=$func_to_tool_file_result eval cmds=\"$old_archive_cmds\" func_len " $cmds" len=$func_len_result if test "$len" -lt "$max_cmd_len" || test "$max_cmd_len" -le -1; then cmds=$old_archive_cmds elif test -n "$archiver_list_spec"; then func_verbose "using command file archive linking..." for obj in $oldobjs do func_to_tool_file "$obj" $ECHO "$func_to_tool_file_result" done > $output_objdir/$libname.libcmd func_to_tool_file "$output_objdir/$libname.libcmd" oldobjs=" $archiver_list_spec$func_to_tool_file_result" cmds=$old_archive_cmds else # the command line is too long to link in one step, link in parts func_verbose "using piecewise archive linking..." save_RANLIB=$RANLIB RANLIB=: objlist= concat_cmds= save_oldobjs=$oldobjs oldobjs= # Is there a better way of finding the last object in the list? for obj in $save_oldobjs do last_oldobj=$obj done eval test_cmds=\"$old_archive_cmds\" func_len " $test_cmds" len0=$func_len_result len=$len0 for obj in $save_oldobjs do func_len " $obj" func_arith $len + $func_len_result len=$func_arith_result func_append objlist " $obj" if test "$len" -lt "$max_cmd_len"; then : else # the above command should be used before it gets too long oldobjs=$objlist if test "$obj" = "$last_oldobj" ; then RANLIB=$save_RANLIB fi test -z "$concat_cmds" || concat_cmds=$concat_cmds~ eval concat_cmds=\"\${concat_cmds}$old_archive_cmds\" objlist= len=$len0 fi done RANLIB=$save_RANLIB oldobjs=$objlist if test "X$oldobjs" = "X" ; then eval cmds=\"\$concat_cmds\" else eval cmds=\"\$concat_cmds~\$old_archive_cmds\" fi fi fi func_execute_cmds "$cmds" 'exit $?' done test -n "$generated" && \ func_show_eval "${RM}r$generated" # Now create the libtool archive. case $output in *.la) old_library= test "$build_old_libs" = yes && old_library="$libname.$libext" func_verbose "creating $output" # Preserve any variables that may affect compiler behavior for var in $variables_saved_for_relink; do if eval test -z \"\${$var+set}\"; then relink_command="{ test -z \"\${$var+set}\" || $lt_unset $var || { $var=; export $var; }; }; $relink_command" elif eval var_value=\$$var; test -z "$var_value"; then relink_command="$var=; export $var; $relink_command" else func_quote_for_eval "$var_value" relink_command="$var=$func_quote_for_eval_result; export $var; $relink_command" fi done # Quote the link command for shipping. relink_command="(cd `pwd`; $SHELL $progpath $preserve_args --mode=relink $libtool_args @inst_prefix_dir@)" relink_command=`$ECHO "$relink_command" | $SED "$sed_quote_subst"` if test "$hardcode_automatic" = yes ; then relink_command= fi # Only create the output if not a dry run. $opt_dry_run || { for installed in no yes; do if test "$installed" = yes; then if test -z "$install_libdir"; then break fi output="$output_objdir/$outputname"i # Replace all uninstalled libtool libraries with the installed ones newdependency_libs= for deplib in $dependency_libs; do case $deplib in *.la) func_basename "$deplib" name="$func_basename_result" func_resolve_sysroot "$deplib" eval libdir=`${SED} -n -e 's/^libdir=\(.*\)$/\1/p' $func_resolve_sysroot_result` test -z "$libdir" && \ func_fatal_error "\`$deplib' is not a valid libtool archive" func_append newdependency_libs " ${lt_sysroot:+=}$libdir/$name" ;; -L*) func_stripname -L '' "$deplib" func_replace_sysroot "$func_stripname_result" func_append newdependency_libs " -L$func_replace_sysroot_result" ;; -R*) func_stripname -R '' "$deplib" func_replace_sysroot "$func_stripname_result" func_append newdependency_libs " -R$func_replace_sysroot_result" ;; *) func_append newdependency_libs " $deplib" ;; esac done dependency_libs="$newdependency_libs" newdlfiles= for lib in $dlfiles; do case $lib in *.la) func_basename "$lib" name="$func_basename_result" eval libdir=`${SED} -n -e 's/^libdir=\(.*\)$/\1/p' $lib` test -z "$libdir" && \ func_fatal_error "\`$lib' is not a valid libtool archive" func_append newdlfiles " ${lt_sysroot:+=}$libdir/$name" ;; *) func_append newdlfiles " $lib" ;; esac done dlfiles="$newdlfiles" newdlprefiles= for lib in $dlprefiles; do case $lib in *.la) # Only pass preopened files to the pseudo-archive (for # eventual linking with the app. that links it) if we # didn't already link the preopened objects directly into # the library: func_basename "$lib" name="$func_basename_result" eval libdir=`${SED} -n -e 's/^libdir=\(.*\)$/\1/p' $lib` test -z "$libdir" && \ func_fatal_error "\`$lib' is not a valid libtool archive" func_append newdlprefiles " ${lt_sysroot:+=}$libdir/$name" ;; esac done dlprefiles="$newdlprefiles" else newdlfiles= for lib in $dlfiles; do case $lib in [\\/]* | [A-Za-z]:[\\/]*) abs="$lib" ;; *) abs=`pwd`"/$lib" ;; esac func_append newdlfiles " $abs" done dlfiles="$newdlfiles" newdlprefiles= for lib in $dlprefiles; do case $lib in [\\/]* | [A-Za-z]:[\\/]*) abs="$lib" ;; *) abs=`pwd`"/$lib" ;; esac func_append newdlprefiles " $abs" done dlprefiles="$newdlprefiles" fi $RM $output # place dlname in correct position for cygwin # In fact, it would be nice if we could use this code for all target # systems that can't hard-code library paths into their executables # and that have no shared library path variable independent of PATH, # but it turns out we can't easily determine that from inspecting # libtool variables, so we have to hard-code the OSs to which it # applies here; at the moment, that means platforms that use the PE # object format with DLL files. See the long comment at the top of # tests/bindir.at for full details. tdlname=$dlname case $host,$output,$installed,$module,$dlname in *cygwin*,*lai,yes,no,*.dll | *mingw*,*lai,yes,no,*.dll | *cegcc*,*lai,yes,no,*.dll) # If a -bindir argument was supplied, place the dll there. if test "x$bindir" != x ; then func_relative_path "$install_libdir" "$bindir" tdlname=$func_relative_path_result$dlname else # Otherwise fall back on heuristic. tdlname=../bin/$dlname fi ;; esac $ECHO > $output "\ # $outputname - a libtool library file # Generated by $PROGRAM (GNU $PACKAGE$TIMESTAMP) $VERSION # # Please DO NOT delete this file! # It is necessary for linking the library. # The name that we can dlopen(3). dlname='$tdlname' # Names of this library. library_names='$library_names' # The name of the static archive. old_library='$old_library' # Linker flags that can not go in dependency_libs. inherited_linker_flags='$new_inherited_linker_flags' # Libraries that this one depends upon. dependency_libs='$dependency_libs' # Names of additional weak libraries provided by this library weak_library_names='$weak_libs' # Version information for $libname. current=$current age=$age revision=$revision # Is this an already installed library? installed=$installed # Should we warn about portability when linking against -modules? shouldnotlink=$module # Files to dlopen/dlpreopen dlopen='$dlfiles' dlpreopen='$dlprefiles' # Directory that this library needs to be installed in: libdir='$install_libdir'" if test "$installed" = no && test "$need_relink" = yes; then $ECHO >> $output "\ relink_command=\"$relink_command\"" fi done } # Do a symbolic link so that the libtool archive can be found in # LD_LIBRARY_PATH before the program is installed. func_show_eval '( cd "$output_objdir" && $RM "$outputname" && $LN_S "../$outputname" "$outputname" )' 'exit $?' ;; esac exit $EXIT_SUCCESS } { test "$opt_mode" = link || test "$opt_mode" = relink; } && func_mode_link ${1+"$@"} # func_mode_uninstall arg... func_mode_uninstall () { $opt_debug RM="$nonopt" files= rmforce= exit_status=0 # This variable tells wrapper scripts just to set variables rather # than running their programs. libtool_install_magic="$magic" for arg do case $arg in -f) func_append RM " $arg"; rmforce=yes ;; -*) func_append RM " $arg" ;; *) func_append files " $arg" ;; esac done test -z "$RM" && \ func_fatal_help "you must specify an RM program" rmdirs= for file in $files; do func_dirname "$file" "" "." dir="$func_dirname_result" if test "X$dir" = X.; then odir="$objdir" else odir="$dir/$objdir" fi func_basename "$file" name="$func_basename_result" test "$opt_mode" = uninstall && odir="$dir" # Remember odir for removal later, being careful to avoid duplicates if test "$opt_mode" = clean; then case " $rmdirs " in *" $odir "*) ;; *) func_append rmdirs " $odir" ;; esac fi # Don't error if the file doesn't exist and rm -f was used. if { test -L "$file"; } >/dev/null 2>&1 || { test -h "$file"; } >/dev/null 2>&1 || test -f "$file"; then : elif test -d "$file"; then exit_status=1 continue elif test "$rmforce" = yes; then continue fi rmfiles="$file" case $name in *.la) # Possibly a libtool archive, so verify it. if func_lalib_p "$file"; then func_source $dir/$name # Delete the libtool libraries and symlinks. for n in $library_names; do func_append rmfiles " $odir/$n" done test -n "$old_library" && func_append rmfiles " $odir/$old_library" case "$opt_mode" in clean) case " $library_names " in *" $dlname "*) ;; *) test -n "$dlname" && func_append rmfiles " $odir/$dlname" ;; esac test -n "$libdir" && func_append rmfiles " $odir/$name $odir/${name}i" ;; uninstall) if test -n "$library_names"; then # Do each command in the postuninstall commands. func_execute_cmds "$postuninstall_cmds" 'test "$rmforce" = yes || exit_status=1' fi if test -n "$old_library"; then # Do each command in the old_postuninstall commands. func_execute_cmds "$old_postuninstall_cmds" 'test "$rmforce" = yes || exit_status=1' fi # FIXME: should reinstall the best remaining shared library. ;; esac fi ;; *.lo) # Possibly a libtool object, so verify it. if func_lalib_p "$file"; then # Read the .lo file func_source $dir/$name # Add PIC object to the list of files to remove. if test -n "$pic_object" && test "$pic_object" != none; then func_append rmfiles " $dir/$pic_object" fi # Add non-PIC object to the list of files to remove. if test -n "$non_pic_object" && test "$non_pic_object" != none; then func_append rmfiles " $dir/$non_pic_object" fi fi ;; *) if test "$opt_mode" = clean ; then noexename=$name case $file in *.exe) func_stripname '' '.exe' "$file" file=$func_stripname_result func_stripname '' '.exe' "$name" noexename=$func_stripname_result # $file with .exe has already been added to rmfiles, # add $file without .exe func_append rmfiles " $file" ;; esac # Do a test to see if this is a libtool program. if func_ltwrapper_p "$file"; then if func_ltwrapper_executable_p "$file"; then func_ltwrapper_scriptname "$file" relink_command= func_source $func_ltwrapper_scriptname_result func_append rmfiles " $func_ltwrapper_scriptname_result" else relink_command= func_source $dir/$noexename fi # note $name still contains .exe if it was in $file originally # as does the version of $file that was added into $rmfiles func_append rmfiles " $odir/$name $odir/${name}S.${objext}" if test "$fast_install" = yes && test -n "$relink_command"; then func_append rmfiles " $odir/lt-$name" fi if test "X$noexename" != "X$name" ; then func_append rmfiles " $odir/lt-${noexename}.c" fi fi fi ;; esac func_show_eval "$RM $rmfiles" 'exit_status=1' done # Try to remove the ${objdir}s in the directories where we deleted files for dir in $rmdirs; do if test -d "$dir"; then func_show_eval "rmdir $dir >/dev/null 2>&1" fi done exit $exit_status } { test "$opt_mode" = uninstall || test "$opt_mode" = clean; } && func_mode_uninstall ${1+"$@"} test -z "$opt_mode" && { help="$generic_help" func_fatal_help "you must specify a MODE" } test -z "$exec_cmd" && \ func_fatal_help "invalid operation mode \`$opt_mode'" if test -n "$exec_cmd"; then eval exec "$exec_cmd" exit $EXIT_FAILURE fi exit $exit_status # The TAGs below are defined such that we never get into a situation # in which we disable both kinds of libraries. Given conflicting # choices, we go for a static library, that is the most portable, # since we can't tell whether shared libraries were disabled because # the user asked for that or because the platform doesn't support # them. This is particularly important on AIX, because we don't # support having both static and shared libraries enabled at the same # time on that platform, so we default to a shared-only configuration. # If a disable-shared tag is given, we'll fallback to a static-only # configuration. But we'll never go from static-only to shared-only. # ### BEGIN LIBTOOL TAG CONFIG: disable-shared build_libtool_libs=no build_old_libs=yes # ### END LIBTOOL TAG CONFIG: disable-shared # ### BEGIN LIBTOOL TAG CONFIG: disable-static build_old_libs=`case $build_libtool_libs in yes) echo no;; *) echo yes;; esac` # ### END LIBTOOL TAG CONFIG: disable-static # Local Variables: # mode:shell-script # sh-indentation:2 # End: # vi:sw=2 apache-couchdb-1.5.0/build-aux/config.guess0000755000175000001440000013016212146350677015510 00000000000000#! /bin/sh # Attempt to guess a canonical system name. # Copyright (C) 1992, 1993, 1994, 1995, 1996, 1997, 1998, 1999, # 2000, 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, # 2011, 2012, 2013 Free Software Foundation, Inc. timestamp='2012-12-30' # This file is free software; you can redistribute it and/or modify it # under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, but # WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU # General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, see . # # As a special exception to the GNU General Public License, if you # distribute this file as part of a program that contains a # configuration script generated by Autoconf, you may include it under # the same distribution terms that you use for the rest of that # program. This Exception is an additional permission under section 7 # of the GNU General Public License, version 3 ("GPLv3"). # # Originally written by Per Bothner. # # You can get the latest version of this script from: # http://git.savannah.gnu.org/gitweb/?p=config.git;a=blob_plain;f=config.guess;hb=HEAD # # Please send patches with a ChangeLog entry to config-patches@gnu.org. me=`echo "$0" | sed -e 's,.*/,,'` usage="\ Usage: $0 [OPTION] Output the configuration name of the system \`$me' is run on. Operation modes: -h, --help print this help, then exit -t, --time-stamp print date of last modification, then exit -v, --version print version number, then exit Report bugs and patches to ." version="\ GNU config.guess ($timestamp) Originally written by Per Bothner. Copyright (C) 1992, 1993, 1994, 1995, 1996, 1997, 1998, 1999, 2000, 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011, 2012, 2013 Free Software Foundation, Inc. This is free software; see the source for copying conditions. There is NO warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE." help=" Try \`$me --help' for more information." # Parse command line while test $# -gt 0 ; do case $1 in --time-stamp | --time* | -t ) echo "$timestamp" ; exit ;; --version | -v ) echo "$version" ; exit ;; --help | --h* | -h ) echo "$usage"; exit ;; -- ) # Stop option processing shift; break ;; - ) # Use stdin as input. break ;; -* ) echo "$me: invalid option $1$help" >&2 exit 1 ;; * ) break ;; esac done if test $# != 0; then echo "$me: too many arguments$help" >&2 exit 1 fi trap 'exit 1' 1 2 15 # CC_FOR_BUILD -- compiler used by this script. Note that the use of a # compiler to aid in system detection is discouraged as it requires # temporary files to be created and, as you can see below, it is a # headache to deal with in a portable fashion. # Historically, `CC_FOR_BUILD' used to be named `HOST_CC'. We still # use `HOST_CC' if defined, but it is deprecated. # Portable tmp directory creation inspired by the Autoconf team. set_cc_for_build=' trap "exitcode=\$?; (rm -f \$tmpfiles 2>/dev/null; rmdir \$tmp 2>/dev/null) && exit \$exitcode" 0 ; trap "rm -f \$tmpfiles 2>/dev/null; rmdir \$tmp 2>/dev/null; exit 1" 1 2 13 15 ; : ${TMPDIR=/tmp} ; { tmp=`(umask 077 && mktemp -d "$TMPDIR/cgXXXXXX") 2>/dev/null` && test -n "$tmp" && test -d "$tmp" ; } || { test -n "$RANDOM" && tmp=$TMPDIR/cg$$-$RANDOM && (umask 077 && mkdir $tmp) ; } || { tmp=$TMPDIR/cg-$$ && (umask 077 && mkdir $tmp) && echo "Warning: creating insecure temp directory" >&2 ; } || { echo "$me: cannot create a temporary directory in $TMPDIR" >&2 ; exit 1 ; } ; dummy=$tmp/dummy ; tmpfiles="$dummy.c $dummy.o $dummy.rel $dummy" ; case $CC_FOR_BUILD,$HOST_CC,$CC in ,,) echo "int x;" > $dummy.c ; for c in cc gcc c89 c99 ; do if ($c -c -o $dummy.o $dummy.c) >/dev/null 2>&1 ; then CC_FOR_BUILD="$c"; break ; fi ; done ; if test x"$CC_FOR_BUILD" = x ; then CC_FOR_BUILD=no_compiler_found ; fi ;; ,,*) CC_FOR_BUILD=$CC ;; ,*,*) CC_FOR_BUILD=$HOST_CC ;; esac ; set_cc_for_build= ;' # This is needed to find uname on a Pyramid OSx when run in the BSD universe. # (ghazi@noc.rutgers.edu 1994-08-24) if (test -f /.attbin/uname) >/dev/null 2>&1 ; then PATH=$PATH:/.attbin ; export PATH fi UNAME_MACHINE=`(uname -m) 2>/dev/null` || UNAME_MACHINE=unknown UNAME_RELEASE=`(uname -r) 2>/dev/null` || UNAME_RELEASE=unknown UNAME_SYSTEM=`(uname -s) 2>/dev/null` || UNAME_SYSTEM=unknown UNAME_VERSION=`(uname -v) 2>/dev/null` || UNAME_VERSION=unknown case "${UNAME_SYSTEM}" in Linux|GNU/*) eval $set_cc_for_build cat <<-EOF > $dummy.c #include #ifdef __UCLIBC__ # ifdef __UCLIBC_CONFIG_VERSION__ LIBC=uclibc __UCLIBC_CONFIG_VERSION__ # else LIBC=uclibc # endif #else # ifdef __dietlibc__ LIBC=dietlibc # else LIBC=gnu # endif #endif EOF eval `$CC_FOR_BUILD -E $dummy.c 2>/dev/null | grep '^LIBC'` ;; esac # Note: order is significant - the case branches are not exclusive. case "${UNAME_MACHINE}:${UNAME_SYSTEM}:${UNAME_RELEASE}:${UNAME_VERSION}" in *:NetBSD:*:*) # NetBSD (nbsd) targets should (where applicable) match one or # more of the tuples: *-*-netbsdelf*, *-*-netbsdaout*, # *-*-netbsdecoff* and *-*-netbsd*. For targets that recently # switched to ELF, *-*-netbsd* would select the old # object file format. This provides both forward # compatibility and a consistent mechanism for selecting the # object file format. # # Note: NetBSD doesn't particularly care about the vendor # portion of the name. We always set it to "unknown". sysctl="sysctl -n hw.machine_arch" UNAME_MACHINE_ARCH=`(/sbin/$sysctl 2>/dev/null || \ /usr/sbin/$sysctl 2>/dev/null || echo unknown)` case "${UNAME_MACHINE_ARCH}" in armeb) machine=armeb-unknown ;; arm*) machine=arm-unknown ;; sh3el) machine=shl-unknown ;; sh3eb) machine=sh-unknown ;; sh5el) machine=sh5le-unknown ;; *) machine=${UNAME_MACHINE_ARCH}-unknown ;; esac # The Operating System including object format, if it has switched # to ELF recently, or will in the future. case "${UNAME_MACHINE_ARCH}" in arm*|i386|m68k|ns32k|sh3*|sparc|vax) eval $set_cc_for_build if echo __ELF__ | $CC_FOR_BUILD -E - 2>/dev/null \ | grep -q __ELF__ then # Once all utilities can be ECOFF (netbsdecoff) or a.out (netbsdaout). # Return netbsd for either. FIX? os=netbsd else os=netbsdelf fi ;; *) os=netbsd ;; esac # The OS release # Debian GNU/NetBSD machines have a different userland, and # thus, need a distinct triplet. However, they do not need # kernel version information, so it can be replaced with a # suitable tag, in the style of linux-gnu. case "${UNAME_VERSION}" in Debian*) release='-gnu' ;; *) release=`echo ${UNAME_RELEASE}|sed -e 's/[-_].*/\./'` ;; esac # Since CPU_TYPE-MANUFACTURER-KERNEL-OPERATING_SYSTEM: # contains redundant information, the shorter form: # CPU_TYPE-MANUFACTURER-OPERATING_SYSTEM is used. echo "${machine}-${os}${release}" exit ;; *:Bitrig:*:*) UNAME_MACHINE_ARCH=`arch | sed 's/Bitrig.//'` echo ${UNAME_MACHINE_ARCH}-unknown-bitrig${UNAME_RELEASE} exit ;; *:OpenBSD:*:*) UNAME_MACHINE_ARCH=`arch | sed 's/OpenBSD.//'` echo ${UNAME_MACHINE_ARCH}-unknown-openbsd${UNAME_RELEASE} exit ;; *:ekkoBSD:*:*) echo ${UNAME_MACHINE}-unknown-ekkobsd${UNAME_RELEASE} exit ;; *:SolidBSD:*:*) echo ${UNAME_MACHINE}-unknown-solidbsd${UNAME_RELEASE} exit ;; macppc:MirBSD:*:*) echo powerpc-unknown-mirbsd${UNAME_RELEASE} exit ;; *:MirBSD:*:*) echo ${UNAME_MACHINE}-unknown-mirbsd${UNAME_RELEASE} exit ;; alpha:OSF1:*:*) case $UNAME_RELEASE in *4.0) UNAME_RELEASE=`/usr/sbin/sizer -v | awk '{print $3}'` ;; *5.*) UNAME_RELEASE=`/usr/sbin/sizer -v | awk '{print $4}'` ;; esac # According to Compaq, /usr/sbin/psrinfo has been available on # OSF/1 and Tru64 systems produced since 1995. I hope that # covers most systems running today. This code pipes the CPU # types through head -n 1, so we only detect the type of CPU 0. ALPHA_CPU_TYPE=`/usr/sbin/psrinfo -v | sed -n -e 's/^ The alpha \(.*\) processor.*$/\1/p' | head -n 1` case "$ALPHA_CPU_TYPE" in "EV4 (21064)") UNAME_MACHINE="alpha" ;; "EV4.5 (21064)") UNAME_MACHINE="alpha" ;; "LCA4 (21066/21068)") UNAME_MACHINE="alpha" ;; "EV5 (21164)") UNAME_MACHINE="alphaev5" ;; "EV5.6 (21164A)") UNAME_MACHINE="alphaev56" ;; "EV5.6 (21164PC)") UNAME_MACHINE="alphapca56" ;; "EV5.7 (21164PC)") UNAME_MACHINE="alphapca57" ;; "EV6 (21264)") UNAME_MACHINE="alphaev6" ;; "EV6.7 (21264A)") UNAME_MACHINE="alphaev67" ;; "EV6.8CB (21264C)") UNAME_MACHINE="alphaev68" ;; "EV6.8AL (21264B)") UNAME_MACHINE="alphaev68" ;; "EV6.8CX (21264D)") UNAME_MACHINE="alphaev68" ;; "EV6.9A (21264/EV69A)") UNAME_MACHINE="alphaev69" ;; "EV7 (21364)") UNAME_MACHINE="alphaev7" ;; "EV7.9 (21364A)") UNAME_MACHINE="alphaev79" ;; esac # A Pn.n version is a patched version. # A Vn.n version is a released version. # A Tn.n version is a released field test version. # A Xn.n version is an unreleased experimental baselevel. # 1.2 uses "1.2" for uname -r. echo ${UNAME_MACHINE}-dec-osf`echo ${UNAME_RELEASE} | sed -e 's/^[PVTX]//' | tr 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' 'abcdefghijklmnopqrstuvwxyz'` # Reset EXIT trap before exiting to avoid spurious non-zero exit code. exitcode=$? trap '' 0 exit $exitcode ;; Alpha\ *:Windows_NT*:*) # How do we know it's Interix rather than the generic POSIX subsystem? # Should we change UNAME_MACHINE based on the output of uname instead # of the specific Alpha model? echo alpha-pc-interix exit ;; 21064:Windows_NT:50:3) echo alpha-dec-winnt3.5 exit ;; Amiga*:UNIX_System_V:4.0:*) echo m68k-unknown-sysv4 exit ;; *:[Aa]miga[Oo][Ss]:*:*) echo ${UNAME_MACHINE}-unknown-amigaos exit ;; *:[Mm]orph[Oo][Ss]:*:*) echo ${UNAME_MACHINE}-unknown-morphos exit ;; *:OS/390:*:*) echo i370-ibm-openedition exit ;; *:z/VM:*:*) echo s390-ibm-zvmoe exit ;; *:OS400:*:*) echo powerpc-ibm-os400 exit ;; arm:RISC*:1.[012]*:*|arm:riscix:1.[012]*:*) echo arm-acorn-riscix${UNAME_RELEASE} exit ;; arm*:riscos:*:*|arm*:RISCOS:*:*) echo arm-unknown-riscos exit ;; SR2?01:HI-UX/MPP:*:* | SR8000:HI-UX/MPP:*:*) echo hppa1.1-hitachi-hiuxmpp exit ;; Pyramid*:OSx*:*:* | MIS*:OSx*:*:* | MIS*:SMP_DC-OSx*:*:*) # akee@wpdis03.wpafb.af.mil (Earle F. Ake) contributed MIS and NILE. if test "`(/bin/universe) 2>/dev/null`" = att ; then echo pyramid-pyramid-sysv3 else echo pyramid-pyramid-bsd fi exit ;; NILE*:*:*:dcosx) echo pyramid-pyramid-svr4 exit ;; DRS?6000:unix:4.0:6*) echo sparc-icl-nx6 exit ;; DRS?6000:UNIX_SV:4.2*:7* | DRS?6000:isis:4.2*:7*) case `/usr/bin/uname -p` in sparc) echo sparc-icl-nx7; exit ;; esac ;; s390x:SunOS:*:*) echo ${UNAME_MACHINE}-ibm-solaris2`echo ${UNAME_RELEASE}|sed -e 's/[^.]*//'` exit ;; sun4H:SunOS:5.*:*) echo sparc-hal-solaris2`echo ${UNAME_RELEASE}|sed -e 's/[^.]*//'` exit ;; sun4*:SunOS:5.*:* | tadpole*:SunOS:5.*:*) echo sparc-sun-solaris2`echo ${UNAME_RELEASE}|sed -e 's/[^.]*//'` exit ;; i86pc:AuroraUX:5.*:* | i86xen:AuroraUX:5.*:*) echo i386-pc-auroraux${UNAME_RELEASE} exit ;; i86pc:SunOS:5.*:* | i86xen:SunOS:5.*:*) eval $set_cc_for_build SUN_ARCH="i386" # If there is a compiler, see if it is configured for 64-bit objects. # Note that the Sun cc does not turn __LP64__ into 1 like gcc does. # This test works for both compilers. if [ "$CC_FOR_BUILD" != 'no_compiler_found' ]; then if (echo '#ifdef __amd64'; echo IS_64BIT_ARCH; echo '#endif') | \ (CCOPTS= $CC_FOR_BUILD -E - 2>/dev/null) | \ grep IS_64BIT_ARCH >/dev/null then SUN_ARCH="x86_64" fi fi echo ${SUN_ARCH}-pc-solaris2`echo ${UNAME_RELEASE}|sed -e 's/[^.]*//'` exit ;; sun4*:SunOS:6*:*) # According to config.sub, this is the proper way to canonicalize # SunOS6. Hard to guess exactly what SunOS6 will be like, but # it's likely to be more like Solaris than SunOS4. echo sparc-sun-solaris3`echo ${UNAME_RELEASE}|sed -e 's/[^.]*//'` exit ;; sun4*:SunOS:*:*) case "`/usr/bin/arch -k`" in Series*|S4*) UNAME_RELEASE=`uname -v` ;; esac # Japanese Language versions have a version number like `4.1.3-JL'. echo sparc-sun-sunos`echo ${UNAME_RELEASE}|sed -e 's/-/_/'` exit ;; sun3*:SunOS:*:*) echo m68k-sun-sunos${UNAME_RELEASE} exit ;; sun*:*:4.2BSD:*) UNAME_RELEASE=`(sed 1q /etc/motd | awk '{print substr($5,1,3)}') 2>/dev/null` test "x${UNAME_RELEASE}" = "x" && UNAME_RELEASE=3 case "`/bin/arch`" in sun3) echo m68k-sun-sunos${UNAME_RELEASE} ;; sun4) echo sparc-sun-sunos${UNAME_RELEASE} ;; esac exit ;; aushp:SunOS:*:*) echo sparc-auspex-sunos${UNAME_RELEASE} exit ;; # The situation for MiNT is a little confusing. The machine name # can be virtually everything (everything which is not # "atarist" or "atariste" at least should have a processor # > m68000). The system name ranges from "MiNT" over "FreeMiNT" # to the lowercase version "mint" (or "freemint"). Finally # the system name "TOS" denotes a system which is actually not # MiNT. But MiNT is downward compatible to TOS, so this should # be no problem. atarist[e]:*MiNT:*:* | atarist[e]:*mint:*:* | atarist[e]:*TOS:*:*) echo m68k-atari-mint${UNAME_RELEASE} exit ;; atari*:*MiNT:*:* | atari*:*mint:*:* | atarist[e]:*TOS:*:*) echo m68k-atari-mint${UNAME_RELEASE} exit ;; *falcon*:*MiNT:*:* | *falcon*:*mint:*:* | *falcon*:*TOS:*:*) echo m68k-atari-mint${UNAME_RELEASE} exit ;; milan*:*MiNT:*:* | milan*:*mint:*:* | *milan*:*TOS:*:*) echo m68k-milan-mint${UNAME_RELEASE} exit ;; hades*:*MiNT:*:* | hades*:*mint:*:* | *hades*:*TOS:*:*) echo m68k-hades-mint${UNAME_RELEASE} exit ;; *:*MiNT:*:* | *:*mint:*:* | *:*TOS:*:*) echo m68k-unknown-mint${UNAME_RELEASE} exit ;; m68k:machten:*:*) echo m68k-apple-machten${UNAME_RELEASE} exit ;; powerpc:machten:*:*) echo powerpc-apple-machten${UNAME_RELEASE} exit ;; RISC*:Mach:*:*) echo mips-dec-mach_bsd4.3 exit ;; RISC*:ULTRIX:*:*) echo mips-dec-ultrix${UNAME_RELEASE} exit ;; VAX*:ULTRIX*:*:*) echo vax-dec-ultrix${UNAME_RELEASE} exit ;; 2020:CLIX:*:* | 2430:CLIX:*:*) echo clipper-intergraph-clix${UNAME_RELEASE} exit ;; mips:*:*:UMIPS | mips:*:*:RISCos) eval $set_cc_for_build sed 's/^ //' << EOF >$dummy.c #ifdef __cplusplus #include /* for printf() prototype */ int main (int argc, char *argv[]) { #else int main (argc, argv) int argc; char *argv[]; { #endif #if defined (host_mips) && defined (MIPSEB) #if defined (SYSTYPE_SYSV) printf ("mips-mips-riscos%ssysv\n", argv[1]); exit (0); #endif #if defined (SYSTYPE_SVR4) printf ("mips-mips-riscos%ssvr4\n", argv[1]); exit (0); #endif #if defined (SYSTYPE_BSD43) || defined(SYSTYPE_BSD) printf ("mips-mips-riscos%sbsd\n", argv[1]); exit (0); #endif #endif exit (-1); } EOF $CC_FOR_BUILD -o $dummy $dummy.c && dummyarg=`echo "${UNAME_RELEASE}" | sed -n 's/\([0-9]*\).*/\1/p'` && SYSTEM_NAME=`$dummy $dummyarg` && { echo "$SYSTEM_NAME"; exit; } echo mips-mips-riscos${UNAME_RELEASE} exit ;; Motorola:PowerMAX_OS:*:*) echo powerpc-motorola-powermax exit ;; Motorola:*:4.3:PL8-*) echo powerpc-harris-powermax exit ;; Night_Hawk:*:*:PowerMAX_OS | Synergy:PowerMAX_OS:*:*) echo powerpc-harris-powermax exit ;; Night_Hawk:Power_UNIX:*:*) echo powerpc-harris-powerunix exit ;; m88k:CX/UX:7*:*) echo m88k-harris-cxux7 exit ;; m88k:*:4*:R4*) echo m88k-motorola-sysv4 exit ;; m88k:*:3*:R3*) echo m88k-motorola-sysv3 exit ;; AViiON:dgux:*:*) # DG/UX returns AViiON for all architectures UNAME_PROCESSOR=`/usr/bin/uname -p` if [ $UNAME_PROCESSOR = mc88100 ] || [ $UNAME_PROCESSOR = mc88110 ] then if [ ${TARGET_BINARY_INTERFACE}x = m88kdguxelfx ] || \ [ ${TARGET_BINARY_INTERFACE}x = x ] then echo m88k-dg-dgux${UNAME_RELEASE} else echo m88k-dg-dguxbcs${UNAME_RELEASE} fi else echo i586-dg-dgux${UNAME_RELEASE} fi exit ;; M88*:DolphinOS:*:*) # DolphinOS (SVR3) echo m88k-dolphin-sysv3 exit ;; M88*:*:R3*:*) # Delta 88k system running SVR3 echo m88k-motorola-sysv3 exit ;; XD88*:*:*:*) # Tektronix XD88 system running UTekV (SVR3) echo m88k-tektronix-sysv3 exit ;; Tek43[0-9][0-9]:UTek:*:*) # Tektronix 4300 system running UTek (BSD) echo m68k-tektronix-bsd exit ;; *:IRIX*:*:*) echo mips-sgi-irix`echo ${UNAME_RELEASE}|sed -e 's/-/_/g'` exit ;; ????????:AIX?:[12].1:2) # AIX 2.2.1 or AIX 2.1.1 is RT/PC AIX. echo romp-ibm-aix # uname -m gives an 8 hex-code CPU id exit ;; # Note that: echo "'`uname -s`'" gives 'AIX ' i*86:AIX:*:*) echo i386-ibm-aix exit ;; ia64:AIX:*:*) if [ -x /usr/bin/oslevel ] ; then IBM_REV=`/usr/bin/oslevel` else IBM_REV=${UNAME_VERSION}.${UNAME_RELEASE} fi echo ${UNAME_MACHINE}-ibm-aix${IBM_REV} exit ;; *:AIX:2:3) if grep bos325 /usr/include/stdio.h >/dev/null 2>&1; then eval $set_cc_for_build sed 's/^ //' << EOF >$dummy.c #include main() { if (!__power_pc()) exit(1); puts("powerpc-ibm-aix3.2.5"); exit(0); } EOF if $CC_FOR_BUILD -o $dummy $dummy.c && SYSTEM_NAME=`$dummy` then echo "$SYSTEM_NAME" else echo rs6000-ibm-aix3.2.5 fi elif grep bos324 /usr/include/stdio.h >/dev/null 2>&1; then echo rs6000-ibm-aix3.2.4 else echo rs6000-ibm-aix3.2 fi exit ;; *:AIX:*:[4567]) IBM_CPU_ID=`/usr/sbin/lsdev -C -c processor -S available | sed 1q | awk '{ print $1 }'` if /usr/sbin/lsattr -El ${IBM_CPU_ID} | grep ' POWER' >/dev/null 2>&1; then IBM_ARCH=rs6000 else IBM_ARCH=powerpc fi if [ -x /usr/bin/oslevel ] ; then IBM_REV=`/usr/bin/oslevel` else IBM_REV=${UNAME_VERSION}.${UNAME_RELEASE} fi echo ${IBM_ARCH}-ibm-aix${IBM_REV} exit ;; *:AIX:*:*) echo rs6000-ibm-aix exit ;; ibmrt:4.4BSD:*|romp-ibm:BSD:*) echo romp-ibm-bsd4.4 exit ;; ibmrt:*BSD:*|romp-ibm:BSD:*) # covers RT/PC BSD and echo romp-ibm-bsd${UNAME_RELEASE} # 4.3 with uname added to exit ;; # report: romp-ibm BSD 4.3 *:BOSX:*:*) echo rs6000-bull-bosx exit ;; DPX/2?00:B.O.S.:*:*) echo m68k-bull-sysv3 exit ;; 9000/[34]??:4.3bsd:1.*:*) echo m68k-hp-bsd exit ;; hp300:4.4BSD:*:* | 9000/[34]??:4.3bsd:2.*:*) echo m68k-hp-bsd4.4 exit ;; 9000/[34678]??:HP-UX:*:*) HPUX_REV=`echo ${UNAME_RELEASE}|sed -e 's/[^.]*.[0B]*//'` case "${UNAME_MACHINE}" in 9000/31? ) HP_ARCH=m68000 ;; 9000/[34]?? ) HP_ARCH=m68k ;; 9000/[678][0-9][0-9]) if [ -x /usr/bin/getconf ]; then sc_cpu_version=`/usr/bin/getconf SC_CPU_VERSION 2>/dev/null` sc_kernel_bits=`/usr/bin/getconf SC_KERNEL_BITS 2>/dev/null` case "${sc_cpu_version}" in 523) HP_ARCH="hppa1.0" ;; # CPU_PA_RISC1_0 528) HP_ARCH="hppa1.1" ;; # CPU_PA_RISC1_1 532) # CPU_PA_RISC2_0 case "${sc_kernel_bits}" in 32) HP_ARCH="hppa2.0n" ;; 64) HP_ARCH="hppa2.0w" ;; '') HP_ARCH="hppa2.0" ;; # HP-UX 10.20 esac ;; esac fi if [ "${HP_ARCH}" = "" ]; then eval $set_cc_for_build sed 's/^ //' << EOF >$dummy.c #define _HPUX_SOURCE #include #include int main () { #if defined(_SC_KERNEL_BITS) long bits = sysconf(_SC_KERNEL_BITS); #endif long cpu = sysconf (_SC_CPU_VERSION); switch (cpu) { case CPU_PA_RISC1_0: puts ("hppa1.0"); break; case CPU_PA_RISC1_1: puts ("hppa1.1"); break; case CPU_PA_RISC2_0: #if defined(_SC_KERNEL_BITS) switch (bits) { case 64: puts ("hppa2.0w"); break; case 32: puts ("hppa2.0n"); break; default: puts ("hppa2.0"); break; } break; #else /* !defined(_SC_KERNEL_BITS) */ puts ("hppa2.0"); break; #endif default: puts ("hppa1.0"); break; } exit (0); } EOF (CCOPTS= $CC_FOR_BUILD -o $dummy $dummy.c 2>/dev/null) && HP_ARCH=`$dummy` test -z "$HP_ARCH" && HP_ARCH=hppa fi ;; esac if [ ${HP_ARCH} = "hppa2.0w" ] then eval $set_cc_for_build # hppa2.0w-hp-hpux* has a 64-bit kernel and a compiler generating # 32-bit code. hppa64-hp-hpux* has the same kernel and a compiler # generating 64-bit code. GNU and HP use different nomenclature: # # $ CC_FOR_BUILD=cc ./config.guess # => hppa2.0w-hp-hpux11.23 # $ CC_FOR_BUILD="cc +DA2.0w" ./config.guess # => hppa64-hp-hpux11.23 if echo __LP64__ | (CCOPTS= $CC_FOR_BUILD -E - 2>/dev/null) | grep -q __LP64__ then HP_ARCH="hppa2.0w" else HP_ARCH="hppa64" fi fi echo ${HP_ARCH}-hp-hpux${HPUX_REV} exit ;; ia64:HP-UX:*:*) HPUX_REV=`echo ${UNAME_RELEASE}|sed -e 's/[^.]*.[0B]*//'` echo ia64-hp-hpux${HPUX_REV} exit ;; 3050*:HI-UX:*:*) eval $set_cc_for_build sed 's/^ //' << EOF >$dummy.c #include int main () { long cpu = sysconf (_SC_CPU_VERSION); /* The order matters, because CPU_IS_HP_MC68K erroneously returns true for CPU_PA_RISC1_0. CPU_IS_PA_RISC returns correct results, however. */ if (CPU_IS_PA_RISC (cpu)) { switch (cpu) { case CPU_PA_RISC1_0: puts ("hppa1.0-hitachi-hiuxwe2"); break; case CPU_PA_RISC1_1: puts ("hppa1.1-hitachi-hiuxwe2"); break; case CPU_PA_RISC2_0: puts ("hppa2.0-hitachi-hiuxwe2"); break; default: puts ("hppa-hitachi-hiuxwe2"); break; } } else if (CPU_IS_HP_MC68K (cpu)) puts ("m68k-hitachi-hiuxwe2"); else puts ("unknown-hitachi-hiuxwe2"); exit (0); } EOF $CC_FOR_BUILD -o $dummy $dummy.c && SYSTEM_NAME=`$dummy` && { echo "$SYSTEM_NAME"; exit; } echo unknown-hitachi-hiuxwe2 exit ;; 9000/7??:4.3bsd:*:* | 9000/8?[79]:4.3bsd:*:* ) echo hppa1.1-hp-bsd exit ;; 9000/8??:4.3bsd:*:*) echo hppa1.0-hp-bsd exit ;; *9??*:MPE/iX:*:* | *3000*:MPE/iX:*:*) echo hppa1.0-hp-mpeix exit ;; hp7??:OSF1:*:* | hp8?[79]:OSF1:*:* ) echo hppa1.1-hp-osf exit ;; hp8??:OSF1:*:*) echo hppa1.0-hp-osf exit ;; i*86:OSF1:*:*) if [ -x /usr/sbin/sysversion ] ; then echo ${UNAME_MACHINE}-unknown-osf1mk else echo ${UNAME_MACHINE}-unknown-osf1 fi exit ;; parisc*:Lites*:*:*) echo hppa1.1-hp-lites exit ;; C1*:ConvexOS:*:* | convex:ConvexOS:C1*:*) echo c1-convex-bsd exit ;; C2*:ConvexOS:*:* | convex:ConvexOS:C2*:*) if getsysinfo -f scalar_acc then echo c32-convex-bsd else echo c2-convex-bsd fi exit ;; C34*:ConvexOS:*:* | convex:ConvexOS:C34*:*) echo c34-convex-bsd exit ;; C38*:ConvexOS:*:* | convex:ConvexOS:C38*:*) echo c38-convex-bsd exit ;; C4*:ConvexOS:*:* | convex:ConvexOS:C4*:*) echo c4-convex-bsd exit ;; CRAY*Y-MP:*:*:*) echo ymp-cray-unicos${UNAME_RELEASE} | sed -e 's/\.[^.]*$/.X/' exit ;; CRAY*[A-Z]90:*:*:*) echo ${UNAME_MACHINE}-cray-unicos${UNAME_RELEASE} \ | sed -e 's/CRAY.*\([A-Z]90\)/\1/' \ -e y/ABCDEFGHIJKLMNOPQRSTUVWXYZ/abcdefghijklmnopqrstuvwxyz/ \ -e 's/\.[^.]*$/.X/' exit ;; CRAY*TS:*:*:*) echo t90-cray-unicos${UNAME_RELEASE} | sed -e 's/\.[^.]*$/.X/' exit ;; CRAY*T3E:*:*:*) echo alphaev5-cray-unicosmk${UNAME_RELEASE} | sed -e 's/\.[^.]*$/.X/' exit ;; CRAY*SV1:*:*:*) echo sv1-cray-unicos${UNAME_RELEASE} | sed -e 's/\.[^.]*$/.X/' exit ;; *:UNICOS/mp:*:*) echo craynv-cray-unicosmp${UNAME_RELEASE} | sed -e 's/\.[^.]*$/.X/' exit ;; F30[01]:UNIX_System_V:*:* | F700:UNIX_System_V:*:*) FUJITSU_PROC=`uname -m | tr 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' 'abcdefghijklmnopqrstuvwxyz'` FUJITSU_SYS=`uname -p | tr 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' 'abcdefghijklmnopqrstuvwxyz' | sed -e 's/\///'` FUJITSU_REL=`echo ${UNAME_RELEASE} | sed -e 's/ /_/'` echo "${FUJITSU_PROC}-fujitsu-${FUJITSU_SYS}${FUJITSU_REL}" exit ;; 5000:UNIX_System_V:4.*:*) FUJITSU_SYS=`uname -p | tr 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' 'abcdefghijklmnopqrstuvwxyz' | sed -e 's/\///'` FUJITSU_REL=`echo ${UNAME_RELEASE} | tr 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' 'abcdefghijklmnopqrstuvwxyz' | sed -e 's/ /_/'` echo "sparc-fujitsu-${FUJITSU_SYS}${FUJITSU_REL}" exit ;; i*86:BSD/386:*:* | i*86:BSD/OS:*:* | *:Ascend\ Embedded/OS:*:*) echo ${UNAME_MACHINE}-pc-bsdi${UNAME_RELEASE} exit ;; sparc*:BSD/OS:*:*) echo sparc-unknown-bsdi${UNAME_RELEASE} exit ;; *:BSD/OS:*:*) echo ${UNAME_MACHINE}-unknown-bsdi${UNAME_RELEASE} exit ;; *:FreeBSD:*:*) UNAME_PROCESSOR=`/usr/bin/uname -p` case ${UNAME_PROCESSOR} in amd64) echo x86_64-unknown-freebsd`echo ${UNAME_RELEASE}|sed -e 's/[-(].*//'` ;; *) echo ${UNAME_PROCESSOR}-unknown-freebsd`echo ${UNAME_RELEASE}|sed -e 's/[-(].*//'` ;; esac exit ;; i*:CYGWIN*:*) echo ${UNAME_MACHINE}-pc-cygwin exit ;; *:MINGW64*:*) echo ${UNAME_MACHINE}-pc-mingw64 exit ;; *:MINGW*:*) echo ${UNAME_MACHINE}-pc-mingw32 exit ;; i*:MSYS*:*) echo ${UNAME_MACHINE}-pc-msys exit ;; i*:windows32*:*) # uname -m includes "-pc" on this system. echo ${UNAME_MACHINE}-mingw32 exit ;; i*:PW*:*) echo ${UNAME_MACHINE}-pc-pw32 exit ;; *:Interix*:*) case ${UNAME_MACHINE} in x86) echo i586-pc-interix${UNAME_RELEASE} exit ;; authenticamd | genuineintel | EM64T) echo x86_64-unknown-interix${UNAME_RELEASE} exit ;; IA64) echo ia64-unknown-interix${UNAME_RELEASE} exit ;; esac ;; [345]86:Windows_95:* | [345]86:Windows_98:* | [345]86:Windows_NT:*) echo i${UNAME_MACHINE}-pc-mks exit ;; 8664:Windows_NT:*) echo x86_64-pc-mks exit ;; i*:Windows_NT*:* | Pentium*:Windows_NT*:*) # How do we know it's Interix rather than the generic POSIX subsystem? # It also conflicts with pre-2.0 versions of AT&T UWIN. Should we # UNAME_MACHINE based on the output of uname instead of i386? echo i586-pc-interix exit ;; i*:UWIN*:*) echo ${UNAME_MACHINE}-pc-uwin exit ;; amd64:CYGWIN*:*:* | x86_64:CYGWIN*:*:*) echo x86_64-unknown-cygwin exit ;; p*:CYGWIN*:*) echo powerpcle-unknown-cygwin exit ;; prep*:SunOS:5.*:*) echo powerpcle-unknown-solaris2`echo ${UNAME_RELEASE}|sed -e 's/[^.]*//'` exit ;; *:GNU:*:*) # the GNU system echo `echo ${UNAME_MACHINE}|sed -e 's,[-/].*$,,'`-unknown-${LIBC}`echo ${UNAME_RELEASE}|sed -e 's,/.*$,,'` exit ;; *:GNU/*:*:*) # other systems with GNU libc and userland echo ${UNAME_MACHINE}-unknown-`echo ${UNAME_SYSTEM} | sed 's,^[^/]*/,,' | tr '[A-Z]' '[a-z]'``echo ${UNAME_RELEASE}|sed -e 's/[-(].*//'`-${LIBC} exit ;; i*86:Minix:*:*) echo ${UNAME_MACHINE}-pc-minix exit ;; aarch64:Linux:*:*) echo ${UNAME_MACHINE}-unknown-linux-${LIBC} exit ;; aarch64_be:Linux:*:*) UNAME_MACHINE=aarch64_be echo ${UNAME_MACHINE}-unknown-linux-${LIBC} exit ;; alpha:Linux:*:*) case `sed -n '/^cpu model/s/^.*: \(.*\)/\1/p' < /proc/cpuinfo` in EV5) UNAME_MACHINE=alphaev5 ;; EV56) UNAME_MACHINE=alphaev56 ;; PCA56) UNAME_MACHINE=alphapca56 ;; PCA57) UNAME_MACHINE=alphapca56 ;; EV6) UNAME_MACHINE=alphaev6 ;; EV67) UNAME_MACHINE=alphaev67 ;; EV68*) UNAME_MACHINE=alphaev68 ;; esac objdump --private-headers /bin/sh | grep -q ld.so.1 if test "$?" = 0 ; then LIBC="gnulibc1" ; fi echo ${UNAME_MACHINE}-unknown-linux-${LIBC} exit ;; arm*:Linux:*:*) eval $set_cc_for_build if echo __ARM_EABI__ | $CC_FOR_BUILD -E - 2>/dev/null \ | grep -q __ARM_EABI__ then echo ${UNAME_MACHINE}-unknown-linux-${LIBC} else if echo __ARM_PCS_VFP | $CC_FOR_BUILD -E - 2>/dev/null \ | grep -q __ARM_PCS_VFP then echo ${UNAME_MACHINE}-unknown-linux-${LIBC}eabi else echo ${UNAME_MACHINE}-unknown-linux-${LIBC}eabihf fi fi exit ;; avr32*:Linux:*:*) echo ${UNAME_MACHINE}-unknown-linux-${LIBC} exit ;; cris:Linux:*:*) echo ${UNAME_MACHINE}-axis-linux-${LIBC} exit ;; crisv32:Linux:*:*) echo ${UNAME_MACHINE}-axis-linux-${LIBC} exit ;; frv:Linux:*:*) echo ${UNAME_MACHINE}-unknown-linux-${LIBC} exit ;; hexagon:Linux:*:*) echo ${UNAME_MACHINE}-unknown-linux-${LIBC} exit ;; i*86:Linux:*:*) echo ${UNAME_MACHINE}-pc-linux-${LIBC} exit ;; ia64:Linux:*:*) echo ${UNAME_MACHINE}-unknown-linux-${LIBC} exit ;; m32r*:Linux:*:*) echo ${UNAME_MACHINE}-unknown-linux-${LIBC} exit ;; m68*:Linux:*:*) echo ${UNAME_MACHINE}-unknown-linux-${LIBC} exit ;; mips:Linux:*:* | mips64:Linux:*:*) eval $set_cc_for_build sed 's/^ //' << EOF >$dummy.c #undef CPU #undef ${UNAME_MACHINE} #undef ${UNAME_MACHINE}el #if defined(__MIPSEL__) || defined(__MIPSEL) || defined(_MIPSEL) || defined(MIPSEL) CPU=${UNAME_MACHINE}el #else #if defined(__MIPSEB__) || defined(__MIPSEB) || defined(_MIPSEB) || defined(MIPSEB) CPU=${UNAME_MACHINE} #else CPU= #endif #endif EOF eval `$CC_FOR_BUILD -E $dummy.c 2>/dev/null | grep '^CPU'` test x"${CPU}" != x && { echo "${CPU}-unknown-linux-${LIBC}"; exit; } ;; or32:Linux:*:*) echo ${UNAME_MACHINE}-unknown-linux-${LIBC} exit ;; padre:Linux:*:*) echo sparc-unknown-linux-${LIBC} exit ;; parisc64:Linux:*:* | hppa64:Linux:*:*) echo hppa64-unknown-linux-${LIBC} exit ;; parisc:Linux:*:* | hppa:Linux:*:*) # Look for CPU level case `grep '^cpu[^a-z]*:' /proc/cpuinfo 2>/dev/null | cut -d' ' -f2` in PA7*) echo hppa1.1-unknown-linux-${LIBC} ;; PA8*) echo hppa2.0-unknown-linux-${LIBC} ;; *) echo hppa-unknown-linux-${LIBC} ;; esac exit ;; ppc64:Linux:*:*) echo powerpc64-unknown-linux-${LIBC} exit ;; ppc:Linux:*:*) echo powerpc-unknown-linux-${LIBC} exit ;; s390:Linux:*:* | s390x:Linux:*:*) echo ${UNAME_MACHINE}-ibm-linux exit ;; sh64*:Linux:*:*) echo ${UNAME_MACHINE}-unknown-linux-${LIBC} exit ;; sh*:Linux:*:*) echo ${UNAME_MACHINE}-unknown-linux-${LIBC} exit ;; sparc:Linux:*:* | sparc64:Linux:*:*) echo ${UNAME_MACHINE}-unknown-linux-${LIBC} exit ;; tile*:Linux:*:*) echo ${UNAME_MACHINE}-unknown-linux-${LIBC} exit ;; vax:Linux:*:*) echo ${UNAME_MACHINE}-dec-linux-${LIBC} exit ;; x86_64:Linux:*:*) echo ${UNAME_MACHINE}-unknown-linux-${LIBC} exit ;; xtensa*:Linux:*:*) echo ${UNAME_MACHINE}-unknown-linux-${LIBC} exit ;; i*86:DYNIX/ptx:4*:*) # ptx 4.0 does uname -s correctly, with DYNIX/ptx in there. # earlier versions are messed up and put the nodename in both # sysname and nodename. echo i386-sequent-sysv4 exit ;; i*86:UNIX_SV:4.2MP:2.*) # Unixware is an offshoot of SVR4, but it has its own version # number series starting with 2... # I am not positive that other SVR4 systems won't match this, # I just have to hope. -- rms. # Use sysv4.2uw... so that sysv4* matches it. echo ${UNAME_MACHINE}-pc-sysv4.2uw${UNAME_VERSION} exit ;; i*86:OS/2:*:*) # If we were able to find `uname', then EMX Unix compatibility # is probably installed. echo ${UNAME_MACHINE}-pc-os2-emx exit ;; i*86:XTS-300:*:STOP) echo ${UNAME_MACHINE}-unknown-stop exit ;; i*86:atheos:*:*) echo ${UNAME_MACHINE}-unknown-atheos exit ;; i*86:syllable:*:*) echo ${UNAME_MACHINE}-pc-syllable exit ;; i*86:LynxOS:2.*:* | i*86:LynxOS:3.[01]*:* | i*86:LynxOS:4.[02]*:*) echo i386-unknown-lynxos${UNAME_RELEASE} exit ;; i*86:*DOS:*:*) echo ${UNAME_MACHINE}-pc-msdosdjgpp exit ;; i*86:*:4.*:* | i*86:SYSTEM_V:4.*:*) UNAME_REL=`echo ${UNAME_RELEASE} | sed 's/\/MP$//'` if grep Novell /usr/include/link.h >/dev/null 2>/dev/null; then echo ${UNAME_MACHINE}-univel-sysv${UNAME_REL} else echo ${UNAME_MACHINE}-pc-sysv${UNAME_REL} fi exit ;; i*86:*:5:[678]*) # UnixWare 7.x, OpenUNIX and OpenServer 6. case `/bin/uname -X | grep "^Machine"` in *486*) UNAME_MACHINE=i486 ;; *Pentium) UNAME_MACHINE=i586 ;; *Pent*|*Celeron) UNAME_MACHINE=i686 ;; esac echo ${UNAME_MACHINE}-unknown-sysv${UNAME_RELEASE}${UNAME_SYSTEM}${UNAME_VERSION} exit ;; i*86:*:3.2:*) if test -f /usr/options/cb.name; then UNAME_REL=`sed -n 's/.*Version //p' /dev/null >/dev/null ; then UNAME_REL=`(/bin/uname -X|grep Release|sed -e 's/.*= //')` (/bin/uname -X|grep i80486 >/dev/null) && UNAME_MACHINE=i486 (/bin/uname -X|grep '^Machine.*Pentium' >/dev/null) \ && UNAME_MACHINE=i586 (/bin/uname -X|grep '^Machine.*Pent *II' >/dev/null) \ && UNAME_MACHINE=i686 (/bin/uname -X|grep '^Machine.*Pentium Pro' >/dev/null) \ && UNAME_MACHINE=i686 echo ${UNAME_MACHINE}-pc-sco$UNAME_REL else echo ${UNAME_MACHINE}-pc-sysv32 fi exit ;; pc:*:*:*) # Left here for compatibility: # uname -m prints for DJGPP always 'pc', but it prints nothing about # the processor, so we play safe by assuming i586. # Note: whatever this is, it MUST be the same as what config.sub # prints for the "djgpp" host, or else GDB configury will decide that # this is a cross-build. echo i586-pc-msdosdjgpp exit ;; Intel:Mach:3*:*) echo i386-pc-mach3 exit ;; paragon:*:*:*) echo i860-intel-osf1 exit ;; i860:*:4.*:*) # i860-SVR4 if grep Stardent /usr/include/sys/uadmin.h >/dev/null 2>&1 ; then echo i860-stardent-sysv${UNAME_RELEASE} # Stardent Vistra i860-SVR4 else # Add other i860-SVR4 vendors below as they are discovered. echo i860-unknown-sysv${UNAME_RELEASE} # Unknown i860-SVR4 fi exit ;; mini*:CTIX:SYS*5:*) # "miniframe" echo m68010-convergent-sysv exit ;; mc68k:UNIX:SYSTEM5:3.51m) echo m68k-convergent-sysv exit ;; M680?0:D-NIX:5.3:*) echo m68k-diab-dnix exit ;; M68*:*:R3V[5678]*:*) test -r /sysV68 && { echo 'm68k-motorola-sysv'; exit; } ;; 3[345]??:*:4.0:3.0 | 3[34]??A:*:4.0:3.0 | 3[34]??,*:*:4.0:3.0 | 3[34]??/*:*:4.0:3.0 | 4400:*:4.0:3.0 | 4850:*:4.0:3.0 | SKA40:*:4.0:3.0 | SDS2:*:4.0:3.0 | SHG2:*:4.0:3.0 | S7501*:*:4.0:3.0) OS_REL='' test -r /etc/.relid \ && OS_REL=.`sed -n 's/[^ ]* [^ ]* \([0-9][0-9]\).*/\1/p' < /etc/.relid` /bin/uname -p 2>/dev/null | grep 86 >/dev/null \ && { echo i486-ncr-sysv4.3${OS_REL}; exit; } /bin/uname -p 2>/dev/null | /bin/grep entium >/dev/null \ && { echo i586-ncr-sysv4.3${OS_REL}; exit; } ;; 3[34]??:*:4.0:* | 3[34]??,*:*:4.0:*) /bin/uname -p 2>/dev/null | grep 86 >/dev/null \ && { echo i486-ncr-sysv4; exit; } ;; NCR*:*:4.2:* | MPRAS*:*:4.2:*) OS_REL='.3' test -r /etc/.relid \ && OS_REL=.`sed -n 's/[^ ]* [^ ]* \([0-9][0-9]\).*/\1/p' < /etc/.relid` /bin/uname -p 2>/dev/null | grep 86 >/dev/null \ && { echo i486-ncr-sysv4.3${OS_REL}; exit; } /bin/uname -p 2>/dev/null | /bin/grep entium >/dev/null \ && { echo i586-ncr-sysv4.3${OS_REL}; exit; } /bin/uname -p 2>/dev/null | /bin/grep pteron >/dev/null \ && { echo i586-ncr-sysv4.3${OS_REL}; exit; } ;; m68*:LynxOS:2.*:* | m68*:LynxOS:3.0*:*) echo m68k-unknown-lynxos${UNAME_RELEASE} exit ;; mc68030:UNIX_System_V:4.*:*) echo m68k-atari-sysv4 exit ;; TSUNAMI:LynxOS:2.*:*) echo sparc-unknown-lynxos${UNAME_RELEASE} exit ;; rs6000:LynxOS:2.*:*) echo rs6000-unknown-lynxos${UNAME_RELEASE} exit ;; PowerPC:LynxOS:2.*:* | PowerPC:LynxOS:3.[01]*:* | PowerPC:LynxOS:4.[02]*:*) echo powerpc-unknown-lynxos${UNAME_RELEASE} exit ;; SM[BE]S:UNIX_SV:*:*) echo mips-dde-sysv${UNAME_RELEASE} exit ;; RM*:ReliantUNIX-*:*:*) echo mips-sni-sysv4 exit ;; RM*:SINIX-*:*:*) echo mips-sni-sysv4 exit ;; *:SINIX-*:*:*) if uname -p 2>/dev/null >/dev/null ; then UNAME_MACHINE=`(uname -p) 2>/dev/null` echo ${UNAME_MACHINE}-sni-sysv4 else echo ns32k-sni-sysv fi exit ;; PENTIUM:*:4.0*:*) # Unisys `ClearPath HMP IX 4000' SVR4/MP effort # says echo i586-unisys-sysv4 exit ;; *:UNIX_System_V:4*:FTX*) # From Gerald Hewes . # How about differentiating between stratus architectures? -djm echo hppa1.1-stratus-sysv4 exit ;; *:*:*:FTX*) # From seanf@swdc.stratus.com. echo i860-stratus-sysv4 exit ;; i*86:VOS:*:*) # From Paul.Green@stratus.com. echo ${UNAME_MACHINE}-stratus-vos exit ;; *:VOS:*:*) # From Paul.Green@stratus.com. echo hppa1.1-stratus-vos exit ;; mc68*:A/UX:*:*) echo m68k-apple-aux${UNAME_RELEASE} exit ;; news*:NEWS-OS:6*:*) echo mips-sony-newsos6 exit ;; R[34]000:*System_V*:*:* | R4000:UNIX_SYSV:*:* | R*000:UNIX_SV:*:*) if [ -d /usr/nec ]; then echo mips-nec-sysv${UNAME_RELEASE} else echo mips-unknown-sysv${UNAME_RELEASE} fi exit ;; BeBox:BeOS:*:*) # BeOS running on hardware made by Be, PPC only. echo powerpc-be-beos exit ;; BeMac:BeOS:*:*) # BeOS running on Mac or Mac clone, PPC only. echo powerpc-apple-beos exit ;; BePC:BeOS:*:*) # BeOS running on Intel PC compatible. echo i586-pc-beos exit ;; BePC:Haiku:*:*) # Haiku running on Intel PC compatible. echo i586-pc-haiku exit ;; x86_64:Haiku:*:*) echo x86_64-unknown-haiku exit ;; SX-4:SUPER-UX:*:*) echo sx4-nec-superux${UNAME_RELEASE} exit ;; SX-5:SUPER-UX:*:*) echo sx5-nec-superux${UNAME_RELEASE} exit ;; SX-6:SUPER-UX:*:*) echo sx6-nec-superux${UNAME_RELEASE} exit ;; SX-7:SUPER-UX:*:*) echo sx7-nec-superux${UNAME_RELEASE} exit ;; SX-8:SUPER-UX:*:*) echo sx8-nec-superux${UNAME_RELEASE} exit ;; SX-8R:SUPER-UX:*:*) echo sx8r-nec-superux${UNAME_RELEASE} exit ;; Power*:Rhapsody:*:*) echo powerpc-apple-rhapsody${UNAME_RELEASE} exit ;; *:Rhapsody:*:*) echo ${UNAME_MACHINE}-apple-rhapsody${UNAME_RELEASE} exit ;; *:Darwin:*:*) UNAME_PROCESSOR=`uname -p` || UNAME_PROCESSOR=unknown case $UNAME_PROCESSOR in i386) eval $set_cc_for_build if [ "$CC_FOR_BUILD" != 'no_compiler_found' ]; then if (echo '#ifdef __LP64__'; echo IS_64BIT_ARCH; echo '#endif') | \ (CCOPTS= $CC_FOR_BUILD -E - 2>/dev/null) | \ grep IS_64BIT_ARCH >/dev/null then UNAME_PROCESSOR="x86_64" fi fi ;; unknown) UNAME_PROCESSOR=powerpc ;; esac echo ${UNAME_PROCESSOR}-apple-darwin${UNAME_RELEASE} exit ;; *:procnto*:*:* | *:QNX:[0123456789]*:*) UNAME_PROCESSOR=`uname -p` if test "$UNAME_PROCESSOR" = "x86"; then UNAME_PROCESSOR=i386 UNAME_MACHINE=pc fi echo ${UNAME_PROCESSOR}-${UNAME_MACHINE}-nto-qnx${UNAME_RELEASE} exit ;; *:QNX:*:4*) echo i386-pc-qnx exit ;; NEO-?:NONSTOP_KERNEL:*:*) echo neo-tandem-nsk${UNAME_RELEASE} exit ;; NSE-*:NONSTOP_KERNEL:*:*) echo nse-tandem-nsk${UNAME_RELEASE} exit ;; NSR-?:NONSTOP_KERNEL:*:*) echo nsr-tandem-nsk${UNAME_RELEASE} exit ;; *:NonStop-UX:*:*) echo mips-compaq-nonstopux exit ;; BS2000:POSIX*:*:*) echo bs2000-siemens-sysv exit ;; DS/*:UNIX_System_V:*:*) echo ${UNAME_MACHINE}-${UNAME_SYSTEM}-${UNAME_RELEASE} exit ;; *:Plan9:*:*) # "uname -m" is not consistent, so use $cputype instead. 386 # is converted to i386 for consistency with other x86 # operating systems. if test "$cputype" = "386"; then UNAME_MACHINE=i386 else UNAME_MACHINE="$cputype" fi echo ${UNAME_MACHINE}-unknown-plan9 exit ;; *:TOPS-10:*:*) echo pdp10-unknown-tops10 exit ;; *:TENEX:*:*) echo pdp10-unknown-tenex exit ;; KS10:TOPS-20:*:* | KL10:TOPS-20:*:* | TYPE4:TOPS-20:*:*) echo pdp10-dec-tops20 exit ;; XKL-1:TOPS-20:*:* | TYPE5:TOPS-20:*:*) echo pdp10-xkl-tops20 exit ;; *:TOPS-20:*:*) echo pdp10-unknown-tops20 exit ;; *:ITS:*:*) echo pdp10-unknown-its exit ;; SEI:*:*:SEIUX) echo mips-sei-seiux${UNAME_RELEASE} exit ;; *:DragonFly:*:*) echo ${UNAME_MACHINE}-unknown-dragonfly`echo ${UNAME_RELEASE}|sed -e 's/[-(].*//'` exit ;; *:*VMS:*:*) UNAME_MACHINE=`(uname -p) 2>/dev/null` case "${UNAME_MACHINE}" in A*) echo alpha-dec-vms ; exit ;; I*) echo ia64-dec-vms ; exit ;; V*) echo vax-dec-vms ; exit ;; esac ;; *:XENIX:*:SysV) echo i386-pc-xenix exit ;; i*86:skyos:*:*) echo ${UNAME_MACHINE}-pc-skyos`echo ${UNAME_RELEASE}` | sed -e 's/ .*$//' exit ;; i*86:rdos:*:*) echo ${UNAME_MACHINE}-pc-rdos exit ;; i*86:AROS:*:*) echo ${UNAME_MACHINE}-pc-aros exit ;; x86_64:VMkernel:*:*) echo ${UNAME_MACHINE}-unknown-esx exit ;; esac eval $set_cc_for_build cat >$dummy.c < # include #endif main () { #if defined (sony) #if defined (MIPSEB) /* BFD wants "bsd" instead of "newsos". Perhaps BFD should be changed, I don't know.... */ printf ("mips-sony-bsd\n"); exit (0); #else #include printf ("m68k-sony-newsos%s\n", #ifdef NEWSOS4 "4" #else "" #endif ); exit (0); #endif #endif #if defined (__arm) && defined (__acorn) && defined (__unix) printf ("arm-acorn-riscix\n"); exit (0); #endif #if defined (hp300) && !defined (hpux) printf ("m68k-hp-bsd\n"); exit (0); #endif #if defined (NeXT) #if !defined (__ARCHITECTURE__) #define __ARCHITECTURE__ "m68k" #endif int version; version=`(hostinfo | sed -n 's/.*NeXT Mach \([0-9]*\).*/\1/p') 2>/dev/null`; if (version < 4) printf ("%s-next-nextstep%d\n", __ARCHITECTURE__, version); else printf ("%s-next-openstep%d\n", __ARCHITECTURE__, version); exit (0); #endif #if defined (MULTIMAX) || defined (n16) #if defined (UMAXV) printf ("ns32k-encore-sysv\n"); exit (0); #else #if defined (CMU) printf ("ns32k-encore-mach\n"); exit (0); #else printf ("ns32k-encore-bsd\n"); exit (0); #endif #endif #endif #if defined (__386BSD__) printf ("i386-pc-bsd\n"); exit (0); #endif #if defined (sequent) #if defined (i386) printf ("i386-sequent-dynix\n"); exit (0); #endif #if defined (ns32000) printf ("ns32k-sequent-dynix\n"); exit (0); #endif #endif #if defined (_SEQUENT_) struct utsname un; uname(&un); if (strncmp(un.version, "V2", 2) == 0) { printf ("i386-sequent-ptx2\n"); exit (0); } if (strncmp(un.version, "V1", 2) == 0) { /* XXX is V1 correct? */ printf ("i386-sequent-ptx1\n"); exit (0); } printf ("i386-sequent-ptx\n"); exit (0); #endif #if defined (vax) # if !defined (ultrix) # include # if defined (BSD) # if BSD == 43 printf ("vax-dec-bsd4.3\n"); exit (0); # else # if BSD == 199006 printf ("vax-dec-bsd4.3reno\n"); exit (0); # else printf ("vax-dec-bsd\n"); exit (0); # endif # endif # else printf ("vax-dec-bsd\n"); exit (0); # endif # else printf ("vax-dec-ultrix\n"); exit (0); # endif #endif #if defined (alliant) && defined (i860) printf ("i860-alliant-bsd\n"); exit (0); #endif exit (1); } EOF $CC_FOR_BUILD -o $dummy $dummy.c 2>/dev/null && SYSTEM_NAME=`$dummy` && { echo "$SYSTEM_NAME"; exit; } # Apollos put the system type in the environment. test -d /usr/apollo && { echo ${ISP}-apollo-${SYSTYPE}; exit; } # Convex versions that predate uname can use getsysinfo(1) if [ -x /usr/convex/getsysinfo ] then case `getsysinfo -f cpu_type` in c1*) echo c1-convex-bsd exit ;; c2*) if getsysinfo -f scalar_acc then echo c32-convex-bsd else echo c2-convex-bsd fi exit ;; c34*) echo c34-convex-bsd exit ;; c38*) echo c38-convex-bsd exit ;; c4*) echo c4-convex-bsd exit ;; esac fi cat >&2 < in order to provide the needed information to handle your system. config.guess timestamp = $timestamp uname -m = `(uname -m) 2>/dev/null || echo unknown` uname -r = `(uname -r) 2>/dev/null || echo unknown` uname -s = `(uname -s) 2>/dev/null || echo unknown` uname -v = `(uname -v) 2>/dev/null || echo unknown` /usr/bin/uname -p = `(/usr/bin/uname -p) 2>/dev/null` /bin/uname -X = `(/bin/uname -X) 2>/dev/null` hostinfo = `(hostinfo) 2>/dev/null` /bin/universe = `(/bin/universe) 2>/dev/null` /usr/bin/arch -k = `(/usr/bin/arch -k) 2>/dev/null` /bin/arch = `(/bin/arch) 2>/dev/null` /usr/bin/oslevel = `(/usr/bin/oslevel) 2>/dev/null` /usr/convex/getsysinfo = `(/usr/convex/getsysinfo) 2>/dev/null` UNAME_MACHINE = ${UNAME_MACHINE} UNAME_RELEASE = ${UNAME_RELEASE} UNAME_SYSTEM = ${UNAME_SYSTEM} UNAME_VERSION = ${UNAME_VERSION} EOF exit 1 # Local variables: # eval: (add-hook 'write-file-hooks 'time-stamp) # time-stamp-start: "timestamp='" # time-stamp-format: "%:y-%02m-%02d" # time-stamp-end: "'" # End: apache-couchdb-1.5.0/build-aux/install-sh0000755000175000001440000003325612021144127015161 00000000000000#!/bin/sh # install - install a program, script, or datafile scriptversion=2011-01-19.21; # UTC # This originates from X11R5 (mit/util/scripts/install.sh), which was # later released in X11R6 (xc/config/util/install.sh) with the # following copyright and license. # # Copyright (C) 1994 X Consortium # # 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 # X CONSORTIUM BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN # AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNEC- # TION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. # # Except as contained in this notice, the name of the X Consortium shall not # be used in advertising or otherwise to promote the sale, use or other deal- # ings in this Software without prior written authorization from the X Consor- # tium. # # # FSF changes to this file are in the public domain. # # Calling this script install-sh is preferred over install.sh, to prevent # `make' implicit rules from creating a file called install from it # when there is no Makefile. # # This script is compatible with the BSD install script, but was written # from scratch. nl=' ' IFS=" "" $nl" # set DOITPROG to echo to test this script # Don't use :- since 4.3BSD and earlier shells don't like it. doit=${DOITPROG-} if test -z "$doit"; then doit_exec=exec else doit_exec=$doit fi # Put in absolute file names if you don't have them in your path; # or use environment vars. chgrpprog=${CHGRPPROG-chgrp} chmodprog=${CHMODPROG-chmod} chownprog=${CHOWNPROG-chown} cmpprog=${CMPPROG-cmp} cpprog=${CPPROG-cp} mkdirprog=${MKDIRPROG-mkdir} mvprog=${MVPROG-mv} rmprog=${RMPROG-rm} stripprog=${STRIPPROG-strip} posix_glob='?' initialize_posix_glob=' test "$posix_glob" != "?" || { if (set -f) 2>/dev/null; then posix_glob= else posix_glob=: fi } ' posix_mkdir= # Desired mode of installed file. mode=0755 chgrpcmd= chmodcmd=$chmodprog chowncmd= mvcmd=$mvprog rmcmd="$rmprog -f" stripcmd= src= dst= dir_arg= dst_arg= copy_on_change=false no_target_directory= usage="\ Usage: $0 [OPTION]... [-T] SRCFILE DSTFILE or: $0 [OPTION]... SRCFILES... DIRECTORY or: $0 [OPTION]... -t DIRECTORY SRCFILES... or: $0 [OPTION]... -d DIRECTORIES... In the 1st form, copy SRCFILE to DSTFILE. In the 2nd and 3rd, copy all SRCFILES to DIRECTORY. In the 4th, create DIRECTORIES. Options: --help display this help and exit. --version display version info and exit. -c (ignored) -C install only if different (preserve the last data modification time) -d create directories instead of installing files. -g GROUP $chgrpprog installed files to GROUP. -m MODE $chmodprog installed files to MODE. -o USER $chownprog installed files to USER. -s $stripprog installed files. -t DIRECTORY install into DIRECTORY. -T report an error if DSTFILE is a directory. Environment variables override the default commands: CHGRPPROG CHMODPROG CHOWNPROG CMPPROG CPPROG MKDIRPROG MVPROG RMPROG STRIPPROG " while test $# -ne 0; do case $1 in -c) ;; -C) copy_on_change=true;; -d) dir_arg=true;; -g) chgrpcmd="$chgrpprog $2" shift;; --help) echo "$usage"; exit $?;; -m) mode=$2 case $mode in *' '* | *' '* | *' '* | *'*'* | *'?'* | *'['*) echo "$0: invalid mode: $mode" >&2 exit 1;; esac shift;; -o) chowncmd="$chownprog $2" shift;; -s) stripcmd=$stripprog;; -t) dst_arg=$2 # Protect names problematic for `test' and other utilities. case $dst_arg in -* | [=\(\)!]) dst_arg=./$dst_arg;; esac shift;; -T) no_target_directory=true;; --version) echo "$0 $scriptversion"; exit $?;; --) shift break;; -*) echo "$0: invalid option: $1" >&2 exit 1;; *) break;; esac shift done if test $# -ne 0 && test -z "$dir_arg$dst_arg"; then # When -d is used, all remaining arguments are directories to create. # When -t is used, the destination is already specified. # Otherwise, the last argument is the destination. Remove it from $@. for arg do if test -n "$dst_arg"; then # $@ is not empty: it contains at least $arg. set fnord "$@" "$dst_arg" shift # fnord fi shift # arg dst_arg=$arg # Protect names problematic for `test' and other utilities. case $dst_arg in -* | [=\(\)!]) dst_arg=./$dst_arg;; esac done fi if test $# -eq 0; then if test -z "$dir_arg"; then echo "$0: no input file specified." >&2 exit 1 fi # It's OK to call `install-sh -d' without argument. # This can happen when creating conditional directories. exit 0 fi if test -z "$dir_arg"; then do_exit='(exit $ret); exit $ret' trap "ret=129; $do_exit" 1 trap "ret=130; $do_exit" 2 trap "ret=141; $do_exit" 13 trap "ret=143; $do_exit" 15 # Set umask so as not to create temps with too-generous modes. # However, 'strip' requires both read and write access to temps. case $mode in # Optimize common cases. *644) cp_umask=133;; *755) cp_umask=22;; *[0-7]) if test -z "$stripcmd"; then u_plus_rw= else u_plus_rw='% 200' fi cp_umask=`expr '(' 777 - $mode % 1000 ')' $u_plus_rw`;; *) if test -z "$stripcmd"; then u_plus_rw= else u_plus_rw=,u+rw fi cp_umask=$mode$u_plus_rw;; esac fi for src do # Protect names problematic for `test' and other utilities. case $src in -* | [=\(\)!]) src=./$src;; esac if test -n "$dir_arg"; then dst=$src dstdir=$dst test -d "$dstdir" dstdir_status=$? else # Waiting for this to be detected by the "$cpprog $src $dsttmp" command # might cause directories to be created, which would be especially bad # if $src (and thus $dsttmp) contains '*'. if test ! -f "$src" && test ! -d "$src"; then echo "$0: $src does not exist." >&2 exit 1 fi if test -z "$dst_arg"; then echo "$0: no destination specified." >&2 exit 1 fi dst=$dst_arg # If destination is a directory, append the input filename; won't work # if double slashes aren't ignored. if test -d "$dst"; then if test -n "$no_target_directory"; then echo "$0: $dst_arg: Is a directory" >&2 exit 1 fi dstdir=$dst dst=$dstdir/`basename "$src"` dstdir_status=0 else # Prefer dirname, but fall back on a substitute if dirname fails. dstdir=` (dirname "$dst") 2>/dev/null || expr X"$dst" : 'X\(.*[^/]\)//*[^/][^/]*/*$' \| \ X"$dst" : 'X\(//\)[^/]' \| \ X"$dst" : 'X\(//\)$' \| \ X"$dst" : 'X\(/\)' \| . 2>/dev/null || echo X"$dst" | sed '/^X\(.*[^/]\)\/\/*[^/][^/]*\/*$/{ s//\1/ q } /^X\(\/\/\)[^/].*/{ s//\1/ q } /^X\(\/\/\)$/{ s//\1/ q } /^X\(\/\).*/{ s//\1/ q } s/.*/./; q' ` test -d "$dstdir" dstdir_status=$? fi fi obsolete_mkdir_used=false if test $dstdir_status != 0; then case $posix_mkdir in '') # Create intermediate dirs using mode 755 as modified by the umask. # This is like FreeBSD 'install' as of 1997-10-28. umask=`umask` case $stripcmd.$umask in # Optimize common cases. *[2367][2367]) mkdir_umask=$umask;; .*0[02][02] | .[02][02] | .[02]) mkdir_umask=22;; *[0-7]) mkdir_umask=`expr $umask + 22 \ - $umask % 100 % 40 + $umask % 20 \ - $umask % 10 % 4 + $umask % 2 `;; *) mkdir_umask=$umask,go-w;; esac # With -d, create the new directory with the user-specified mode. # Otherwise, rely on $mkdir_umask. if test -n "$dir_arg"; then mkdir_mode=-m$mode else mkdir_mode= fi posix_mkdir=false case $umask in *[123567][0-7][0-7]) # POSIX mkdir -p sets u+wx bits regardless of umask, which # is incompatible with FreeBSD 'install' when (umask & 300) != 0. ;; *) tmpdir=${TMPDIR-/tmp}/ins$RANDOM-$$ trap 'ret=$?; rmdir "$tmpdir/d" "$tmpdir" 2>/dev/null; exit $ret' 0 if (umask $mkdir_umask && exec $mkdirprog $mkdir_mode -p -- "$tmpdir/d") >/dev/null 2>&1 then if test -z "$dir_arg" || { # Check for POSIX incompatibilities with -m. # HP-UX 11.23 and IRIX 6.5 mkdir -m -p sets group- or # other-writeable bit of parent directory when it shouldn't. # FreeBSD 6.1 mkdir -m -p sets mode of existing directory. ls_ld_tmpdir=`ls -ld "$tmpdir"` case $ls_ld_tmpdir in d????-?r-*) different_mode=700;; d????-?--*) different_mode=755;; *) false;; esac && $mkdirprog -m$different_mode -p -- "$tmpdir" && { ls_ld_tmpdir_1=`ls -ld "$tmpdir"` test "$ls_ld_tmpdir" = "$ls_ld_tmpdir_1" } } then posix_mkdir=: fi rmdir "$tmpdir/d" "$tmpdir" else # Remove any dirs left behind by ancient mkdir implementations. rmdir ./$mkdir_mode ./-p ./-- 2>/dev/null fi trap '' 0;; esac;; esac if $posix_mkdir && ( umask $mkdir_umask && $doit_exec $mkdirprog $mkdir_mode -p -- "$dstdir" ) then : else # The umask is ridiculous, or mkdir does not conform to POSIX, # or it failed possibly due to a race condition. Create the # directory the slow way, step by step, checking for races as we go. case $dstdir in /*) prefix='/';; [-=\(\)!]*) prefix='./';; *) prefix='';; esac eval "$initialize_posix_glob" oIFS=$IFS IFS=/ $posix_glob set -f set fnord $dstdir shift $posix_glob set +f IFS=$oIFS prefixes= for d do test X"$d" = X && continue prefix=$prefix$d if test -d "$prefix"; then prefixes= else if $posix_mkdir; then (umask=$mkdir_umask && $doit_exec $mkdirprog $mkdir_mode -p -- "$dstdir") && break # Don't fail if two instances are running concurrently. test -d "$prefix" || exit 1 else case $prefix in *\'*) qprefix=`echo "$prefix" | sed "s/'/'\\\\\\\\''/g"`;; *) qprefix=$prefix;; esac prefixes="$prefixes '$qprefix'" fi fi prefix=$prefix/ done if test -n "$prefixes"; then # Don't fail if two instances are running concurrently. (umask $mkdir_umask && eval "\$doit_exec \$mkdirprog $prefixes") || test -d "$dstdir" || exit 1 obsolete_mkdir_used=true fi fi fi if test -n "$dir_arg"; then { test -z "$chowncmd" || $doit $chowncmd "$dst"; } && { test -z "$chgrpcmd" || $doit $chgrpcmd "$dst"; } && { test "$obsolete_mkdir_used$chowncmd$chgrpcmd" = false || test -z "$chmodcmd" || $doit $chmodcmd $mode "$dst"; } || exit 1 else # Make a couple of temp file names in the proper directory. dsttmp=$dstdir/_inst.$$_ rmtmp=$dstdir/_rm.$$_ # Trap to clean up those temp files at exit. trap 'ret=$?; rm -f "$dsttmp" "$rmtmp" && exit $ret' 0 # Copy the file name to the temp name. (umask $cp_umask && $doit_exec $cpprog "$src" "$dsttmp") && # and set any options; do chmod last to preserve setuid bits. # # If any of these fail, we abort the whole thing. If we want to # ignore errors from any of these, just make sure not to ignore # errors from the above "$doit $cpprog $src $dsttmp" command. # { test -z "$chowncmd" || $doit $chowncmd "$dsttmp"; } && { test -z "$chgrpcmd" || $doit $chgrpcmd "$dsttmp"; } && { test -z "$stripcmd" || $doit $stripcmd "$dsttmp"; } && { test -z "$chmodcmd" || $doit $chmodcmd $mode "$dsttmp"; } && # If -C, don't bother to copy if it wouldn't change the file. if $copy_on_change && old=`LC_ALL=C ls -dlL "$dst" 2>/dev/null` && new=`LC_ALL=C ls -dlL "$dsttmp" 2>/dev/null` && eval "$initialize_posix_glob" && $posix_glob set -f && set X $old && old=:$2:$4:$5:$6 && set X $new && new=:$2:$4:$5:$6 && $posix_glob set +f && test "$old" = "$new" && $cmpprog "$dst" "$dsttmp" >/dev/null 2>&1 then rm -f "$dsttmp" else # Rename the file to the real destination. $doit $mvcmd -f "$dsttmp" "$dst" 2>/dev/null || # The rename failed, perhaps because mv can't rename something else # to itself, or perhaps because mv is so ancient that it does not # support -f. { # Now remove or move aside any old file at destination location. # We try this two ways since rm can't unlink itself on some # systems and the destination file might be busy for other # reasons. In this case, the final cleanup might fail but the new # file should still install successfully. { test ! -f "$dst" || $doit $rmcmd -f "$dst" 2>/dev/null || { $doit $mvcmd -f "$dst" "$rmtmp" 2>/dev/null && { $doit $rmcmd -f "$rmtmp" 2>/dev/null; :; } } || { echo "$0: cannot unlink or rename $dst" >&2 (exit 1); exit 1 } } && # Now rename the file to the real destination. $doit $mvcmd "$dsttmp" "$dst" } fi || exit 1 trap '' 0 fi done # Local variables: # eval: (add-hook 'write-file-hooks 'time-stamp) # time-stamp-start: "scriptversion=" # time-stamp-format: "%:y-%02m-%02d.%02H" # time-stamp-time-zone: "UTC" # time-stamp-end: "; # UTC" # End: apache-couchdb-1.5.0/build-aux/config.sub0000755000175000001440000010612412146350677015154 00000000000000#! /bin/sh # Configuration validation subroutine script. # Copyright (C) 1992, 1993, 1994, 1995, 1996, 1997, 1998, 1999, # 2000, 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, # 2011, 2012, 2013 Free Software Foundation, Inc. timestamp='2013-01-11' # This file is free software; you can redistribute it and/or modify it # under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, but # WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU # General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, see . # # As a special exception to the GNU General Public License, if you # distribute this file as part of a program that contains a # configuration script generated by Autoconf, you may include it under # the same distribution terms that you use for the rest of that # program. This Exception is an additional permission under section 7 # of the GNU General Public License, version 3 ("GPLv3"). # Please send patches with a ChangeLog entry to config-patches@gnu.org. # # Configuration subroutine to validate and canonicalize a configuration type. # Supply the specified configuration type as an argument. # If it is invalid, we print an error message on stderr and exit with code 1. # Otherwise, we print the canonical config type on stdout and succeed. # You can get the latest version of this script from: # http://git.savannah.gnu.org/gitweb/?p=config.git;a=blob_plain;f=config.sub;hb=HEAD # This file is supposed to be the same for all GNU packages # and recognize all the CPU types, system types and aliases # that are meaningful with *any* GNU software. # Each package is responsible for reporting which valid configurations # it does not support. The user should be able to distinguish # a failure to support a valid configuration from a meaningless # configuration. # The goal of this file is to map all the various variations of a given # machine specification into a single specification in the form: # CPU_TYPE-MANUFACTURER-OPERATING_SYSTEM # or in some cases, the newer four-part form: # CPU_TYPE-MANUFACTURER-KERNEL-OPERATING_SYSTEM # It is wrong to echo any other type of specification. me=`echo "$0" | sed -e 's,.*/,,'` usage="\ Usage: $0 [OPTION] CPU-MFR-OPSYS $0 [OPTION] ALIAS Canonicalize a configuration name. Operation modes: -h, --help print this help, then exit -t, --time-stamp print date of last modification, then exit -v, --version print version number, then exit Report bugs and patches to ." version="\ GNU config.sub ($timestamp) Copyright (C) 1992, 1993, 1994, 1995, 1996, 1997, 1998, 1999, 2000, 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011, 2012, 2013 Free Software Foundation, Inc. This is free software; see the source for copying conditions. There is NO warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE." help=" Try \`$me --help' for more information." # Parse command line while test $# -gt 0 ; do case $1 in --time-stamp | --time* | -t ) echo "$timestamp" ; exit ;; --version | -v ) echo "$version" ; exit ;; --help | --h* | -h ) echo "$usage"; exit ;; -- ) # Stop option processing shift; break ;; - ) # Use stdin as input. break ;; -* ) echo "$me: invalid option $1$help" exit 1 ;; *local*) # First pass through any local machine types. echo $1 exit ;; * ) break ;; esac done case $# in 0) echo "$me: missing argument$help" >&2 exit 1;; 1) ;; *) echo "$me: too many arguments$help" >&2 exit 1;; esac # Separate what the user gave into CPU-COMPANY and OS or KERNEL-OS (if any). # Here we must recognize all the valid KERNEL-OS combinations. maybe_os=`echo $1 | sed 's/^\(.*\)-\([^-]*-[^-]*\)$/\2/'` case $maybe_os in nto-qnx* | linux-gnu* | linux-android* | linux-dietlibc | linux-newlib* | \ linux-musl* | linux-uclibc* | uclinux-uclibc* | uclinux-gnu* | kfreebsd*-gnu* | \ knetbsd*-gnu* | netbsd*-gnu* | \ kopensolaris*-gnu* | \ storm-chaos* | os2-emx* | rtmk-nova*) os=-$maybe_os basic_machine=`echo $1 | sed 's/^\(.*\)-\([^-]*-[^-]*\)$/\1/'` ;; android-linux) os=-linux-android basic_machine=`echo $1 | sed 's/^\(.*\)-\([^-]*-[^-]*\)$/\1/'`-unknown ;; *) basic_machine=`echo $1 | sed 's/-[^-]*$//'` if [ $basic_machine != $1 ] then os=`echo $1 | sed 's/.*-/-/'` else os=; fi ;; esac ### Let's recognize common machines as not being operating systems so ### that things like config.sub decstation-3100 work. We also ### recognize some manufacturers as not being operating systems, so we ### can provide default operating systems below. case $os in -sun*os*) # Prevent following clause from handling this invalid input. ;; -dec* | -mips* | -sequent* | -encore* | -pc532* | -sgi* | -sony* | \ -att* | -7300* | -3300* | -delta* | -motorola* | -sun[234]* | \ -unicom* | -ibm* | -next | -hp | -isi* | -apollo | -altos* | \ -convergent* | -ncr* | -news | -32* | -3600* | -3100* | -hitachi* |\ -c[123]* | -convex* | -sun | -crds | -omron* | -dg | -ultra | -tti* | \ -harris | -dolphin | -highlevel | -gould | -cbm | -ns | -masscomp | \ -apple | -axis | -knuth | -cray | -microblaze*) os= basic_machine=$1 ;; -bluegene*) os=-cnk ;; -sim | -cisco | -oki | -wec | -winbond) os= basic_machine=$1 ;; -scout) ;; -wrs) os=-vxworks basic_machine=$1 ;; -chorusos*) os=-chorusos basic_machine=$1 ;; -chorusrdb) os=-chorusrdb basic_machine=$1 ;; -hiux*) os=-hiuxwe2 ;; -sco6) os=-sco5v6 basic_machine=`echo $1 | sed -e 's/86-.*/86-pc/'` ;; -sco5) os=-sco3.2v5 basic_machine=`echo $1 | sed -e 's/86-.*/86-pc/'` ;; -sco4) os=-sco3.2v4 basic_machine=`echo $1 | sed -e 's/86-.*/86-pc/'` ;; -sco3.2.[4-9]*) os=`echo $os | sed -e 's/sco3.2./sco3.2v/'` basic_machine=`echo $1 | sed -e 's/86-.*/86-pc/'` ;; -sco3.2v[4-9]*) # Don't forget version if it is 3.2v4 or newer. basic_machine=`echo $1 | sed -e 's/86-.*/86-pc/'` ;; -sco5v6*) # Don't forget version if it is 3.2v4 or newer. basic_machine=`echo $1 | sed -e 's/86-.*/86-pc/'` ;; -sco*) os=-sco3.2v2 basic_machine=`echo $1 | sed -e 's/86-.*/86-pc/'` ;; -udk*) basic_machine=`echo $1 | sed -e 's/86-.*/86-pc/'` ;; -isc) os=-isc2.2 basic_machine=`echo $1 | sed -e 's/86-.*/86-pc/'` ;; -clix*) basic_machine=clipper-intergraph ;; -isc*) basic_machine=`echo $1 | sed -e 's/86-.*/86-pc/'` ;; -lynx*178) os=-lynxos178 ;; -lynx*5) os=-lynxos5 ;; -lynx*) os=-lynxos ;; -ptx*) basic_machine=`echo $1 | sed -e 's/86-.*/86-sequent/'` ;; -windowsnt*) os=`echo $os | sed -e 's/windowsnt/winnt/'` ;; -psos*) os=-psos ;; -mint | -mint[0-9]*) basic_machine=m68k-atari os=-mint ;; esac # Decode aliases for certain CPU-COMPANY combinations. case $basic_machine in # Recognize the basic CPU types without company name. # Some are omitted here because they have special meanings below. 1750a | 580 \ | a29k \ | aarch64 | aarch64_be \ | alpha | alphaev[4-8] | alphaev56 | alphaev6[78] | alphapca5[67] \ | alpha64 | alpha64ev[4-8] | alpha64ev56 | alpha64ev6[78] | alpha64pca5[67] \ | am33_2.0 \ | arc \ | arm | arm[bl]e | arme[lb] | armv[2-8] | armv[3-8][lb] | armv7[arm] \ | avr | avr32 \ | be32 | be64 \ | bfin \ | c4x | clipper \ | d10v | d30v | dlx | dsp16xx | dvp \ | epiphany \ | fido | fr30 | frv \ | h8300 | h8500 | hppa | hppa1.[01] | hppa2.0 | hppa2.0[nw] | hppa64 \ | hexagon \ | i370 | i860 | i960 | ia64 \ | ip2k | iq2000 \ | le32 | le64 \ | lm32 \ | m32c | m32r | m32rle | m68000 | m68k | m88k \ | maxq | mb | microblaze | microblazeel | mcore | mep | metag \ | mips | mipsbe | mipseb | mipsel | mipsle \ | mips16 \ | mips64 | mips64el \ | mips64octeon | mips64octeonel \ | mips64orion | mips64orionel \ | mips64r5900 | mips64r5900el \ | mips64vr | mips64vrel \ | mips64vr4100 | mips64vr4100el \ | mips64vr4300 | mips64vr4300el \ | mips64vr5000 | mips64vr5000el \ | mips64vr5900 | mips64vr5900el \ | mipsisa32 | mipsisa32el \ | mipsisa32r2 | mipsisa32r2el \ | mipsisa64 | mipsisa64el \ | mipsisa64r2 | mipsisa64r2el \ | mipsisa64sb1 | mipsisa64sb1el \ | mipsisa64sr71k | mipsisa64sr71kel \ | mipsr5900 | mipsr5900el \ | mipstx39 | mipstx39el \ | mn10200 | mn10300 \ | moxie \ | mt \ | msp430 \ | nds32 | nds32le | nds32be \ | nios | nios2 \ | ns16k | ns32k \ | open8 \ | or32 \ | pdp10 | pdp11 | pj | pjl \ | powerpc | powerpc64 | powerpc64le | powerpcle \ | pyramid \ | rl78 | rx \ | score \ | sh | sh[1234] | sh[24]a | sh[24]aeb | sh[23]e | sh[34]eb | sheb | shbe | shle | sh[1234]le | sh3ele \ | sh64 | sh64le \ | sparc | sparc64 | sparc64b | sparc64v | sparc86x | sparclet | sparclite \ | sparcv8 | sparcv9 | sparcv9b | sparcv9v \ | spu \ | tahoe | tic4x | tic54x | tic55x | tic6x | tic80 | tron \ | ubicom32 \ | v850 | v850e | v850e1 | v850e2 | v850es | v850e2v3 \ | we32k \ | x86 | xc16x | xstormy16 | xtensa \ | z8k | z80) basic_machine=$basic_machine-unknown ;; c54x) basic_machine=tic54x-unknown ;; c55x) basic_machine=tic55x-unknown ;; c6x) basic_machine=tic6x-unknown ;; m6811 | m68hc11 | m6812 | m68hc12 | m68hcs12x | picochip) basic_machine=$basic_machine-unknown os=-none ;; m88110 | m680[12346]0 | m683?2 | m68360 | m5200 | v70 | w65 | z8k) ;; ms1) basic_machine=mt-unknown ;; strongarm | thumb | xscale) basic_machine=arm-unknown ;; xgate) basic_machine=$basic_machine-unknown os=-none ;; xscaleeb) basic_machine=armeb-unknown ;; xscaleel) basic_machine=armel-unknown ;; # We use `pc' rather than `unknown' # because (1) that's what they normally are, and # (2) the word "unknown" tends to confuse beginning users. i*86 | x86_64) basic_machine=$basic_machine-pc ;; # Object if more than one company name word. *-*-*) echo Invalid configuration \`$1\': machine \`$basic_machine\' not recognized 1>&2 exit 1 ;; # Recognize the basic CPU types with company name. 580-* \ | a29k-* \ | aarch64-* | aarch64_be-* \ | alpha-* | alphaev[4-8]-* | alphaev56-* | alphaev6[78]-* \ | alpha64-* | alpha64ev[4-8]-* | alpha64ev56-* | alpha64ev6[78]-* \ | alphapca5[67]-* | alpha64pca5[67]-* | arc-* \ | arm-* | armbe-* | armle-* | armeb-* | armv*-* \ | avr-* | avr32-* \ | be32-* | be64-* \ | bfin-* | bs2000-* \ | c[123]* | c30-* | [cjt]90-* | c4x-* \ | clipper-* | craynv-* | cydra-* \ | d10v-* | d30v-* | dlx-* \ | elxsi-* \ | f30[01]-* | f700-* | fido-* | fr30-* | frv-* | fx80-* \ | h8300-* | h8500-* \ | hppa-* | hppa1.[01]-* | hppa2.0-* | hppa2.0[nw]-* | hppa64-* \ | hexagon-* \ | i*86-* | i860-* | i960-* | ia64-* \ | ip2k-* | iq2000-* \ | le32-* | le64-* \ | lm32-* \ | m32c-* | m32r-* | m32rle-* \ | m68000-* | m680[012346]0-* | m68360-* | m683?2-* | m68k-* \ | m88110-* | m88k-* | maxq-* | mcore-* | metag-* \ | microblaze-* | microblazeel-* \ | mips-* | mipsbe-* | mipseb-* | mipsel-* | mipsle-* \ | mips16-* \ | mips64-* | mips64el-* \ | mips64octeon-* | mips64octeonel-* \ | mips64orion-* | mips64orionel-* \ | mips64r5900-* | mips64r5900el-* \ | mips64vr-* | mips64vrel-* \ | mips64vr4100-* | mips64vr4100el-* \ | mips64vr4300-* | mips64vr4300el-* \ | mips64vr5000-* | mips64vr5000el-* \ | mips64vr5900-* | mips64vr5900el-* \ | mipsisa32-* | mipsisa32el-* \ | mipsisa32r2-* | mipsisa32r2el-* \ | mipsisa64-* | mipsisa64el-* \ | mipsisa64r2-* | mipsisa64r2el-* \ | mipsisa64sb1-* | mipsisa64sb1el-* \ | mipsisa64sr71k-* | mipsisa64sr71kel-* \ | mipsr5900-* | mipsr5900el-* \ | mipstx39-* | mipstx39el-* \ | mmix-* \ | mt-* \ | msp430-* \ | nds32-* | nds32le-* | nds32be-* \ | nios-* | nios2-* \ | none-* | np1-* | ns16k-* | ns32k-* \ | open8-* \ | orion-* \ | pdp10-* | pdp11-* | pj-* | pjl-* | pn-* | power-* \ | powerpc-* | powerpc64-* | powerpc64le-* | powerpcle-* \ | pyramid-* \ | rl78-* | romp-* | rs6000-* | rx-* \ | sh-* | sh[1234]-* | sh[24]a-* | sh[24]aeb-* | sh[23]e-* | sh[34]eb-* | sheb-* | shbe-* \ | shle-* | sh[1234]le-* | sh3ele-* | sh64-* | sh64le-* \ | sparc-* | sparc64-* | sparc64b-* | sparc64v-* | sparc86x-* | sparclet-* \ | sparclite-* \ | sparcv8-* | sparcv9-* | sparcv9b-* | sparcv9v-* | sv1-* | sx?-* \ | tahoe-* \ | tic30-* | tic4x-* | tic54x-* | tic55x-* | tic6x-* | tic80-* \ | tile*-* \ | tron-* \ | ubicom32-* \ | v850-* | v850e-* | v850e1-* | v850es-* | v850e2-* | v850e2v3-* \ | vax-* \ | we32k-* \ | x86-* | x86_64-* | xc16x-* | xps100-* \ | xstormy16-* | xtensa*-* \ | ymp-* \ | z8k-* | z80-*) ;; # Recognize the basic CPU types without company name, with glob match. xtensa*) basic_machine=$basic_machine-unknown ;; # Recognize the various machine names and aliases which stand # for a CPU type and a company and sometimes even an OS. 386bsd) basic_machine=i386-unknown os=-bsd ;; 3b1 | 7300 | 7300-att | att-7300 | pc7300 | safari | unixpc) basic_machine=m68000-att ;; 3b*) basic_machine=we32k-att ;; a29khif) basic_machine=a29k-amd os=-udi ;; abacus) basic_machine=abacus-unknown ;; adobe68k) basic_machine=m68010-adobe os=-scout ;; alliant | fx80) basic_machine=fx80-alliant ;; altos | altos3068) basic_machine=m68k-altos ;; am29k) basic_machine=a29k-none os=-bsd ;; amd64) basic_machine=x86_64-pc ;; amd64-*) basic_machine=x86_64-`echo $basic_machine | sed 's/^[^-]*-//'` ;; amdahl) basic_machine=580-amdahl os=-sysv ;; amiga | amiga-*) basic_machine=m68k-unknown ;; amigaos | amigados) basic_machine=m68k-unknown os=-amigaos ;; amigaunix | amix) basic_machine=m68k-unknown os=-sysv4 ;; apollo68) basic_machine=m68k-apollo os=-sysv ;; apollo68bsd) basic_machine=m68k-apollo os=-bsd ;; aros) basic_machine=i386-pc os=-aros ;; aux) basic_machine=m68k-apple os=-aux ;; balance) basic_machine=ns32k-sequent os=-dynix ;; blackfin) basic_machine=bfin-unknown os=-linux ;; blackfin-*) basic_machine=bfin-`echo $basic_machine | sed 's/^[^-]*-//'` os=-linux ;; bluegene*) basic_machine=powerpc-ibm os=-cnk ;; c54x-*) basic_machine=tic54x-`echo $basic_machine | sed 's/^[^-]*-//'` ;; c55x-*) basic_machine=tic55x-`echo $basic_machine | sed 's/^[^-]*-//'` ;; c6x-*) basic_machine=tic6x-`echo $basic_machine | sed 's/^[^-]*-//'` ;; c90) basic_machine=c90-cray os=-unicos ;; cegcc) basic_machine=arm-unknown os=-cegcc ;; convex-c1) basic_machine=c1-convex os=-bsd ;; convex-c2) basic_machine=c2-convex os=-bsd ;; convex-c32) basic_machine=c32-convex os=-bsd ;; convex-c34) basic_machine=c34-convex os=-bsd ;; convex-c38) basic_machine=c38-convex os=-bsd ;; cray | j90) basic_machine=j90-cray os=-unicos ;; craynv) basic_machine=craynv-cray os=-unicosmp ;; cr16 | cr16-*) basic_machine=cr16-unknown os=-elf ;; crds | unos) basic_machine=m68k-crds ;; crisv32 | crisv32-* | etraxfs*) basic_machine=crisv32-axis ;; cris | cris-* | etrax*) basic_machine=cris-axis ;; crx) basic_machine=crx-unknown os=-elf ;; da30 | da30-*) basic_machine=m68k-da30 ;; decstation | decstation-3100 | pmax | pmax-* | pmin | dec3100 | decstatn) basic_machine=mips-dec ;; decsystem10* | dec10*) basic_machine=pdp10-dec os=-tops10 ;; decsystem20* | dec20*) basic_machine=pdp10-dec os=-tops20 ;; delta | 3300 | motorola-3300 | motorola-delta \ | 3300-motorola | delta-motorola) basic_machine=m68k-motorola ;; delta88) basic_machine=m88k-motorola os=-sysv3 ;; dicos) basic_machine=i686-pc os=-dicos ;; djgpp) basic_machine=i586-pc os=-msdosdjgpp ;; dpx20 | dpx20-*) basic_machine=rs6000-bull os=-bosx ;; dpx2* | dpx2*-bull) basic_machine=m68k-bull os=-sysv3 ;; ebmon29k) basic_machine=a29k-amd os=-ebmon ;; elxsi) basic_machine=elxsi-elxsi os=-bsd ;; encore | umax | mmax) basic_machine=ns32k-encore ;; es1800 | OSE68k | ose68k | ose | OSE) basic_machine=m68k-ericsson os=-ose ;; fx2800) basic_machine=i860-alliant ;; genix) basic_machine=ns32k-ns ;; gmicro) basic_machine=tron-gmicro os=-sysv ;; go32) basic_machine=i386-pc os=-go32 ;; h3050r* | hiux*) basic_machine=hppa1.1-hitachi os=-hiuxwe2 ;; h8300hms) basic_machine=h8300-hitachi os=-hms ;; h8300xray) basic_machine=h8300-hitachi os=-xray ;; h8500hms) basic_machine=h8500-hitachi os=-hms ;; harris) basic_machine=m88k-harris os=-sysv3 ;; hp300-*) basic_machine=m68k-hp ;; hp300bsd) basic_machine=m68k-hp os=-bsd ;; hp300hpux) basic_machine=m68k-hp os=-hpux ;; hp3k9[0-9][0-9] | hp9[0-9][0-9]) basic_machine=hppa1.0-hp ;; hp9k2[0-9][0-9] | hp9k31[0-9]) basic_machine=m68000-hp ;; hp9k3[2-9][0-9]) basic_machine=m68k-hp ;; hp9k6[0-9][0-9] | hp6[0-9][0-9]) basic_machine=hppa1.0-hp ;; hp9k7[0-79][0-9] | hp7[0-79][0-9]) basic_machine=hppa1.1-hp ;; hp9k78[0-9] | hp78[0-9]) # FIXME: really hppa2.0-hp basic_machine=hppa1.1-hp ;; hp9k8[67]1 | hp8[67]1 | hp9k80[24] | hp80[24] | hp9k8[78]9 | hp8[78]9 | hp9k893 | hp893) # FIXME: really hppa2.0-hp basic_machine=hppa1.1-hp ;; hp9k8[0-9][13679] | hp8[0-9][13679]) basic_machine=hppa1.1-hp ;; hp9k8[0-9][0-9] | hp8[0-9][0-9]) basic_machine=hppa1.0-hp ;; hppa-next) os=-nextstep3 ;; hppaosf) basic_machine=hppa1.1-hp os=-osf ;; hppro) basic_machine=hppa1.1-hp os=-proelf ;; i370-ibm* | ibm*) basic_machine=i370-ibm ;; i*86v32) basic_machine=`echo $1 | sed -e 's/86.*/86-pc/'` os=-sysv32 ;; i*86v4*) basic_machine=`echo $1 | sed -e 's/86.*/86-pc/'` os=-sysv4 ;; i*86v) basic_machine=`echo $1 | sed -e 's/86.*/86-pc/'` os=-sysv ;; i*86sol2) basic_machine=`echo $1 | sed -e 's/86.*/86-pc/'` os=-solaris2 ;; i386mach) basic_machine=i386-mach os=-mach ;; i386-vsta | vsta) basic_machine=i386-unknown os=-vsta ;; iris | iris4d) basic_machine=mips-sgi case $os in -irix*) ;; *) os=-irix4 ;; esac ;; isi68 | isi) basic_machine=m68k-isi os=-sysv ;; m68knommu) basic_machine=m68k-unknown os=-linux ;; m68knommu-*) basic_machine=m68k-`echo $basic_machine | sed 's/^[^-]*-//'` os=-linux ;; m88k-omron*) basic_machine=m88k-omron ;; magnum | m3230) basic_machine=mips-mips os=-sysv ;; merlin) basic_machine=ns32k-utek os=-sysv ;; microblaze*) basic_machine=microblaze-xilinx ;; mingw64) basic_machine=x86_64-pc os=-mingw64 ;; mingw32) basic_machine=i386-pc os=-mingw32 ;; mingw32ce) basic_machine=arm-unknown os=-mingw32ce ;; miniframe) basic_machine=m68000-convergent ;; *mint | -mint[0-9]* | *MiNT | *MiNT[0-9]*) basic_machine=m68k-atari os=-mint ;; mipsEE* | ee | ps2) basic_machine=mips64r5900el-scei case $os in -linux*) ;; *) os=-elf ;; esac ;; iop) basic_machine=mipsel-scei os=-irx ;; dvp) basic_machine=dvp-scei os=-elf ;; mips3*-*) basic_machine=`echo $basic_machine | sed -e 's/mips3/mips64/'` ;; mips3*) basic_machine=`echo $basic_machine | sed -e 's/mips3/mips64/'`-unknown ;; monitor) basic_machine=m68k-rom68k os=-coff ;; morphos) basic_machine=powerpc-unknown os=-morphos ;; msdos) basic_machine=i386-pc os=-msdos ;; ms1-*) basic_machine=`echo $basic_machine | sed -e 's/ms1-/mt-/'` ;; msys) basic_machine=i386-pc os=-msys ;; mvs) basic_machine=i370-ibm os=-mvs ;; nacl) basic_machine=le32-unknown os=-nacl ;; ncr3000) basic_machine=i486-ncr os=-sysv4 ;; netbsd386) basic_machine=i386-unknown os=-netbsd ;; netwinder) basic_machine=armv4l-rebel os=-linux ;; news | news700 | news800 | news900) basic_machine=m68k-sony os=-newsos ;; news1000) basic_machine=m68030-sony os=-newsos ;; news-3600 | risc-news) basic_machine=mips-sony os=-newsos ;; necv70) basic_machine=v70-nec os=-sysv ;; next | m*-next ) basic_machine=m68k-next case $os in -nextstep* ) ;; -ns2*) os=-nextstep2 ;; *) os=-nextstep3 ;; esac ;; nh3000) basic_machine=m68k-harris os=-cxux ;; nh[45]000) basic_machine=m88k-harris os=-cxux ;; nindy960) basic_machine=i960-intel os=-nindy ;; mon960) basic_machine=i960-intel os=-mon960 ;; nonstopux) basic_machine=mips-compaq os=-nonstopux ;; np1) basic_machine=np1-gould ;; neo-tandem) basic_machine=neo-tandem ;; nse-tandem) basic_machine=nse-tandem ;; nsr-tandem) basic_machine=nsr-tandem ;; op50n-* | op60c-*) basic_machine=hppa1.1-oki os=-proelf ;; openrisc | openrisc-*) basic_machine=or32-unknown ;; os400) basic_machine=powerpc-ibm os=-os400 ;; OSE68000 | ose68000) basic_machine=m68000-ericsson os=-ose ;; os68k) basic_machine=m68k-none os=-os68k ;; pa-hitachi) basic_machine=hppa1.1-hitachi os=-hiuxwe2 ;; paragon) basic_machine=i860-intel os=-osf ;; parisc) basic_machine=hppa-unknown os=-linux ;; parisc-*) basic_machine=hppa-`echo $basic_machine | sed 's/^[^-]*-//'` os=-linux ;; pbd) basic_machine=sparc-tti ;; pbb) basic_machine=m68k-tti ;; pc532 | pc532-*) basic_machine=ns32k-pc532 ;; pc98) basic_machine=i386-pc ;; pc98-*) basic_machine=i386-`echo $basic_machine | sed 's/^[^-]*-//'` ;; pentium | p5 | k5 | k6 | nexgen | viac3) basic_machine=i586-pc ;; pentiumpro | p6 | 6x86 | athlon | athlon_*) basic_machine=i686-pc ;; pentiumii | pentium2 | pentiumiii | pentium3) basic_machine=i686-pc ;; pentium4) basic_machine=i786-pc ;; pentium-* | p5-* | k5-* | k6-* | nexgen-* | viac3-*) basic_machine=i586-`echo $basic_machine | sed 's/^[^-]*-//'` ;; pentiumpro-* | p6-* | 6x86-* | athlon-*) basic_machine=i686-`echo $basic_machine | sed 's/^[^-]*-//'` ;; pentiumii-* | pentium2-* | pentiumiii-* | pentium3-*) basic_machine=i686-`echo $basic_machine | sed 's/^[^-]*-//'` ;; pentium4-*) basic_machine=i786-`echo $basic_machine | sed 's/^[^-]*-//'` ;; pn) basic_machine=pn-gould ;; power) basic_machine=power-ibm ;; ppc | ppcbe) basic_machine=powerpc-unknown ;; ppc-* | ppcbe-*) basic_machine=powerpc-`echo $basic_machine | sed 's/^[^-]*-//'` ;; ppcle | powerpclittle | ppc-le | powerpc-little) basic_machine=powerpcle-unknown ;; ppcle-* | powerpclittle-*) basic_machine=powerpcle-`echo $basic_machine | sed 's/^[^-]*-//'` ;; ppc64) basic_machine=powerpc64-unknown ;; ppc64-*) basic_machine=powerpc64-`echo $basic_machine | sed 's/^[^-]*-//'` ;; ppc64le | powerpc64little | ppc64-le | powerpc64-little) basic_machine=powerpc64le-unknown ;; ppc64le-* | powerpc64little-*) basic_machine=powerpc64le-`echo $basic_machine | sed 's/^[^-]*-//'` ;; ps2) basic_machine=i386-ibm ;; pw32) basic_machine=i586-unknown os=-pw32 ;; rdos | rdos64) basic_machine=x86_64-pc os=-rdos ;; rdos32) basic_machine=i386-pc os=-rdos ;; rom68k) basic_machine=m68k-rom68k os=-coff ;; rm[46]00) basic_machine=mips-siemens ;; rtpc | rtpc-*) basic_machine=romp-ibm ;; s390 | s390-*) basic_machine=s390-ibm ;; s390x | s390x-*) basic_machine=s390x-ibm ;; sa29200) basic_machine=a29k-amd os=-udi ;; sb1) basic_machine=mipsisa64sb1-unknown ;; sb1el) basic_machine=mipsisa64sb1el-unknown ;; sde) basic_machine=mipsisa32-sde os=-elf ;; sei) basic_machine=mips-sei os=-seiux ;; sequent) basic_machine=i386-sequent ;; sh) basic_machine=sh-hitachi os=-hms ;; sh5el) basic_machine=sh5le-unknown ;; sh64) basic_machine=sh64-unknown ;; sparclite-wrs | simso-wrs) basic_machine=sparclite-wrs os=-vxworks ;; sps7) basic_machine=m68k-bull os=-sysv2 ;; spur) basic_machine=spur-unknown ;; st2000) basic_machine=m68k-tandem ;; stratus) basic_machine=i860-stratus os=-sysv4 ;; strongarm-* | thumb-*) basic_machine=arm-`echo $basic_machine | sed 's/^[^-]*-//'` ;; sun2) basic_machine=m68000-sun ;; sun2os3) basic_machine=m68000-sun os=-sunos3 ;; sun2os4) basic_machine=m68000-sun os=-sunos4 ;; sun3os3) basic_machine=m68k-sun os=-sunos3 ;; sun3os4) basic_machine=m68k-sun os=-sunos4 ;; sun4os3) basic_machine=sparc-sun os=-sunos3 ;; sun4os4) basic_machine=sparc-sun os=-sunos4 ;; sun4sol2) basic_machine=sparc-sun os=-solaris2 ;; sun3 | sun3-*) basic_machine=m68k-sun ;; sun4) basic_machine=sparc-sun ;; sun386 | sun386i | roadrunner) basic_machine=i386-sun ;; sv1) basic_machine=sv1-cray os=-unicos ;; symmetry) basic_machine=i386-sequent os=-dynix ;; t3e) basic_machine=alphaev5-cray os=-unicos ;; t90) basic_machine=t90-cray os=-unicos ;; tile*) basic_machine=$basic_machine-unknown os=-linux-gnu ;; tx39) basic_machine=mipstx39-unknown ;; tx39el) basic_machine=mipstx39el-unknown ;; toad1) basic_machine=pdp10-xkl os=-tops20 ;; tower | tower-32) basic_machine=m68k-ncr ;; tpf) basic_machine=s390x-ibm os=-tpf ;; udi29k) basic_machine=a29k-amd os=-udi ;; ultra3) basic_machine=a29k-nyu os=-sym1 ;; v810 | necv810) basic_machine=v810-nec os=-none ;; vaxv) basic_machine=vax-dec os=-sysv ;; vms) basic_machine=vax-dec os=-vms ;; vpp*|vx|vx-*) basic_machine=f301-fujitsu ;; vxworks960) basic_machine=i960-wrs os=-vxworks ;; vxworks68) basic_machine=m68k-wrs os=-vxworks ;; vxworks29k) basic_machine=a29k-wrs os=-vxworks ;; w65*) basic_machine=w65-wdc os=-none ;; w89k-*) basic_machine=hppa1.1-winbond os=-proelf ;; xbox) basic_machine=i686-pc os=-mingw32 ;; xps | xps100) basic_machine=xps100-honeywell ;; xscale-* | xscalee[bl]-*) basic_machine=`echo $basic_machine | sed 's/^xscale/arm/'` ;; ymp) basic_machine=ymp-cray os=-unicos ;; z8k-*-coff) basic_machine=z8k-unknown os=-sim ;; z80-*-coff) basic_machine=z80-unknown os=-sim ;; none) basic_machine=none-none os=-none ;; # Here we handle the default manufacturer of certain CPU types. It is in # some cases the only manufacturer, in others, it is the most popular. w89k) basic_machine=hppa1.1-winbond ;; op50n) basic_machine=hppa1.1-oki ;; op60c) basic_machine=hppa1.1-oki ;; romp) basic_machine=romp-ibm ;; mmix) basic_machine=mmix-knuth ;; rs6000) basic_machine=rs6000-ibm ;; vax) basic_machine=vax-dec ;; pdp10) # there are many clones, so DEC is not a safe bet basic_machine=pdp10-unknown ;; pdp11) basic_machine=pdp11-dec ;; we32k) basic_machine=we32k-att ;; sh[1234] | sh[24]a | sh[24]aeb | sh[34]eb | sh[1234]le | sh[23]ele) basic_machine=sh-unknown ;; sparc | sparcv8 | sparcv9 | sparcv9b | sparcv9v) basic_machine=sparc-sun ;; cydra) basic_machine=cydra-cydrome ;; orion) basic_machine=orion-highlevel ;; orion105) basic_machine=clipper-highlevel ;; mac | mpw | mac-mpw) basic_machine=m68k-apple ;; pmac | pmac-mpw) basic_machine=powerpc-apple ;; *-unknown) # Make sure to match an already-canonicalized machine name. ;; *) echo Invalid configuration \`$1\': machine \`$basic_machine\' not recognized 1>&2 exit 1 ;; esac # Here we canonicalize certain aliases for manufacturers. case $basic_machine in *-digital*) basic_machine=`echo $basic_machine | sed 's/digital.*/dec/'` ;; *-commodore*) basic_machine=`echo $basic_machine | sed 's/commodore.*/cbm/'` ;; *) ;; esac # Decode manufacturer-specific aliases for certain operating systems. if [ x"$os" != x"" ] then case $os in # First match some system type aliases # that might get confused with valid system types. # -solaris* is a basic system type, with this one exception. -auroraux) os=-auroraux ;; -solaris1 | -solaris1.*) os=`echo $os | sed -e 's|solaris1|sunos4|'` ;; -solaris) os=-solaris2 ;; -svr4*) os=-sysv4 ;; -unixware*) os=-sysv4.2uw ;; -gnu/linux*) os=`echo $os | sed -e 's|gnu/linux|linux-gnu|'` ;; # First accept the basic system types. # The portable systems comes first. # Each alternative MUST END IN A *, to match a version number. # -sysv* is not here because it comes later, after sysvr4. -gnu* | -bsd* | -mach* | -minix* | -genix* | -ultrix* | -irix* \ | -*vms* | -sco* | -esix* | -isc* | -aix* | -cnk* | -sunos | -sunos[34]*\ | -hpux* | -unos* | -osf* | -luna* | -dgux* | -auroraux* | -solaris* \ | -sym* | -kopensolaris* | -plan9* \ | -amigaos* | -amigados* | -msdos* | -newsos* | -unicos* | -aof* \ | -aos* | -aros* \ | -nindy* | -vxsim* | -vxworks* | -ebmon* | -hms* | -mvs* \ | -clix* | -riscos* | -uniplus* | -iris* | -rtu* | -xenix* \ | -hiux* | -386bsd* | -knetbsd* | -mirbsd* | -netbsd* \ | -bitrig* | -openbsd* | -solidbsd* \ | -ekkobsd* | -kfreebsd* | -freebsd* | -riscix* | -lynxos* \ | -bosx* | -nextstep* | -cxux* | -aout* | -elf* | -oabi* \ | -ptx* | -coff* | -ecoff* | -winnt* | -domain* | -vsta* \ | -udi* | -eabi* | -lites* | -ieee* | -go32* | -aux* \ | -chorusos* | -chorusrdb* | -cegcc* \ | -cygwin* | -msys* | -pe* | -psos* | -moss* | -proelf* | -rtems* \ | -mingw32* | -mingw64* | -linux-gnu* | -linux-android* \ | -linux-newlib* | -linux-musl* | -linux-uclibc* \ | -uxpv* | -beos* | -mpeix* | -udk* \ | -interix* | -uwin* | -mks* | -rhapsody* | -darwin* | -opened* \ | -openstep* | -oskit* | -conix* | -pw32* | -nonstopux* \ | -storm-chaos* | -tops10* | -tenex* | -tops20* | -its* | -irx* \ | -os2* | -vos* | -palmos* | -uclinux* | -nucleus* \ | -morphos* | -superux* | -rtmk* | -rtmk-nova* | -windiss* \ | -powermax* | -dnix* | -nx6 | -nx7 | -sei* | -dragonfly* \ | -skyos* | -haiku* | -rdos* | -toppers* | -drops* | -es*) # Remember, each alternative MUST END IN *, to match a version number. ;; -qnx*) case $basic_machine in x86-* | i*86-*) ;; *) os=-nto$os ;; esac ;; -nto-qnx*) ;; -nto*) os=`echo $os | sed -e 's|nto|nto-qnx|'` ;; -sim | -es1800* | -hms* | -xray | -os68k* | -none* | -v88r* \ | -windows* | -osx | -abug | -netware* | -os9* | -beos* | -haiku* \ | -macos* | -mpw* | -magic* | -mmixware* | -mon960* | -lnews*) ;; -mac*) os=`echo $os | sed -e 's|mac|macos|'` ;; -linux-dietlibc) os=-linux-dietlibc ;; -linux*) os=`echo $os | sed -e 's|linux|linux-gnu|'` ;; -sunos5*) os=`echo $os | sed -e 's|sunos5|solaris2|'` ;; -sunos6*) os=`echo $os | sed -e 's|sunos6|solaris3|'` ;; -opened*) os=-openedition ;; -os400*) os=-os400 ;; -wince*) os=-wince ;; -osfrose*) os=-osfrose ;; -osf*) os=-osf ;; -utek*) os=-bsd ;; -dynix*) os=-bsd ;; -acis*) os=-aos ;; -atheos*) os=-atheos ;; -syllable*) os=-syllable ;; -386bsd) os=-bsd ;; -ctix* | -uts*) os=-sysv ;; -nova*) os=-rtmk-nova ;; -ns2 ) os=-nextstep2 ;; -nsk*) os=-nsk ;; # Preserve the version number of sinix5. -sinix5.*) os=`echo $os | sed -e 's|sinix|sysv|'` ;; -sinix*) os=-sysv4 ;; -tpf*) os=-tpf ;; -triton*) os=-sysv3 ;; -oss*) os=-sysv3 ;; -svr4) os=-sysv4 ;; -svr3) os=-sysv3 ;; -sysvr4) os=-sysv4 ;; # This must come after -sysvr4. -sysv*) ;; -ose*) os=-ose ;; -es1800*) os=-ose ;; -xenix) os=-xenix ;; -*mint | -mint[0-9]* | -*MiNT | -MiNT[0-9]*) os=-mint ;; -aros*) os=-aros ;; -zvmoe) os=-zvmoe ;; -dicos*) os=-dicos ;; -nacl*) ;; -none) ;; *) # Get rid of the `-' at the beginning of $os. os=`echo $os | sed 's/[^-]*-//'` echo Invalid configuration \`$1\': system \`$os\' not recognized 1>&2 exit 1 ;; esac else # Here we handle the default operating systems that come with various machines. # The value should be what the vendor currently ships out the door with their # machine or put another way, the most popular os provided with the machine. # Note that if you're going to try to match "-MANUFACTURER" here (say, # "-sun"), then you have to tell the case statement up towards the top # that MANUFACTURER isn't an operating system. Otherwise, code above # will signal an error saying that MANUFACTURER isn't an operating # system, and we'll never get to this point. case $basic_machine in score-*) os=-elf ;; spu-*) os=-elf ;; *-acorn) os=-riscix1.2 ;; arm*-rebel) os=-linux ;; arm*-semi) os=-aout ;; c4x-* | tic4x-*) os=-coff ;; hexagon-*) os=-elf ;; tic54x-*) os=-coff ;; tic55x-*) os=-coff ;; tic6x-*) os=-coff ;; # This must come before the *-dec entry. pdp10-*) os=-tops20 ;; pdp11-*) os=-none ;; *-dec | vax-*) os=-ultrix4.2 ;; m68*-apollo) os=-domain ;; i386-sun) os=-sunos4.0.2 ;; m68000-sun) os=-sunos3 ;; m68*-cisco) os=-aout ;; mep-*) os=-elf ;; mips*-cisco) os=-elf ;; mips*-*) os=-elf ;; or32-*) os=-coff ;; *-tti) # must be before sparc entry or we get the wrong os. os=-sysv3 ;; sparc-* | *-sun) os=-sunos4.1.1 ;; *-be) os=-beos ;; *-haiku) os=-haiku ;; *-ibm) os=-aix ;; *-knuth) os=-mmixware ;; *-wec) os=-proelf ;; *-winbond) os=-proelf ;; *-oki) os=-proelf ;; *-hp) os=-hpux ;; *-hitachi) os=-hiux ;; i860-* | *-att | *-ncr | *-altos | *-motorola | *-convergent) os=-sysv ;; *-cbm) os=-amigaos ;; *-dg) os=-dgux ;; *-dolphin) os=-sysv3 ;; m68k-ccur) os=-rtu ;; m88k-omron*) os=-luna ;; *-next ) os=-nextstep ;; *-sequent) os=-ptx ;; *-crds) os=-unos ;; *-ns) os=-genix ;; i370-*) os=-mvs ;; *-next) os=-nextstep3 ;; *-gould) os=-sysv ;; *-highlevel) os=-bsd ;; *-encore) os=-bsd ;; *-sgi) os=-irix ;; *-siemens) os=-sysv4 ;; *-masscomp) os=-rtu ;; f30[01]-fujitsu | f700-fujitsu) os=-uxpv ;; *-rom68k) os=-coff ;; *-*bug) os=-coff ;; *-apple) os=-macos ;; *-atari*) os=-mint ;; *) os=-none ;; esac fi # Here we handle the case where we know the os, and the CPU type, but not the # manufacturer. We pick the logical manufacturer. vendor=unknown case $basic_machine in *-unknown) case $os in -riscix*) vendor=acorn ;; -sunos*) vendor=sun ;; -cnk*|-aix*) vendor=ibm ;; -beos*) vendor=be ;; -hpux*) vendor=hp ;; -mpeix*) vendor=hp ;; -hiux*) vendor=hitachi ;; -unos*) vendor=crds ;; -dgux*) vendor=dg ;; -luna*) vendor=omron ;; -genix*) vendor=ns ;; -mvs* | -opened*) vendor=ibm ;; -os400*) vendor=ibm ;; -ptx*) vendor=sequent ;; -tpf*) vendor=ibm ;; -vxsim* | -vxworks* | -windiss*) vendor=wrs ;; -aux*) vendor=apple ;; -hms*) vendor=hitachi ;; -mpw* | -macos*) vendor=apple ;; -*mint | -mint[0-9]* | -*MiNT | -MiNT[0-9]*) vendor=atari ;; -vos*) vendor=stratus ;; esac basic_machine=`echo $basic_machine | sed "s/unknown/$vendor/"` ;; esac echo $basic_machine$os exit # Local variables: # eval: (add-hook 'write-file-hooks 'time-stamp) # time-stamp-start: "timestamp='" # time-stamp-format: "%:y-%02m-%02d" # time-stamp-end: "'" # End: apache-couchdb-1.5.0/build-aux/missing0000755000175000001440000002415212021144127014547 00000000000000#! /bin/sh # Common stub for a few missing GNU programs while installing. scriptversion=2012-01-06.13; # UTC # Copyright (C) 1996, 1997, 1999, 2000, 2002, 2003, 2004, 2005, 2006, # 2008, 2009, 2010, 2011, 2012 Free Software Foundation, Inc. # Originally by Fran,cois Pinard , 1996. # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2, or (at your option) # any later version. # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # You should have received a copy of the GNU General Public License # along with this program. If not, see . # As a special exception to the GNU General Public License, if you # distribute this file as part of a program that contains a # configuration script generated by Autoconf, you may include it under # the same distribution terms that you use for the rest of that program. if test $# -eq 0; then echo 1>&2 "Try \`$0 --help' for more information" exit 1 fi run=: sed_output='s/.* --output[ =]\([^ ]*\).*/\1/p' sed_minuso='s/.* -o \([^ ]*\).*/\1/p' # In the cases where this matters, `missing' is being run in the # srcdir already. if test -f configure.ac; then configure_ac=configure.ac else configure_ac=configure.in fi msg="missing on your system" case $1 in --run) # Try to run requested program, and just exit if it succeeds. run= shift "$@" && exit 0 # Exit code 63 means version mismatch. This often happens # when the user try to use an ancient version of a tool on # a file that requires a minimum version. In this case we # we should proceed has if the program had been absent, or # if --run hadn't been passed. if test $? = 63; then run=: msg="probably too old" fi ;; -h|--h|--he|--hel|--help) echo "\ $0 [OPTION]... PROGRAM [ARGUMENT]... Handle \`PROGRAM [ARGUMENT]...' for when PROGRAM is missing, or return an error status if there is no known handling for PROGRAM. Options: -h, --help display this help and exit -v, --version output version information and exit --run try to run the given command, and emulate it if it fails Supported PROGRAM values: aclocal touch file \`aclocal.m4' autoconf touch file \`configure' autoheader touch file \`config.h.in' autom4te touch the output file, or create a stub one automake touch all \`Makefile.in' files bison create \`y.tab.[ch]', if possible, from existing .[ch] flex create \`lex.yy.c', if possible, from existing .c help2man touch the output file lex create \`lex.yy.c', if possible, from existing .c makeinfo touch the output file yacc create \`y.tab.[ch]', if possible, from existing .[ch] Version suffixes to PROGRAM as well as the prefixes \`gnu-', \`gnu', and \`g' are ignored when checking the name. Send bug reports to ." exit $? ;; -v|--v|--ve|--ver|--vers|--versi|--versio|--version) echo "missing $scriptversion (GNU Automake)" exit $? ;; -*) echo 1>&2 "$0: Unknown \`$1' option" echo 1>&2 "Try \`$0 --help' for more information" exit 1 ;; esac # normalize program name to check for. program=`echo "$1" | sed ' s/^gnu-//; t s/^gnu//; t s/^g//; t'` # Now exit if we have it, but it failed. Also exit now if we # don't have it and --version was passed (most likely to detect # the program). This is about non-GNU programs, so use $1 not # $program. case $1 in lex*|yacc*) # Not GNU programs, they don't have --version. ;; *) if test -z "$run" && ($1 --version) > /dev/null 2>&1; then # We have it, but it failed. exit 1 elif test "x$2" = "x--version" || test "x$2" = "x--help"; then # Could not run --version or --help. This is probably someone # running `$TOOL --version' or `$TOOL --help' to check whether # $TOOL exists and not knowing $TOOL uses missing. exit 1 fi ;; esac # If it does not exist, or fails to run (possibly an outdated version), # try to emulate it. case $program in aclocal*) echo 1>&2 "\ WARNING: \`$1' is $msg. You should only need it if you modified \`acinclude.m4' or \`${configure_ac}'. You might want to install the \`Automake' and \`Perl' packages. Grab them from any GNU archive site." touch aclocal.m4 ;; autoconf*) echo 1>&2 "\ WARNING: \`$1' is $msg. You should only need it if you modified \`${configure_ac}'. You might want to install the \`Autoconf' and \`GNU m4' packages. Grab them from any GNU archive site." touch configure ;; autoheader*) echo 1>&2 "\ WARNING: \`$1' is $msg. You should only need it if you modified \`acconfig.h' or \`${configure_ac}'. You might want to install the \`Autoconf' and \`GNU m4' packages. Grab them from any GNU archive site." files=`sed -n 's/^[ ]*A[CM]_CONFIG_HEADER(\([^)]*\)).*/\1/p' ${configure_ac}` test -z "$files" && files="config.h" touch_files= for f in $files; do case $f in *:*) touch_files="$touch_files "`echo "$f" | sed -e 's/^[^:]*://' -e 's/:.*//'`;; *) touch_files="$touch_files $f.in";; esac done touch $touch_files ;; automake*) echo 1>&2 "\ WARNING: \`$1' is $msg. You should only need it if you modified \`Makefile.am', \`acinclude.m4' or \`${configure_ac}'. You might want to install the \`Automake' and \`Perl' packages. Grab them from any GNU archive site." find . -type f -name Makefile.am -print | sed 's/\.am$/.in/' | while read f; do touch "$f"; done ;; autom4te*) echo 1>&2 "\ WARNING: \`$1' is needed, but is $msg. You might have modified some files without having the proper tools for further handling them. You can get \`$1' as part of \`Autoconf' from any GNU archive site." file=`echo "$*" | sed -n "$sed_output"` test -z "$file" && file=`echo "$*" | sed -n "$sed_minuso"` if test -f "$file"; then touch $file else test -z "$file" || exec >$file echo "#! /bin/sh" echo "# Created by GNU Automake missing as a replacement of" echo "# $ $@" echo "exit 0" chmod +x $file exit 1 fi ;; bison*|yacc*) echo 1>&2 "\ WARNING: \`$1' $msg. You should only need it if you modified a \`.y' file. You may need the \`Bison' package in order for those modifications to take effect. You can get \`Bison' from any GNU archive site." rm -f y.tab.c y.tab.h if test $# -ne 1; then eval LASTARG=\${$#} case $LASTARG in *.y) SRCFILE=`echo "$LASTARG" | sed 's/y$/c/'` if test -f "$SRCFILE"; then cp "$SRCFILE" y.tab.c fi SRCFILE=`echo "$LASTARG" | sed 's/y$/h/'` if test -f "$SRCFILE"; then cp "$SRCFILE" y.tab.h fi ;; esac fi if test ! -f y.tab.h; then echo >y.tab.h fi if test ! -f y.tab.c; then echo 'main() { return 0; }' >y.tab.c fi ;; lex*|flex*) echo 1>&2 "\ WARNING: \`$1' is $msg. You should only need it if you modified a \`.l' file. You may need the \`Flex' package in order for those modifications to take effect. You can get \`Flex' from any GNU archive site." rm -f lex.yy.c if test $# -ne 1; then eval LASTARG=\${$#} case $LASTARG in *.l) SRCFILE=`echo "$LASTARG" | sed 's/l$/c/'` if test -f "$SRCFILE"; then cp "$SRCFILE" lex.yy.c fi ;; esac fi if test ! -f lex.yy.c; then echo 'main() { return 0; }' >lex.yy.c fi ;; help2man*) echo 1>&2 "\ WARNING: \`$1' is $msg. You should only need it if you modified a dependency of a manual page. You may need the \`Help2man' package in order for those modifications to take effect. You can get \`Help2man' from any GNU archive site." file=`echo "$*" | sed -n "$sed_output"` test -z "$file" && file=`echo "$*" | sed -n "$sed_minuso"` if test -f "$file"; then touch $file else test -z "$file" || exec >$file echo ".ab help2man is required to generate this page" exit $? fi ;; makeinfo*) echo 1>&2 "\ WARNING: \`$1' is $msg. You should only need it if you modified a \`.texi' or \`.texinfo' file, or any other file indirectly affecting the aspect of the manual. The spurious call might also be the consequence of using a buggy \`make' (AIX, DU, IRIX). You might want to install the \`Texinfo' package or the \`GNU make' package. Grab either from any GNU archive site." # The file to touch is that specified with -o ... file=`echo "$*" | sed -n "$sed_output"` test -z "$file" && file=`echo "$*" | sed -n "$sed_minuso"` if test -z "$file"; then # ... or it is the one specified with @setfilename ... infile=`echo "$*" | sed 's/.* \([^ ]*\) *$/\1/'` file=`sed -n ' /^@setfilename/{ s/.* \([^ ]*\) *$/\1/ p q }' $infile` # ... or it is derived from the source name (dir/f.texi becomes f.info) test -z "$file" && file=`echo "$infile" | sed 's,.*/,,;s,.[^.]*$,,'`.info fi # If the file does not exist, the user really needs makeinfo; # let's fail without touching anything. test -f $file || exit 1 touch $file ;; *) echo 1>&2 "\ WARNING: \`$1' is needed, and is $msg. You might have modified some files without having the proper tools for further handling them. Check the \`README' file, it often tells you about the needed prerequisites for installing this package. You may also peek at any GNU archive site, in case some other package would contain this missing \`$1' program." exit 1 ;; esac exit 0 # Local variables: # eval: (add-hook 'write-file-hooks 'time-stamp) # time-stamp-start: "scriptversion=" # time-stamp-format: "%:y-%02m-%02d.%02H" # time-stamp-time-zone: "UTC" # time-stamp-end: "; # UTC" # End: apache-couchdb-1.5.0/build-aux/dist-error0000755000175000001440000000171712230722213015172 00000000000000#!/bin/sh -e # 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. # This script is called by the build system and is used to provide an error # about missing or empty files. Some files are optional, and will be built when # the environment allows. But these files are required for distribution. cat << EOF ERROR: This file is missing or incomplete: $1 This file is optional at build and install time, but is required when preparing a distribution. EOF exit 1 apache-couchdb-1.5.0/build-aux/sphinx-build0000755000175000001440000000402012230722213015474 00000000000000#!/bin/sh -e # 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. # This script is called by the build system and is used to call sphinx-build if # is is available, or alternatively, emit a warning, and perform a no-op. Any # required directories or Makefiles are created and stubbed out as appropriate. if test -z "`which sphinx-build`"; then missing=yes cat << EOF WARNING: 'sphinx-build' is needed, and is missing on your system. You might have modified some files without having the proper tools for further handling them. EOF fi if test "$2" = "texinfo"; then if test -z "`which makeinfo`"; then missing=yes cat << EOF WARNING: 'makeinfo' is needed, and is missing on your system. You might have modified some files without having the proper tools for further handling them. EOF fi if test "$missing" != "yes"; then sphinx-build $* else mkdir -p texinfo echo "info:" > texinfo/Makefile fi fi if test "$2" = "latex"; then if test -z "`which pdflatex`"; then missing=yes cat << EOF WARNING: 'pdflatex' is needed, and is missing on your system. You might have modified some files without having the proper tools for further handling them. EOF fi if test "$missing" != "yes"; then sphinx-build $* else mkdir -p latex echo "all-pdf:" > latex/Makefile fi fi if test "$2" = "html"; then if test "$missing" != "yes"; then sphinx-build $* else mkdir -p html fi fi apache-couchdb-1.5.0/build-aux/sphinx-touch0000755000175000001440000000162412230722213015526 00000000000000#!/bin/sh -e # 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. # This script is called by the build system and is used to touch the list of # expected output files when sphinx-build is not available. If the files exist, # this will satisfy make. If they do not exist, we create of empty files. if test -z "`which sphinx-build`"; then for file in $*; do mkdir -p `dirname $file` touch $file done fiapache-couchdb-1.5.0/INSTALL.Windows0000644000175000001440000001275412230722213013745 00000000000000Apache CouchDB README.Windows ============================== For a high-level guide to Microsoft Windows. Troubleshooting --------------- There is a troubleshooting guide: http://wiki.apache.org/couchdb/Troubleshooting There is a wiki for general documentation: http://wiki.apache.org/couchdb/ And some Windows-specific tips: http://wiki.apache.org/couchdb/Quirks_on_Windows There are collection of friendly mailing lists: http://couchdb.apache.org/community/lists.html Please work through these in order if you experience any problems. Dependencies ------------ You will need the following installed: * Erlang OTP (>=14B01, =4.*) (http://icu-project.org/) * OpenSSL (>=0.9.8r) (http://www.openssl.org/) * Mozilla SpiderMonkey (=1.8.5) (http://www.mozilla.org/js/spidermonkey/) * libcurl (>=7.20) (http://curl.haxx.se/libcurl/) * Cygwin (http://www.cygwin.com/) * Microsoft SDK 7.0 or 7.1 (http://www.microsoft.com/en-us/download/details.aspx?id=8279) * Python (>= 2.68) for docs (http://python.org/) * Python Sphinx (>=1.1.3) (http://pypi.python.org/pypi/Sphinx) General Notes ------------- * When installing Cygwin, be sure to select all the `development` tools. * When installing Erlang, you must build it from source. * The CouchDB build requires a number of the Erlang build scripts. * All dependent libraries should be built with the same version of microsoft SDK. * Do not try to link against libraries built with, or included in, Cygwin or MingW. They are not compatible with the Erlang/OTP or CouchDB build scripts. * ICU version 4.6 and later will build cleanly using MSBuild. * Python and Sphinx are optional for building the online documentation. Use cygwin-provided Python and install Sphinx via easy_install or pip. Further information is here http://pypi.python.org/pypi/setuptools#id4 Setting Up Cygwin ----------------- Before starting any Cygwin terminals, run: set CYGWIN=nontsec To set up your environment, run: [VS_BIN]/vcvars32.bat Replace [VS_BIN] with the path to your Visual Studio `bin` directory. You must check that: * The `which link` command points to the Microsoft linker. * The `which cl` command points to the Microsoft compiler. * The `which mc` command points to the Microsoft message compiler. * The `which mt` command points to the Microsoft manifest tool. * The `which nmake` command points to the Microsoft make tool. If you do not do this, the build may fail due to Cygwin ones found in `/usr/bin` being used instead. Building Erlang --------------- You must include Win32 OpenSSL, built statically from source. Use exactly the same version as required by the Erlang/OTP build process. However, you can skip the GUI tools by running: echo "skipping gs" > lib/gs/SKIP echo "skipping ic" > lib/ic/SKIP echo "skipping jinterface" > lib/jinterface/SKIP Follow the rest of the Erlang instructions as described. After running: ./otp_build release -a You should run: ./release/win32/Install.exe -s This will set up the release/win32/bin directory correctly. The CouchDB installation scripts currently write their data directly into this location. To set up your environment for building CouchDB, run: eval `./otp_build env_win32` To set up the `ERL_TOP` environment variable, run: export ERL_TOP=[ERL_TOP] Replace `[ERL_TOP]` with the Erlang source directory name. Remember to use `/cygdrive/c/` instead of `c:/` as the directory prefix. To set up your path, run: export PATH=$ERL_TOP/release/win32/erts-5.8.5/bin:$PATH If everything was successful, you should be ready to build CouchDB. Relax. Building CouchDB ---------------- Note that `win32-curl` is only required if you wish to run the developer tests. The documentation step may be skipped using `--disable-docs` if you wish. Once you have satisfied the dependencies you should run: ./configure \ --with-js-include=/cygdrive/c/path_to_spidermonkey_include \ --with-js-lib=/cygdrive/c/path_to_spidermonkey_lib \ --with-win32-icu-binaries=/cygdrive/c/path_to_icu_binaries_root \ --with-erlang=$ERL_TOP/release/win32/usr/include \ --with-win32-curl=/cygdrive/c/path/to/curl/root/directory \ --with-openssl-bin-dir=/cygdrive/c/openssl/bin \ --with-msvc-redist-dir=/cygdrive/c/dir/with/vcredist_platform_executable \ --disable-init \ --disable-launchd \ --prefix=$ERL_TOP/release/win32 This command could take a while to complete. If everything was successful you should see the following message: You have configured Apache CouchDB, time to relax. Relax. To install CouchDB you should run: make install If everything was successful you should see the following message: You have installed Apache CouchDB, time to relax. Relax. To build the .exe installer package, you should run: make dist Alternatively, you may run CouchDB directly from the build tree, but to avoid any contamination do not run `make dist` after this. First Run --------- You can start the CouchDB server by running: $ERL_TOP/release/win32/bin/couchdb.bat When CouchDB starts it should eventually display the following message: Apache CouchDB has started, time to relax. Relax. To check that everything has worked, point your web browser to: http://127.0.0.1:5984/_utils/index.html From here you should run the verification tests in Firefox. apache-couchdb-1.5.0/AUTHORS0000644000175000001440000000205312230722213012322 00000000000000Apache CouchDB AUTHORS ====================== A number of people have contributed directly to Apache CouchDB by writing documentation or developing software. Some of these people are: * Damien Katz * Jan Lehnardt * Noah Slater * Christopher Lenz * J. Chris Anderson * Paul Joseph Davis * Adam Kocoloski * Jason Davies * Mark Hammond * BenoƮt Chesneau * Filipe Manana * Robert Newson * Randall Leeds * Bob Dionne * Dave Cottlehuber * Jason Smith * Joan Touzet * Dale Harvey * Dirkjan Ochtman * Alexander Shorin * Garren Smith * Sue Lockwood For a list of other credits see the `THANKS` file. apache-couchdb-1.5.0/INSTALL0000644000175000001440000003660012021144127012310 00000000000000Installation Instructions ************************* Copyright (C) 1994-1996, 1999-2002, 2004-2011 Free Software Foundation, Inc. Copying and distribution of this file, with or without modification, are permitted in any medium without royalty provided the copyright notice and this notice are preserved. This file is offered as-is, without warranty of any kind. Basic Installation ================== Briefly, the shell commands `./configure; make; make install' should configure, build, and install this package. The following more-detailed instructions are generic; see the `README' file for instructions specific to this package. Some packages provide this `INSTALL' file but do not implement all of the features documented below. The lack of an optional feature in a given package is not necessarily a bug. More recommendations for GNU packages can be found in *note Makefile Conventions: (standards)Makefile Conventions. The `configure' shell script attempts to guess correct values for various system-dependent variables used during compilation. It uses those values to create a `Makefile' in each directory of the package. It may also create one or more `.h' files containing system-dependent definitions. Finally, it creates a shell script `config.status' that you can run in the future to recreate the current configuration, and a file `config.log' containing compiler output (useful mainly for debugging `configure'). It can also use an optional file (typically called `config.cache' and enabled with `--cache-file=config.cache' or simply `-C') that saves the results of its tests to speed up reconfiguring. Caching is disabled by default to prevent problems with accidental use of stale cache files. If you need to do unusual things to compile the package, please try to figure out how `configure' could check whether to do them, and mail diffs or instructions to the address given in the `README' so they can be considered for the next release. If you are using the cache, and at some point `config.cache' contains results you don't want to keep, you may remove or edit it. The file `configure.ac' (or `configure.in') is used to create `configure' by a program called `autoconf'. You need `configure.ac' if you want to change it or regenerate `configure' using a newer version of `autoconf'. The simplest way to compile this package is: 1. `cd' to the directory containing the package's source code and type `./configure' to configure the package for your system. Running `configure' might take a while. While running, it prints some messages telling which features it is checking for. 2. Type `make' to compile the package. 3. Optionally, type `make check' to run any self-tests that come with the package, generally using the just-built uninstalled binaries. 4. Type `make install' to install the programs and any data files and documentation. When installing into a prefix owned by root, it is recommended that the package be configured and built as a regular user, and only the `make install' phase executed with root privileges. 5. Optionally, type `make installcheck' to repeat any self-tests, but this time using the binaries in their final installed location. This target does not install anything. Running this target as a regular user, particularly if the prior `make install' required root privileges, verifies that the installation completed correctly. 6. You can remove the program binaries and object files from the source code directory by typing `make clean'. To also remove the files that `configure' created (so you can compile the package for a different kind of computer), type `make distclean'. There is also a `make maintainer-clean' target, but that is intended mainly for the package's developers. If you use it, you may have to get all sorts of other programs in order to regenerate files that came with the distribution. 7. Often, you can also type `make uninstall' to remove the installed files again. In practice, not all packages have tested that uninstallation works correctly, even though it is required by the GNU Coding Standards. 8. Some packages, particularly those that use Automake, provide `make distcheck', which can by used by developers to test that all other targets like `make install' and `make uninstall' work correctly. This target is generally not run by end users. Compilers and Options ===================== Some systems require unusual options for compilation or linking that the `configure' script does not know about. Run `./configure --help' for details on some of the pertinent environment variables. You can give `configure' initial values for configuration parameters by setting variables in the command line or in the environment. Here is an example: ./configure CC=c99 CFLAGS=-g LIBS=-lposix *Note Defining Variables::, for more details. Compiling For Multiple Architectures ==================================== You can compile the package for more than one kind of computer at the same time, by placing the object files for each architecture in their own directory. To do this, you can use GNU `make'. `cd' to the directory where you want the object files and executables to go and run the `configure' script. `configure' automatically checks for the source code in the directory that `configure' is in and in `..'. This is known as a "VPATH" build. With a non-GNU `make', it is safer to compile the package for one architecture at a time in the source code directory. After you have installed the package for one architecture, use `make distclean' before reconfiguring for another architecture. On MacOS X 10.5 and later systems, you can create libraries and executables that work on multiple system types--known as "fat" or "universal" binaries--by specifying multiple `-arch' options to the compiler but only a single `-arch' option to the preprocessor. Like this: ./configure CC="gcc -arch i386 -arch x86_64 -arch ppc -arch ppc64" \ CXX="g++ -arch i386 -arch x86_64 -arch ppc -arch ppc64" \ CPP="gcc -E" CXXCPP="g++ -E" This is not guaranteed to produce working output in all cases, you may have to build one architecture at a time and combine the results using the `lipo' tool if you have problems. Installation Names ================== By default, `make install' installs the package's commands under `/usr/local/bin', include files under `/usr/local/include', etc. You can specify an installation prefix other than `/usr/local' by giving `configure' the option `--prefix=PREFIX', where PREFIX must be an absolute file name. You can specify separate installation prefixes for architecture-specific files and architecture-independent files. If you pass the option `--exec-prefix=PREFIX' to `configure', the package uses PREFIX as the prefix for installing programs and libraries. Documentation and other data files still use the regular prefix. In addition, if you use an unusual directory layout you can give options like `--bindir=DIR' to specify different values for particular kinds of files. Run `configure --help' for a list of the directories you can set and what kinds of files go in them. In general, the default for these options is expressed in terms of `${prefix}', so that specifying just `--prefix' will affect all of the other directory specifications that were not explicitly provided. The most portable way to affect installation locations is to pass the correct locations to `configure'; however, many packages provide one or both of the following shortcuts of passing variable assignments to the `make install' command line to change installation locations without having to reconfigure or recompile. The first method involves providing an override variable for each affected directory. For example, `make install prefix=/alternate/directory' will choose an alternate location for all directory configuration variables that were expressed in terms of `${prefix}'. Any directories that were specified during `configure', but not in terms of `${prefix}', must each be overridden at install time for the entire installation to be relocated. The approach of makefile variable overrides for each directory variable is required by the GNU Coding Standards, and ideally causes no recompilation. However, some platforms have known limitations with the semantics of shared libraries that end up requiring recompilation when using this method, particularly noticeable in packages that use GNU Libtool. The second method involves providing the `DESTDIR' variable. For example, `make install DESTDIR=/alternate/directory' will prepend `/alternate/directory' before all installation names. The approach of `DESTDIR' overrides is not required by the GNU Coding Standards, and does not work on platforms that have drive letters. On the other hand, it does better at avoiding recompilation issues, and works well even when some directory options were not specified in terms of `${prefix}' at `configure' time. Optional Features ================= If the package supports it, you can cause programs to be installed with an extra prefix or suffix on their names by giving `configure' the option `--program-prefix=PREFIX' or `--program-suffix=SUFFIX'. Some packages pay attention to `--enable-FEATURE' options to `configure', where FEATURE indicates an optional part of the package. They may also pay attention to `--with-PACKAGE' options, where PACKAGE is something like `gnu-as' or `x' (for the X Window System). The `README' should mention any `--enable-' and `--with-' options that the package recognizes. For packages that use the X Window System, `configure' can usually find the X include and library files automatically, but if it doesn't, you can use the `configure' options `--x-includes=DIR' and `--x-libraries=DIR' to specify their locations. Some packages offer the ability to configure how verbose the execution of `make' will be. For these packages, running `./configure --enable-silent-rules' sets the default to minimal output, which can be overridden with `make V=1'; while running `./configure --disable-silent-rules' sets the default to verbose, which can be overridden with `make V=0'. Particular systems ================== On HP-UX, the default C compiler is not ANSI C compatible. If GNU CC is not installed, it is recommended to use the following options in order to use an ANSI C compiler: ./configure CC="cc -Ae -D_XOPEN_SOURCE=500" and if that doesn't work, install pre-built binaries of GCC for HP-UX. HP-UX `make' updates targets which have the same time stamps as their prerequisites, which makes it generally unusable when shipped generated files such as `configure' are involved. Use GNU `make' instead. On OSF/1 a.k.a. Tru64, some versions of the default C compiler cannot parse its `' header file. The option `-nodtk' can be used as a workaround. If GNU CC is not installed, it is therefore recommended to try ./configure CC="cc" and if that doesn't work, try ./configure CC="cc -nodtk" On Solaris, don't put `/usr/ucb' early in your `PATH'. This directory contains several dysfunctional programs; working variants of these programs are available in `/usr/bin'. So, if you need `/usr/ucb' in your `PATH', put it _after_ `/usr/bin'. On Haiku, software installed for all users goes in `/boot/common', not `/usr/local'. It is recommended to use the following options: ./configure --prefix=/boot/common Specifying the System Type ========================== There may be some features `configure' cannot figure out automatically, but needs to determine by the type of machine the package will run on. Usually, assuming the package is built to be run on the _same_ architectures, `configure' can figure that out, but if it prints a message saying it cannot guess the machine type, give it the `--build=TYPE' option. TYPE can either be a short name for the system type, such as `sun4', or a canonical name which has the form: CPU-COMPANY-SYSTEM where SYSTEM can have one of these forms: OS KERNEL-OS See the file `config.sub' for the possible values of each field. If `config.sub' isn't included in this package, then this package doesn't need to know the machine type. If you are _building_ compiler tools for cross-compiling, you should use the option `--target=TYPE' to select the type of system they will produce code for. If you want to _use_ a cross compiler, that generates code for a platform different from the build platform, you should specify the "host" platform (i.e., that on which the generated programs will eventually be run) with `--host=TYPE'. Sharing Defaults ================ If you want to set default values for `configure' scripts to share, you can create a site shell script called `config.site' that gives default values for variables like `CC', `cache_file', and `prefix'. `configure' looks for `PREFIX/share/config.site' if it exists, then `PREFIX/etc/config.site' if it exists. Or, you can set the `CONFIG_SITE' environment variable to the location of the site script. A warning: not all `configure' scripts look for a site script. Defining Variables ================== Variables not defined in a site shell script can be set in the environment passed to `configure'. However, some packages may run configure again during the build, and the customized values of these variables may be lost. In order to avoid this problem, you should set them in the `configure' command line, using `VAR=value'. For example: ./configure CC=/usr/local2/bin/gcc causes the specified `gcc' to be used as the C compiler (unless it is overridden in the site shell script). Unfortunately, this technique does not work for `CONFIG_SHELL' due to an Autoconf bug. Until the bug is fixed you can use this workaround: CONFIG_SHELL=/bin/bash /bin/bash ./configure CONFIG_SHELL=/bin/bash `configure' Invocation ====================== `configure' recognizes the following options to control how it operates. `--help' `-h' Print a summary of all of the options to `configure', and exit. `--help=short' `--help=recursive' Print a summary of the options unique to this package's `configure', and exit. The `short' variant lists options used only in the top level, while the `recursive' variant lists options also present in any nested packages. `--version' `-V' Print the version of Autoconf used to generate the `configure' script, and exit. `--cache-file=FILE' Enable the cache: use and save the results of the tests in FILE, traditionally `config.cache'. FILE defaults to `/dev/null' to disable caching. `--config-cache' `-C' Alias for `--cache-file=config.cache'. `--quiet' `--silent' `-q' Do not print messages saying which checks are being made. To suppress all normal output, redirect it to `/dev/null' (any error messages will still be shown). `--srcdir=DIR' Look for the package's source code in directory DIR. Usually `configure' can determine that directory automatically. `--prefix=DIR' Use DIR as the installation prefix. *note Installation Names:: for more details, including other options available for fine-tuning the installation locations. `--no-create' `-n' Run the configure checks, but stop before creating any output files. `configure' also accepts some other, not widely useful, options. Run `configure --help' for more details. apache-couchdb-1.5.0/DEVELOPERS0000644000175000001440000001216012230722213012645 00000000000000Apache CouchDB DEVELOPERS ========================= Before you start here, read `INSTALL.Unix` (or `INSTALL.Windows`) and follow the setup instructions including the installation of all the listed dependencies for your system. Only follow these instructions if you are building from a source checkout. If you're unsure what this means, ignore this document. Dependencies ------------ You will need the following installed: * GNU Libtool (http://www.gnu.org/software/libtool/) * GNU Automake (>=1.6.3) (http://www.gnu.org/software/automake/) * GNU Autoconf (>=2.63) (http://www.gnu.org/software/autoconf/) * GNU Autoconf Archive (http://www.gnu.org/software/autoconf-archive/) * pkg-config (http://www.freedesktop.org/wiki/Software/pkg-config) You may also need: * Sphinx (http://sphinx.pocoo.org/) * LaTex (http://www.latex-project.org/) * GNU Texinfo (http://www.gnu.org/software/texinfo/) * GNU help2man (http://www.gnu.org/software/help2man/) * GnuPG (http://www.gnupg.org/) * md5sum (http://www.microbrew.org/tools/md5sha1sum/) * sha1sum (http://www.microbrew.org/tools/md5sha1sum/) The first of these optional dependencies are required for building the documentation. The last three are needed to build releases. You will need these optional dependencies installed if: * You are working on the documentation, or * You are preparing a distribution archive However, you do not need them if: * You are building from a distribution archive, or * You don't care about building the documentation Here is a list of *optional* dependencies for various operating systems. Installation will be easiest, when you install them all. Debian-based (inc. Ubuntu) Systems ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ sudo apt-get install help2man sudo apt-get install python-sphinx sudo apt-get install texlive-latex-base sudo apt-get install texlive-latex-recommended sudo apt-get install texlive-latex-extra sudo apt-get install texlive-fonts-recommended sudo apt-get install texinfo sudo apt-get install gnupg Gentoo-based Systems ~~~~~~~~~~~~~~~~~~~~ sudo emerge texinfo sudo emerge gnupg sudo emerge coreutils sudo emerge pkgconfig sudo emerge help2man sudo USE=latex emerge sphinx RedHat-based (Fedora, Centos, RHEL) Systems ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ sudo yum install help2man sudo yum install python-sphinx sudo yum install python-docutils sudo yum install python-pygments sudo yum install texlive-latex sudo yum install texlive-latex-fonts sudo yum install texinfo sudo yum install gnupg Mac OS X ~~~~~~~~ Install Homebrew, if you do not have it already: https://github.com/mxcl/homebrew Unless you want to install the optional dependencies, skip to the next section. Install what else we can with Homebrew: brew install help2man brew install gnupg brew install md5sha1sum If you don't already have pip installed, install it: sudo easy_install pip Now, install the required Python packages: sudo pip install sphinx sudo pip install docutils sudo pip install pygments Download MaxTeX from here: http://www.tug.org/mactex/ Follow the instructions to get a working LaTeX install on your system. Windows ~~~~~~~ Follow the instructions in INSTALL.Windows and build all components from source, using the same Visual C++ compiler and runtime. Bootstrapping ------------- Bootstrap the pristine source by running: ./bootstrap You must repeat this step every time you update your source checkout. Configuring ----------- Configure the source by running: ./configure Note that this will not fail when the optional dependencies are missing. To ensure the optional dependencies are installed, run: ./configure --enable-strictness If you don't care about docs and want to skip the whole thing, run: ./configure --disable-docs If you're working on the build system itself, you can run: ./configure --disable-tests This skips the tests allowing quicker `make' cycles. If you want to build it into different destination than `/usr/local`. ./configure --prefix=/ Testing ------- Check the test suite by running: make check Generate a coverage report by running: make cover Please report any problems to the developer's mailing list. Releasing --------- The release procedure is documented here: https://wiki.apache.org/couchdb/Release_Procedure Unix-like Systems ~~~~~~~~~~~~~~~~~ Prepare the release artefacts by running: make distcheck You can prepare signed release artefacts by running: make distsign The release artefacts can be found in the root source directory. Microsoft Windows ~~~~~~~~~~~~~~~~~ Prepare the release artefacts by running: make dist The release artefacts can be found in the `etc/windows` directory. Until the build system has been improved, you must make sure that you run this command from a clean source checkout. If you do not, your test database and log files will be bundled up in the release artefact.