Insert package version(s) into source code

I would like to use the package version (Git tag and/or commit hash) in the source code for automated version information within the executables, also checking the Git status.

I implemented a function that calls Git (git rev-parse HEAD, git tag --contains ..., checking changes via git status -z) to get the according information, but in order for this to work for the executable this should be executed during compile time i.e. a (freestanding) macro should be used.

Unfortunately, during macros expansion calling an external program does not seem to be allowed (error: Failed to receive result from plugin), and I also think that such a macro #packageVersion could be a nice feature to be added "side by side" to #function or #filePath.

I also tried to include the "swift-package-manager“ package but this failed.

Maybe someone has an idea (or some code?) how to get the package version (or even as an additional feature all resolved package versions) into the source code, and is it true that calling an external program during macro expansion does not work?

1 Like

This could potentially help you: Add git information to PD context by neonichu · Pull Request #7202 · apple/swift-package-manager · GitHub

1 Like

Great! Hopefully this change will be merged, so I just would have a wait a little bit, which is OK for me. :slight_smile: Thanks.

...Of course, getting the version info for all resolved packages would also be nice...

...This would still have to be worked out, at best added to standard Swift for easy usage.

I think this would be possible with a Swift package build plugin (to get the current git version and generate a file with a single version variable or something). It wouldn’t be as elegant as a macro but it should be usable.

1 Like

It would similarly be very interesting/useful to be able to retrieve the Swift toolchain version that is being used. Would you have any thoughts on that @NeoNacho in terms of if that's achievable and/or wanted? For me personally it would be very useful since I'm working with nightlies a lot and running benchmarks. Often performance will vary across new toolchain versions for some of the benchmarking work I'm doing (autodiff and Keypath related in most cases).

We already have a swift package build plugin for the git commit hash indeed so that MR is a very welcome improvement over that!

Edit: @NeoNacho the MR you linked to does not allow for passing the git information along to the actual Swift source code does it? Maybe I'm missing something obvious though?