Пример #1
0
    def test_replace_in_file(self):
        output = ConanOutput(sys.stdout)
        replace_in_file(self.win_file, "nis", "nus", output=output)
        replace_in_file(self.bytes_file, "nis", "nus", output=output)

        content = tools.load(self.win_file)
        self.assertNotIn("nis", content)
        self.assertIn("nus", content)

        content = tools.load(self.bytes_file)
        self.assertNotIn("nis", content)
        self.assertIn("nus", content)
Пример #2
0
 def conan_basic_setup_interface_test(self):
     """
     Check conan_basic_setup() interface is the same one for cmake and cmake_multi generators
     """
     conanbuildinfo = load(
         os.path.join(self.client.current_folder, "conanbuildinfo.cmake"))
     conanbuildinfo_multi = load(
         os.path.join(self.client.current_folder,
                      "conanbuildinfo_multi.cmake"))
     expected = "set(options TARGETS NO_OUTPUT_DIRS SKIP_RPATH KEEP_RPATHS SKIP_STD SKIP_FPIC)"
     self.assertIn(expected, conanbuildinfo)
     self.assertIn(expected, conanbuildinfo_multi)
Пример #3
0
    def _get_id(self, with_cppstd, settings_values=None):
        # Create the conanfile with corresponding settings
        settings = [
            "os",
            "compiler",
        ]
        if with_cppstd:
            settings += ["cppstd"]
        conanfile = self.conanfile.format(settings='", "'.join(settings))
        self.t.save({"conanfile.py": conanfile}, clean_first=True)

        # Create the string with the command line settings
        settings_values = settings_values or dict()
        settings_values_str = [
            "-s {k}={v}".format(k=k, v=v) for k, v in settings_values.items()
        ]
        settings_values_str = " ".join(settings_values_str)

        # Call `conan info`
        json_file = os.path.join(self.t.current_folder, "tmp.json")
        self.t.run('info . {} --json="{}"'.format(settings_values_str,
                                                  json_file))
        info_output = self.t.out
        data = json.loads(load(json_file))
        self.assertEqual(len(data), 1)

        # Return ID, output
        return data[0]["id"], info_output
Пример #4
0
    def _get_file_conf(self, section, varname=None):
        """ Gets the section or variable from config file.
        If the queried element is not found an exception is raised.
        """
        try:
            if not os.path.exists(self.config_filename):
                jwt_random_secret = ''.join(
                    random.choice(string.ascii_letters) for _ in range(24))
                updown_random_secret = ''.join(
                    random.choice(string.ascii_letters) for _ in range(24))
                server_conf = default_server_conf.format(
                    jwt_secret=jwt_random_secret,
                    updown_secret=updown_random_secret)
                save(self.config_filename, server_conf)

            if not self._loaded:
                self._loaded = True
                # To avoid encoding problems we use our tools.load
                if six.PY3:
                    self.read_string(tools.load(self.config_filename))
                else:
                    self.read(self.config_filename)

            if varname:
                section = dict(self.items(section))
                return section[varname]
            else:
                return self.items(section)
        except NoSectionError:
            raise ConanException("No section '%s' found" % section)
        except Exception as exc:
            logger.debug(exc)
            raise ConanException("Invalid configuration, "
                                 "missing %s: %s" % (section, varname))
Пример #5
0
def patch_default_base_profile(conan_api, profile_abs_path):
    """If we have a profile including default, but the users default in config is that the default
    is other, we have to change the include"""
    text = tools.load(profile_abs_path)
    if "include(default)" in text:  # User didn't specified a custom profile
        default_profile_name = os.path.basename(
            conan_api._client_cache.default_profile_path)
        if not os.path.exists(conan_api._client_cache.default_profile_path):
            conan_api.create_profile(default_profile_name, detect=True)

        if default_profile_name != "default":  # User have a different default profile name
            # https://github.com/conan-io/conan-package-tools/issues/121
            text = text.replace("include(default)",
                                "include(%s)" % default_profile_name)
            tools.save(profile_abs_path, text)
Пример #6
0
def get_profiles(client_cache, build_config, base_profile_name=None):

    base_profile_text = ""
    if base_profile_name:
        base_profile_path = os.path.join(client_cache.profiles_path,
                                         base_profile_name)
        base_profile_text = tools.load(base_profile_path)
    base_profile_name = base_profile_name or "default"
    tmp = """
include(%s)

[settings]
%s
[options]
%s
[env]
%s
[build_requires]
%s
"""

    def pairs_lines(items):
        return "\n".join(["%s=%s" % (k, v) for k, v in items])

    settings = pairs_lines(sorted(build_config.settings.items()))
    options = pairs_lines(build_config.options.items())
    env_vars = pairs_lines(build_config.env_vars.items())
    br_lines = ""
    for pattern, build_requires in build_config.build_requires.items():
        br_lines += "\n".join(
            ["%s:%s" % (pattern, br) for br in build_requires])

    if os.getenv("CONAN_BUILD_REQUIRES"):
        brs = os.getenv("CONAN_BUILD_REQUIRES").split(",")
        brs = ['*:%s' % br.strip() if ":" not in br else br for br in brs]
        if br_lines:
            br_lines += "\n"
        br_lines += "\n".join(brs)

    profile_text = tmp % (base_profile_name, settings, options, env_vars,
                          br_lines)
    return profile_text, base_profile_text
Пример #7
0
    def test_unix_to_dos_unit(self):
        def save_file(contents):
            tmp = temp_folder()
            filepath = os.path.join(tmp, "a_file.txt")
            save(filepath, contents)
            return filepath

        fp = save_file(b"a line\notherline\n")
        if platform.system() != "Windows":
            output = check_output_runner(["file", fp],
                                         stderr=subprocess.STDOUT)
            self.assertIn("ASCII text", str(output))
            self.assertNotIn("CRLF", str(output))

            tools.unix2dos(fp)
            output = check_output_runner(["file", fp],
                                         stderr=subprocess.STDOUT)
            self.assertIn("ASCII text", str(output))
            self.assertIn("CRLF", str(output))
        else:
            fc = tools.load(fp)
            self.assertNotIn("\r\n", fc)
            tools.unix2dos(fp)
            fc = tools.load(fp)
            self.assertIn("\r\n", fc)

        self.assertEqual("a line\r\notherline\r\n", str(tools.load(fp)))

        fp = save_file(b"a line\r\notherline\r\n")
        if platform.system() != "Windows":
            output = check_output_runner(["file", fp],
                                         stderr=subprocess.STDOUT)
            self.assertIn("ASCII text", str(output))
            self.assertIn("CRLF", str(output))

            tools.dos2unix(fp)
            output = check_output_runner(["file", fp],
                                         stderr=subprocess.STDOUT)
            self.assertIn("ASCII text", str(output))
            self.assertNotIn("CRLF", str(output))
        else:
            fc = tools.load(fp)
            self.assertIn("\r\n", fc)
            tools.dos2unix(fp)
            fc = tools.load(fp)
            self.assertNotIn("\r\n", fc)

        self.assertEqual("a line\notherline\n", str(tools.load(fp)))
Пример #8
0
    def get_command(self, project_file, props_file_path=None, targets=None, upgrade_project=True,
                    build_type=None, arch=None, parallel=True, toolset=None, platforms=None,
                    use_env=False, properties=None, output_binary_log=None, verbosity=None):

        targets = targets or []
        properties = properties or {}
        command = []

        if upgrade_project and not get_env("CONAN_SKIP_VS_PROJECTS_UPGRADE", False):
            command.append('devenv "%s" /upgrade &&' % project_file)
        else:
            self._output.info("Skipped sln project upgrade")

        build_type = build_type or self._settings.get_safe("build_type")
        arch = arch or self._settings.get_safe("arch")
        toolset = toolset or tools.msvs_toolset(self._settings)
        verbosity = os.getenv("CONAN_MSBUILD_VERBOSITY") or verbosity or "minimal"
        if not build_type:
            raise ConanException("Cannot build_sln_command, build_type not defined")
        if not arch:
            raise ConanException("Cannot build_sln_command, arch not defined")

        command.append('msbuild "%s" /p:Configuration="%s"' % (project_file, build_type))
        msvc_arch = {'x86': 'x86',
                     'x86_64': 'x64',
                     'armv7': 'ARM',
                     'armv8': 'ARM64'}
        if platforms:
            msvc_arch.update(platforms)
        msvc_arch = msvc_arch.get(str(arch))
        try:
            sln = tools.load(project_file)
            pattern = re.compile(r"GlobalSection\(SolutionConfigurationPlatforms\)"
                                 r"(.*?)EndGlobalSection", re.DOTALL)
            solution_global = pattern.search(sln).group(1)
            lines = solution_global.splitlines()
            lines = [s.split("=")[0].strip() for s in lines]
        except Exception:
            pass  # TODO: !!! what are we catching here? tools.load? .group(1)? .splitlines?
        else:
            config = "%s|%s" % (build_type, msvc_arch)
            if config not in "".join(lines):
                self._output.warn("***** The configuration %s does not exist in this solution *****"
                                  % config)
                self._output.warn("Use 'platforms' argument to define your architectures")

        if output_binary_log:
            msbuild_version = MSBuild.get_version(self._settings)
            if msbuild_version >= "15.3":  # http://msbuildlog.com/
                command.append('/bl' if isinstance(output_binary_log, bool)
                               else '/bl:"%s"' % output_binary_log)
            else:
                raise ConanException("MSBuild version detected (%s) does not support "
                                     "'output_binary_log' ('/bl')" % msbuild_version)

        if use_env:
            command.append('/p:UseEnv=true')

        if msvc_arch:
            command.append('/p:Platform="%s"' % msvc_arch)

        if parallel:
            command.append('/m:%s' % cpu_count(output=self._output))

        if targets:
            command.append("/target:%s" % ";".join(targets))

        if toolset:
            command.append('/p:PlatformToolset="%s"' % toolset)

        if verbosity:
            command.append('/verbosity:%s' % verbosity)

        if props_file_path:
            command.append('/p:ForceImportBeforeCppTargets="%s"' % props_file_path)

        for name, value in properties.items():
            command.append('/p:%s="%s"' % (name, value))

        return " ".join(command)
Пример #9
0
    def package(self):
        # Extract the License/s from the header to a file
        with tools.chdir(self.ZIP_FOLDER_NAME):
            tmp = tools.load("zlib.h")
            license_contents = tmp[2:tmp.find("*/", 1)]
            tools.save("LICENSE", license_contents)

        # Copy the license files
        self.copy("LICENSE", src=self.ZIP_FOLDER_NAME, dst=".")

        # Copy pc file
        self.copy("*.pc", dst="", keep_path=False)

        # Copying zlib.h, zutil.h, zconf.h
        self.copy("*.h",
                  "include",
                  "%s" % self.ZIP_FOLDER_NAME,
                  keep_path=False)
        self.copy("*.h", "include", "%s" % "_build", keep_path=False)

        # Copying static and dynamic libs
        if tools.os_info.is_windows:
            if self.options.shared:
                build_dir = os.path.join(self.ZIP_FOLDER_NAME, "_build")
                self.copy(pattern="*.dll",
                          dst="bin",
                          src=build_dir,
                          keep_path=False)
                build_dir = os.path.join(self.ZIP_FOLDER_NAME, "_build/lib")
                self.copy(pattern="*zlibd.lib",
                          dst="lib",
                          src=build_dir,
                          keep_path=False)
                self.copy(pattern="*zlib.lib",
                          dst="lib",
                          src=build_dir,
                          keep_path=False)
                self.copy(pattern="*zlib.dll.a",
                          dst="lib",
                          src=build_dir,
                          keep_path=False)
            else:
                build_dir = os.path.join(self.ZIP_FOLDER_NAME, "_build/lib")
                # MinGW
                self.copy(pattern="libzlibstaticd.a",
                          dst="lib",
                          src=build_dir,
                          keep_path=False)
                self.copy(pattern="libzlibstatic.a",
                          dst="lib",
                          src=build_dir,
                          keep_path=False)
                # Visual Studio
                self.copy(pattern="zlibstaticd.lib",
                          dst="lib",
                          src=build_dir,
                          keep_path=False)
                self.copy(pattern="zlibstatic.lib",
                          dst="lib",
                          src=build_dir,
                          keep_path=False)

                lib_path = os.path.join(self.package_folder, "lib")
                suffix = "d" if self.settings.build_type == "Debug" else ""
                if self.settings.compiler == "Visual Studio":
                    current_lib = os.path.join(lib_path,
                                               "zlibstatic%s.lib" % suffix)
                    os.rename(current_lib,
                              os.path.join(lib_path, "zlib%s.lib" % suffix))
                elif self.settings.compiler == "gcc":
                    current_lib = os.path.join(lib_path, "libzlibstatic.a")
                    os.rename(current_lib, os.path.join(lib_path, "libzlib.a"))
        else:
            build_dir = os.path.join(self.ZIP_FOLDER_NAME)
            if self.options.shared:
                if self.settings.os == "Macos":
                    self.copy(pattern="*.dylib",
                              dst="lib",
                              src=build_dir,
                              keep_path=False)
                else:
                    self.copy(pattern="*.so*",
                              dst="lib",
                              src=build_dir,
                              keep_path=False)
            else:
                self.copy(pattern="*.a",
                          dst="lib",
                          src=build_dir,
                          keep_path=False)
Пример #10
0
def load_profile(profile_abs_path, client_cache):
    text = tools.load(profile_abs_path)
    profile, _ = _load_profile(text, os.path.dirname(profile_abs_path),
                               client_cache.profiles_path)
    return profile