use of org.python.pydev.core.docutils.ImportHandle in project Pydev by fabioz.
the class TddQuickFixParticipant method addProps.
@Override
public void addProps(MarkerAnnotationAndPosition markerAnnotation, IAnalysisPreferences analysisPreferences, String line, PySelection ps, int offset, IPythonNature nature, PyEdit edit, List<ICompletionProposalHandle> props) throws BadLocationException, CoreException {
if (nature == null) {
return;
}
ICodeCompletionASTManager astManager = nature.getAstManager();
if (astManager == null) {
return;
}
if (markerAnnotation.position == null) {
return;
}
IMarker marker = markerAnnotation.markerAnnotation.getMarker();
Integer id = (Integer) marker.getAttribute(AnalysisRunner.PYDEV_ANALYSIS_TYPE);
int start = markerAnnotation.position.offset;
int end = start + markerAnnotation.position.length;
ps.setSelection(start, end);
String markerContents;
try {
markerContents = ps.getSelectedText();
} catch (Exception e1) {
// Selection may be wrong.
return;
}
IDocument doc = ps.getDoc();
List<String> parametersAfterCall = ps.getParametersAfterCall(end);
switch(id) {
case IAnalysisPreferences.TYPE_UNDEFINED_VARIABLE:
addCreateClassOption(ps, edit, props, markerContents, parametersAfterCall);
addCreateMethodOption(ps, edit, props, markerContents, parametersAfterCall);
break;
case IAnalysisPreferences.TYPE_UNDEFINED_IMPORT_VARIABLE:
// Say we had something as:
// import sys
// sys.Bar
// in which case 'Bar' is undefined
// in this situation, the activationTokenAndQual would be "sys." and "Bar"
// and we want to get the definition for "sys"
String[] activationTokenAndQual = ps.getActivationTokenAndQualifier(true);
if (activationTokenAndQual[0].endsWith(".")) {
ArrayList<IDefinition> selected = findDefinitions(nature, edit, start - 2, doc);
for (IDefinition iDefinition : selected) {
IModule module = iDefinition.getModule();
if (module.getFile() != null) {
Definition definition = (Definition) iDefinition;
File file = module.getFile();
if (definition.ast == null) {
// if we have no ast in the definition, it means the module itself was found (global scope)
// Add option to create class at the given module!
addCreateClassOption(ps, edit, props, markerContents, parametersAfterCall, file);
addCreateMethodOption(ps, edit, props, markerContents, parametersAfterCall, file);
} else if (definition.ast instanceof ClassDef) {
ClassDef classDef = (ClassDef) definition.ast;
// Ok, we should create a field or method in this case (accessing a classmethod or staticmethod)
PyCreateMethodOrField pyCreateMethod = new PyCreateMethodOrField();
String className = NodeUtils.getNameFromNameTok(classDef.name);
pyCreateMethod.setCreateInClass(className);
pyCreateMethod.setCreateAs(PyCreateMethodOrField.CLASSMETHOD);
addCreateClassmethodOption(ps, edit, props, markerContents, parametersAfterCall, pyCreateMethod, file, className);
}
}
}
}
break;
case IAnalysisPreferences.TYPE_UNRESOLVED_IMPORT:
// This case is the following: from other_module4 import Foo
// with 'Foo' being undefined.
// So, we have to suggest creating a Foo class/method in other_module4
PyImportsHandling importsHandling = new PyImportsHandling(ps.getDoc(), false);
int offsetLine = ps.getLineOfOffset(start);
String selectedText = ps.getSelectedText();
Tuple<IModule, String> found = null;
String foundFromImportStr = null;
boolean isImportFrom = false;
OUT: for (ImportHandle handle : importsHandling) {
if (handle.startFoundLine == offsetLine || handle.endFoundLine == offsetLine || (handle.startFoundLine < offsetLine && handle.endFoundLine > offsetLine)) {
List<ImportHandleInfo> importInfo = handle.getImportInfo();
for (ImportHandleInfo importHandleInfo : importInfo) {
String fromImportStr = importHandleInfo.getFromImportStr();
List<String> importedStr = importHandleInfo.getImportedStr();
for (String imported : importedStr) {
if (selectedText.equals(imported)) {
if (fromImportStr != null) {
foundFromImportStr = fromImportStr + "." + imported;
isImportFrom = true;
} else {
// if fromImportStr == null, it's not a from xxx import yyy (i.e.: simple import)
foundFromImportStr = imported;
}
try {
String currentModule = nature.resolveModule(edit.getEditorFile());
ICompletionState state = CompletionStateFactory.getEmptyCompletionState(nature, new CompletionCache());
found = nature.getAstManager().findModule(foundFromImportStr, currentModule, state, new SourceModule(currentModule, edit.getEditorFile(), edit.getAST(), null, nature));
} catch (Exception e) {
Log.log(e);
}
break OUT;
}
}
}
break OUT;
}
}
boolean addOptionToCreateClassOrMethod = isImportFrom;
if (found != null && found.o1 != null) {
// or just create a class or method at the end.
if (found.o1 instanceof SourceModule) {
// if all was found, there's nothing left to create.
if (found.o2 != null && found.o2.length() > 0) {
SourceModule sourceModule = (SourceModule) found.o1;
File file = sourceModule.getFile();
if (found.o2.indexOf('.') != -1) {
// We have to create some intermediary structure.
if (!addOptionToCreateClassOrMethod) {
// Cannot create class or method from the info (only the module structure).
if (sourceModule.getName().endsWith(".__init__")) {
File f = getFileStructure(file.getParentFile(), found.o2);
addCreateModuleOption(ps, edit, props, markerContents, f);
}
} else {
// Ok, the leaf may be a class or method.
if (sourceModule.getName().endsWith(".__init__")) {
String moduleName = FullRepIterable.getWithoutLastPart(sourceModule.getName());
String withoutLastPart = FullRepIterable.getWithoutLastPart(found.o2);
moduleName += "." + withoutLastPart;
String classOrMethodName = FullRepIterable.getLastPart(found.o2);
File f = getFileStructure(file.getParentFile(), withoutLastPart);
addCreateClassInNewModuleOption(ps, edit, props, classOrMethodName, moduleName, parametersAfterCall, f);
addCreateMethodInNewModuleOption(ps, edit, props, classOrMethodName, moduleName, parametersAfterCall, f);
}
}
} else {
// Ok, it's all there, we just have to create the leaf.
if (!addOptionToCreateClassOrMethod || sourceModule.getName().endsWith(".__init__")) {
// Cannot create class or method from the info (only the module structure).
if (sourceModule.getName().endsWith(".__init__")) {
File f = new File(file.getParent(), found.o2 + FileTypesPreferences.getDefaultDottedPythonExtension());
addCreateModuleOption(ps, edit, props, markerContents, f);
}
} else {
// Ok, the leaf may be a class or method.
addCreateClassOption(ps, edit, props, markerContents, parametersAfterCall, file);
addCreateMethodOption(ps, edit, props, markerContents, parametersAfterCall, file);
}
}
}
}
} else if (foundFromImportStr != null) {
// We couldn't find anything there, so, we have to create the modules structure as needed and
// maybe create a class or module at the end (but only if it's an import from).
// Ok, it's all there, we just have to create the leaf.
// Discover the source folder where we should create the structure.
File editorFile = edit.getEditorFile();
String onlyProjectPythonPathStr = nature.getPythonPathNature().getOnlyProjectPythonPathStr(false);
List<String> split = StringUtils.splitAndRemoveEmptyTrimmed(onlyProjectPythonPathStr, '|');
for (int i = 0; i < split.size(); i++) {
String fullPath = FileUtils.getFileAbsolutePath(split.get(i));
fullPath = PythonPathHelper.getDefaultPathStr(fullPath);
split.set(i, fullPath);
}
HashSet<String> projectSourcePath = new HashSet<String>(split);
if (projectSourcePath.size() == 0) {
// No source folder for editor... this shouldn't happen (code analysis wouldn't even run on it).
return;
}
String fullPath = FileUtils.getFileAbsolutePath(editorFile);
fullPath = PythonPathHelper.getDefaultPathStr(fullPath);
String foundSourceFolderFullPath = null;
if (projectSourcePath.size() == 1) {
foundSourceFolderFullPath = projectSourcePath.iterator().next();
} else {
for (String string : projectSourcePath) {
if (fullPath.startsWith(string)) {
// Use this as the source folder
foundSourceFolderFullPath = string;
break;
}
}
}
if (foundSourceFolderFullPath != null) {
if (!addOptionToCreateClassOrMethod) {
// Cannot create class or method from the info (only the module structure).
File f = getFileStructure(new File(foundSourceFolderFullPath), foundFromImportStr);
addCreateModuleOption(ps, edit, props, foundFromImportStr, f);
} else {
// Ok, the leaf may be a class or method.
String moduleName = FullRepIterable.getWithoutLastPart(foundFromImportStr);
File file = getFileStructure(new File(foundSourceFolderFullPath), moduleName);
String lastPart = FullRepIterable.getLastPart(foundFromImportStr);
addCreateClassInNewModuleOption(ps, edit, props, lastPart, moduleName, parametersAfterCall, file);
addCreateMethodInNewModuleOption(ps, edit, props, lastPart, moduleName, parametersAfterCall, file);
}
}
}
break;
}
}
use of org.python.pydev.core.docutils.ImportHandle in project Pydev by fabioz.
the class ImportArranger method deleteImports.
private List<Tuple<Integer, String>> deleteImports(List<Tuple3<Integer, String, ImportHandle>> list) {
// sort in inverse order (for removal of the string of the document).
List<Tuple<Integer, String>> linesToDelete = new ArrayList<>();
Collections.sort(list, new Comparator<Tuple3<Integer, String, ImportHandle>>() {
@Override
public int compare(Tuple3<Integer, String, ImportHandle> o1, Tuple3<Integer, String, ImportHandle> o2) {
return o2.o1.compareTo(o1.o1);
}
});
// ok, now we have to delete all lines with imports.
for (Iterator<Tuple3<Integer, String, ImportHandle>> iter = list.iterator(); iter.hasNext(); ) {
Tuple3<Integer, String, ImportHandle> element = iter.next();
String s = element.o2;
int max = StringUtils.countLineBreaks(s);
for (int i = 0; i <= max; i++) {
int lineToDel = (element.o1).intValue();
int j = lineToDel + i;
linesToDelete.add(new Tuple(j, PySelection.getLine(doc, j)));
}
}
Comparator<? super Tuple<Integer, String>> c = new Comparator<Tuple<Integer, String>>() {
@Override
public int compare(Tuple<Integer, String> o1, Tuple<Integer, String> o2) {
// reversed compare (o2 first o1 last).
return Integer.compare(o2.o1, o1.o1);
}
};
Collections.sort(linesToDelete, c);
return linesToDelete;
}
use of org.python.pydev.core.docutils.ImportHandle in project Pydev by fabioz.
the class ImportArranger method pruneEmptyImports.
private void pruneEmptyImports(List<Tuple3<Integer, String, ImportHandle>> list) {
Iterator<Tuple3<Integer, String, ImportHandle>> it = list.iterator();
while (it.hasNext()) {
ImportHandle ih = it.next().o3;
List<ImportHandleInfo> info = ih.getImportInfo();
Iterator<ImportHandleInfo> itInfo = info.iterator();
while (itInfo.hasNext()) {
if (itInfo.next().getImportedStr().isEmpty()) {
itInfo.remove();
}
}
if (info.size() == 0) {
it.remove();
}
}
}
use of org.python.pydev.core.docutils.ImportHandle in project Pydev by fabioz.
the class AssistImportToLocal method getProps.
@Override
public List<ICompletionProposalHandle> getProps(PySelection ps, IImageCache imageCache, File f, IPythonNature nature, IPyEdit edit, int offset) throws BadLocationException, MisconfigurationException {
boolean addOnlyGlobalImports = true;
boolean allowBadInput = false;
Tuple<String, Integer> currToken = ps.getCurrToken();
List<ICompletionProposalHandle> ret = new ArrayList<ICompletionProposalHandle>();
if (currToken.o1 != null && currToken.o1.length() > 0) {
int startOfImportLine = ps.getStartOfImportLine();
if (startOfImportLine == -1) {
return ret;
}
int startOffset = ps.getLineOffset(startOfImportLine);
PyImportsIterator pyImportsIterator = new PyImportsIterator(ps.getDoc(), addOnlyGlobalImports, allowBadInput, startOffset);
OUT: while (pyImportsIterator.hasNext()) {
ImportHandle handle = pyImportsIterator.next();
List<ImportHandleInfo> importInfo = handle.getImportInfo();
for (ImportHandleInfo importHandleInfo : importInfo) {
List<String> importedStr = importHandleInfo.getImportedStr();
int startLine = importHandleInfo.getStartLine();
int endLine = importHandleInfo.getEndLine();
if (ps.getLineOfOffset() < startLine) {
continue;
}
if (ps.getLineOfOffset() > endLine) {
// Stop iterating.
break OUT;
}
for (String s : importedStr) {
if (s.equals(currToken.o1)) {
// Found!
IProgressMonitor monitor = new NullProgressMonitor();
final RefactoringRequest req = PyRefactorAction.createRefactoringRequest(monitor, (PyEdit) edit, ps);
req.setAdditionalInfo(RefactoringRequest.FIND_DEFINITION_IN_ADDITIONAL_INFO, false);
req.setAdditionalInfo(RefactoringRequest.FIND_REFERENCES_ONLY_IN_LOCAL_SCOPE, true);
req.fillActivationTokenAndQualifier();
ret.add(CompletionProposalFactory.get().createMoveImportsToLocalCompletionProposal(req, s, importHandleInfo, imageCache.get(UIConstants.ASSIST_MOVE_IMPORT), "Move import to local scope(s)"));
}
}
}
}
}
return ret;
}
use of org.python.pydev.core.docutils.ImportHandle in project Pydev by fabioz.
the class ImportArranger method fillImportStructures.
/**
* Fills the import structure passed, so that the imports from will be grouped by the 'from' part and the regular
* imports will be in a separate list.
*/
private void fillImportStructures(List<Tuple3<Integer, String, ImportHandle>> list, TreeMap<String, FromImportEntries> importsWithFrom, List<ImportHandleInfo> importsWithoutFrom) {
// fill the info
for (Tuple3<Integer, String, ImportHandle> element : list) {
List<ImportHandleInfo> importInfo = element.o3.getImportInfo();
for (ImportHandleInfo importHandleInfo : importInfo) {
String fromImportStr = importHandleInfo.getFromImportStrWithoutUnwantedChars();
if (fromImportStr == null) {
importsWithoutFrom.add(importHandleInfo);
} else {
FromImportEntries lst = importsWithFrom.get(fromImportStr);
if (lst == null) {
lst = new FromImportEntries();
importsWithFrom.put(fromImportStr, lst);
}
lst.add(importHandleInfo);
}
}
}
}
Aggregations