Handle sources in packages

In the previous tutorial section we created a Conan package for a “Hello World” C++ library. We used the exports_sources attribute of the Conanfile to declare the location of the sources for the library. This method is the simplest way to define the location of the source files when they are in the same folder as the Conanfile. However, sometimes the source files are stored in a repository or a file in a remote server, and not in the same location as the Conanfile. In this section, we will modify the recipe we created previously by adding a source() method and explain how to:

  • Retrieve the sources from a zip file stored in a remote repository.

  • Retrieve the sources from a branch of a git repository.

Please, first clone the sources to recreate this project. You can find them in the examples2 repository on GitHub:

  1. $ git clone https://github.com/conan-io/examples2.git
  2. $ cd examples2/tutorial/creating_packages/handle_sources

The structure of the project is the same as the one in the previous example but without the library sources:

  1. .
  2. ├── CMakeLists.txt
  3. ├── conanfile.py
  4. └── test_package
  5. ├── CMakeLists.txt
  6. ├── conanfile.py
  7. └── src
  8. └── example.cpp

Sources from a zip file stored in a remote repository

Let’s have a look at the changes in the conanfile.py:

  1. from conan import ConanFile
  2. from conan.tools.cmake import CMakeToolchain, CMake, cmake_layout
  3. from conan.tools.files import get
  4. class helloRecipe(ConanFile):
  5. name = "hello"
  6. version = "1.0"
  7. ...
  8. # Binary configuration
  9. settings = "os", "compiler", "build_type", "arch"
  10. options = {"shared": [True, False], "fPIC": [True, False]}
  11. default_options = {"shared": False, "fPIC": True}
  12. def source(self):
  13. # Please, be aware that using the head of the branch instead of an immutable tag
  14. # or commit is a bad practice and not allowed by Conan
  15. get(self, "https://github.com/conan-io/libhello/archive/refs/heads/main.zip",
  16. strip_root=True)
  17. def config_options(self):
  18. if self.settings.os == "Windows":
  19. del self.options.fPIC
  20. def layout(self):
  21. cmake_layout(self)
  22. def generate(self):
  23. tc = CMakeToolchain(self)
  24. tc.generate()
  25. def build(self):
  26. cmake = CMake(self)
  27. cmake.configure()
  28. cmake.build()
  29. def package(self):
  30. cmake = CMake(self)
  31. cmake.install()
  32. def package_info(self):
  33. self.cpp_info.libs = ["hello"]

As you can see, the recipe is the same but instead of declaring the exports_sources attribute as we did previously, i.e.

  1. exports_sources = "CMakeLists.txt", "src/*", "include/*"

we declare a source() method with this information:

  1. def source(self):
  2. # Please, be aware that using the head of the branch instead of an immutable tag
  3. # or commit is strongly discouraged, unsupported by Conan and likely to cause issues
  4. get(self, "https://github.com/conan-io/libhello/archive/refs/heads/main.zip",
  5. strip_root=True)

We used the conan.tools.files.get() tool that will first download the zip file from the URL that we pass as an argument and then unzip it. Note that we pass the strip_root=True argument so that if all the unzipped contents are in a single folder, all the contents are moved to the parent folder (check the conan.tools.files.unzip() reference for more details).

Warning

It is expected that retrieving the sources in the future produces the same results. Using mutable source origins, like a moving reference in git (e.g HEAD branch), or the URL to a file where the contents may change over time, is strongly discouraged and not supported. Not following this practice will result in undefined behavior likely to cause breakages

The contents of the zip file are the same as the sources we previously had beside the Conan recipe, so if you do a conan create the results will be the same as before.

  1. $ conan create .
  2. ...
  3. -------- Installing packages ----------
  4. Installing (downloading, building) binaries...
  5. hello/1.0: Calling source() in /Users/user/.conan2/p/0fcb5ffd11025446/s/.
  6. Downloading update_source.zip
  7. hello/1.0: Unzipping 3.7KB
  8. Unzipping 100 %
  9. hello/1.0: Copying sources to build folder
  10. hello/1.0: Building your package in /Users/user/.conan2/p/tmp/369786d0fb355069/b
  11. ...
  12. -------- Testing the package: Running test() ----------
  13. hello/1.0 (test package): Running test()
  14. hello/1.0 (test package): RUN: ./example
  15. hello/1.0: Hello World Release!
  16. hello/1.0: __x86_64__ defined
  17. hello/1.0: __cplusplus199711
  18. hello/1.0: __GNUC__4
  19. hello/1.0: __GNUC_MINOR__2
  20. hello/1.0: __clang_major__13
  21. hello/1.0: __clang_minor__1
  22. hello/1.0: __apple_build_version__13160021

Please, check the highlighted lines with the messages about the download and unzip operation.

Sources from a branch in a git repository

Now, let’s modify the source() method to bring the sources from a git repository instead of a zip file. We show just the relevant parts:

  1. ...
  2. from conan.tools.scm import Git
  3. class helloRecipe(ConanFile):
  4. name = "hello"
  5. version = "1.0"
  6. ...
  7. def source(self):
  8. git = Git(self)
  9. git.clone(url="https://github.com/conan-io/libhello.git", target=".")
  10. ...

Here, we use the conan.tools.scm.Git() tool. The Git class implements several methods to work with git repositories. In this case, we call the clone method to clone the https://github.com/conan-io/libhello.git repository in the default branch using the same folder for cloning the sources instead of a subfolder (passing the target="." argument).

Warning

As above, this is only a simple example. The source origin for Git() also has to be immutable, it is necessary to checkout out an immutable tag or a specific commit to guarantee the correct behavior. Using the HEAD of the repository is not allowed and can cause undefined behavior and breakages.

To checkout a commit or tag in the repository we use the checkout() method of the Git tool:

  1. def source(self):
  2. git = Git(self)
  3. git.clone(url="https://github.com/conan-io/libhello.git", target=".")
  4. git.checkout("<tag> or <commit hash>")

For more information about the Git class methods, please check the conan.tools.scm.Git() reference.

Note that it’s also possible to run other commands by invoking the self.run() method.

Using the conandata.yml file

We can write a file named conandata.yml in the same folder of the conanfile.py. This file will be automatically exported and parsed by Conan and we can read that information from the recipe. This is handy for example to extract the URLs of the external sources repositories, zip files etc. This is an example of conandata.yml:

  1. sources:
  2. "1.0":
  3. url: "https://github.com/conan-io/libhello/archive/refs/heads/main.zip"
  4. sha256: "7bc71c682895758a996ccf33b70b91611f51252832b01ef3b4675371510ee466"
  5. strip_root: true
  6. "1.1":
  7. url: ...
  8. sha256: ...

The recipe doesn’t need to be modified for each version of the code. We can pass all the keys of the specified version (url, sha256, and strip_root) as arguments to the get function, that, in this case, allow us to verify that the downloaded zip file has the correct sha256. So we could modify the source method to this:

  1. def source(self):
  2. get(self, **self.conan_data["sources"][self.version])
  3. # Similar to:
  4. # data = self.conan_data["sources"][self.version]
  5. # get(self, data["url"], sha256=data["sha256"], strip_root=data["strip_root"])

See also