-
-
Save josuigoa/33265344d99a4bfcf6221335807892e8 to your computer and use it in GitHub Desktop.
Macro - validate a JSON compiletime
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* @author Mark Knol | |
*/ | |
class MacroJsonValidator { | |
public static macro function validateJson(path:String) { | |
if (sys.FileSystem.exists(path)) { | |
var content = sys.io.File.getContent(path); | |
try { | |
// Test the json by parsing it. | |
// It will throw an error when you made a mistake. | |
haxe.Json.parse(content); | |
} catch (error:String) { | |
// create position inside the json, FlashDevelop handles this very nice. | |
var position = Std.parseInt(error.split("position").pop()); | |
var pos = haxe.macro.Context.makePosition({ | |
min:position, | |
max:position + 1, | |
file:path | |
}); | |
var char_count = 20; | |
var startInd = Std.int(Math.max(0, position-char_count)); | |
var endInd = Std.int(Math.min(content.length, position+char_count)); | |
var pre = content.substring(startInd, position); | |
var post = content.substring(position, endInd); | |
haxe.macro.Context.error(path + " is not valid Json. \n..." + pre + "*ERROR*" + post, pos); | |
//haxe.macro.Context.error(path + " is not valid Json. " + error, pos); | |
} | |
} else { | |
haxe.macro.Context.warning(path + " does not exist", haxe.macro.Context.currentPos()); | |
} | |
return macro null; | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Test { | |
static function main() { | |
#if debug | |
MacroJsonValidator.validateJson("bin/inc/json/levels.json"); | |
MacroJsonValidator.validateJson("bin/inc/json/copy.json"); | |
#end | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment