Search code examples
pythonconan

Read configuration file to populate name of package in conanfile.py


I have a conanfile.py in the root of my repository. Next to it is a configuration file. To not repeat myself, I would like to read this configuration file in my conanfile.py and populate some properties of the ConanFile object, including the name of the package:

class MyConan(ConanFile):
    name = # ... load from configuration file

conanfile.py is executed form multiple locations and I haven't found a consistent way to find out the location of my configuration file. When executed in the repo, then I can use __file__. In the conan cache however, I don't know how to put my configuration file into the export folder or how to retrieve the exported sources directory early enough during initialization of the class. Is it even possible to achieve loading of meta data in the conanfile.py?


Solution

  • The solution was actually quite simple and straight forward after I had removed the readonly flag from the file data.json (otherwise exporting will fail with "Permission denied", at least on Windows):

    import json
    import os
    
    from conans import ConanFile, load
    
    
    class MyConan(ConanFile):
        exports = "data.json"
    
        def init(self):
            data = json.loads(load(os.path.join(self.recipe_folder, "data.json")))
            self.name = data["name"]
    

    This solution is documented here: https://docs.conan.io/en/latest/reference/conanfile/methods.html#init