Ejemplo n.º 1
0
 def test_api_conanfile_loader_shouldnt_cache(self):
     tmp = temp_folder()
     with environment_append({"CONAN_USER_HOME": tmp}):
         with chdir(tmp):
             try:
                 old_stdout = sys.stdout
                 result = StringIO()
                 sys.stdout = result
                 api, _, _ = ConanAPIV1.factory()
                 api._user_io.out = TestBufferConanOutput()
                 conanfile = dedent("""
                     from conans import ConanFile
                     class Pkg(ConanFile):
                         def build(self):
                             self.output.info("NUMBER 42!!")
                     """)
                 save("conanfile.py", conanfile)
                 api.create(".", "pkg", "version", "user", "channel")
                 self.assertIn("pkg/version@user/channel: NUMBER 42!!",
                               result.getvalue())
                 save("conanfile.py", conanfile.replace("42", "123"))
                 api.create(".", "pkg", "version", "user", "channel")
                 self.assertIn("pkg/version@user/channel: NUMBER 123!!",
                               result.getvalue())
             finally:
                 sys.stdout = old_stdout
Ejemplo n.º 2
0
    def test_global_tools_overrided(self):
        client = TestClient()

        conanfile = """
from conans import ConanFile, tools

class HelloConan(ConanFile):
    name = "Hello"
    version = "0.1"

    def build(self):
        assert(tools.net._global_requester != None)
        assert(tools.files._global_output != None)
        """
        client.save({"conanfile.py": conanfile})

        client.run("install .")
        client.run("build .")

        # Not test the real commmand get_command if it's setting the module global vars
        tmp = temp_folder()
        conf = default_client_conf.replace(
            "\n[proxies]", "\n[proxies]\nhttp = http://myproxy.com")
        os.mkdir(os.path.join(tmp, ".conan"))
        save(os.path.join(tmp, ".conan", CONAN_CONF), conf)
        with tools.environment_append({"CONAN_USER_HOME": tmp}):
            conan_api, _, _ = ConanAPIV1.factory()
        conan_api.remote_list()
        self.assertEquals(tools.net._global_requester.proxies,
                          {"http": "http://myproxy.com"})
        self.assertIsNotNone(tools.files._global_output.warn)
Ejemplo n.º 3
0
    def test_global_tools_overrided(self):
        client = TestClient()

        conanfile = """
from conans import ConanFile, tools

class HelloConan(ConanFile):
    name = "Hello"
    version = "0.1"

    def build(self):
        assert(tools.net._global_requester != None)
        assert(tools.files._global_output != None)
        """
        client.save({"conanfile.py": conanfile})

        client.run("install .")
        client.run("build .")

        # Not test the real commmand get_command if it's setting the module global vars
        tmp = temp_folder()
        conf = default_client_conf.replace("\n[proxies]", "\n[proxies]\nhttp = http://myproxy.com")
        os.mkdir(os.path.join(tmp, ".conan"))
        save(os.path.join(tmp, ".conan", CONAN_CONF), conf)
        with tools.environment_append({"CONAN_USER_HOME": tmp}):
            conan_api, _, _ = ConanAPIV1.factory()
        conan_api.remote_list()
        self.assertEquals(tools.net._global_requester.proxies, {"http": "http://myproxy.com"})
        self.assertIsNotNone(tools.files._global_output.warn)
Ejemplo n.º 4
0
 def export(self):
     # Export the driver dependency recipes when the coda-oss recipe is
     # exported.
     (cpm, _, _) = ConanAPIV1.factory()
     for dep_name, dep_info in self._get_in_tree_dependencies().items():
         cpm.export(os.path.join(self.recipe_folder, dep_info["path"]),
                    dep_name, dep_info["version"], dep_info["user"],
                    dep_info["channel"])
Ejemplo n.º 5
0
    def curdir_test(self):
        tmp_folder = temp_folder()
        conanfile = """from conans import ConanFile
class Pkg(ConanFile):
    name = "lib"
    version = "1.0"
"""
        tools.save(os.path.join(tmp_folder, "conanfile.py"), conanfile)
        with tools.chdir(tmp_folder):
            api, _, _ = ConanAPIV1.factory()
            api.create(".", name="lib", version="1.0", user="******", channel="channel")
            self.assertEquals(tmp_folder, os.getcwd())
            api.create(".", name="lib", version="1.0", user="******", channel="channel2")
            self.assertEquals(tmp_folder, os.getcwd())
Ejemplo n.º 6
0
 def setUp(self):
     self.old_folder = os.getcwd()
     self.tmp_folder = mkdir_tmp()
     os.chmod(self.tmp_folder, 0o777)
     self.conan_home = self.tmp_folder
     os.chdir(self.tmp_folder)
     # user_home = "c:/tmp/home"  # Cache
     self.old_env = dict(os.environ)
     os.environ.update({
         "CONAN_USER_HOME": self.conan_home,
         "CONAN_PIP_PACKAGE": "0"
     })
     self.output = TestBufferConanOutput()
     self.api, self.client_cache, _ = ConanAPIV1.factory()
     print("Testing with Conan Folder=%s" % self.client_cache.conan_folder)
Ejemplo n.º 7
0
    def test_preprocessor_called_second_api_call(self):
        """"When calling twice to conan create with the Conan python API, the default
        settings shouldn't be cached. To test that the default profile is not cached,
        this test is verifying that the setting preprocessor is adjusting the runtime
        to MDd when build_type=Debug after a different call to conan create that could
        cache the runtime to MD (issue reported at: #4246) """
        tmp = temp_folder()
        with environment_append({"CONAN_USER_HOME": tmp}):
            with chdir(tmp):
                api = ConanAPIV1(output=TestBufferConanOutput())
                api.new(name="lib/1.0@conan/stable", bare=True)

                def get_conaninfo(info):
                    package_id = info["installed"][0]["packages"][0]["id"]
                    pref = PackageReference.loads("lib/1.0@conan/stable:%s" %
                                                  package_id)
                    cache = ClientCache(api.cache_folder,
                                        TestBufferConanOutput())
                    folder = cache.package_layout(pref.ref).package(pref)
                    return load(os.path.join(folder, "conaninfo.txt"))

                settings = [
                    "compiler=Visual Studio", "compiler.version=15",
                    "build_type=Release"
                ]
                info = api.create(".",
                                  name=None,
                                  version=None,
                                  user="******",
                                  channel="stable",
                                  settings=settings)
                self.assertIn("compiler.runtime=MD", get_conaninfo(info))

                settings = [
                    "compiler=Visual Studio", "compiler.version=15",
                    "build_type=Debug"
                ]
                info = api.create(".",
                                  name=None,
                                  version=None,
                                  user="******",
                                  channel="stable",
                                  settings=settings)
                self.assertIn("compiler.runtime=MDd", get_conaninfo(info))
Ejemplo n.º 8
0
    def test_api_conanfile_loader_shouldnt_cache(self):
        tmp = temp_folder()
        with environment_append({"CONAN_USER_HOME": tmp}):
            with chdir(tmp):
                output = TestBufferConanOutput()
                api = ConanAPIV1(output=output)

                conanfile = dedent("""
                    from conans import ConanFile
                    class Pkg(ConanFile):
                        def build(self):
                            self.output.info("NUMBER 42!!")
                    """)
                save("conanfile.py", conanfile)
                api.create(".", "pkg", "version", "user", "channel")
                self.assertIn("pkg/version@user/channel: NUMBER 42!!", output)
                save("conanfile.py", conanfile.replace("42", "123"))
                api.create(".", "pkg", "version", "user", "channel")
                self.assertIn("pkg/version@user/channel: NUMBER 123!!", output)
Ejemplo n.º 9
0
    def curdir_test(self):
        tmp_folder = temp_folder()
        conanfile = """from conans import ConanFile
class Pkg(ConanFile):
    name = "lib"
    version = "1.0"
"""
        tools.save(os.path.join(tmp_folder, "conanfile.py"), conanfile)
        with tools.chdir(tmp_folder):
            # Needed to not write in the real computer cache
            with tools.environment_append({"CONAN_USER_HOME": tmp_folder}):
                api, _, _ = ConanAPIV1.factory()
                api.create(".",
                           name="lib",
                           version="1.0",
                           user="******",
                           channel="channel")
                self.assertEqual(tmp_folder, os.getcwd())
                api.create(".",
                           name="lib",
                           version="1.0",
                           user="******",
                           channel="channel2")
                self.assertEqual(tmp_folder, os.getcwd())
Ejemplo n.º 10
0
import os
import sys

from conans.client.conan_api import ConanAPIV1

api, _, _ = ConanAPIV1.factory()


def run():
    if sys.argv[1:]:
        create(sys.argv[1])
        return

    directory = os.fsencode("packages")
    for file in os.listdir(directory):
        create(os.fsdecode(file))
        print("\n-------------------\n")


def create(name):
    api.create("packages/%s" % name, user="******", channel="stable")


if __name__ == '__main__':
    run()
Ejemplo n.º 11
0
    def __init__(self, conanfile="conanfile.py", debug=False):
        logging.basicConfig(level=logging.DEBUG if debug else logging.ERROR)

        conanfile_path = os.path.join(os.getcwd(), conanfile)
        logging.debug("conanfile_path=%s", conanfile_path)

        try:
            self.gitrepo = Repo('.')
        except (InvalidGitRepositoryError, NoSuchPathError):
            print(
                "GitPython error."
                "\nEnsure your are executing this script in a git-controlled directory."
                "\nMake sure the 'git' binary is available in your path.")
            raise

        self.git_active_branch = self.gitrepo.active_branch
        try:
            self.git_remote_origin_url = self.gitrepo.remotes.origin.url
        except AttributeError:
            print("Git repo needs a remote origin repository")
            raise

        try:
            try:
                from conans.client.loader_parse import load_conanfile_class
                self.conanfile = self.loader.load_conanfile(conanfile_path)
            except ImportError:
                from conans.client.conan_api import ConanAPIV1
                conan_api, _, _ = ConanAPIV1.factory()
                self.conanfile = conan_api._loader.load_class(conanfile_path)
        except ConanException as e:
            logging.debug(e)
            print("Could not load: %s" % conanfile_path)
            raise
        else:
            self.options = {}
            self.default_options = {}

            try:
                print("Extracting options.")
                self.options = self.parse_options(self.conanfile.options)
            except Exception as e:
                logging.debug(e)
                print("No options found in conanfile. Skipping.")
                pass
            else:
                try:
                    print("Extracting default_options.")
                    default_options = self.parse_options(
                        self.conanfile.default_options)
                except Exception as e:
                    logging.debug(e)
                    print("No default options found in conanfile. Skipping.")
                else:
                    if isinstance(default_options, dict):
                        self.default_options = default_options
                    else:
                        for key, value in default_options.as_list():
                            self.default_options[key] = value
            finally:
                self.user = None
                self.channel = None

                self.custom_content = 'This is additional text to insert into the README.'
Ejemplo n.º 12
0
    def withConan(self,
                  conanfile: str = None,
                  options: list = [],
                  settings: list = [],
                  remotes=[]):
        if options is None:
            options = []
        elif type(options) is str:
            options = [options]

        if settings is None:
            settings = []
        elif type(settings) is str:
            settings = [settings]

        if "CUSTOM_CONAN" in os.environ:
            # Utility for Conan versions installed from source
            import sys
            sys.path.append(os.environ["CUSTOM_CONAN"])

        from conans.client.conan_api import ConanAPIV1 as conan_api
        from conans import __version__ as conan_version

        conan, _, _ = conan_api.factory()

        if type(remotes) == list and len(remotes) != 0:
            for remote in remotes:
                name = remote["remote_name"]
                url = remote["url"]
                existingRemotes = conan.remote_list()

                filterByUrl = [
                    eRem for eRem in existingRemotes if eRem.url == url
                ]
                if len(filterByUrl) > 0:
                    continue

                filterByName = [
                    eRem for eRem in existingRemotes
                    if eRem.name.lower() == name.lower()
                ]
                if (len(filterByName) > 0):
                    import random
                    remote["remote_name"] = remote["remote_name"] + str(
                        random.randint(0, 99999))

                conan.remote_add(**remote)

        buildDirectory = os.path.join(os.getcwd(), self.path)
        if not os.path.exists(buildDirectory):
            os.makedirs(buildDirectory)

        data = {"modified": 0}
        if os.path.isfile(os.path.join(self.path, "EnvMod.json")):
            with open(os.path.join(self.path, "EnvMod.json"), "r") as f:
                data = json.load(f)

        conanfilePath = os.path.join(
            os.getcwd(), "conanfile.txt") if conanfile is None else conanfile
        if not os.path.isfile(conanfilePath):
            conanfilePath = os.path.join(os.getcwd(), "conanfile.py")

        lastMod = os.path.getmtime(conanfilePath)
        if data["modified"] < lastMod:
            profile = self.environment[
                "profile"] if "profile" in self.environment else "default"
            if "settings" in self.environment:
                settings = settings + self.environment["settings"].split(",")
            if "options" in self.environment:
                options = options + self.environment["options"].split(",")
            conan.install(conanfilePath,
                          generators=["scons"],
                          install_folder=buildDirectory,
                          options=options,
                          settings=settings,
                          build=["missing"],
                          profile_names=[profile])
            data["modified"] = lastMod
            with open(os.path.join(self.path, "EnvMod.json"), "w") as f:
                json.dump(data, f)

        conan = self.environment.SConscript(
            os.path.join(self.path, "SConscript_conan"))

        self.environment.MergeFlags(conan["conan"])
Ejemplo n.º 13
0
 def __init__(self):
     self._conan_api, _, _ = ConanAPIV1.factory()
Ejemplo n.º 14
0
 def __init__(self, conan_user_home: types.PATH, cwd: types.PATH):
     self._cwd = cwd
     self.stream = StringIO()
     output = ConanOutput(self.stream, self.stream, color=False)
     conan_api = ConanAPIV1(cache_folder=conan_user_home, output=output)
     self.cmd = Command(conan_api)