Beispiel #1
0
    def _run(self, command):
        compiler = self._settings.get_safe("compiler")
        conan_v2_error("compiler setting should be defined.", not compiler)
        the_os = self._settings.get_safe("os")
        is_clangcl = the_os == "Windows" and compiler == "clang"
        is_msvc = compiler == "Visual Studio"
        is_intel = compiler == "intel"
        context = tools.no_op()

        if (is_msvc or is_clangcl) and platform.system() == "Windows":
            if self.generator in [
                    "Ninja", "NMake Makefiles", "NMake Makefiles JOM"
            ]:
                vcvars_dict = tools.vcvars_dict(self._settings,
                                                force=True,
                                                filter_known_paths=False,
                                                output=self._conanfile.output)
                context = _environment_add(vcvars_dict,
                                           post=self._append_vcvars)
        elif is_intel:
            if self.generator in [
                    "Ninja", "NMake Makefiles", "NMake Makefiles JOM",
                    "Unix Makefiles"
            ]:
                intel_compilervars_dict = tools.intel_compilervars_dict(
                    self._conanfile, force=True)
                context = _environment_add(intel_compilervars_dict,
                                           post=self._append_vcvars)
        with context:
            self._conanfile.run(command)
Beispiel #2
0
def build_sln_command(settings, sln_path, targets=None, upgrade_project=True, build_type=None,
                      arch=None, parallel=True, toolset=None, platforms=None, output=None,
                      verbosity=None, definitions=None):
    """
    Use example:
        build_command = build_sln_command(self.settings, "myfile.sln", targets=["SDL2_image"])
        command = "%s && %s" % (tools.vcvars_command(self.settings), build_command)
        self.run(command)
    """
    conan_v2_error("'tools.build_sln_command' is deprecated, use 'MSBuild()' helper instead")
    from conans.client.build.msbuild import MSBuild
    tmp = MSBuild(settings)
    output = default_output(output, fn_name='conans.client.tools.win.build_sln_command')
    tmp._output = output

    # Generate the properties file
    props_file_contents = tmp._get_props_file_contents(definitions)
    tmp_path = os.path.join(mkdir_tmp(), ".conan_properties")
    save(tmp_path, props_file_contents)

    # Build command
    command = tmp.get_command(sln_path, tmp_path,
                              targets=targets, upgrade_project=upgrade_project,
                              build_type=build_type, arch=arch, parallel=parallel,
                              toolset=toolset, platforms=platforms, use_env=False,
                              verbosity=verbosity)

    return command
Beispiel #3
0
    def _build(self, build_type=None, target=None):
        bf = self._conanfile.build_folder
        if self._build_folder:
            bf = os.path.join(self._conanfile.build_folder, self._build_folder)

        if build_type and not self._is_multiconfiguration:
            self._conanfile.output.error(
                "Don't specify 'build_type' at build time for "
                "single-config build systems")

        bt = build_type or self._conanfile.settings.get_safe("build_type")
        conan_v2_error("build_type setting should be defined.", not bt)

        if bt and self._is_multiconfiguration:
            build_config = "--config %s" % bt
        else:
            build_config = ""

        args = []
        if target is not None:
            args = ["--target", target]

        cmd_line_args = _cmake_cmd_line_args(self._conanfile, self._generator,
                                             self._parallel)
        if cmd_line_args:
            args += ['--'] + cmd_line_args

        arg_list = [args_to_string([bf]), build_config, args_to_string(args)]
        command = "%s --build %s" % (self._cmake_program,
                                     join_arguments(arg_list))
        self._conanfile.output.info("CMake command: %s" % command)
        self._conanfile.run(command)
Beispiel #4
0
def run_configure_method(conanfile, down_options, down_ref, ref):
    """ Run all the config-related functions for the given conanfile object """

    # Avoid extra time manipulating the sys.path for python
    with get_env_context_manager(conanfile, without_python=True):
        if hasattr(conanfile, "config"):
            conan_v2_error("config() has been deprecated. Use config_options() and configure()")
            with conanfile_exception_formatter(str(conanfile), "config"):
                conanfile.config()

        with conanfile_exception_formatter(str(conanfile), "config_options"):
            conanfile.config_options()

        conanfile.options.propagate_upstream(down_options, down_ref, ref)

        if hasattr(conanfile, "config"):
            with conanfile_exception_formatter(str(conanfile), "config"):
                conanfile.config()

        with conanfile_exception_formatter(str(conanfile), "configure"):
            conanfile.configure()

        conanfile.settings.validate()  # All has to be ok!
        conanfile.options.validate()
        # Recipe provides its own name if nothing else is defined
        conanfile.provides = make_tuple(conanfile.provides or conanfile.name)

        if conanfile.deprecated:
            from six import string_types
            message = "Recipe '%s' is deprecated" % conanfile.display_name
            if isinstance(conanfile.deprecated, string_types):
                message += " in favor of '%s'" % conanfile.deprecated
            message += ". Please, consider changing your requirements."
            conanfile.output.warn(message)
Beispiel #5
0
    def initialize(self, settings, env, buildenv=None):
        self._conan_buildenv = buildenv
        if isinstance(self.generators, str):
            self.generators = [self.generators]
        # User defined options
        self.options = create_options(self)
        self.requires = create_requirements(self)
        self.settings = create_settings(self, settings)

        conan_v2_error("Setting 'cppstd' is deprecated in favor of 'compiler.cppstd',"
                       " please update your recipe.", 'cppstd' in self.settings.fields)

        # needed variables to pack the project
        self.cpp_info = None  # Will be initialized at processing time
        self._conan_dep_cpp_info = None  # Will be initialized at processing time
        self.deps_cpp_info = DepsCppInfo()

        # environment variables declared in the package_info
        self.env_info = None  # Will be initialized at processing time
        self.deps_env_info = DepsEnvInfo()

        # user declared variables
        self.user_info = None
        # Keys are the package names (only 'host' if different contexts)
        self.deps_user_info = DepsUserInfo()

        # user specified env variables
        self._conan_env_values = env.copy()  # user specified -e

        if self.description is not None and not isinstance(self.description, six.string_types):
            raise ConanException("Recipe 'description' must be a string.")

        if not hasattr(self, "virtualenv"):  # Allow the user to override it with True or False
            self.virtualenv = True
Beispiel #6
0
def msvc_build_command(settings,
                       sln_path,
                       targets=None,
                       upgrade_project=True,
                       build_type=None,
                       arch=None,
                       parallel=True,
                       force_vcvars=False,
                       toolset=None,
                       platforms=None,
                       output=None):
    """ Do both: set the environment variables and call the .sln build
    """
    conan_v2_error(
        "'tools.msvc_build_command' is deprecated, use 'MSBuild()' helper instead"
    )
    vcvars_cmd = vcvars_command(settings, force=force_vcvars, output=output)
    build = build_sln_command(settings,
                              sln_path,
                              targets,
                              upgrade_project,
                              build_type,
                              arch,
                              parallel,
                              toolset=toolset,
                              platforms=platforms,
                              output=output)
    command = "%s && %s" % (vcvars_cmd, build)
    return command
Beispiel #7
0
    def __init__(self, conanfile, backend=None, build_type=None, append_vcvars=False):
        """
        :param conanfile: Conanfile instance (or settings for retro compatibility)
        :param backend: Generator name to use or none to autodetect.
               Possible values: ninja,vs,vs2010,vs2015,vs2017,xcode
        :param build_type: Overrides default build type comming from settings
        """
        self._conanfile = conanfile
        self._settings = conanfile.settings
        self._append_vcvars = append_vcvars

        self._os = self._ss("os")

        self._compiler = self._ss("compiler")
        conan_v2_error("compiler setting should be defined.", not self._compiler)

        self._compiler_version = self._ss("compiler.version")

        self._build_type = self._ss("build_type")

        self.backend = backend or "ninja"  # Other backends are poorly supported, not default other.

        self.options = dict()
        if self._conanfile.package_folder:
            self.options['prefix'] = self._conanfile.package_folder
        self.options['libdir'] = DEFAULT_LIB
        self.options['bindir'] = DEFAULT_BIN
        self.options['sbindir'] = DEFAULT_BIN
        self.options['libexecdir'] = DEFAULT_BIN
        self.options['includedir'] = DEFAULT_INCLUDE

        # C++ standard
        cppstd = cppstd_from_settings(self._conanfile.settings)
        cppstd_conan2meson = {
            '98': 'c++03', 'gnu98': 'gnu++03',
            '11': 'c++11', 'gnu11': 'gnu++11',
            '14': 'c++14', 'gnu14': 'gnu++14',
            '17': 'c++17', 'gnu17': 'gnu++17',
            '20': 'c++1z', 'gnu20': 'gnu++1z'
        }

        if cppstd:
            self.options['cpp_std'] = cppstd_conan2meson[cppstd]

        # shared
        shared = self._so("shared")
        self.options['default_library'] = "shared" if shared is None or shared else "static"

        # fpic
        if self._os and "Windows" not in self._os:
            fpic = self._so("fPIC")
            if fpic is not None:
                shared = self._so("shared")
                self.options['b_staticpic'] = "true" if (fpic or shared) else "false"

        self.build_dir = None
        if build_type and build_type != self._build_type:
            # Call the setter to warn and update the definitions if needed
            self.build_type = build_type
Beispiel #8
0
 def channel(self):
     if not self._conan_channel:
         _env_channel = os.getenv("CONAN_CHANNEL")
         conan_v2_error("Environment variable 'CONAN_CHANNEL' is deprecated", _env_channel)
         self._conan_channel = _env_channel or self.default_channel
         if not self._conan_channel:
             raise ConanException("channel not defined, but self.channel is used in conanfile")
     return self._conan_channel
Beispiel #9
0
 def user(self):
     if not self._conan_user:
         _env_username = os.getenv("CONAN_USERNAME")
         conan_v2_error("Environment variable 'CONAN_USERNAME' is deprecated", _env_username)
         self._conan_user = _env_username or self.default_user
         if not self._conan_user:
             raise ConanException("user not defined, but self.user is used in conanfile")
     return self._conan_user
Beispiel #10
0
 def build(self, args=None, build_dir=None, targets=None):
     if not self._conanfile.should_build:
         return
     conan_v2_error("build_type setting should be defined.",
                    not self._build_type)
     self._run_meson_targets(args=args,
                             build_dir=build_dir,
                             targets=targets)
Beispiel #11
0
 def __call__(self, reference):
     conan_v2_error("Old syntax for python_requires is deprecated")
     if not self.valid:
         raise ConanException("Invalid use of python_requires(%s)" % reference)
     try:
         python_req = self._look_for_require(reference)
         self._requires.append(python_req)
         return python_req.module
     except NotFoundException:
         raise ConanException('Unable to find python_requires("{}") in remotes'.format(reference))
Beispiel #12
0
 def build_modules_paths(self):
     if self._build_modules_paths is None:
         if isinstance(self.build_modules, list):  # FIXME: This should be just a plain dict
             conan_v2_error("Use 'self.cpp_info.build_modules[\"<generator>\"] = "
                            "{the_list}' instead".format(the_list=self.build_modules))
             self.build_modules = BuildModulesDict.from_list(self.build_modules)
             # Invalidate necessary, get_build_modules used raise_incorrect_components_definition
             self._build_modules = None
         tmp = dict_to_abs_paths(BuildModulesDict(self.get_build_modules()), self.rootpath)
         self._build_modules_paths = tmp
     return self._build_modules_paths
Beispiel #13
0
    def __init__(self, conanfile, win_bash=False, include_rpath_flags=False):
        """
        FIXME: include_rpath_flags CONAN 2.0 to default True? Could break many packages in center
        """
        self._conanfile = conanfile
        self._win_bash = win_bash
        self._include_rpath_flags = include_rpath_flags
        self.subsystem = OSInfo().detect_windows_subsystem(
        ) if self._win_bash else None
        self._deps_cpp_info = conanfile.deps_cpp_info
        self._os = conanfile.settings.get_safe("os")
        self._os_version = conanfile.settings.get_safe("os.version")
        self._os_sdk = conanfile.settings.get_safe("os.sdk")
        self._os_subsystem = conanfile.settings.get_safe("os.subsystem")
        self._arch = conanfile.settings.get_safe("arch")
        self._os_target, self._arch_target = get_target_os_arch(conanfile)

        self._build_type = conanfile.settings.get_safe("build_type")

        self._compiler = conanfile.settings.get_safe("compiler")
        conan_v2_error("compiler setting should be defined.",
                       not self._compiler)

        self._compiler_version = conanfile.settings.get_safe(
            "compiler.version")
        self._compiler_runtime = conanfile.settings.get_safe(
            "compiler.runtime")
        self._libcxx = conanfile.settings.get_safe("compiler.libcxx")
        self._cppstd = cppstd_from_settings(conanfile.settings)

        # Set the generic objects before mapping to env vars to let the user
        # alter some value
        self.libs = list(self._deps_cpp_info.libs)
        self.libs.extend(list(self._deps_cpp_info.system_libs))
        self.include_paths = list(self._deps_cpp_info.include_paths)
        self.library_paths = list(self._deps_cpp_info.lib_paths)

        self.defines = self._configure_defines()
        # Will go to CFLAGS and CXXFLAGS ["-m64" "-m32", "-g", "-s"]
        self.flags = self._configure_flags()
        # Only c++ flags [-stdlib, -library], will go to CXXFLAGS
        self.cxx_flags = self._configure_cxx_flags()
        # cpp standard
        self.cppstd_flag = cppstd_flag(conanfile.settings)
        # Not -L flags, ["-m64" "-m32"]
        self.link_flags = self._configure_link_flags()  # TEST!
        # Precalculate -fPIC
        self.fpic = self._configure_fpic()

        # Precalculate build, host, target triplets
        self.build, self.host, self.target = self._get_host_build_target_flags(
        )
Beispiel #14
0
 def build_modules_paths(self):
     if self._build_modules_paths is None:
         if isinstance(self.build_modules,
                       list):  # FIXME: This should be just a plain dict
             conan_v2_error(
                 "Use 'self.cpp_info.build_modules[\"<generator>\"] = "
                 "{the_list}' instead".format(the_list=self.build_modules))
             self.build_modules = BuildModulesDict.from_list(
                 self.build_modules)
         tmp = dict_to_abs_paths(BuildModulesDict(self.build_modules),
                                 self.rootpath)
         self._build_modules_paths = tmp
     return self._build_modules_paths
Beispiel #15
0
 def _get_filename(self, cpp_info, pkg_name):
     # FIXME: This is a workaround to be able to use existing recipes that declare
     # FIXME: cpp_info.filenames["cmake_find_package_multi"] = "xxxxx"
     name = cpp_info.filenames.get(self.name)
     if name is not None:
         return name
     find_name = cpp_info.filenames.get("cmake_find_package_multi")
     if find_name is not None:
         # Not displaying a warning, too noisy as this is called many times
         conan_v2_error(
             "'{}' defines information for 'cmake_find_package_multi', "
             "but not 'CMakeDeps'".format(pkg_name))
         return find_name
     return cpp_info._name
Beispiel #16
0
    def get_name(self, generator, default_name=True):
        name = super(CppInfo, self).get_name(generator, default_name=default_name)

        # Legacy logic for pkg_config generator
        from conans.client.generators.pkg_config import PkgConfigGenerator
        if generator == PkgConfigGenerator.name:
            fallback = self._name.lower() if self._name != self._ref_name else self._ref_name
            if PkgConfigGenerator.name not in self.names and self._name != self._name.lower():
                conan_v2_error("Generated file and name for {gen} generator will change in"
                               " Conan v2 to '{name}'. Use 'self.cpp_info.names[\"{gen}\"]"
                               " = \"{fallback}\"' in your recipe to continue using current name."
                               .format(gen=PkgConfigGenerator.name, name=name, fallback=fallback))
            name = self.names.get(generator, fallback)
        return name
Beispiel #17
0
 def make(self, args="", make_program=None, target=None, vars=None):
     if not self._conanfile.should_build:
         return
     conan_v2_error("build_type setting should be defined.",
                    not self._build_type)
     make_program = os.getenv(
         "CONAN_MAKE_PROGRAM") or make_program or "make"
     with environment_append(vars or self.vars):
         str_args = args_to_string(args)
         cpu_count_option = (("-j%s" %
                              cpu_count(output=self._conanfile.output)) if
                             ("-j" not in str_args
                              and "nmake" not in make_program.lower()) else
                             None)
         self._conanfile.run("%s" % join_arguments(
             [make_program, target, str_args, cpu_count_option]),
                             win_bash=self._win_bash,
                             subsystem=self.subsystem)
Beispiel #18
0
    def get_name(self, generator, default_name=True):
        name = super(CppInfo, self).get_name(generator,
                                             default_name=default_name)

        # Legacy logic for pkg_config generator, do not enter this logic if the properties model
        # is used: https://github.com/conan-io/conan/issues/10309
        from conans.client.generators.pkg_config import PkgConfigGenerator
        if generator == PkgConfigGenerator.name and self.get_property(
                "pkg_config_name") is None:
            fallback = self._name.lower(
            ) if self._name != self._ref_name else self._ref_name
            if PkgConfigGenerator.name not in self.names and self._name != self._name.lower(
            ):
                conan_v2_error(
                    "Generated file and name for {gen} generator will change in"
                    " Conan v2 to '{name}'. Use 'self.cpp_info.names[\"{gen}\"]"
                    " = \"{fallback}\"' in your recipe to continue using current name."
                    .format(gen=PkgConfigGenerator.name,
                            name=name,
                            fallback=fallback))
            name = self.names.get(generator, fallback)
        return name
Beispiel #19
0
def _replace_scm_data_in_recipe(package_layout, scm_data, scm_to_conandata):
    if scm_to_conandata:
        conandata_path = os.path.join(package_layout.export(), DATA_YML)
        conandata_yml = {}
        if os.path.exists(conandata_path):
            conandata_yml = yaml.safe_load(load(conandata_path))
            conandata_yml = conandata_yml or {
            }  # In case the conandata is a blank file
            if '.conan' in conandata_yml:
                raise ConanException(
                    "Field '.conan' inside '{}' file is reserved to "
                    "Conan usage.".format(DATA_YML))
        scm_data_copied = scm_data.as_dict()
        scm_data_copied.pop('username', None)
        scm_data_copied.pop('password', None)
        conandata_yml['.conan'] = {'scm': scm_data_copied}

        save(conandata_path,
             yaml.safe_dump(conandata_yml, default_flow_style=False))
    else:
        conan_v2_error("general.scm_to_conandata should be set to 1")
        _replace_scm_data_in_conanfile(package_layout.conanfile(), scm_data)
Beispiel #20
0
def create_options(conanfile):
    try:
        package_options = PackageOptions(getattr(conanfile, "options", None))
        options = Options(package_options)

        default_options = getattr(conanfile, "default_options", None)
        if default_options:
            if isinstance(default_options, dict):
                default_values = OptionsValues(default_options)
            elif isinstance(default_options, (list, tuple)):
                conan_v2_error("Declare 'default_options' as a dictionary")
                default_values = OptionsValues(default_options)
            elif isinstance(default_options, six.string_types):
                conan_v2_error("Declare 'default_options' as a dictionary")
                default_values = OptionsValues.loads(default_options)
            else:
                raise ConanException("Please define your default_options as list, "
                                     "multiline string or dictionary")
            options.values = default_values
        return options
    except Exception as e:
        raise ConanException("Error while initializing options. %s" % str(e))
Beispiel #21
0
def _check_cppstd(settings):
    compiler = settings.get_safe("compiler")
    compiler_version = settings.get_safe("compiler.version")
    cppstd = settings.get_safe("cppstd")
    compiler_cppstd = settings.get_safe("compiler.cppstd")

    if not cppstd and not compiler_cppstd:
        return

    # Checks: one or the other, but not both
    if cppstd and compiler_cppstd:
        raise ConanException(
            "Do not use settings 'compiler.cppstd' together with 'cppstd'."
            " Use only the former one.")

    conan_v2_error(
        "Setting 'cppstd' is deprecated in favor of 'compiler.cppstd'", cppstd)

    if compiler not in ("gcc", "clang", "apple-clang", "Visual Studio"):
        return

    # Check that we have a flag available for that value of the C++ Standard
    def check_flag_available(values_range, value, setting_id):
        available = [
            v for v in values_range
            if cppstd_flag(compiler, compiler_version, v)
        ]
        if str(value) not in available:
            raise ConanException(
                "The specified '%s=%s' is not available "
                "for '%s %s'. Possible values are %s'" %
                (setting_id, value, compiler, compiler_version, available))

    if cppstd:
        check_flag_available(settings.cppstd.values_range, cppstd, "cppstd")
    else:
        check_flag_available(settings.compiler.cppstd.values_range,
                             compiler_cppstd, "compiler.cppstd")
Beispiel #22
0
    def print_inspect(self, inspect, raw=False):
        for k, v in inspect.items():
            if k == "default_options":
                conan_v2_error("Declare 'default_options' as a dictionary", not isinstance(v, dict))

                if isinstance(v, str):
                    v = OptionsValues.loads(v)
                elif isinstance(v, tuple):
                    v = OptionsValues(v)
                elif isinstance(v, list):
                    v = OptionsValues(tuple(v))
                elif isinstance(v, dict):
                    v = OptionsValues(v)

            if raw:
                self._out.write(str(v))
            else:
                if isinstance(v, (dict, OptionsValues)):
                    self._out.writeln("%s:" % k)
                    for ok, ov in sorted(v.items()):
                        self._out.writeln("    %s: %s" % (ok, ov))
                else:
                    self._out.writeln("%s: %s" % (k, str(v)))
Beispiel #23
0
 def collect_libs(self, folder=None):
     conan_v2_error(
         "'self.collect_libs' is deprecated, use 'tools.collect_libs(self)' instead"
     )
     return tools.collect_libs(self, folder=folder)
Beispiel #24
0
 def extend(self, items):
     conan_v2_error(
         "Use 'self.cpp_info.build_modules[\"<generator>\"].extend({items})' "
         "instead".format(items=items))
     for item in items:
         self._append(item)
Beispiel #25
0
 def append(self, item):
     conan_v2_error(
         "Use 'self.cpp_info.build_modules[\"<generator>\"].append(\"{item}\")' "
         'instead'.format(item=item))
     self._append(item)
Beispiel #26
0
 def set_cppflags(self, value):
     conan_v2_error(
         "'cpp_info.cppflags' is deprecated, use 'cxxflags' instead")
     self.cxxflags = value
Beispiel #27
0
 def get_cppflags(self):
     conan_v2_error(
         "'cpp_info.cppflags' is deprecated, use 'cxxflags' instead")
     return self.cxxflags
Beispiel #28
0
 def name(self):
     conan_v2_error("Use 'get_name(generator)' instead")
     return self._name