Skip to content

Instantly share code, notes, and snippets.

@JakubNer
Created September 6, 2018 23:16
Show Gist options
  • Save JakubNer/25dc1db824e5d10bbc38b89d87cc1232 to your computer and use it in GitHub Desktop.
Save JakubNer/25dc1db824e5d10bbc38b89d87cc1232 to your computer and use it in GitHub Desktop.
A Nashorn (JavaScript) script to search out variable definitions in comments and use their values in other places in the file where placeholder comments are present.
// This is a Nashorn (JavaScript) script to search out variable definitions in comments and use their values
// in other places in the file where placeholder comments are present.
//
// SYNOPSIS
//
// jjs variablize.jjs -- ${PATH}
//
// DESCRIPTION
//
// Go through file at ${PATH} and search out all variable definitions as per regular expression:
//
// \/\*\s*(\w*)\s*=\s*(.*?)\s*\*\/
//
// The pattern matches stings such as:
//
// /* foo = bar */
//
// Where group 1 (foo) is the variable name, group 2 (bar) is the value.
//
//
// With these definitions, search the rest of ${PATH} for regular expression:
//
// \/\*\s*(\w*)\s*\*\/(.*?)\/\*\*\/
//
// The pattern matches strings such as:
//
// /* foo */ .. /**/
//
// Where group 1 (foo) is the variable name, group 2 ( .. ) will be replaced by the value (bar)
//
// args
var filePath = arguments[0];
// imports
var String=Java.type("java.lang.String");
var StringBuffer=Java.type("java.lang.StringBuffer");
var File=Java.type("java.io.File");
var FileSystems=Java.type("java.nio.file.FileSystems");
var Files=Java.type("java.nio.file.Files");
var FileWriter=Java.type("java.io.FileWriter");
var StandardCharsets=Java.type("java.nio.charset.StandardCharsets");
var buf = new String(Files.readAllBytes(FileSystems.getDefault().getPath(filePath)), StandardCharsets.UTF_8);
var matches = {}
var definitionRegexp = /\/\*\s*(\w*)\s*=\s*(.*?)\s*\*\//g;
var match = definitionRegexp.exec(buf);
while (match != null) {
matches[match[1]] = match[2];
print("DEF " + match[1] + " = " + match[2])
match = definitionRegexp.exec(buf);
}
for (var match in matches) {
var replacementRegexp = new RegExp('(\\/\\*\\s*'+match+'\\s*\\*\\/)(.*?)\\/\\*\\*\\/','g');
buf = buf.replace(replacementRegexp,'$1' + matches[match] + '/**/');
}
var fw = new FileWriter(FileSystems.getDefault().getPath(filePath));
fw.write(buf);
fw.close();
@JakubNer
Copy link
Author

JakubNer commented Sep 6, 2018

Adding as "External Tool" in IntelliJ

Go to "External Tools"

For Program point to Nashorn: C:\Program Files\Java\jdk1.8.0_171\bin\jjs.exe
For Arguments point to your script on file system: C:\Users\jner\usr\variabilize.jjs -- "$FilePath$"
For Working directory point to some temp (it's not used): C:\Users\jner\tmp

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment