use of org.python.pydev.core.PythonNatureWithoutProjectException in project Pydev by fabioz.
the class AdditionalProjectInterpreterInfo method getAdditionalInfoAndNature.
public static List<Tuple<AbstractAdditionalTokensInfo, IPythonNature>> getAdditionalInfoAndNature(IPythonNature nature, boolean addSystemInfo, boolean addReferencingProjects, boolean addReferencedProjects) throws MisconfigurationException {
List<Tuple<AbstractAdditionalTokensInfo, IPythonNature>> ret = new ArrayList<Tuple<AbstractAdditionalTokensInfo, IPythonNature>>();
IProject project = nature.getProject();
// get for the system info
if (addSystemInfo) {
AbstractAdditionalTokensInfo systemInfo;
try {
systemInfo = AdditionalSystemInterpreterInfo.getAdditionalSystemInfo(InterpreterManagersAPI.getInterpreterManager(nature), nature.getProjectInterpreter().getExecutableOrJar());
} catch (MisconfigurationException e) {
throw e;
} catch (PythonNatureWithoutProjectException e) {
throw new RuntimeException(e);
}
ret.add(new Tuple<AbstractAdditionalTokensInfo, IPythonNature>(systemInfo, new SystemPythonNature(nature.getRelatedInterpreterManager())));
}
// get for the current project
if (project != null) {
AbstractAdditionalTokensInfo additionalInfoForProject = getAdditionalInfoForProject(nature);
if (additionalInfoForProject != null) {
ret.add(new Tuple<AbstractAdditionalTokensInfo, IPythonNature>(additionalInfoForProject, nature));
}
try {
if (addReferencedProjects) {
// get for the referenced projects
Set<IProject> referencedProjects = ProjectModulesManager.getReferencedProjects(project);
for (IProject refProject : referencedProjects) {
additionalInfoForProject = getAdditionalInfoForProject(PythonNature.getPythonNature(refProject));
if (additionalInfoForProject != null) {
ret.add(new Tuple<AbstractAdditionalTokensInfo, IPythonNature>(additionalInfoForProject, PythonNature.getPythonNature(refProject)));
}
}
}
if (addReferencingProjects) {
Set<IProject> referencingProjects = ProjectModulesManager.getReferencingProjects(project);
for (IProject refProject : referencingProjects) {
additionalInfoForProject = getAdditionalInfoForProject(PythonNature.getPythonNature(refProject));
if (additionalInfoForProject != null) {
ret.add(new Tuple<AbstractAdditionalTokensInfo, IPythonNature>(additionalInfoForProject, PythonNature.getPythonNature(refProject)));
}
}
}
} catch (Exception e) {
Log.log(e);
}
}
return ret;
}
use of org.python.pydev.core.PythonNatureWithoutProjectException in project Pydev by fabioz.
the class PythonNature method getVersionAndError.
@Override
public Tuple<String, String> getVersionAndError(boolean translateIfInterpreter) throws CoreException {
if (project != null) {
if (versionPropertyCache == null) {
String storeVersion = getStore().getPropertyFromXml(getPythonProjectVersionQualifiedName());
if (storeVersion == null) {
// there is no such property set (let's set it to the default)
// will set the versionPropertyCache too
setVersion(getDefaultVersion(false), null);
} else {
// now, before returning and setting in the cache, let's make sure it's a valid version.
if (!IPythonNature.Versions.ALL_VERSIONS_ANY_FLAVOR.contains(storeVersion)) {
Log.log("The stored version is invalid (" + storeVersion + "). Setting default.");
// will set the versionPropertyCache too
setVersion(getDefaultVersion(false), null);
} else {
// Ok, it's correct.
versionPropertyCache = storeVersion;
}
}
}
} else {
String msg = "Trying to get version without project set. Returning default.";
Log.log(msg);
return new Tuple<String, String>(getDefaultVersion(translateIfInterpreter), msg);
}
if (versionPropertyCache == null) {
String msg = "The cached version is null. Returning default.";
Log.log(msg);
return new Tuple<String, String>(getDefaultVersion(translateIfInterpreter), msg);
} else if (!IPythonNature.Versions.ALL_VERSIONS_ANY_FLAVOR.contains(versionPropertyCache)) {
String msg = "The cached version (" + versionPropertyCache + ") is invalid. Returning default.";
Log.log(msg);
return new Tuple<String, String>(getDefaultVersion(translateIfInterpreter), msg);
}
if (translateIfInterpreter && versionPropertyCache.endsWith(IPythonNature.Versions.INTERPRETER_VERSION)) {
Tuple<String, String> split = StringUtils.splitOnFirst(versionPropertyCache, ' ');
String errorMessage;
try {
IInterpreterInfo info = this.getProjectInterpreter();
String version = info.getVersion();
if (version != null) {
return new Tuple<String, String>(IPythonNature.Versions.convertToInternalVersion(new FastStringBuffer(split.o1, 6).append(' '), version), null);
} else {
errorMessage = "Unable to get version from interpreter info: " + info.getNameForUI() + " - " + info.getExecutableOrJar();
Log.log(errorMessage);
}
} catch (MisconfigurationException | PythonNatureWithoutProjectException e) {
Log.log(e);
errorMessage = e.getMessage();
}
return new Tuple<String, String>(split.o1 + " " + "2.7", errorMessage + " (in project: " + getProject() + ")");
}
return new Tuple<String, String>(versionPropertyCache, null);
}
use of org.python.pydev.core.PythonNatureWithoutProjectException in project Pydev by fabioz.
the class PyOrganizeImports method organizeImports.
@SuppressWarnings("unchecked")
private void organizeImports(PyEdit edit, final IDocument doc, IFile f, PySelection ps) throws MisconfigurationException, PythonNatureWithoutProjectException {
DocumentRewriteSession session = null;
String endLineDelim = ps.getEndLineDelim();
List<IOrganizeImports> participants = null;
if (f == null && !automatic) {
// organizing single file ...
// let's see if someone wants to make a better implementation in another plugin...
participants = ExtensionHelper.getParticipants(ExtensionHelper.PYDEV_ORGANIZE_IMPORTS);
for (IOrganizeImports organizeImports : participants) {
if (!organizeImports.beforePerformArrangeImports(ps, edit, f)) {
return;
}
}
}
String fileContents = doc.get();
if (fileContents.contains("isort:skip_file") || fileContents.length() == 0) {
return;
}
IAdaptable projectAdaptable = edit != null ? edit : f;
String indentStr = edit != null ? edit.getIndentPrefs().getIndentationString() : DefaultIndentPrefs.get(f).getIndentationString();
session = TextSelectionUtils.startWrite(doc);
try {
// Important: the remove and later update have to be done in the same session (since the remove
// will just remove some names and he actual perform will remove the remaining if needed).
// i.e.: from a import b <-- b will be removed by the OrganizeImportsFixesUnused and the
// from a will be removed in the performArrangeImports later on.
boolean removeUnusedImports = false;
if (!automatic) {
// Only go through the removal of unused imports if it's manually activated (not on automatic mode).
removeUnusedImports = ImportsPreferencesPage.getDeleteUnusedImports(projectAdaptable);
if (removeUnusedImports) {
new OrganizeImportsFixesUnused().beforePerformArrangeImports(ps, edit, f);
}
}
Set<String> knownThirdParty = new HashSet<String>();
// isort itself already has a reasonable stdLib, so, don't do our own.
String importEngine = ImportsPreferencesPage.getImportEngine(projectAdaptable);
if (edit != null) {
IPythonNature pythonNature = edit.getPythonNature();
if (pythonNature != null) {
IInterpreterInfo projectInterpreter = pythonNature.getProjectInterpreter();
ISystemModulesManager modulesManager = projectInterpreter.getModulesManager();
ModulesKey[] onlyDirectModules = modulesManager.getOnlyDirectModules();
Set<String> stdLib = new HashSet<>();
for (ModulesKey modulesKey : onlyDirectModules) {
if (modulesKey.file == null) {
int i = modulesKey.name.indexOf('.');
String name;
if (i < 0) {
name = modulesKey.name;
} else {
name = modulesKey.name.substring(0, i);
}
// Add all names to std lib
stdLib.add(name);
}
}
for (ModulesKey modulesKey : onlyDirectModules) {
int i = modulesKey.name.indexOf('.');
String name;
if (i < 0) {
name = modulesKey.name;
} else {
name = modulesKey.name.substring(0, i);
}
// Consider all in site-packages to be third party.
if (modulesKey.file != null && modulesKey.file.toString().contains("site-packages")) {
stdLib.remove(name);
knownThirdParty.add(name);
}
}
}
}
switch(importEngine) {
case ImportsPreferencesPage.IMPORT_ENGINE_ISORT:
if (fileContents.length() > 0) {
File targetFile = edit != null ? edit.getEditorFile() : null;
if (targetFile == null) {
if (f != null) {
IPath location = f.getLocation();
if (location != null) {
targetFile = location.toFile();
}
}
}
String isortResult = JythonModules.makeISort(fileContents, targetFile, knownThirdParty);
if (isortResult != null) {
try {
DocUtils.updateDocRangeWithContents(doc, fileContents, isortResult.toString());
} catch (Exception e) {
Log.log(StringUtils.format("Error trying to apply isort result. Curr doc:\n>>>%s\n<<<.\nNew doc:\\n>>>%s\\n<<<.", fileContents, isortResult.toString()), e);
}
}
}
break;
case ImportsPreferencesPage.IMPORT_ENGINE_REGULAR_SORT:
performArrangeImports(doc, removeUnusedImports, endLineDelim, indentStr, automatic, edit);
break;
default:
// case ImportsPreferencesPage.IMPORT_ENGINE_PEP_8:
if (f == null) {
f = edit.getIFile();
}
IProject p = f != null ? f.getProject() : null;
pep8PerformArrangeImports(doc, removeUnusedImports, endLineDelim, p, indentStr, automatic, edit);
break;
}
if (participants != null) {
for (IOrganizeImports organizeImports : participants) {
organizeImports.afterPerformArrangeImports(ps, edit);
}
}
} finally {
TextSelectionUtils.endWrite(doc, session);
}
}
use of org.python.pydev.core.PythonNatureWithoutProjectException in project Pydev by fabioz.
the class AbstractManageEnvEditorAction method run.
@Override
public void run() {
try {
final IPythonNature pythonNature = edit.getPythonNature();
if (pythonNature == null) {
PyDialogHelpers.openCritical("Unable to execute pip", "The related editor does not have an associated python nature.");
return;
}
IInterpreterInfo projectInterpreter = pythonNature.getProjectInterpreter();
if (projectInterpreter == null) {
PyDialogHelpers.openCritical("Unable to execute pip", "The related editor does not have an associated interpreter.");
return;
}
doRun(pythonNature, projectInterpreter);
} catch (MisconfigurationException | PythonNatureWithoutProjectException e) {
Log.log(e);
}
}
use of org.python.pydev.core.PythonNatureWithoutProjectException in project Pydev by fabioz.
the class AbstractASTManager method getCompletionFromFuncDefReturn.
@Override
public TokensList getCompletionFromFuncDefReturn(ICompletionState state, IModule module, IDefinition definition, boolean considerYieldTheReturnType) throws CompletionRecursionException {
TokensList ret = new TokensList();
if (!(module instanceof SourceModule)) {
return ret;
}
if (!(definition instanceof Definition)) {
return ret;
}
Definition def = (Definition) definition;
FunctionDef functionDef = (FunctionDef) def.ast;
ITypeInfo type = NodeUtils.getReturnTypeFromFuncDefAST(functionDef);
if (type != null) {
ICompletionState copy = state.getCopy();
copy.setActivationToken(type.getActTok());
try (NoExceptionCloseable x = copy.pushLookingFor(LookingFor.LOOKING_FOR_INSTANCED_VARIABLE)) {
stmtType[] body = functionDef.body;
if (body.length > 0) {
copy.setLine(body[0].beginLine - 1);
copy.setCol(body[0].beginColumn - 1);
}
IModule definitionModule = def.module;
state.checkDefinitionMemory(definitionModule, def);
TokensList tks = this.getCompletionsForModule(definitionModule, copy);
if (tks.notEmpty()) {
// TODO: This is not ideal... ideally, we'd return this info along instead of setting
// it in the token, but this may be hard as we have to touch LOTS of places for
// this information to get to the needed place.
tks.setGeneratorType(type);
ret.addAll(tks);
// Ok, resolved rtype!
return ret;
} else {
// Try to deal with some token that's not imported
List<IPyDevCompletionParticipant> participants = ExtensionHelper.getParticipants(ExtensionHelper.PYDEV_COMPLETION);
for (IPyDevCompletionParticipant participant : participants) {
TokensList collection = participant.getCompletionsForType(copy);
if (collection != null && collection.notEmpty()) {
ret.addAll(collection);
// Ok, resolved rtype!
return ret;
}
}
}
}
}
List<Return> returns = ReturnVisitor.findReturns(functionDef);
Stream<exprType> map = returns.stream().map(r -> r.value);
if (considerYieldTheReturnType) {
List<Yield> yields = YieldVisitor.findYields(functionDef);
map = Stream.concat(map, yields.stream().map(yield -> yield.value));
}
for (Iterator<exprType> it = map.iterator(); it.hasNext(); ) {
exprType value = it.next();
if (value == null) {
continue;
}
String act = NodeUtils.getFullRepresentationString(value);
if (act == null) {
// may happen if the return we're seeing is a return without anything (keep on going to check other returns)
continue;
}
ITokenCompletionRequest request = new TokenCompletionRequest(act, def.module, state.getNature(), "", def.line - 1, def.col - 1);
TokensList tokensList = new TokensList();
ICompletionState copy = state.getCopy();
copy.setActivationToken(act);
copy.setLine(value.beginLine - 1);
copy.setCol(value.beginColumn - 1);
LookingFor lookingFor = null;
if (value instanceof Call) {
lookingFor = ICompletionState.LookingFor.LOOKING_FOR_INSTANCED_VARIABLE;
}
try (NoExceptionCloseable x = state.pushLookingFor(lookingFor)) {
IModule definitionModule = def.module;
state.checkDefinitionMemory(definitionModule, def);
try {
PyCodeCompletion.doTokenCompletion(request, this, tokensList, act, copy);
} catch (MisconfigurationException | IOException | CoreException | PythonNatureWithoutProjectException e) {
throw new RuntimeException(e);
}
if (lookingFor != null) {
tokensList.setLookingFor(lookingFor);
}
ret.addAll(tokensList);
}
}
return ret;
}
Aggregations