Skip to content

Instantly share code, notes, and snippets.

@fornwall
Created June 4, 2010 23:14
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save fornwall/426070 to your computer and use it in GitHub Desktop.
Save fornwall/426070 to your computer and use it in GitHub Desktop.
EclipseScript examples (see http://eclipsescript.org)
<?xml version="1.0" encoding="UTF-8"?>
<projectDescription>
<name>eclipsescript-examples</name>
<comment></comment>
<projects>
</projects>
<buildSpec>
</buildSpec>
<natures>
</natures>
</projectDescription>
// show the import statements from the currently edited java file using JDT api
var editedFile = eclipse.editors.file;
var compilationUnit = Packages.org.eclipse.jdt.core.JavaCore.create(editedFile);
if (compilationUnit == null) eclipse.runtime.die('You are not editing a java file!');
var message = "The following packages are imported:\n";
for each (var i in compilationUnit.imports) message += i.elementName + "\n";
eclipse.window.alert(message);
// replace the current selection with a color picked from a color picker
var dialog = new Packages.org.eclipse.swt.widgets.ColorDialog(eclipse.runtime.shell);
var color = dialog.open();
if (color != null) {
var hex = function(i) { var s = java.lang.Integer.toHexString(i); return (s.length == 1 ? '0' : '') + s; }
var string = ('#' + hex(color.red) + hex(color.green) + hex(color.blue)).toUpperCase();
eclipse.editors.replaceSelection(string);
}
// my first eclipse script
var jsFiles = eclipse.resources.filesMatching('.*\.js', eclipse.resources.workspace.root);
eclipse.window.alert('Number of .js files in workspace: ' + jsFiles.length);
// using a background job to measure the size of a project
var project = eclipse.resources.currentProject;
if (project == null) eclipse.runtime.die('No project with name: ' + project.name);
eclipse.console.println('Project: ' + project.name);
eclipse.runtime.schedule(function run(monitor) {
for each (var fileType in ['java', 'js', 'css', 'sql', 'jsp', 'html']) {
var files = eclipse.resources.filesMatching('.*\.' + fileType, project);
monitor.beginTask('Counting .' + fileType + ' lines in project ' + project.name, files.length);
var totalCount = 0;
for each (var file in files) {
if (monitor.canceled) return false;
var str = eclipse.resources.read(file);
totalCount += str.split("\n").length;
monitor.worked(1);
}
eclipse.console.println('Number of ' + fileType + ' lines: ' + totalCount + ' in ' + files.length + ' files');
}
});
// post the currently selected text to gist
var selection = eclipse.editors.selection || eclipse.runtime.die('No current selection');
var snippet = selection.text.replace(/\s+$/, '');
var fileName = (eclipse.editors.file == null) ? 'snippet.txt' : eclipse.editors.file.name;
eclipse.runtime.schedule(function(monitor) {
monitor.beginTask('Submitting snippet', -1);
var postURL = new java.net.URL('http://gist.github.com/api/v1/xml/new');
var connection = postURL.openConnection();
connection.doOutput = true;
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
var out = new java.io.OutputStreamWriter(connection.outputStream);
out.write("files[Snippet from " + fileName + "]=" + java.net.URLEncoder.encode(snippet, 'utf-8'));
out.close();
var doc = eclipse.xml.parse(connection);
var repo = 'http://gist.github.com/' + doc.getElementsByTagName('repo').item(0).textContent;
eclipse.editors.clipboard = repo;
eclipse.window.status = 'Snippet URL copied to clipboard';
eclipse.window.open(repo);
});
// wrap method bodies in timing statements
var editedFile = eclipse.editors.file;
var compilationUnit = Packages.org.eclipse.jdt.core.JavaCore.create(editedFile);
if (compilationUnit == null) eclipse.runtime.die('You are not editing a java file!');
var parser = org.eclipse.jdt.core.dom.ASTParser.newParser(Packages.org.eclipse.jdt.core.dom.AST.JLS3);
parser.setKind(org.eclipse.jdt.core.dom.ASTParser.K_COMPILATION_UNIT);
parser.setSource(compilationUnit);
parser.setResolveBindings(true);
var astRoot = parser.createAST(null);
astRoot.recordModifications();
var ast = astRoot.getAST();
astRoot.accept(new Packages.org.eclipse.jdt.core.dom.ASTVisitor({
visit: function(arg) {
if (arg instanceof Packages.org.eclipse.jdt.core.dom.MethodDeclaration) {
var methodDeclaration = arg;
var methodBlock = methodDeclaration.body;
if (methodBlock == null) // abstract methods has no body:
return this.super$visit(arg);
var methodStatements = methodBlock.statements();
var origStatements = new Packages.java.util.ArrayList(methodStatements);
methodStatements.clear();
var foundSuperBlock = false;
// do not wrap super() call try-finally block
for (var i = 0; i < origStatements.size(); i++) {
var statement = origStatements.get(i);
if (statement instanceof Packages.org.eclipse.jdt.core.dom.SuperConstructorInvocation) {
foundSuperBlock = true;
origStatements.remove(i);
methodStatements.add(statement);
break;
}
}
var tryStatement = ast.newTryStatement();
methodStatements.add(tryStatement);
tryStatement.body.statements().addAll(origStatements);
var startTimeAssignment = ast.newAssignment();
var startTimeDeclarationFrament = ast.newVariableDeclarationFragment();
startTimeDeclarationFrament.setName(ast.newSimpleName("_startTime"));
var startTimeDeclarationExpression = ast.newVariableDeclarationExpression(startTimeDeclarationFrament);
startTimeDeclarationExpression.setType(ast.newPrimitiveType(Packages.org.eclipse.jdt.core.dom.PrimitiveType.LONG));
startTimeAssignment.setLeftHandSide(startTimeDeclarationExpression);
var currentTimeInvocation = ast.newMethodInvocation();
currentTimeInvocation.setExpression(ast.newSimpleName("System"));
currentTimeInvocation.setName(ast.newSimpleName("currentTimeMillis"));
startTimeAssignment.setRightHandSide(currentTimeInvocation);
methodBlock.statements().add(foundSuperBlock ? 1 : 0, ast.newExpressionStatement(startTimeAssignment));
var passedTimeAssignment = ast.newAssignment();
passedTimeAssignment.setOperator(Packages.org.eclipse.jdt.core.dom.Assignment.Operator.ASSIGN);
// assignment left
var passedTimeAssignmentFragment = ast.newVariableDeclarationFragment();
passedTimeAssignmentFragment.setName(ast.newSimpleName("_passedTime"));
var passedTimeAssignmentExpression = ast.newVariableDeclarationExpression(passedTimeAssignmentFragment);
passedTimeAssignmentExpression.setType(ast.newPrimitiveType(Packages.org.eclipse.jdt.core.dom.PrimitiveType.LONG));
passedTimeAssignment.setLeftHandSide(passedTimeAssignmentExpression);
// assignment right
var minusExpression = ast.newInfixExpression();
minusExpression.setOperator(Packages.org.eclipse.jdt.core.dom.InfixExpression.Operator.MINUS);
currentTimeInvocation = ast.newMethodInvocation();
currentTimeInvocation.setExpression(ast.newSimpleName("System"));
currentTimeInvocation.setName(ast.newSimpleName("currentTimeMillis"));
minusExpression.setLeftOperand(currentTimeInvocation);
minusExpression.setRightOperand(ast.newSimpleName("_startTime"));
passedTimeAssignment.setRightHandSide(minusExpression);
var infixExpression = ast.newInfixExpression();
infixExpression.setOperator(Packages.org.eclipse.jdt.core.dom.InfixExpression.Operator.PLUS);
var stringLiteral = ast.newStringLiteral();
var parentName = methodDeclaration.parent.name || ('anonymous-subclass-of-' + methodDeclaration.parent.parent.type);
stringLiteral.setLiteralValue("Time executing " + parentName + "#" + methodDeclaration.name + ": ");
infixExpression.setLeftOperand(stringLiteral);
infixExpression.setRightOperand(ast.newSimpleName("_passedTime"));
var systemOutInvocation = ast.newMethodInvocation();
systemOutInvocation.setExpression(ast.newQualifiedName(ast.newSimpleName("System"), ast.newSimpleName("out")));
systemOutInvocation.setName(ast.newSimpleName("println"));
systemOutInvocation.arguments().add(infixExpression);
var finallyBlock = ast.newBlock();
finallyBlock.statements().add(ast.newExpressionStatement(passedTimeAssignment));
finallyBlock.statements().add(ast.newExpressionStatement(systemOutInvocation));
tryStatement.setFinally(finallyBlock);
}
return this.super$visit(arg);
}
}));
var doc = eclipse.editors.document;
var textEdits = astRoot.rewrite(doc, null);
textEdits.apply(doc);
// put a problem marker on every method returning a String
var editedFile = eclipse.editors.file;
var compilationUnit = Packages.org.eclipse.jdt.core.JavaCore.create(editedFile);
if (compilationUnit == null) eclipse.runtime.die('You are not editing a java file!');
function parse(compilationUnit) {
var parser = org.eclipse.jdt.core.dom.ASTParser.newParser(Packages.org.eclipse.jdt.core.dom.AST.JLS3);
parser.setKind(org.eclipse.jdt.core.dom.ASTParser.K_COMPILATION_UNIT);
parser.setSource(compilationUnit);
parser.setResolveBindings(true);
return parser.createAST(null);
}
var IMarker = Packages.org.eclipse.core.resources.IMarker;
var document = eclipse.editors.document;
// clear up old markers from this script
for each (var m in editedFile.findMarkers(IMarker.PROBLEM, false, 0))
if (m.getAttribute('method_return_string_marker') == true) m['delete']();
parse(compilationUnit).accept(new Packages.org.eclipse.jdt.core.dom.ASTVisitor({
visit: function(arg) {
if (arg instanceof Packages.org.eclipse.jdt.core.dom.MethodDeclaration) {
if (arg.returnType2 == 'String') {
var line = document.getLineOfOffset(arg.startPosition);
var marker = editedFile.createMarker(IMarker.PROBLEM);
marker.setAttribute(IMarker.MESSAGE, "Method returns String");
marker.setAttribute(IMarker.PRIORITY, IMarker.PRIORITY_HIGH);
marker.setAttribute(IMarker.SEVERITY, IMarker.SEVERITY_ERROR);
marker.setAttribute(IMarker.LINE_NUMBER, line+1);
marker.setAttribute('method_return_string_marker', true);
}
}
return this.super$visit(arg);
}
}));
// transforms the currently selected text to upper case
if (eclipse.editors.selection == null) eclipse.runtime.die('No text selected!');
eclipse.editors.replaceSelection(eclipse.editors.selection.text.toUpperCase());
// warn about all lines containing System.out
if (eclipse.editors.document == null) eclipse.runtime.die('No currently edited file');
var lineCount = 0;
for each (var line in eclipse.editors.document.get().split("\n")) {
lineCount++;
if (line.indexOf('System.out') != -1)
eclipse.console.println("Line " + lineCount + " contains System.out");
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment