String projectName = commandLine.getValue(Options.PROJECT_OPTION);
String interpreterNameOrPath = commandLine.getValue("i");
String version = commandLine.getValue(Options.VERSION_OPTION);
IProject project = ProjectUtils.getProject(projectName);
PythonNature nature = PythonNature.getPythonNature(project);
if (nature == null){
throw new RuntimeException(
Services.getMessage("python.missing.nature"));
}
IInterpreterInfo interpreter = null;
IInterpreterManager manager = nature.getRelatedInterpreterManager();
IInterpreterInfo[] existing = manager.getInterpreterInfos();
for (IInterpreterInfo info : existing){
if (info.getName().equals(interpreterNameOrPath) ||
info.getExecutableOrJar().equals(interpreterNameOrPath))
{
interpreter = info;
break;
}
}
File path = new File(interpreterNameOrPath);
if (interpreter == null && path.exists() && path.isFile()){
HashSet<String> skip = new HashSet<String>();
for (IInterpreterInfo info : existing){
skip.add(info.getExecutableOrJar());
}
interpreter = manager.createInterpreterInfo(
interpreterNameOrPath, new NullProgressMonitor(), false);
interpreter.setName(FileUtils.getBaseName(interpreterNameOrPath));
IInterpreterInfo[] updated = new IInterpreterInfo[existing.length + 1];
System.arraycopy(existing, 0, updated, 0, existing.length);
updated[updated.length - 1] = interpreter;
manager.setInfos(updated, skip, new NullProgressMonitor());
}else if (interpreter == null){
throw new RuntimeException(Services.getMessage(
"python.interpreter.not.found", interpreterNameOrPath));
}
if (version == null){
version = nature.getVersion();
}
// ensure the version is valid for the new interpreter
ArrayList<String> grammars = new ArrayList<String>();
String[] parts = StringUtils.split(interpreter.getVersion(), ".");
double iversion = Double.parseDouble(parts[0] + '.' + parts[1]);
for (String grammar : IPythonNature.Versions.ALL_PYTHON_VERSIONS){
grammar = grammar.replace("python ", "");
double gversion = Double.parseDouble(grammar);
if (gversion <= iversion &&
grammar.charAt(0) == interpreter.getVersion().charAt(0))
{
grammars.add(grammar);
}
}
if (!grammars.contains(version)){
Collections.sort(grammars);
version = grammars.get(grammars.size() - 1);
}
nature.setVersion(version, interpreter.getName());
return Services.getMessage("python.interpreter.set", projectName);
}