I'm writing a macro that needs to open a directory which is in the same folder as my macro class. The problem is that I need to be able to do the same thing, without the need to be aware about macro's folder.
My question is simple, is there a way to open the FileSystem in macro, in the current directory.
e.g : a (b (Macro.hx, c (...) ) )
I need to open "c" directly when I'm running macro methods from "Macro.hx"
If you have an idea, Thank you :)
You can use a function like this inside of a macro:
static function loadFileAsString(path:String) {
try {
var p = haxe.macro.Context.resolvePath(path);
return sys.io.File.getContent(p);
}
catch(e:Dynamic) {
return haxe.macro.Context.error('Failed to load file $path: $e', Context.currentPos());
}
}
Basically, Context.resolvePath will resolve a path relative to all of your class paths. So if your macro is in a file my/package/MyMacro.hx, and you want to load my/package/MyMacroData.json, you could use:
haxe.macro.Context.resolvePath( 'my/package/MyMacroData.json' );
This will check every classpath in your build - including any haxelibs etc, so it will find your file, but it will be possible to "shadow" it, by having a file in the same package/location but in a different class path or haxelib, so try to use a unique package/name so this doesn't happen by accident.
But it should work fine for you, I use it in my compiletime library if you want to look at an example implementation. I've linked to the function with the relevant code.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With