Can you walk a filesystem in comptime and create a structure of multiple @embedFile?

I may just experiment with this later, but Zig’s filesystem API has been pretty confusing so I decided to just ask if anyone knows. I essentially wanna embed an array of file data along with their respective filenames, every file found in a directory, all in comptime. I already have a bash script that generates such C-code, but I got thinking if Zig comptime can fully perform such task.

No, comptime doesn’t support recursing down a file tree, just embedding individual files.

To implement what you’re asking you would currently have to use the build system to create a zig file that lists all the individual @embedFile calls.

I don’t know if this was ever proposed before as a proper proposal issue on GH. If it never was, it might be worth discussing it, maybe.

3 Likes

This is one of those situations where it’s easier to generate the list using a scripting language like PHP. I mean, it’s unlikely that you’d want to allow end-users to link in arbitrary files. What files are in the folder in question is probably determined by you. In theory you could just type in their names. That’s annoying of course and rather error-prone. With PHP you can get the list with a single line of code. Heck, you can do this with Bash. The only hard part is adding the code generation step into your build file so it occurs automatically.

Yup. Already did it in bash. The use case is not for user modification, but to build some resources / media data into an audiovisual production’s executable so that everything is fully contained in a single that doesn’t need extraction.

Are you running the script as a build step or just manually?

As a build step. It’s not for a professional-quality software, though, but a piece of art or hobby project.

Can you post the code for the build step? I may need to do this at some point and the documentation at the moment isn’t terribly instructive.

I’ve played around with this idea lately, put together an example here.

Basically the build script walks the specified directory and makes this list of paths available to the main program (or library). In main, you can now comptime-embed the the directory’s content, making it available via the binary you ship.
The only ‘catch’ I’ve noted is that the directory you embed has to be part of the module (i.e. within its path); which in most cases shouldn’t be an issue, however you have to keep it in mind.