-
Notifications
You must be signed in to change notification settings - Fork 226
Expand file tree
/
Copy pathJycompileAntTask.java
More file actions
79 lines (72 loc) · 2.85 KB
/
JycompileAntTask.java
File metadata and controls
79 lines (72 loc) · 2.85 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
package org.python.util;
import java.io.File;
import java.util.Properties;
import java.util.Set;
import org.apache.tools.ant.BuildException;
import org.python.core.PyException;
import org.python.core.PySystemState;
import org.python.core.RegistryKey;
import org.python.core.imp;
import org.python.modules._py_compile;
/**
* Compiles all python files in a directory to bytecode, and writes them to another directory,
* possibly the same one.
*/
public class JycompileAntTask extends GlobMatchingTask {
@Override
public void process(Set<File> toCompile) throws BuildException {
if (toCompile.size() == 0) {
return;
} else if (toCompile.size() > 1) {
log("Compiling " + toCompile.size() + " files");
} else if (toCompile.size() == 1) {
log("Compiling 1 file");
}
Properties props = new Properties();
props.setProperty(RegistryKey.PYTHON_CACHEDIR_SKIP, "true");
PySystemState.initialize(System.getProperties(), props);
for (File src : toCompile) {
try {
String name = _py_compile.getModuleName(src);
String compiledFilePath = name.replace('.', '/');
if (src.getName().endsWith("__init__.py")) {
compiledFilePath += "/__init__.py";
} else {
compiledFilePath += ".py";
// so we can apply imp.makeCompiledFilename
}
File compiled = new File(destDir,
imp.makeCompiledFilename(compiledFilePath));
compile(src, compiled, name);
} catch (RuntimeException e) {
log("Could not compile " + src);
throw e;
}
}
}
/**
* Compiles the python file <code>src</code> to bytecode filling in <code>moduleName</code> as
* its name, and stores it in <code>compiled</code>. This is called by process for every file
* that's compiled, so subclasses can override this method to affect or track the compilation.
*/
protected void compile(File src, File compiled, String moduleName) {
byte[] bytes;
try {
bytes = imp.compileSource(moduleName, src);
} catch (PyException pye) {
pye.printStackTrace();
throw new BuildException("Compile failed; see the compiler error output for details.");
}
File dir = compiled.getParentFile();
if (!dir.exists() && !compiled.getParentFile().mkdirs()) {
throw new BuildException("Unable to make directory for compiled file: " + compiled);
}
imp.cacheCompiledSource(src.getAbsolutePath(), compiled.getAbsolutePath(), bytes);
}
protected String getFrom() {
return "*.py";
}
protected String getTo() {
return imp.makeCompiledFilename(getFrom());
}
}