Search code examples
macroshaxe

Access the compilation date during compilation in Haxe


I was wondering whether it is possible to access external information - like the current date during compilation.

It would then be possible to do something like this:

class MyInfo {
    private var buildDate:Int = --- AUTOMATICALLY INSERT THE CURRENT UNIX DATE TIME HERE ---;

    public function getInfo():String { // example usage
        return "This library was compiled the " + buildDate;
    }
}

I thought about accessing this information in the compilation bat/sh/make file and then pass it to the compiler, too. (Something similar to "-D".) However the Haxe compiler does not seem to support an argument like:

haxe --main MyInfo --js test.js -SOMEARG date=$(date)

So that I could use the content of the variable date afterwards ...


Solution

  • This can be done with macros (code executing at compile-time).

    Your date example is covered in the cookbook, here. You can find more about macros in the haxe manual or in the cookbook.

    Edit: Minimal example:

    class Test {
      public static function main() {
        trace(getBuildTime());
      }
    
      public static macro function getBuildTime() {
        var buildTime = Math.floor(Date.now().getTime() / 1000);
    
        return macro $v{buildTime};
      }
    }
    

    The time will be computed at compile-time.