Skip to content

Instantly share code, notes, and snippets.

@zachmargolis
Last active August 29, 2015 14:03
Show Gist options
  • Save zachmargolis/c3afd166ca86c78d194a to your computer and use it in GitHub Desktop.
Save zachmargolis/c3afd166ca86c78d194a to your computer and use it in GitHub Desktop.
Java the Script
$ ./java-the-script
Usage: ./java-the-script -e JAVA_CODE
-i, --import PACKAGE import PACKAGE before compiling code
--debug debug mode: print the generated Java source
-e JAVA_CODE Java source to compile and run
-h, --help Show this message
$ echo "wooooo" | ./java-the-script -e 'System.out.println(STDIN.read().toUpperCase());'
WOOOOO
$ ./java-the-script -i java.util.Calendar -e 'System.out.println(Calendar.getInstance().get(Calendar.YEAR));'
2014
#!/usr/bin/env ruby
require 'optparse'
require 'tmpdir'
java_code = ""
imports = []
print_usage = false
debug_mode = false
parser = OptionParser.new do |opts|
opts.banner = "Usage: #{$0} -e JAVA_CODE"
opts.on('-i', '--import PACKAGE', 'import PACKAGE before compiling code') do |lib|
imports << lib
end
opts.on('--debug', 'debug mode: print the generated Java source') do
debug_mode = true
end
opts.on('-e JAVA_CODE', 'Java source to compile and run') do |java_expr|
java_code = java_expr
end
opts.on_tail('-h', '--help', 'Show this message') do
print_usage = true
end
end
parser.parse!(ARGV)
if java_code.empty? || print_usage
puts parser
exit 1
end
imports << 'java.io.BufferedReader'
imports << 'java.io.InputStream'
imports << 'java.io.InputStreamReader'
imports << 'java.io.IOException'
import_declarations = imports.map do |import|
"import #{import};"
end.join("\n")
if !java_code.end_with?(';')
java_code << ';'
end
java_source = <<JAVA
#{import_declarations}
public class JavaTheScript {
public static class StandardIn {
private final BufferedReader reader;
public StandardIn(InputStream in) {
reader = new BufferedReader(new InputStreamReader(System.in));;
}
public String read() {
StringBuilder builder = new StringBuilder();
try {
while (reader.ready()) {
builder.append(reader.readLine());
}
} catch (IOException ex) {
// chillin.
}
return builder.toString();
}
public String readLine() {
try {
return reader.readLine();
} catch (IOException ex) {
return "";
}
}
}
public static void main(String[] args) {
StandardIn STDIN = new StandardIn(System.in);
#{java_code}
}
}
JAVA
if debug_mode
puts java_source
exit 0
end
Dir.mktmpdir do |dir|
Dir.chdir(dir) do
java_filename = 'JavaTheScript.java'
File.open(java_filename, 'w') { |f| f.write java_source }
system("javac", java_filename)
exec("java", "JavaTheScript")
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment