Merge remote-tracking branch 'origin/master'

This commit is contained in:
Ilya.Kazakevich
2014-10-07 18:05:42 +04:00
80 changed files with 11054 additions and 276 deletions
-1
View File
@@ -4,6 +4,5 @@
.idea/workspace.xml
/out
.DS_Store
/python/helpers/python-skeletons
/test-system
/test-config
+1 -1
View File
@@ -1,3 +1,3 @@
<component name="DependencyValidationManager">
<scope name="util-rt dependencies" pattern="(lib:*..*||src:*..*)&amp;&amp;!lib:java..*&amp;&amp;!lib:javax..*&amp;&amp;!src[util-rt]:*..*" />
<scope name="util-rt dependencies" pattern="(lib:*..*||src:*..*)&amp;&amp;!lib:java..*&amp;&amp;!lib:javax..*&amp;&amp;!src[util-rt]:*..*&amp;&amp;!src[annotations]:*..*" />
</component>
@@ -223,7 +223,7 @@ public class JavaSafeDeleteProcessor extends SafeDeleteProcessorDelegateBase {
if (element instanceof PsiMethod) {
final PsiClass containingClass = ((PsiMethod)element).getContainingClass();
if (!containingClass.hasModifierProperty(PsiModifier.ABSTRACT)) {
if (containingClass != null && !containingClass.hasModifierProperty(PsiModifier.ABSTRACT)) {
final PsiMethod[] superMethods = ((PsiMethod) element).findSuperMethods();
for (PsiMethod superMethod : superMethods) {
if (isInside(superMethod, allElementsToDelete)) continue;
@@ -639,13 +639,15 @@ public class JavaDocInfoGenerator {
String text = o.toString();
PsiType type = variable.getType();
if (type.equalsToText(CommonClassNames.JAVA_LANG_STRING)) {
text = "\"" + StringUtil.escapeLineBreak(StringUtil.shortenPathWithEllipsis(text, 120)) + "\"";
text = "\"" + StringUtil.escapeStringCharacters(StringUtil.shortenPathWithEllipsis(text, 120)) + "\"";
}
else if (type.equalsToText("char")) {
text = "'" + text + "'";
}
else if (type.equalsToText("char")) text = "'" + text + "'";
try {
return instance.getElementFactory().createExpressionFromText(text, variable);
} catch (IncorrectOperationException ex) {
LOG.error(text, ex);
LOG.info("type:" + type.getCanonicalText() + "; text: " + text, ex);
}
}
}
@@ -0,0 +1,4 @@
class Foo {{
<caret>blah
// <caret>blah
}}
@@ -0,0 +1,4 @@
class Foo {{
return<caret>
// return<caret>
}}
@@ -1428,6 +1428,10 @@ class XInternalError {}
myFixture.assertPreferredCompletionItems(0, "arraycopy")
}
public void testMulticaretCompletionFromNonPrimaryCaretWithTab() {
doTest '\t'
}
public void "test complete lowercase class name"() {
myFixture.addClass("package foo; public class myClass {}")
myFixture.configureByText "a.java", """
@@ -55,6 +55,7 @@ public class SingleInspectionProfilePanelTest extends LightIdeaTestCase {
assertEquals(1, InspectionProfileTest.countInitializedTools(model));
assertEquals("foo", getInspection(profile).myAdditionalJavadocTags);
panel.disposeUI();
}
public void testModifyInstantiatedTool() throws Exception {
@@ -82,6 +83,7 @@ public class SingleInspectionProfilePanelTest extends LightIdeaTestCase {
assertEquals(1, InspectionProfileTest.countInitializedTools(model));
assertEquals("bar", getInspection(profile).myAdditionalJavadocTags);
panel.disposeUI();
}
public void testDoNotChangeSettingsOnCancel() throws Exception {
@@ -15,6 +15,7 @@
*/
package com.intellij.openapi.application;
import com.intellij.openapi.components.ServiceManager;
import com.intellij.openapi.util.BuildNumber;
import java.awt.*;
@@ -52,7 +53,7 @@ public abstract class ApplicationInfo {
}
public static ApplicationInfo getInstance() {
return ApplicationManager.getApplication().getComponent(ApplicationInfo.class);
return ServiceManager.getService(ApplicationInfo.class);
}
public static boolean helpAvailable() {
@@ -19,7 +19,7 @@ import com.intellij.ide.plugins.PluginManagerCore;
import com.intellij.openapi.application.ApplicationNamesInfo;
import com.intellij.openapi.application.PathManager;
import com.intellij.openapi.application.ex.ApplicationInfoEx;
import com.intellij.openapi.components.ApplicationComponent;
import com.intellij.openapi.components.NamedComponent;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.util.*;
import com.intellij.openapi.util.text.StringUtil;
@@ -40,7 +40,7 @@ import java.util.List;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;
public class ApplicationInfoImpl extends ApplicationInfoEx implements JDOMExternalizable, ApplicationComponent {
public class ApplicationInfoImpl extends ApplicationInfoEx implements JDOMExternalizable, NamedComponent {
private static final Logger LOG = Logger.getInstance("#com.intellij.openapi.application.impl.ApplicationInfoImpl");
private String myCodeName = null;
@@ -175,14 +175,12 @@ public class ApplicationInfoImpl extends ApplicationInfoEx implements JDOMExtern
@NonNls private static final String CUSTOMIZE_IDE_WIZARD_STEPS = "customize-ide-wizard";
@NonNls private static final String STEPS_PROVIDER = "provider";
public void initComponent() { }
public void disposeComponent() { }
@Override
public Calendar getBuildDate() {
return myBuildDate;
}
@Override
public Calendar getMajorReleaseBuildDate() {
return myMajorReleaseBuildDate != null ? myMajorReleaseBuildDate : myBuildDate;
}
@@ -211,14 +209,17 @@ public class ApplicationInfoImpl extends ApplicationInfoEx implements JDOMExtern
return getBuild().asString();
}
@Override
public String getMajorVersion() {
return myMajorVersion;
}
@Override
public String getMinorVersion() {
return myMinorVersion;
}
@Override
public String getVersionName() {
final String fullName = ApplicationNamesInfo.getInstance().getFullProductName();
if (myEAP && !StringUtil.isEmptyOrSpaces(myCodeName)) {
@@ -227,6 +228,7 @@ public class ApplicationInfoImpl extends ApplicationInfoEx implements JDOMExtern
return fullName;
}
@Override
@NonNls
public String getHelpURL() {
return "jar:file:///" + getHelpJarPath() + "!/" + myHelpRootName;
@@ -247,14 +249,17 @@ public class ApplicationInfoImpl extends ApplicationInfoEx implements JDOMExtern
return PathManager.getHomePath() + File.separator + "help" + File.separator + myHelpFileName;
}
@Override
public String getSplashImageUrl() {
return mySplashImageUrl;
}
@Override
public Color getSplashTextColor() {
return mySplashTextColor;
}
@Override
public String getAboutImageUrl() {
return myAboutImageUrl;
}
@@ -279,10 +284,12 @@ public class ApplicationInfoImpl extends ApplicationInfoEx implements JDOMExtern
return myProgressTailIcon;
}
@Override
public String getIconUrl() {
return myIconUrl;
}
@Override
public String getSmallIconUrl() {
return mySmallIconUrl;
}
@@ -293,18 +300,22 @@ public class ApplicationInfoImpl extends ApplicationInfoEx implements JDOMExtern
return myBigIconUrl;
}
@Override
public String getOpaqueIconUrl() {
return myOpaqueIconUrl;
}
@Override
public String getToolWindowIconUrl() {
return myToolWindowIconUrl;
}
@Override
public String getWelcomeScreenCaptionUrl() {
return myWelcomeScreenCaptionUrl;
}
@Override
public String getWelcomeScreenDeveloperSloganUrl() {
return myWelcomeScreenDeveloperSloganUrl;
}
@@ -325,30 +336,37 @@ public class ApplicationInfoImpl extends ApplicationInfoEx implements JDOMExtern
return myEditorBackgroundImageUrl;
}
@Override
public String getPackageCode() {
return myPackageCode;
}
@Override
public boolean isEAP() {
return myEAP;
}
@Override
public UpdateUrls getUpdateUrls() {
return myUpdateUrls;
}
@Override
public String getDocumentationUrl() {
return myDocumentationUrl;
}
@Override
public String getSupportUrl() {
return mySupportUrl;
}
@Override
public String getEAPFeedbackUrl() {
return myEAPFeedbackUrl;
}
@Override
public String getReleaseFeedbackUrl() {
return myReleaseFeedbackUrl;
}
@@ -358,18 +376,22 @@ public class ApplicationInfoImpl extends ApplicationInfoEx implements JDOMExtern
return myPluginManagerUrl;
}
@Override
public String getPluginsListUrl() {
return myPluginsListUrl;
}
@Override
public String getPluginsDownloadUrl() {
return myPluginsDownloadUrl;
}
@Override
public String getBuiltinPluginsUrl() {
return myBuiltinPluginsUrl;
}
@Override
public String getWebHelpUrl() {
return myWebHelpUrl;
}
@@ -384,14 +406,17 @@ public class ApplicationInfoImpl extends ApplicationInfoEx implements JDOMExtern
return myHasContextHelp;
}
@Override
public String getWhatsNewUrl() {
return myWhatsNewUrl;
}
@Override
public String getWinKeymapUrl() {
return myWinKeymapUrl;
}
@Override
public String getMacKeymapUrl() {
return myMacKeymapUrl;
}
@@ -405,6 +430,7 @@ public class ApplicationInfoImpl extends ApplicationInfoEx implements JDOMExtern
return myAboutLinkColor;
}
@Override
public String getFullApplicationName() {
@NonNls StringBuilder buffer = new StringBuilder();
buffer.append(getVersionName());
@@ -423,6 +449,7 @@ public class ApplicationInfoImpl extends ApplicationInfoEx implements JDOMExtern
return buffer.toString();
}
@Override
public boolean showLicenseeInfo() {
return myShowLicensee;
}
@@ -478,6 +505,7 @@ public class ApplicationInfoImpl extends ApplicationInfoEx implements JDOMExtern
return ourShadowInstance;
}
@Override
public void readExternal(Element parentNode) throws InvalidDataException {
Element versionElement = parentNode.getChild(ELEMENT_VERSION);
if (versionElement != null) {
@@ -737,14 +765,17 @@ public class ApplicationInfoImpl extends ApplicationInfoEx implements JDOMExtern
return new Color((int)rgb, rgb > 0xffffff);
}
@Override
public void writeExternal(Element element) throws WriteExternalException {
throw new WriteExternalException();
}
@Override
public List<PluginChooserPage> getPluginChooserPages() {
return myPluginChooserPages;
}
@Override
@NotNull
public String getComponentName() {
return ApplicationNamesInfo.getComponentName();
@@ -761,10 +792,12 @@ public class ApplicationInfoImpl extends ApplicationInfoEx implements JDOMExtern
}
}
@Override
public String getCheckingUrl() {
return myCheckingUrl;
}
@Override
public String getPatchesUrl() {
return myPatchesUrl;
}
@@ -781,14 +814,17 @@ public class ApplicationInfoImpl extends ApplicationInfoEx implements JDOMExtern
myDependentPlugin = e.getAttributeValue("depends");
}
@Override
public String getTitle() {
return myTitle;
}
@Override
public String getCategory() {
return myCategory;
}
@Override
public String getDependentPlugin() {
return myDependentPlugin;
}
@@ -15,34 +15,25 @@
*/
package com.intellij.openapi.editor.colors.ex;
import com.intellij.openapi.components.NamedComponent;
import com.intellij.openapi.components.ServiceManager;
import com.intellij.openapi.components.*;
import com.intellij.openapi.editor.colors.EditorColorsScheme;
import com.intellij.openapi.editor.colors.impl.DefaultColorsScheme;
import com.intellij.openapi.util.InvalidDataException;
import com.intellij.openapi.util.JDOMExternalizable;
import com.intellij.openapi.util.WriteExternalException;
import org.jdom.Element;
import org.jetbrains.annotations.NonNls;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.ArrayList;
import java.util.List;
/**
* @author max
*/
public class DefaultColorSchemesManager implements JDOMExternalizable, NamedComponent {
@State(
name = "DefaultColorSchemesManager",
storages = @Storage(file = StoragePathMacros.APP_CONFIG + "/other.xml")
)
public class DefaultColorSchemesManager implements PersistentStateComponent<Element> {
private final List<DefaultColorsScheme> mySchemes;
@NonNls private static final String SCHEME_ELEMENT = "scheme";
@Override
@NotNull
public String getComponentName() {
return "DefaultColorSchemesManager";
}
public DefaultColorSchemesManager() {
mySchemes = new ArrayList<DefaultColorsScheme>();
}
@@ -51,20 +42,24 @@ public class DefaultColorSchemesManager implements JDOMExternalizable, NamedComp
return ServiceManager.getService(DefaultColorSchemesManager.class);
}
@Nullable
@Override
public void readExternal(Element element) throws InvalidDataException {
List schemes = element.getChildren(SCHEME_ELEMENT);
for (Object scheme : schemes) {
Element schemeElement = (Element)scheme;
DefaultColorsScheme newScheme = new DefaultColorsScheme(this);
newScheme.readExternal(schemeElement);
mySchemes.add(newScheme);
}
public Element getState() {
return null;
}
@Override
public void writeExternal(Element element) throws WriteExternalException {
throw new WriteExternalException();
public void loadState(Element state) {
for (Element schemeElement : state.getChildren(SCHEME_ELEMENT)) {
DefaultColorsScheme newScheme = new DefaultColorsScheme(this);
try {
newScheme.readExternal(schemeElement);
}
catch (InvalidDataException e) {
throw new RuntimeException(e);
}
mySchemes.add(newScheme);
}
}
public DefaultColorsScheme[] getAllSchemes() {
@@ -30,6 +30,7 @@ import com.intellij.execution.process.ProcessHandler;
import com.intellij.execution.process.ProcessTerminatedListener;
import com.intellij.execution.rmi.RemoteProcessSupport;
import com.intellij.execution.runners.ProgramRunner;
import com.intellij.openapi.Disposable;
import com.intellij.openapi.actionSystem.AnAction;
import com.intellij.openapi.application.PathManager;
import com.intellij.openapi.components.impl.stores.StorageUtil;
@@ -72,7 +73,7 @@ import java.util.concurrent.atomic.AtomicReference;
* @author Denis Zhdanov
* @since 8/9/13 3:37 PM
*/
public class RemoteExternalSystemCommunicationManager implements ExternalSystemCommunicationManager {
public class RemoteExternalSystemCommunicationManager implements ExternalSystemCommunicationManager, Disposable {
private static final Logger LOG = Logger.getInstance("#" + RemoteExternalSystemCommunicationManager.class.getName());
@@ -265,4 +266,9 @@ public class RemoteExternalSystemCommunicationManager implements ExternalSystemC
public void clear() {
mySupport.stopAll(true);
}
@Override
public void dispose() {
shutdown(false);
}
}
@@ -86,6 +86,8 @@ public class ProjectDataManager {
@SuppressWarnings("unchecked")
public <T> void importData(@NotNull Collection<DataNode<?>> nodes, @NotNull Project project, boolean synchronous) {
if(project.isDisposed()) return;
Map<Key<?>, List<DataNode<?>>> grouped = ExternalSystemApiUtil.group(nodes);
for (Map.Entry<Key<?>, List<DataNode<?>>> entry : grouped.entrySet()) {
// Simple class cast makes ide happy but compiler fails.
@@ -99,6 +101,8 @@ public class ProjectDataManager {
@SuppressWarnings("unchecked")
public <T> void importData(@NotNull Key<T> key, @NotNull Collection<DataNode<T>> nodes, @NotNull Project project, boolean synchronous) {
if(project.isDisposed()) return;
ensureTheDataIsReadyToUse(nodes);
List<ProjectDataService<?, ?>> services = myServices.getValue().get(key);
if (services == null) {
@@ -148,11 +152,13 @@ public class ProjectDataManager {
}
public void updateExternalProjectData(@NotNull Project project, @NotNull ExternalProjectInfo externalProjectInfo) {
ExternalProjectsDataStorage.getInstance(project).add(externalProjectInfo);
if(!project.isDisposed()) {
ExternalProjectsDataStorage.getInstance(project).add(externalProjectInfo);
}
}
@Nullable
public ExternalProjectInfo getExternalProjectData(@NotNull Project project, @NotNull ProjectSystemId projectSystemId, @NotNull String externalProjectPath) {
return ExternalProjectsDataStorage.getInstance(project).get(projectSystemId, externalProjectPath);
return !project.isDisposed() ? ExternalProjectsDataStorage.getInstance(project).get(projectSystemId, externalProjectPath) : null;
}
}
Binary file not shown.

After

Width:  |  Height:  |  Size: 319 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 622 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 620 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 326 B

@@ -39,14 +39,17 @@ public class CompletionInitializationContext {
public static @NonNls final String DUMMY_IDENTIFIER = CompletionUtilCore.DUMMY_IDENTIFIER;
public static @NonNls final String DUMMY_IDENTIFIER_TRIMMED = CompletionUtilCore.DUMMY_IDENTIFIER_TRIMMED;
private final Editor myEditor;
@NotNull
private final Caret myCaret;
private final PsiFile myFile;
private final CompletionType myCompletionType;
private final int myInvocationCount;
private final OffsetMap myOffsetMap;
private String myDummyIdentifier = DUMMY_IDENTIFIER;
public CompletionInitializationContext(final Editor editor, final Caret caret, final PsiFile file, final CompletionType completionType, int invocationCount) {
public CompletionInitializationContext(final Editor editor, final @NotNull Caret caret, final PsiFile file, final CompletionType completionType, int invocationCount) {
myEditor = editor;
myCaret = caret;
myFile = file;
myCompletionType = completionType;
myInvocationCount = invocationCount;
@@ -92,6 +95,11 @@ public class CompletionInitializationContext {
return myEditor;
}
@NotNull
public Caret getCaret() {
return myCaret;
}
@NotNull
public CompletionType getCompletionType() {
return myCompletionType;
@@ -193,7 +193,7 @@ public class CodeCompletionHandlerBase {
insertDummyIdentifier(initializationContext[0], hasModifiers, invocationCount);
}
private CompletionInitializationContext runContributorsBeforeCompletion(Editor editor, PsiFile psiFile, int invocationCount, Caret caret) {
private CompletionInitializationContext runContributorsBeforeCompletion(Editor editor, PsiFile psiFile, int invocationCount, @NotNull Caret caret) {
final Ref<CompletionContributor> current = Ref.create(null);
CompletionInitializationContext context = new CompletionInitializationContext(editor, caret, psiFile, myCompletionType, invocationCount) {
CompletionContributor dummyIdentifierChanger;
@@ -296,7 +296,8 @@ public class CodeCompletionHandlerBase {
final Semaphore freezeSemaphore = new Semaphore();
freezeSemaphore.down();
final CompletionProgressIndicator indicator = new CompletionProgressIndicator(editor, parameters, this, freezeSemaphore,
final CompletionProgressIndicator indicator = new CompletionProgressIndicator(editor, initContext.getCaret(),
parameters, this, freezeSemaphore,
initContext.getOffsetMap(), hasModifiers, lookup);
Disposer.register(indicator, hostMap);
Disposer.register(indicator, context.getOffsetMap());
@@ -602,7 +603,7 @@ public class CodeCompletionHandlerBase {
final CompletionLookupArranger.StatisticsUpdate update) {
final Editor editor = indicator.getEditor();
final int caretOffset = editor.getCaretModel().getOffset();
final int caretOffset = indicator.getCaret().getOffset();
int idEndOffset = indicator.getIdentifierEndOffset();
if (idEndOffset < 0) {
idEndOffset = CompletionInitializationContext.calcDefaultIdentifierEnd(editor, caretOffset);
@@ -39,6 +39,7 @@ import com.intellij.openapi.application.WriteAction;
import com.intellij.openapi.command.CommandProcessor;
import com.intellij.openapi.command.WriteCommandAction;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.editor.Caret;
import com.intellij.openapi.editor.Editor;
import com.intellij.openapi.progress.ProcessCanceledException;
import com.intellij.openapi.progress.ProgressManager;
@@ -88,6 +89,8 @@ import java.util.concurrent.ConcurrentLinkedQueue;
public class CompletionProgressIndicator extends ProgressIndicatorBase implements CompletionProcess, Disposable {
private static final Logger LOG = Logger.getInstance("#com.intellij.codeInsight.completion.CompletionProgressIndicator");
private final Editor myEditor;
@NotNull
private final Caret myCaret;
private final CompletionParameters myParameters;
private final CodeCompletionHandlerBase myHandler;
private final LookupImpl myLookup;
@@ -132,6 +135,7 @@ public class CompletionProgressIndicator extends ProgressIndicatorBase implement
private final int myStartCaret;
public CompletionProgressIndicator(final Editor editor,
@NotNull Caret caret,
CompletionParameters parameters,
CodeCompletionHandlerBase handler,
Semaphore freezeSemaphore,
@@ -139,6 +143,7 @@ public class CompletionProgressIndicator extends ProgressIndicatorBase implement
boolean hasModifiers,
LookupImpl lookup) {
myEditor = editor;
myCaret = caret;
myParameters = parameters;
myHandler = handler;
myFreezeSemaphore = freezeSemaphore;
@@ -575,6 +580,11 @@ public class CompletionProgressIndicator extends ProgressIndicatorBase implement
return myEditor;
}
@NotNull
public Caret getCaret() {
return myCaret;
}
public boolean isRepeatedInvocation(CompletionType completionType, Editor editor) {
if (completionType != myParameters.getCompletionType() || editor != myEditor) {
return false;
@@ -56,8 +56,10 @@ import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.*;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
/**
* @author Vladimir Kondratyev
@@ -131,7 +133,7 @@ public class IdeEventQueue extends EventQueue {
private final Set<EventDispatcher> myDispatchers = new LinkedHashSet<EventDispatcher>();
private final Set<EventDispatcher> myPostProcessors = new LinkedHashSet<EventDispatcher>();
private final Set<Runnable> myReady = new HashSet<Runnable>();
private final Set<Runnable> myReady = ContainerUtil.newHashSet();
private boolean myKeyboardBusy;
private boolean myDispatchingFocusEvent;
@@ -329,7 +331,7 @@ public class IdeEventQueue extends EventQueue {
}
private static class InertialMouseRouter {
private static int MOUSE_WHEEL_RESTART_THRESHOLD = 50;
private static final int MOUSE_WHEEL_RESTART_THRESHOLD = 50;
private static Component wheelDestinationComponent = null;
private static long lastMouseWheel = 0;
@@ -556,7 +558,7 @@ public class IdeEventQueue extends EventQueue {
}
else if (e instanceof MouseEvent) {
MouseEvent me = (MouseEvent)e;
if (myMouseEventDispatcher.patchClickCount(me) && me.getID() == MouseEvent.MOUSE_CLICKED) {
if (IdeMouseEventDispatcher.patchClickCount(me) && me.getID() == MouseEvent.MOUSE_CLICKED) {
final MouseEvent toDispatch =
new MouseEvent(me.getComponent(), me.getID(), System.currentTimeMillis(), me.getModifiers(), me.getX(), me.getY(), 1,
me.isPopupTrigger(), me.getButton());
@@ -590,9 +592,8 @@ public class IdeEventQueue extends EventQueue {
}
public boolean wasRootRecentlyClicked(Component component) {
if (component == null || lastClickEvent == null || lastClickEvent.getComponent() == null)
return false;
return SwingUtilities.getRoot(lastClickEvent.getComponent()) == SwingUtilities.getRoot(component);
return component != null && lastClickEvent != null && lastClickEvent.getComponent() != null &&
SwingUtilities.getRoot(lastClickEvent.getComponent()) == SwingUtilities.getRoot(component);
}
private static void fixStickyWindow(KeyboardFocusManager mgr, Window wnd, String resetMethod) {
@@ -71,8 +71,8 @@ public class DefaultProjectStoreImpl extends ProjectStoreImpl {
}
@Override
protected MySaveSession createSaveSession(@NotNull StorageData storageData) {
return new MySaveSession(storageData) {
protected XmlElementStorageSaveSession createSaveSession(@NotNull StorageData storageData) {
return new XmlElementStorageSaveSession(storageData) {
@Override
protected void doSave(@Nullable Element element) {
// we must set empty element instead of null as indicator - ProjectManager state is ready to save
@@ -21,7 +21,6 @@ import com.intellij.notification.Notifications;
import com.intellij.openapi.Disposable;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.components.*;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.util.JDOMUtil;
import com.intellij.openapi.util.io.BufferExposingByteArrayOutputStream;
import com.intellij.openapi.util.io.FileUtil;
@@ -43,8 +42,6 @@ import java.util.Collections;
import java.util.Set;
public class FileBasedStorage extends XmlElementStorage {
private static final Logger LOG = Logger.getInstance(FileBasedStorage.class);
private final String myFilePath;
private final File myFile;
private volatile VirtualFile myCachedVirtualFile;
@@ -104,11 +101,11 @@ public class FileBasedStorage extends XmlElementStorage {
}
@Override
protected MySaveSession createSaveSession(@NotNull StorageData storageData) {
protected XmlElementStorageSaveSession createSaveSession(@NotNull StorageData storageData) {
return new FileSaveSession(storageData);
}
private class FileSaveSession extends MySaveSession {
private class FileSaveSession extends XmlElementStorageSaveSession {
protected FileSaveSession(@NotNull StorageData storageData) {
super(storageData);
}
@@ -134,6 +131,10 @@ public class FileBasedStorage extends XmlElementStorage {
LOG.error(e);
}
if (LOG.isDebugEnabled() && myFileSpec.equals(StoragePathMacros.MODULE_FILE)) {
LOG.debug("doSave " + getFilePath());
}
if (content == null) {
StorageUtil.deleteFile(myFile, this, getVirtualFile());
myCachedVirtualFile = null;
@@ -306,4 +307,9 @@ public class FileBasedStorage extends XmlElementStorage {
FileUtil.writeToFile(file, out.getInternalBuffer(), 0, out.size());
return file;
}
@Override
public String toString() {
return getFilePath();
}
}
@@ -15,7 +15,6 @@
*/
package com.intellij.openapi.components.impl.stores;
import com.intellij.codeInspection.SmartHashMap;
import com.intellij.openapi.Disposable;
import com.intellij.openapi.application.Application;
import com.intellij.openapi.application.ApplicationManager;
@@ -414,9 +413,13 @@ public abstract class StateStorageManagerImpl implements StateStorageManager, Di
@Override
public SaveSession startSave(@NotNull ExternalizationSession externalizationSession) {
StateStorageManagerExternalizationSession myExternalizationSession = (StateStorageManagerExternalizationSession)externalizationSession;
if (myExternalizationSession.mySessions.isEmpty()) {
return null;
}
List<SaveSession> saveSessions = null;
for (StateStorage stateStorage : myExternalizationSession.mySessions.keySet()) {
SaveSession saveSession = stateStorage.startSave(myExternalizationSession.mySessions.get(stateStorage));
for (Map.Entry<StateStorage, StateStorage.ExternalizationSession> entry : myExternalizationSession.mySessions.entrySet()) {
SaveSession saveSession = entry.getKey().startSave(entry.getValue());
if (saveSession != null) {
if (saveSessions == null) {
saveSessions = new SmartList<SaveSession>();
@@ -448,7 +451,7 @@ public abstract class StateStorageManagerImpl implements StateStorageManager, Di
}
private final class StateStorageManagerExternalizationSession implements ExternalizationSession {
final Map<StateStorage, StateStorage.ExternalizationSession> mySessions = new SmartHashMap<StateStorage, StateStorage.ExternalizationSession>();
final Map<StateStorage, StateStorage.ExternalizationSession> mySessions = new LinkedHashMap<StateStorage, StateStorage.ExternalizationSession>();
@Override
public void setState(@NotNull Storage[] storageSpecs, @NotNull Object component, @NotNull String componentName, @NotNull Object state) {
@@ -19,12 +19,10 @@ import com.intellij.openapi.Disposable;
import com.intellij.openapi.components.*;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.options.CurrentUserHolder;
import com.intellij.openapi.util.Disposer;
import com.intellij.openapi.util.JDOMUtil;
import com.intellij.openapi.util.Pair;
import com.intellij.openapi.util.WriteExternalException;
import com.intellij.openapi.util.*;
import com.intellij.openapi.util.io.BufferExposingByteArrayOutputStream;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.util.containers.ContainerUtil;
import gnu.trove.THashMap;
import gnu.trove.TObjectLongHashMap;
import org.jdom.Document;
@@ -40,7 +38,7 @@ import java.io.InputStream;
import java.util.*;
public abstract class XmlElementStorage implements StateStorage, Disposable {
private static final Logger LOG = Logger.getInstance(XmlElementStorage.class);
protected static final Logger LOG = Logger.getInstance(XmlElementStorage.class);
private final static RoamingElementFilter DISABLED_ROAMING_ELEMENT_FILTER = new RoamingElementFilter(RoamingType.DISABLED);
@@ -174,6 +172,9 @@ public abstract class XmlElementStorage implements StateStorage, Disposable {
@Override
@Nullable
public final ExternalizationSession startExternalization() {
if (LOG.isDebugEnabled() && myFileSpec.equals(StoragePathMacros.MODULE_FILE)) {
LOG.debug("startExternalization: mySavingDisabled " + mySavingDisabled + " for " + toString());
}
return mySavingDisabled ? null : createSaveSession(getStorageData());
}
@@ -181,21 +182,33 @@ public abstract class XmlElementStorage implements StateStorage, Disposable {
@Override
public SaveSession startSave(@NotNull ExternalizationSession externalizationSession) {
if (mySavingDisabled) {
if (LOG.isDebugEnabled() && myFileSpec.equals(StoragePathMacros.MODULE_FILE)) {
LOG.debug("startSave: saving disabled for " + toString());
}
return null;
}
else {
MySaveSession session = (MySaveSession)externalizationSession;
XmlElementStorageSaveSession session = (XmlElementStorageSaveSession)externalizationSession;
if (LOG.isDebugEnabled() && myFileSpec.equals(StoragePathMacros.MODULE_FILE)) {
LOG.debug("startSave: session " + session.myCopiedStorageData + " for " + toString());
}
return session.myCopiedStorageData == null ? null : session;
}
}
protected abstract MySaveSession createSaveSession(@NotNull StorageData storageData);
protected abstract XmlElementStorageSaveSession createSaveSession(@NotNull StorageData storageData);
public void disableSaving() {
if (LOG.isDebugEnabled()) {
LOG.debug("Saving disabled for " + toString());
}
mySavingDisabled = true;
}
public void enableSaving() {
if (LOG.isDebugEnabled()) {
LOG.debug("Saving enabled for " + toString());
}
mySavingDisabled = false;
}
@@ -223,23 +236,29 @@ public abstract class XmlElementStorage implements StateStorage, Disposable {
StorageData oldData = myLoadedData;
StorageData newData = getStorageData(true);
if (oldData == null) {
if (LOG.isDebugEnabled()) {
LOG.debug("analyzeExternalChangesAndUpdateIfNeed: old data null, load new for " + toString());
}
result.addAll(newData.getComponentNames());
}
else {
Set<String> changedComponentNames = oldData.getChangedComponentNames(newData, myPathMacroSubstitutor);
if (changedComponentNames != null) {
if (LOG.isDebugEnabled()) {
LOG.debug("analyzeExternalChangesAndUpdateIfNeed: changedComponentNames + " + changedComponentNames + " for " + toString());
}
if (!ContainerUtil.isEmpty(changedComponentNames)) {
result.addAll(changedComponentNames);
}
}
}
protected abstract class MySaveSession implements SaveSession, ExternalizationSession {
protected abstract class XmlElementStorageSaveSession implements SaveSession, ExternalizationSession {
private final StorageData myOriginalStorageData;
private StorageData myCopiedStorageData;
private final Map<String, Element> myNewLiveStates = new THashMap<String, Element>();
public MySaveSession(@NotNull StorageData storageData) {
public XmlElementStorageSaveSession(@NotNull StorageData storageData) {
myOriginalStorageData = storageData;
}
@@ -247,6 +266,10 @@ public abstract class XmlElementStorage implements StateStorage, Disposable {
public final void setState(@NotNull Object component, @NotNull String componentName, @NotNull Object state, @Nullable Storage storageSpec) {
Element element;
try {
//noinspection deprecation
if (LOG.isDebugEnabled() && state instanceof JDOMExternalizable && componentName.endsWith("ApplicationInfo")) {
return;
}
element = DefaultStateSerializer.serializeState(state, storageSpec);
}
catch (WriteExternalException e) {
@@ -277,6 +300,7 @@ public abstract class XmlElementStorage implements StateStorage, Disposable {
try {
doSave(getElement(myCopiedStorageData, isCollapsePathsOnSave(), myNewLiveStates));
myLoadedData = myCopiedStorageData;
}
catch (IOException e) {
throw new StateStorageException(e);
@@ -116,7 +116,6 @@ public final class WindowManagerImpl extends WindowManagerEx implements NamedCom
private Rectangle myFrameBounds;
private int myFrameExtendedState;
private final WindowAdapter myActivationListener;
private final ApplicationInfoEx myApplicationInfoEx;
private final DataManager myDataManager;
private final ActionManagerEx myActionManager;
private final UISettings myUiSettings;
@@ -125,11 +124,9 @@ public final class WindowManagerImpl extends WindowManagerEx implements NamedCom
* invoked by reflection
*/
public WindowManagerImpl(DataManager dataManager,
ApplicationInfoEx applicationInfoEx,
ActionManagerEx actionManager,
UISettings uiSettings,
MessageBus bus) {
myApplicationInfoEx = applicationInfoEx;
myDataManager = dataManager;
myActionManager = actionManager;
myUiSettings = uiSettings;
@@ -524,7 +521,7 @@ public final class WindowManagerImpl extends WindowManagerEx implements NamedCom
}
public void showFrame() {
final IdeFrameImpl frame = new IdeFrameImpl(myApplicationInfoEx,
final IdeFrameImpl frame = new IdeFrameImpl(ApplicationInfoEx.getInstanceEx(),
myActionManager, myUiSettings, myDataManager,
ApplicationManager.getApplication());
myProject2Frame.put(null, frame);
@@ -595,7 +592,7 @@ public final class WindowManagerImpl extends WindowManagerEx implements NamedCom
frame.setProject(project);
}
else {
frame = new IdeFrameImpl(myApplicationInfoEx, myActionManager, myUiSettings,
frame = new IdeFrameImpl(ApplicationInfoEx.getInstanceEx(), myActionManager, myUiSettings,
myDataManager, ApplicationManager.getApplication());
final Rectangle bounds = ProjectFrameBounds.getInstance(project).getBounds();
@@ -55,10 +55,10 @@
<applicationService serviceInterface="com.intellij.ide.ui.search.SearchableOptionsRegistrar"
serviceImplementation="com.intellij.ide.ui.search.SearchableOptionsRegistrarImpl"/>
<applicationService serviceInterface="com.intellij.openapi.fileEditor.impl.EditorEmptyTextPainter"
serviceImplementation="com.intellij.openapi.fileEditor.impl.EditorEmptyTextPainter" />
serviceImplementation="com.intellij.openapi.fileEditor.impl.EditorEmptyTextPainter"/>
<applicationService serviceInterface="com.intellij.openapi.editor.EditorCopyPasteHelper"
serviceImplementation="com.intellij.openapi.editor.impl.EditorCopyPasteHelperImpl" />
serviceImplementation="com.intellij.openapi.editor.impl.EditorCopyPasteHelperImpl"/>
<applicationService serviceImplementation="com.intellij.openapi.options.ex.IdeConfigurablesGroup"/>
@@ -139,8 +139,7 @@
<applicationService serviceInterface="com.intellij.openapi.options.SchemesManagerFactory"
serviceImplementation="com.intellij.openapi.options.SchemesManagerFactoryImpl"/>
<applicationService serviceInterface="com.intellij.openapi.editor.colors.ex.DefaultColorSchemesManager"
serviceImplementation="com.intellij.openapi.editor.colors.ex.DefaultColorSchemesManager"/>
<applicationService serviceImplementation="com.intellij.openapi.editor.colors.ex.DefaultColorSchemesManager"/>
<applicationService serviceInterface="com.intellij.openapi.editor.colors.TextAttributesKey$TextAttributeKeyDefaultsProvider"
serviceImplementation="com.intellij.openapi.editor.colors.impl.TextAttributeKeyDefaultsProviderImpl"/>
<applicationService serviceInterface="com.intellij.openapi.editor.colors.EditorColorsManager"
@@ -157,6 +156,8 @@
serviceImplementation="com.intellij.application.options.PathMacrosImpl"/>
<applicationService serviceImplementation="com.intellij.openapi.util.DimensionService"/>
<applicationService serviceInterface="com.intellij.openapi.application.ApplicationInfo"
serviceImplementation="com.intellij.openapi.application.impl.ApplicationInfoImpl"/>
<projectService serviceInterface="com.intellij.openapi.vfs.ReadonlyStatusHandler"
serviceImplementation="com.intellij.openapi.vcs.readOnlyHandler.ReadonlyStatusHandlerImpl"/>
@@ -208,7 +209,8 @@
serviceImplementation="com.intellij.openapi.project.impl.ProjectReloadStateImpl"/>
<!-- General -->
<applicationConfigurable groupId="appearance" groupWeight="120" key="title.general" bundle="messages.IdeBundle" id="preferences.general" instance="com.intellij.ide.GeneralSettingsConfigurable"/>
<applicationConfigurable groupId="appearance" groupWeight="120" key="title.general" bundle="messages.IdeBundle" id="preferences.general"
instance="com.intellij.ide.GeneralSettingsConfigurable"/>
<!-- Appearance -->
<applicationConfigurable groupId="appearance" groupWeight="150" instance="com.intellij.ide.ui.AppearanceConfigurable" id="preferences.lookFeel" key="title.appearance"
@@ -233,7 +235,7 @@
<actionFromOptionDescriptorProvider implementation="com.intellij.ide.plugins.InstalledPluginsManagerMain$PluginsActionFromOptionDescriptorProvider"/>
<applicationConfigurable parentId="preferences.general" instance="com.intellij.util.net.HttpProxyConfigurable" id="http.proxy" displayName="HTTP Proxy"/>
<applicationConfigurable groupId="tools" displayName="Server Certificates" instance="com.intellij.util.net.ssl.CertificateConfigurable"/>
<applicationConfigurable groupId="tools" instance="com.intellij.openapi.diff.impl.external.DiffOptionsForm" id="diff" displayName="External Diff Tools" />
<applicationConfigurable groupId="tools" instance="com.intellij.openapi.diff.impl.external.DiffOptionsForm" id="diff" displayName="External Diff Tools"/>
<!--<applicationConfigurable instance="com.intellij.ui.switcher.QuickAccessConfigurable"/>-->
<fileTypeFactory implementation="com.intellij.openapi.fileTypes.impl.PlatformFileTypeFactory"/>
@@ -270,8 +272,8 @@
<bundledKeymapProvider implementation="com.intellij.openapi.keymap.impl.DefaultBundledKeymaps"/>
<!-- <checkinHandlerFactory implementation="com.intellij.openapi.vcs.CheckRemoteStatusCheckinHandlerFactory"/> -->
<statistics.usagesCollector implementation="com.intellij.ide.plugins.DisabledPluginsUsagesCollector"/>
<statistics.usagesCollector implementation="com.intellij.ide.plugins.NonBundledPluginsUsagesCollector"/>
<statistics.usagesCollector implementation="com.intellij.ide.plugins.DisabledPluginsUsagesCollector"/>
<statistics.usagesCollector implementation="com.intellij.ide.plugins.NonBundledPluginsUsagesCollector"/>
<statistics.usagesCollector implementation="com.intellij.featureStatistics.FeaturesUsageCollector"/>
<statistics.usagesCollector implementation="com.intellij.openapi.vcs.statistics.VcsUsagesCollector"/>
<statistics.usagesCollector implementation="com.intellij.internal.statistic.UsageTrigger$MyCollector"/>
@@ -1,10 +1,5 @@
<components>
<application-components>
<component>
<interface-class>com.intellij.openapi.application.ApplicationInfo</interface-class>
<implementation-class>com.intellij.openapi.application.impl.ApplicationInfoImpl</implementation-class>
</component>
<component>
<interface-class>com.intellij.openapi.project.ProjectManager</interface-class>
<implementation-class>com.intellij.openapi.project.impl.ProjectManagerImpl</implementation-class>
@@ -921,12 +921,8 @@
<keyboard-shortcut first-keystroke="control shift PERIOD"/>
</action>
<action id="StructuralSearchPlugin.StructuralSearchAction">
<keyboard-shortcut first-keystroke="control shift S"/>
</action>
<action id="StructuralSearchPlugin.StructuralReplaceAction">
<keyboard-shortcut first-keystroke="control shift M"/>
</action>
<action id="StructuralSearchPlugin.StructuralSearchAction"/>
<action id="StructuralSearchPlugin.StructuralReplaceAction"/>
<action id="DuplicatesForm.SendToLeft">
<keyboard-shortcut first-keystroke="control 1"/>
</action>
@@ -97,8 +97,8 @@ public class XmlElementStorageTest extends LightPlatformLangTestCase {
}
@Override
protected MySaveSession createSaveSession(@NotNull StorageData storageData) {
return new MySaveSession(storageData) {
protected XmlElementStorageSaveSession createSaveSession(@NotNull StorageData storageData) {
return new XmlElementStorageSaveSession(storageData) {
@Override
protected void doSave(@Nullable Element element) {
mySavedElement = element == null ? null : element.clone();
@@ -722,6 +722,7 @@ public class AllIcons {
public static final Icon DeleteContentRoot = IconLoader.getIcon("/modules/deleteContentRoot.png"); // 9x9
public static final Icon DeleteContentRootRollover = IconLoader.getIcon("/modules/deleteContentRootRollover.png"); // 9x9
public static final Icon Edit = IconLoader.getIcon("/modules/edit.png"); // 14x14
public static final Icon ExcludedGeneratedRoot = IconLoader.getIcon("/modules/excludedGeneratedRoot.png"); // 16x16
public static final Icon ExcludeRoot = IconLoader.getIcon("/modules/excludeRoot.png"); // 16x16
public static final Icon GeneratedFolder = IconLoader.getIcon("/modules/generatedFolder.png"); // 16x16
public static final Icon GeneratedSourceRoot = IconLoader.getIcon("/modules/generatedSourceRoot.png"); // 16x16
@@ -44,6 +44,11 @@ public class RollbackLineStatusAction extends DumbAwareAction {
e.getPresentation().setEnabledAndVisible(false);
return;
}
if (!isSomeChangeSelected(editor, tracker)) {
e.getPresentation().setVisible(true);
e.getPresentation().setEnabled(false);
return;
}
e.getPresentation().setEnabledAndVisible(true);
}
@@ -57,6 +62,14 @@ public class RollbackLineStatusAction extends DumbAwareAction {
rollback(tracker, editor, null);
}
protected static boolean isSomeChangeSelected(@NotNull Editor editor, @NotNull LineStatusTracker tracker) {
List<Caret> carets = editor.getCaretModel().getAllCarets();
if (carets.size() != 1) return true;
Caret caret = carets.get(0);
if (caret.hasSelection()) return true;
return tracker.getRangeForLine(caret.getLogicalPosition().line) != null;
}
protected static void rollback(@NotNull LineStatusTracker tracker, @Nullable Editor editor, @Nullable Range range) {
assert editor != null || range != null;
@@ -32,6 +32,10 @@ import org.jdom.Element;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
/**
* @deprecated to remove in IDEA 15
*/
@Deprecated
@State(
name = "VcsManagerConfiguration",
storages = @Storage(file = StoragePathMacros.MODULE_FILE)
@@ -119,6 +119,10 @@ public class Executor {
}
}
public static void overwrite(@NotNull String fileName, @NotNull String content) throws IOException {
overwrite(child(fileName), content);
}
public static void overwrite(@NotNull File file, @NotNull String content) throws IOException {
FileUtil.writeToFile(file, content.getBytes(), false);
}
@@ -92,7 +92,7 @@ public class NewStringBufferWithCharArgumentInspection extends BaseInspection {
}
final PsiExpression argument = arguments[0];
final String text = argument.getText();
final String newArgument = '"' + StringUtil.escapeStringCharacters(text.substring(1, text.length() - 1)) + '"';
final String newArgument = '"' + StringUtil.escapeStringCharacters(StringUtil.stripQuotesAroundValue(text)) + '"';
PsiReplacementUtil.replaceExpression(argument, newArgument);
}
}
@@ -21,6 +21,8 @@ import com.intellij.notification.NotificationListener;
import com.intellij.openapi.application.ModalityState;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.util.Condition;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.openapi.vcs.FilePath;
import com.intellij.openapi.vcs.VcsNotifier;
import com.intellij.openapi.vcs.changes.*;
@@ -42,12 +44,18 @@ import git4idea.merge.GitConflictResolver;
import git4idea.repo.GitRepository;
import git4idea.util.UntrackedFilesNotifier;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import javax.swing.event.HyperlinkEvent;
import java.io.File;
import java.io.IOException;
import java.util.*;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicReference;
@@ -80,18 +88,19 @@ public class GitCherryPicker {
}
public void cherryPick(@NotNull Map<GitRepository, List<VcsFullCommitDetails>> commitsInRoots) {
List<GitCommitWrapper> successfulCommits = new ArrayList<GitCommitWrapper>();
List<GitCommitWrapper> successfulCommits = ContainerUtil.newArrayList();
List<GitCommitWrapper> alreadyPicked = ContainerUtil.newArrayList();
DvcsUtil.workingTreeChangeStarted(myProject);
try {
for (Map.Entry<GitRepository, List<VcsFullCommitDetails>> entry : commitsInRoots.entrySet()) {
GitRepository repository = entry.getKey();
boolean result = cherryPick(repository, entry.getValue(), successfulCommits);
boolean result = cherryPick(repository, entry.getValue(), successfulCommits, alreadyPicked);
repository.update();
if (!result) {
return;
}
}
notifySuccess(successfulCommits);
notifyResult(successfulCommits, alreadyPicked);
}
finally {
DvcsUtil.workingTreeChangeFinished(myProject);
@@ -100,7 +109,7 @@ public class GitCherryPicker {
// return true to continue with other roots, false to break execution
private boolean cherryPick(@NotNull GitRepository repository, @NotNull List<VcsFullCommitDetails> commits,
@NotNull List<GitCommitWrapper> successfulCommits) {
@NotNull List<GitCommitWrapper> successfulCommits, @NotNull List<GitCommitWrapper> alreadyPicked) {
for (VcsFullCommitDetails commit : commits) {
GitSimpleEventDetector conflictDetector = new GitSimpleEventDetector(CHERRY_PICK_CONFLICT);
GitSimpleEventDetector localChangesOverwrittenDetector = new GitSimpleEventDetector(LOCAL_CHANGES_OVERWRITTEN_BY_CHERRY_PICK);
@@ -115,7 +124,7 @@ public class GitCherryPicker {
}
else {
boolean committed = updateChangeListManagerShowCommitDialogAndRemoveChangeListOnSuccess(repository, commitWrapper,
successfulCommits);
successfulCommits, alreadyPicked);
if (!committed) {
notifyCommitCancelled(commitWrapper, successfulCommits);
return false;
@@ -129,7 +138,7 @@ public class GitCherryPicker {
if (mergeCompleted) {
boolean committed = updateChangeListManagerShowCommitDialogAndRemoveChangeListOnSuccess(repository, commitWrapper,
successfulCommits);
successfulCommits, alreadyPicked);
if (!committed) {
notifyCommitCancelled(commitWrapper, successfulCommits);
return false;
@@ -156,6 +165,10 @@ public class GitCherryPicker {
commitWrapper, successfulCommits);
return false;
}
else if (isNothingToCommitMessage(result)) {
alreadyPicked.add(commitWrapper);
return true;
}
else {
notifyError(result.getErrorOutputAsHtmlString(), commitWrapper, successfulCommits);
return false;
@@ -164,26 +177,32 @@ public class GitCherryPicker {
return true;
}
private static boolean isNothingToCommitMessage(@NotNull GitCommandResult result) {
if (!result.getErrorOutputAsJoinedString().isEmpty()) {
return false;
}
String stdout = result.getOutputAsJoinedString();
return stdout.contains("nothing to commit") || stdout.contains("previous cherry-pick is now empty");
}
private boolean updateChangeListManagerShowCommitDialogAndRemoveChangeListOnSuccess(@NotNull GitRepository repository,
@NotNull GitCommitWrapper commit,
@NotNull List<GitCommitWrapper> successfulCommits) {
@NotNull List<GitCommitWrapper> successfulCommits,
@NotNull List<GitCommitWrapper> alreadyPicked) {
CherryPickData data = updateChangeListManager(commit.getCommit());
if (data == null) {
alreadyPicked.add(commit);
return true;
}
boolean committed = showCommitDialogAndWaitForCommit(repository, commit, data.myChangeList, data.myCommitMessage);
if (committed) {
removeChangeList(data);
myChangeListManager.removeChangeList(data.myChangeList);
successfulCommits.add(commit);
return true;
}
return false;
}
private void removeChangeList(CherryPickData list) {
myChangeListManager.setDefaultChangeList(list.myPreviouslyDefaultChangeList);
if (!myChangeListManager.getDefaultChangeList().equals(list.myChangeList)) {
myChangeListManager.removeChangeList(list.myChangeList);
}
}
private void notifyConflictWarning(@NotNull GitRepository repository, @NotNull GitCommitWrapper commit,
@NotNull List<GitCommitWrapper> successfulCommits) {
NotificationListener resolveLinkListener = new ResolveLinkListener(myProject, myGit, myPlatformFacade, repository.getRoot(),
@@ -206,16 +225,16 @@ public class GitCherryPicker {
VcsNotifier.getInstance(myProject).notifyMinorWarning("Cherry-pick cancelled", description, null);
}
@Nullable
private CherryPickData updateChangeListManager(@NotNull final VcsFullCommitDetails commit) {
final Collection<FilePath> paths = ChangesUtil.getPaths(commit.getChanges());
refreshChangedFiles(paths);
final String commitMessage = createCommitMessage(commit);
LocalChangeList previouslyDefaultChangeList = myChangeListManager.getDefaultChangeList();
LocalChangeList changeList = createChangeListAfterUpdate(commit, paths, commitMessage);
return new CherryPickData(changeList, commitMessage, previouslyDefaultChangeList);
return changeList == null ? null : new CherryPickData(changeList, commitMessage);
}
@NotNull
@Nullable
private LocalChangeList createChangeListAfterUpdate(@NotNull final VcsFullCommitDetails commit, @NotNull final Collection<FilePath> paths,
@NotNull final String commitMessage) {
final AtomicReference<LocalChangeList> changeList = new AtomicReference<LocalChangeList>();
@@ -224,7 +243,7 @@ public class GitCherryPicker {
public void run() {
myChangeListManager.invokeAfterUpdate(new Runnable() {
public void run() {
changeList.set(createChangeList(commit, commitMessage));
changeList.set(createChangeListIfThereAreChanges(commit, commitMessage));
}
}, InvokeAfterUpdateMode.SYNCHRONOUS_NOT_CANCELLABLE, "Cherry-pick",
new Consumer<VcsDirtyScopeManager>() {
@@ -346,9 +365,37 @@ public class GitCherryPicker {
return description;
}
private void notifySuccess(@NotNull List<GitCommitWrapper> successfulCommits) {
String description = getCommitsDetails(successfulCommits);
VcsNotifier.getInstance(myProject).notifySuccess("Cherry-pick successful", description);
private void notifyResult(@NotNull List<GitCommitWrapper> successfulCommits, @NotNull List<GitCommitWrapper> alreadyPicked) {
if (alreadyPicked.isEmpty()) {
VcsNotifier.getInstance(myProject).notifySuccess("Cherry-pick successful", getCommitsDetails(successfulCommits));
}
else if (!successfulCommits.isEmpty()) {
String title = String.format("Cherry-picked %d commits from %d", successfulCommits.size(),
successfulCommits.size() + alreadyPicked.size());
String description = getCommitsDetails(successfulCommits) + "<hr/>" + formAlreadyPickedDescription(alreadyPicked, true);
VcsNotifier.getInstance(myProject).notifySuccess(title, description);
}
else {
VcsNotifier.getInstance(myProject).notifyImportantWarning("Nothing to cherry-pick",
formAlreadyPickedDescription(alreadyPicked, false));
}
}
@NotNull
private static String formAlreadyPickedDescription(@NotNull List<GitCommitWrapper> alreadyPicked, boolean but) {
String hashes = StringUtil.join(alreadyPicked, new Function<GitCommitWrapper, String>() {
@Override
public String fun(GitCommitWrapper commit) {
return commit.getCommit().getId().toShortString();
}
}, ", ");
if (but) {
String wasnt = alreadyPicked.size() == 1 ? "wasn't" : "weren't";
String it = alreadyPicked.size() == 1 ? "it" : "them";
return String.format("%s %s picked, because all changes from %s have already been applied.", hashes, wasnt, it);
}
return String.format("All changes from %s have already been applied", hashes);
}
@NotNull
@@ -373,19 +420,69 @@ public class GitCherryPicker {
}
}));
VfsUtil.markDirtyAndRefresh(false, false, false, ArrayUtil.toObjectArray(virtualFiles, VirtualFile.class));
VcsDirtyScopeManager.getInstance(myProject).filePathsDirty(filePaths, null);
}
@NotNull
private LocalChangeList createChangeList(@NotNull VcsFullCommitDetails commit, @NotNull String commitMessage) {
Collection<Change> changes = commit.getChanges();
if (!changes.isEmpty()) {
String changeListName = createNameForChangeList(commitMessage, 0).replace('\n', ' ');
final LocalChangeList changeList = ((ChangeListManagerEx)myChangeListManager).addChangeList(changeListName, commitMessage, commit);
myChangeListManager.moveChangesTo(changeList, changes.toArray(new Change[changes.size()]));
myChangeListManager.setDefaultChangeList(changeList);
@Nullable
private LocalChangeList createChangeListIfThereAreChanges(@NotNull VcsFullCommitDetails commit, @NotNull String commitMessage) {
Collection<Change> originalChanges = commit.getChanges();
if (originalChanges.isEmpty()) {
LOG.info("Empty commit " + commit.getId());
return null;
}
if (noChangesAfterCherryPick(originalChanges)) {
LOG.info("No changes after cherry-picking " + commit.getId());
return null;
}
String changeListName = createNameForChangeList(commitMessage, 0).replace('\n', ' ');
LocalChangeList changeList = ((ChangeListManagerEx)myChangeListManager).addChangeList(changeListName, commitMessage, commit);
changeList = (LocalChangeList)moveChanges(originalChanges, changeList);
if (changeList != null && !changeList.getChanges().isEmpty()) {
return changeList;
}
return myChangeListManager.getDefaultChangeList();
LOG.warn("No changes were moved to the changelist. Changes from commit: " + originalChanges +
"\nAll changes: " + myChangeListManager.getAllChanges());
myChangeListManager.removeChangeList(changeList);
return null;
}
private boolean noChangesAfterCherryPick(@NotNull Collection<Change> originalChanges) {
final Collection<Change> allChanges = myChangeListManager.getAllChanges();
return !ContainerUtil.exists(originalChanges, new Condition<Change>() {
@Override
public boolean value(Change change) {
return allChanges.contains(change);
}
});
}
@Nullable
private ChangeList moveChanges(@NotNull Collection<Change> originalChanges, @NotNull LocalChangeList targetChangeList) {
// 1. We have to listen to CLM changes, because moveChangesTo is asynchronous
// 2. We have to collect the real target change list, because the original target list (passed to moveChangesTo) is not updated in time.
final CountDownLatch moveChangesWaiter = new CountDownLatch(1);
final AtomicReference<ChangeList> resultingChangeList = new AtomicReference<ChangeList>();
ChangeListAdapter listener = new ChangeListAdapter() {
@Override
public void changesMoved(Collection<Change> changes, ChangeList fromList, ChangeList toList) {
resultingChangeList.set(toList);
moveChangesWaiter.countDown();
}
};
try {
myChangeListManager.addChangeListListener(listener);
myChangeListManager.moveChangesTo(targetChangeList, originalChanges.toArray(new Change[originalChanges.size()]));
moveChangesWaiter.await(100, TimeUnit.SECONDS);
return resultingChangeList.get();
}
catch (InterruptedException e) {
LOG.error(e);
return null;
}
finally {
myChangeListManager.removeChangeListListener(listener);
}
}
@NotNull
@@ -403,14 +500,12 @@ public class GitCherryPicker {
}
private static class CherryPickData {
private final LocalChangeList myChangeList;
private final String myCommitMessage;
private final LocalChangeList myPreviouslyDefaultChangeList;
@NotNull private final LocalChangeList myChangeList;
@NotNull private final String myCommitMessage;
private CherryPickData(LocalChangeList list, String message, LocalChangeList previouslyDefaultChangeList) {
private CherryPickData(@NotNull LocalChangeList list, @NotNull String message) {
myChangeList = list;
myCommitMessage = message;
myPreviouslyDefaultChangeList = previouslyDefaultChangeList;
}
}
@@ -20,7 +20,7 @@ import org.jetbrains.annotations.NotNull;
/**
*/
public class GitPushTagMode implements VcsPushOptionValue {
public final class GitPushTagMode implements VcsPushOptionValue {
public static GitPushTagMode ALL = new GitPushTagMode("All", "--tags");
public static GitPushTagMode FOLLOW = new GitPushTagMode("Current Branch", "--follow-tags");
@@ -28,7 +28,13 @@ public class GitPushTagMode implements VcsPushOptionValue {
@NotNull private final String myTitle;
@NotNull private final String myArgument;
public GitPushTagMode(@NotNull String title, @NotNull String argument) {
// for deserialization
@SuppressWarnings("UnusedDeclaration")
public GitPushTagMode() {
this(ALL.getTitle(), ALL.getArgument());
}
private GitPushTagMode(@NotNull String title, @NotNull String argument) {
myTitle = title;
myArgument = argument;
}
@@ -47,4 +53,24 @@ public class GitPushTagMode implements VcsPushOptionValue {
public String getArgument() {
return myArgument;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
GitPushTagMode mode = (GitPushTagMode)o;
if (!myArgument.equals(mode.myArgument)) return false;
if (!myTitle.equals(mode.myTitle)) return false;
return true;
}
@Override
public int hashCode() {
int result = myTitle.hashCode();
result = 31 * result + myArgument.hashCode();
return result;
}
}
@@ -4,12 +4,11 @@ Background:
Given enabled auto-commit in the settings
Given new committed files file.txt, a.txt, conflict.txt with initial content
Given branch feature
Given commit f5027a3 on branch feature
"""
fix #1
Author: John Bro
M file.txt "feature changes"
M file.txt "initial content\nfeature changes"
"""
Scenario: Simple cherry-pick
@@ -82,7 +81,7 @@ Background:
M conflict.txt "feature version"
"""
When I cherry-pick the commit bb6453c and don't resolve conflicts
Then active changelist is 'feature content (cherry picked from commit bb6453c)'
Then there is changelist 'feature content (cherry picked from commit bb6453c)'
And warning notification is shown 'Cherry-picked with conflicts'
"""
bb6453c feature content
@@ -137,7 +136,7 @@ Background:
M conflict.txt "feature version"
"""
When I cherry-pick the commit bb6453c, resolve conflicts and don't commit
Then active changelist is 'feature content (cherry picked from commit bb6453c)'
Then there is changelist 'feature content (cherry picked from commit bb6453c)'
And no notification is shown
Scenario: Cherry-pick 2 commits
@@ -220,53 +219,53 @@ Background:
"""
And merge dialog should be shown
#Scenario: Notify if changes have already been applied (IDEA-73548)
# Given commit eef9832 on branch master
# """
# fix #1 manually incorporated
# M file.txt "feature changes"
# """
# When I cherry-pick the commit f5027a3
# Then the last commit is eef9832
# And warning notification is shown 'Nothing to cherry-pick'
# """
# All changes from f5027a3 fix #1 have already been applied
# """
#
#Scenario: Cherry-pick 3 commits, second commit have already been applied (IDEA-73548)
# Given commit c123abc on branch feature
# """
# fix #2
# M file.txt "feature changes\nmore feature changes"
# """
# Given commit d123abc on branch feature
# """
# fix #3
# M file.txt "feature changes\nmore feature changes\nmore feature changes"
# """
# Given commit e123abc on branch feature
# """
# fix for f2
# M a.txt "feature changes"
# """
# Given commit e098fed on branch master
# """
# fix for f2 manually incorporated
# M a.txt "feature changes"
# """
# When I cherry-pick commits c123abc, d123abc and e123abc
# Then `git log -2` should return
# """
# fix #3
# (cherry picked from commit c123abc)
# -----
# fix #2
# (cherry picked from commit f5027a3)
# """
# And warning notification is shown 'Cherry-picked 2 commits'
# """
# c123abc fix #2
# d123abc fix #3
# <hr/>
# Commit e123abc wasn't picked, because all changes from it have already been applied.
# """
Scenario: Notify if changes have already been applied (IDEA-73548)
Given commit eef9832 on branch master
"""
fix #1 manually incorporated
M file.txt "initial content\nfeature changes"
"""
When I cherry-pick the commit f5027a3
Then the last commit is eef9832
And warning notification is shown 'Nothing to cherry-pick'
"""
All changes from f5027a3 have already been applied
"""
Scenario: Cherry-pick 3 commits, second commit have already been applied (IDEA-73548)
Given commit c123abc on branch feature
"""
fix #2
A newfile.txt "initial content"
"""
Given commit d123abc on branch feature
"""
fix #3
M newfile.txt "initial content\nfeature changes"
"""
Given commit e123abc on branch feature
"""
fix for f2
M a.txt "initial content\nfeature changes"
"""
Given commit e098fed on branch master
"""
fix for f2 manually incorporated
M a.txt "initial content\nfeature changes"
"""
When I cherry-pick commits c123abc, d123abc and e123abc
Then `git log -2` should return
"""
fix #3
(cherry picked from commit d123abc)
-----
fix #2
(cherry picked from commit c123abc)
"""
And success notification is shown 'Cherry-picked 2 commits from 3'
"""
c123abc fix #2
d123abc fix #3
<hr/>
e123abc wasn't picked, because all changes from it have already been applied.
"""
@@ -15,8 +15,6 @@ Feature: Git Cherry-Pick When Auto-Commit is deselected
Scenario: Simple cherry-pick
When I cherry-pick the commit f5027a3
Then commit dialog should be shown
And active changelist is 'fix #1 (cherry picked from commit f5027a3)'
Scenario: Simple cherry-pick, agree to commit
When I cherry-pick the commit f5027a3 and commit
@@ -34,7 +32,7 @@ Feature: Git Cherry-Pick When Auto-Commit is deselected
Scenario: Simple cherry-pick, cancel commit
When I cherry-pick the commit f5027a3 and don't commit
Then nothing is committed
And active changelist is 'fix #1 (cherry picked from commit f5027a3)'
And there is changelist 'fix #1 (cherry picked from commit f5027a3)'
And no notification is shown
Scenario: Cherry-pick 2 commits
@@ -67,7 +65,7 @@ Feature: Git Cherry-Pick When Auto-Commit is deselected
(cherry picked from commit f5027a3)
"""
And working tree is dirty
And active changelist is 'fix #2 (cherry picked from commit abc1234)'
And there is changelist 'fix #2 (cherry picked from commit abc1234)'
And warning notification is shown 'Cherry-pick cancelled'
"""
abc1234 fix #2
@@ -18,12 +18,13 @@ package git4idea;
import com.intellij.openapi.util.Pair;
import com.intellij.openapi.util.text.StringUtil;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import static com.intellij.openapi.vcs.Executor.echo;
import static com.intellij.openapi.vcs.Executor.overwrite;
import static com.intellij.openapi.vcs.Executor.touch;
import static git4idea.GitCucumberWorld.virtualCommits;
import static git4idea.test.GitExecutor.git;
@@ -42,10 +43,10 @@ public class CommitDetails {
private static class Change {
public void apply() {
public void apply() throws IOException {
switch (myType) {
case MODIFIED:
echo(myFile, myContent);
overwrite(myFile, myContent);
break;
case ADDED:
touch(myFile, myContent);
@@ -159,7 +160,7 @@ public class CommitDetails {
int secondSpace = change.indexOf(' ', firstSpace + 1);
return new Change(parseType(change.substring(0, firstSpace)),
change.substring(firstSpace + 1, secondSpace),
change.substring(secondSpace + 1));
StringUtil.unescapeStringCharacters(StringUtil.unquoteString(change.substring(secondSpace + 1))));
}
private static Change.Type parseType(String type) {
@@ -181,7 +182,7 @@ public class CommitDetails {
/**
* @return real commit details.
*/
public CommitDetails apply() {
public CommitDetails apply() throws IOException {
for (Change change : myChanges) {
change.apply();
}
@@ -70,14 +70,15 @@ public class GeneralStepdefs {
notificationType.equals("error") ? NotificationType.ERROR : null;
Notification actualNotification = lastNotification();
assertNotNull("Notification should be shown", actualNotification);
assertEquals("Notification type is incorrect", type, actualNotification.getType());
assertEquals("Notification title is incorrect", title, actualNotification.getTitle());
assertEquals("Notification type is incorrect in " + actualNotification, type, actualNotification.getType());
assertEquals("Notification title is incorrect in" + actualNotification, title, actualNotification.getTitle());
assertNotificationContent(content, actualNotification.getContent());
}
private static void assertNotificationContent(String expected, String actual) {
expected = virtualCommits.replaceVirtualHashes(expected);
assertEquals("Notification content is incorrect", StringUtil.convertLineSeparators(expected), StringUtil.convertLineSeparators(adjustNotificationContent(actual)));
assertEquals("Notification content is incorrect", StringUtil.convertLineSeparators(expected),
StringUtil.convertLineSeparators(adjustNotificationContent(actual)));
}
private static String adjustNotificationContent(String content) {
@@ -15,33 +15,30 @@
*/
package git4idea;
import com.google.common.base.Function;
import com.google.common.collect.Collections2;
import com.intellij.mock.MockVirtualFile;
import com.intellij.openapi.components.ServiceManager;
import com.intellij.openapi.util.ThrowableComputable;
import com.intellij.openapi.util.Condition;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.openapi.vcs.FilePathImpl;
import com.intellij.openapi.vcs.changes.Change;
import com.intellij.openapi.vcs.VcsException;
import com.intellij.openapi.vcs.changes.LocalChangeList;
import com.intellij.openapi.vcs.history.VcsRevisionNumber;
import com.intellij.openapi.vfs.newvfs.impl.NullVirtualFile;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.testFramework.vcs.MockChangeListManager;
import com.intellij.testFramework.vcs.MockContentRevision;
import com.intellij.util.ArrayUtil;
import com.intellij.util.Function;
import com.intellij.util.containers.ContainerUtil;
import com.intellij.vcs.log.Hash;
import com.intellij.vcs.log.VcsFullCommitDetails;
import com.intellij.vcs.log.VcsLogObjectsFactory;
import com.intellij.vcs.log.impl.HashImpl;
import cucumber.annotation.en.And;
import cucumber.annotation.en.Given;
import cucumber.annotation.en.Then;
import cucumber.annotation.en.When;
import git4idea.cherrypick.GitCherryPicker;
import git4idea.config.GitVersionSpecialty;
import git4idea.history.GitHistoryUtils;
import git4idea.test.MockVcsHelper;
import org.jetbrains.annotations.NotNull;
import java.util.*;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import static com.intellij.openapi.vcs.Executor.echo;
import static git4idea.GitCucumberWorld.*;
@@ -63,7 +60,7 @@ public class GitCherryPickStepdefs {
}
@When("^I cherry-pick the commit (\\w+)$")
public void I_cherry_pick_the_commit(String hash) {
public void I_cherry_pick_the_commit(String hash) throws VcsException {
cherryPick(hash);
}
@@ -175,6 +172,11 @@ public class GitCherryPickStepdefs {
expectedMessage = expectedMessage.replace("\n", "").replace(" ", "");
actualMessage = actualMessage.replace("\n", "").replace(" ", "");
}
else {
// replace just double \n between subject and body to avoid lengthy feature steps
expectedMessage = expectedMessage.replace("\n\n", "\n");
actualMessage = actualMessage.replace("\n\n", "\n");
}
expectedMessage = virtualCommits.replaceVirtualHashes(expectedMessage);
assertEquals("Commit doesn't match", expectedMessage, trimHash(actualMessage));
}
@@ -214,62 +216,45 @@ public class GitCherryPickStepdefs {
assertTrue("Commit dialog was not shown", myVcsHelper.commitDialogWasShown());
}
@Then("^active changelist is '(.+)'$")
public void active_changelist_is(String name) throws Throwable {
assertActiveChangeList(virtualCommits.replaceVirtualHashes(name));
@Then("^there is changelist '(.*)'$")
public void there_is_changelist(@NotNull final String name) throws Throwable {
List<LocalChangeList> changeLists = myChangeListManager.getChangeListsCopy();
assertTrue("Didn't find changelist with name '" + name + "' among :" + changeLists,
ContainerUtil.exists(changeLists, new Condition<LocalChangeList>() {
@Override
public boolean value(LocalChangeList list) {
return list.getName().equals(virtualCommits.replaceVirtualHashes(name));
}
}));
}
private static void assertOnlyDefaultChangelist() {
String DEFAULT = MockChangeListManager.DEFAULT_CHANGE_LIST_NAME;
assertChangeLists(Collections.singleton(DEFAULT), DEFAULT);
assertEquals("Only default change list is expected", 1, myChangeListManager.getChangeListsNumber());
assertEquals("Default changelist is not active", DEFAULT, myChangeListManager.getDefaultChangeList().getName());
}
private static void assertChangeLists(Collection<String> changeLists, String activeChangelist) {
List<LocalChangeList> lists = myChangeListManager.getChangeLists();
Collection<String> listNames = Collections2.transform(lists, new Function<LocalChangeList, String>() {
private static void cherryPick(final List<String> virtualHashes) throws VcsException {
List<VcsFullCommitDetails> commits = loadDetails(ContainerUtil.map(virtualHashes, new Function<String, String>() {
@Override
public String apply(LocalChangeList input) {
return input.getName();
public String fun(String virtualHash) {
return virtualCommits.getRealCommit(virtualHash).getHash();
}
});
assertEquals("Change lists are different", new ArrayList<String>(changeLists), new ArrayList<String>(listNames));
assertActiveChangeList(activeChangelist);
}
}), myProjectDir);
private static void assertActiveChangeList(String name) {
assertEquals("Wrong active changelist", name, myChangeListManager.getDefaultChangeList().getName());
}
private static void cherryPick(List<String> virtualHashes) {
List<VcsFullCommitDetails> commits = ContainerUtil.newArrayList();
for (String virtualHash : virtualHashes) {
commits.add(createMockCommit(virtualHash));
}
new GitCherryPicker(myProject, myGit, myPlatformFacade, mySettings.isAutoCommitOnCherryPick())
.cherryPick(Collections.singletonMap(myRepository, commits));
.cherryPick(Collections.singletonMap(myRepository, commits));
}
private static void cherryPick(String... virtualHashes) {
private static List<VcsFullCommitDetails> loadDetails(List<String> hashes, @NotNull VirtualFile root) throws VcsException {
String noWalk = GitVersionSpecialty.NO_WALK_UNSORTED.existsIn(myVcs.getVersion()) ? "--no-walk=unsorted" : "--no-walk";
List<String> params = new ArrayList<String>();
params.add(noWalk);
params.addAll(hashes);
return new ArrayList<VcsFullCommitDetails>(GitHistoryUtils.history(myProject, root, ArrayUtil.toStringArray(params)));
}
private static void cherryPick(String... virtualHashes) throws VcsException {
cherryPick(Arrays.asList(virtualHashes));
}
private static VcsFullCommitDetails createMockCommit(String virtualHash) {
CommitDetails realCommit = virtualCommits.getRealCommit(virtualHash);
return mockCommit(realCommit.getHash(), realCommit.getMessage());
}
private static VcsFullCommitDetails mockCommit(String hash, String message) {
final List<Change> changes = new ArrayList<Change>();
changes.add(new Change(null, new MockContentRevision(new FilePathImpl(new MockVirtualFile("name")), VcsRevisionNumber.NULL)));
return ServiceManager.getService(myProject, VcsLogObjectsFactory.class).createFullDetails(
HashImpl.build(hash), Collections.<Hash>emptyList(), 0, NullVirtualFile.INSTANCE, message, "John Smith", "john@mail.com", message,
"John Smith", "john@mail.com", 0, new ThrowableComputable<Collection<Change>, Exception>() {
@Override
public Collection<Change> compute() throws Exception {
return changes;
}
}
);
}
}
@@ -152,6 +152,12 @@ public class GradleExecutionHelper {
commandLineArgs.add(GradleConstants.OFFLINE_MODE_CMD_OPTION);
}
final Application application = ApplicationManager.getApplication();
if(application != null && application.isUnitTestMode()) {
commandLineArgs.add("--info");
commandLineArgs.add("--recompile-scripts");
}
if (!commandLineArgs.isEmpty()) {
LOG.info("Passing command-line args to Gradle Tooling API: " + commandLineArgs);
// filter nulls and empty strings
@@ -224,7 +230,7 @@ public class GradleExecutionHelper {
}
}
catch (Throwable e) {
// ignore
LOG.debug("Gradle connection close error", e);
}
}
}
@@ -30,9 +30,9 @@ import org.gradle.wrapper.GradleWrapperMain;
import org.intellij.lang.annotations.Language;
import org.jetbrains.annotations.NonNls;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.plugins.gradle.remote.GradleJavaHelper;
import org.jetbrains.plugins.gradle.settings.DistributionType;
import org.jetbrains.plugins.gradle.settings.GradleProjectSettings;
import org.jetbrains.plugins.gradle.settings.GradleSettings;
import org.jetbrains.plugins.gradle.util.GradleConstants;
import org.junit.Rule;
import org.junit.rules.TestName;
@@ -73,6 +73,7 @@ public abstract class GradleImportingTestCase extends ExternalSystemImportingTes
public void setUp() throws Exception {
super.setUp();
myProjectSettings = new GradleProjectSettings();
GradleSettings.getInstance(myProject).setGradleVmOptions("-Xmx64m -XX:MaxPermSize=64m");
System.setProperty(ExternalSystemExecutionSettings.REMOTE_PROCESS_IDLE_TTL_IN_MS_KEY, String.valueOf(GRADLE_DAEMON_TTL_MS));
configureWrapper();
}
@@ -123,14 +123,19 @@ public abstract class AbstractModelBuilderTest {
((DefaultGradleConnector)connector).daemonMaxIdleTime(daemonMaxIdleTime, TimeUnit.SECONDS);
ProjectConnection connection = connector.connect();
final ProjectImportAction projectImportAction = new ProjectImportAction(false);
projectImportAction.addExtraProjectModelClasses(getModels());
BuildActionExecuter<ProjectImportAction.AllModels> buildActionExecutor = connection.action(projectImportAction);
File initScript = GradleExecutionHelper.generateInitScript(false, getToolingExtensionClasses());
assertNotNull(initScript);
buildActionExecutor.withArguments("--recompile-scripts", GradleConstants.INIT_SCRIPT_CMD_OPTION, initScript.getAbsolutePath());
allModels = buildActionExecutor.run();
assertNotNull(allModels);
try {
final ProjectImportAction projectImportAction = new ProjectImportAction(false);
projectImportAction.addExtraProjectModelClasses(getModels());
BuildActionExecuter<ProjectImportAction.AllModels> buildActionExecutor = connection.action(projectImportAction);
File initScript = GradleExecutionHelper.generateInitScript(false, getToolingExtensionClasses());
assertNotNull(initScript);
buildActionExecutor.setJvmArguments("-Xmx64m", "-XX:MaxPermSize=64m");
buildActionExecutor.withArguments("--info", "--recompile-scripts", GradleConstants.INIT_SCRIPT_CMD_OPTION, initScript.getAbsolutePath());
allModels = buildActionExecutor.run();
assertNotNull(allModels);
} finally {
connection.close();
}
}
@NotNull
@@ -207,14 +207,17 @@ public class SearchingForTestsTask extends Task.Backgroundable {
}
}
}
map.put(ApplicationManager.getApplication().runReadAction(
final String className = ApplicationManager.getApplication().runReadAction(
new Computable<String>() {
@Nullable
public String compute() {
return ClassUtil.getJVMClassName(entry.getKey());
}
}
), methods);
);
if (className != null) {
map.put(className, methods);
}
}
// We have groups we wish to limit to.
Collection<String> groupNames = null;
@@ -0,0 +1,7 @@
The current maintainer:
* Andrey Vlasovskikh <andrey.vlasovskikh@jetbrains.com>
Contributors:
TODO: The list of contributors
@@ -0,0 +1,13 @@
Copyright 2013 The python-skeletons authors
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
+237
View File
@@ -0,0 +1,237 @@
Python Skeletons
================
_This proposal is a draft._
Python skeletons are Python files that contain API definitions of existing
libraries extended for static analysis tools.
Rationale
---------
Python is a dynamic language less suitable for static code analysis than static
languages like C or Java. Although Python static analysis tools can extract
some information from Python source code without executing it, this information
is often very shallow and incomplete.
Dynamic features of Python are very useful for user code. But using these
features in APIs of third-party libraries and the standard library is not
always a good idea. Tools (and users, in fact) need clear definitions of APIs.
Often library API definitions are quite static and easy to grasp (defined
using `class`, `def`), but types of function parameters and return values
usually are not specified. Sometimes API definitions involve metaprogramming.
As there is not enough information in API definition code of libraries,
developers of static analysis tools collect extended API data themselves and
store it in their own formats. For example, PyLint uses imperative AST
transformations of API modules in order to extend them with hard-coded data.
PyCharm extends APIs via its proprietary database of declarative type
annotations. The absence of a common extended API information format makes it
hard for developers and users of tools to collect and share data.
Proposal
--------
The proposal is to create a common database of extended API definitions as a
collection of Python files called skeletons. Static analysis tools already
understand Python code, so it should be easy to start extracting API
definitions from these Python skeleton files. Regular function and class
definitions can be extended with additional docstrings and decorators, e.g. for
providing types of function parameters and return values. Static analysis tools
may use a subset of information contained in skeleton files needed for their
operation. Using Python files instead of a custom API definition format will
also make it easier for users to populate the skeletons database.
Declarative Python API definitions for static analysis tools cannot cover all
dynamic tricks used in real APIs of libraries: some of them still require
library-specific code analysis. Nevertheless the skeletons database is enough
for many libraries.
The proposed [python-skeletons](https://github.com/JetBrains/python-skeletons)
repository is hosted on GitHub.
Conventions
-----------
Skeletons should contain syntactically correct Python code, preferably compatible
with Python 2.6-3.3.
Skeletons should respect [PEP-8](http://www.python.org/dev/peps/pep-0008/) and
[PEP-257](http://www.python.org/dev/peps/pep-0257/) style guides.
If you need to reference the members of the original module of a skeleton, you
should import it explicitly. For example, in a skeleton for the `foo` module:
import foo
class C(foo.B):
def bar():
"""Do bar and return Bar.
:rtype: foo.Bar
"""
return foo.Bar()
Modules can be referenced in docstring without explicit imports.
The body of a function in a skeleton file should consist of a single `return`
statement that returns a simple value of the declared return type (e.g. `0`
for `int`, `False` for `bool`, `Foo()` for `Foo`). If the function returns
something non-trivial, its may consist of a `pass` statement.
### Types
There is no standard notation for specifying types in Python code. We would
like this standard to emerge, see the related work below.
The current understanding is that a standard for optional type annotations in
Python could use the syntax of function annotations in Python 3 and decorators
as a fallback in Python 2. The type system should be relatively simple, but it
has to include parametric (generic) types for collections and probably more.
As a temporary solution, we propose a simple way of specifying types in
skeletons using Sphinx docstrings using the following notation:
Foo # Class Foo visible in the current scope
x.y.Bar # Class Bar from x.y module
Foo | Bar # Foo or Bar
(Foo, Bar) # Tuple of Foo and Bar
list[Foo] # List of Foo elements
dict[Foo, Bar] # Dict from Foo to Bar
T # Generic type (T-Z are reserved for generics)
T <= Foo # Generic type with upper bound Foo
Foo[T] # Foo parameterized with T
(Foo, Bar) -> Baz # Function of Foo and Bar that returns Baz
There are several shortcuts available:
unknown # Unknown type
None # type(None)
string # Py2: str | unicode, Py3: str
bytestring # Py2: str | unicode, Py3: bytes
bytes # Py2: str, Py3: bytes
unicode # Py2: unicode, Py3: str
The syntax is a subject to change. It is almost compatible to Python (except
function types), but its semantics differs from Python (no `|`, no implicitly
visible names, no generic types). So you cannot use these expressions in
Python 3 function annotations.
If you want to create a parameterized class, you should define its parameters
in the mock return type of a constructor:
class C(object):
"""Some collection C that can contain values of T."""
def __init__(self, value):
"""Initialize C.
:type value: T
:rtype: C[T]
"""
pass
def get(self):
"""Return the contained value.
:rtype: T
"""
pass
### Versioning
The recommended way of checking the version of Python is:
import sys
if sys.version_info >= (2, 7) and sys.version_info < (3,):
def from_27_until_30():
pass
A skeleton should document the most recently released version of a library. Use
deprecation warnings for functions that have been removed from the API.
Skeletons for built-in symbols is an exception. There are two modules:
`__builtin__` for Python 2 and `builtins` for Python 3.
Related Work
------------
The JavaScript community is also interested in formalizing API definitions and
specifying types. They have come up with several JavaScript dialects that
support optional types: TypeScript, Dart. There is a JavaScript initiative
similar to the proposed Python skeletons called
[DefinitelyTyped](https://github.com/borisyankov/DefinitelyTyped). The idea is
to use TypeScript API stubs for various JavaScript libraries.
There are many approaches to specifying types in Python, none of them is widely
adopted at the moment:
* A series of old (2005) posts by GvR:
[1](http://www.artima.com/weblogs/viewpost.jsp?thread=85551),
[2](http://www.artima.com/weblogs/viewpost.jsp?thread=86641),
[3](http://www.artima.com/weblogs/viewpost.jsp?thread=87182)
* String-based [python-rightarrow](https://github.com/kennknowles/python-rightarrow)
library
* Expression-based [typeannotations](https://github.com/ceronman/typeannotations)
library for Python 3
* [mypy](http://www.mypy-lang.org/) Python dialect
* [pytypes](https://github.com/pytypes/pytypes): Optional typing for Python proposal
* [Proposal: Use mypy syntax for function annotations](https://mail.python.org/pipermail/python-ideas/2014-August/028618.html) by GvR
See also the notes on function annotations in
[PEP-8](http://www.python.org/dev/peps/pep-0008/).
PyCharm / IntelliJ
------------------
PyCharm 3 and the Python plugin 3.x for IntelliJ can extract the following
information from the skeletons:
* Parameters of functions and methods
* Return types and parameter types of functions and methods
* Types of assignment targets
* Extra module members
* Extra class members
* TODO
PyCharm 3 comes with a snapshot of the Python skeletons repository (Python
plugin 3.0.1 for IntelliJ still doesn't include this repository). You
**should not** modify it, because it will be updated with the PyCharm / Python
plugin for IntelliJ installation. If you want to change the skeletons, clone
the skeletons GitHub repository into your PyCharm/IntelliJ config directory:
cd <config directory>
git clone https://github.com/JetBrains/python-skeletons.git
where `<config directory>` is:
* PyCharm
* Mac OS X: `~/Library/Preferences/PyCharmXX`
* Linux: `~/.PyCharmXX/config`
* Windows: `<User home>\.PyCharmXX\config`
* IntelliJ
* Mac OS X: `~/Library/Preferences/IntelliJIdeaXX`
* Linux: `~/.IntelliJIdeaXX/config`
* Windows: `<User home>\.IntelliJIdeaXX\config`
Please send your PyCharm/IntelliJ-related bug reports and feature requests to
[PyCharm issue tracker](http://youtrack.jetbrains.com/issues/PY).
Feedback
--------
If you want to contribute, send your pull requests to the Python skeletons
repository on GitHub. Please make sure, that you follow the conventions above.
Use [code-quality](http://mail.python.org/mailman/listinfo/code-quality)
mailing list to discuss Python skeletons.
+126
View File
@@ -0,0 +1,126 @@
"""Skeleton for 'StringIO' stdlib module."""
import StringIO as _StringIO
class StringIO(object):
"""Reads and writes a string buffer (also known as memory files)."""
def __init__(self, buffer=None):
"""When a StringIO object is created, it can be initialized to an existing
string by passing the string to the constructor.
:type buffer: T <= bytes | unicode
:rtype: _StringIO.StringIO[T]
"""
self.closed = False
def getvalue(self):
"""Retrieve the entire contents of the "file" at any time before the
StringIO object's close() method is called.
:rtype: T
"""
pass
def close(self):
"""Free the memory buffer.
:rtype: None
"""
pass
def flush(self):
"""Flush the internal buffer.
:rtype: None
"""
pass
def isatty(self):
"""Return True if the file is connected to a tty(-like) device,
else False.
:rtype: bool
"""
return False
def __iter__(self):
"""Return an iterator over lines.
:rtype: _StringIO.StringIO[T]
"""
return self
def next(self):
"""Returns the next input line.
:rtype: T
"""
pass
def read(self, size=-1):
"""Read at most size bytes or characters from the buffer.
:type size: numbers.Integral
:rtype: T
"""
pass
def readline(self, size=-1):
"""Read one entire line from the buffer.
:type size: numbers.Integral
:rtype: T
"""
pass
def readlines(self, sizehint=-1):
"""Read until EOF using readline() and return a list containing the
lines thus read.
:type sizehint: numbers.Integral
:rtype: list[T]
"""
pass
def seek(self, offset, whence=0):
"""Set the buffer's current position, like stdio's fseek().
:type offset: numbers.Integral
:type whence: numbers.Integral
:rtype: None
"""
pass
def tell(self):
"""Return the buffer's current position, like stdio's ftell().
:rtype: int
"""
pass
def truncate(self, size=-1):
"""Truncate the buffer's size.
:type size: numbers.Integral
:rtype: None
"""
pass
def write(self, str):
""""Write bytes or a string to the buffer.
:type str: T
:rtype: None
"""
pass
def writelines(self, sequence):
"""Write a sequence of bytes or strings to the buffer.
:type sequence: collections.Iterable[T]
:rtype: None
"""
pass
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,12 @@
"""Skeleton for 'asyncio' stdlib module."""
import asyncio
def get_event_loop():
"""Get the event loop for the current context.
:rtype: asyncio.AbstractEventLoop
"""
pass
+60
View File
@@ -0,0 +1,60 @@
# coding=utf-8
"""
Python Behave skeletons (https://pythonhosted.org/behave/)
"""
def given(pattern):
"""Decorates a function, so that it will become a new step
definition.
:param pattern pattern to match, may be regular expression or something else depends on step matcher
"""
pass
def when(pattern):
"""Decorates a function, so that it will become a new step
definition.
:param pattern pattern to match, may be regular expression or something else depends on step matcher
"""
pass
def then(pattern):
"""Decorates a function, so that it will become a new step
definition.
:param pattern pattern to match, may be regular expression or something else depends on step matcher
"""
pass
def step(pattern):
"""Decorates a function, so that it will become a new step
definition.
:param pattern pattern to match, may be regular expression or something else depends on step matcher
"""
pass
def Given(pattern):
"""Decorates a function, so that it will become a new step
definition.
:param pattern pattern to match, may be regular expression or something else depends on step matcher
"""
pass
def When(pattern):
"""Decorates a function, so that it will become a new step
definition.
:param pattern pattern to match, may be regular expression or something else depends on step matcher
"""
pass
def Then(pattern):
"""Decorates a function, so that it will become a new step
definition.
:param pattern pattern to match, may be regular expression or something else depends on step matcher
"""
pass
def Step(pattern):
"""Decorates a function, so that it will become a new step
definition.
:param pattern pattern to match, may be regular expression or something else depends on step matcher
"""
pass
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,131 @@
"""Skeleton for 'cStringIO' stdlib module."""
import cStringIO
def StringIO(s=None):
"""Return a StringIO-like stream for reading or writing.
:type s: T <= bytes | unicode
:rtype: cStringIO.OutputType[T]
"""
return cStringIO.OutputType(s)
class OutputType(object):
def __init__(self, s):
"""Create an OutputType object.
:rtype: cStringIO.OutputType[T <= bytes | unicode]
"""
pass
def getvalue(self):
"""Retrieve the entire contents of the "file" at any time before the
StringIO object's close() method is called.
:rtype: T
"""
pass
def close(self):
"""Free the memory buffer.
:rtype: None
"""
pass
def flush(self):
"""Flush the internal buffer.
:rtype: None
"""
pass
def isatty(self):
"""Return True if the file is connected to a tty(-like) device,
else False.
:rtype: bool
"""
return False
def __iter__(self):
"""Return an iterator over lines.
:rtype: cStringIO.OutputType[T]
"""
return self
def next(self):
"""Returns the next input line.
:rtype: T
"""
pass
def read(self, size=-1):
"""Read at most size bytes or characters from the buffer.
:type size: numbers.Integral
:rtype: T
"""
pass
def readline(self, size=-1):
"""Read one entire line from the buffer.
:type size: numbers.Integral
:rtype: T
"""
pass
def readlines(self, sizehint=-1):
"""Read until EOF using readline() and return a list containing the
lines thus read.
:type sizehint: numbers.Integral
:rtype: list[T]
"""
return []
def seek(self, offset, whence=0):
"""Set the buffer's current position, like stdio's fseek().
:type offset: numbers.Integral
:type whence: numbers.Integral
:rtype: None
"""
pass
def tell(self):
"""Return the buffer's current position, like stdio's ftell().
:rtype: int
"""
return 0
def truncate(self, size=-1):
"""Truncate the buffer's size.
:type size: numbers.Integral
:rtype: None
"""
pass
def write(self, str):
""""Write bytes or a string to the buffer.
:type str: T
:rtype: None
"""
pass
def writelines(self, sequence):
"""Write a sequence of bytes or strings to the buffer.
:type sequence: collections.Iterable[T]
:rtype: None
"""
pass
@@ -0,0 +1,26 @@
"""Skeleton for 'collections' stdlib module."""
import sys
import collections
class Iterator(collections.Iterable):
def __init__(self):
"""
:rtype: collections.Iterator[T]
"""
pass
if sys.version_info >= (3, 0):
def __next__(self):
"""
:rtype: T
"""
pass
def next(self):
"""
:rtype: T
"""
pass
+625
View File
@@ -0,0 +1,625 @@
"""Skeleton for 'datetime' stdlib module."""
import sys
import datetime as _datetime
from time import struct_time
class timedelta(object):
"""A timedelta object represents a duration, the difference between two
dates or times."""
def __init__(self, days=0, seconds=0, microseconds=0, milliseconds=0,
minutes=0, hours=0, weeks=0):
"""Create a timedelta object.
:type days: numbers.Real
:type seconds: numbers.Real
:type microseconds: numbers.Real
:type milliseconds: numbers.Real
:type minutes: numbers.Real
:type hours: numbers.Real
:type weeks: numbers.Real
"""
self.days = 0
self.seconds = 0
self.microseconds = 0
def __add__(self, other):
"""Add timedelta, date or datetime.
:type other: T <= _datetime.timedelta | _datetime.date | _datetime.datetime
:rtype: T
"""
pass
def __radd__(self, other):
"""Add timedelta, date or datetime.
:type other: T <= _datetime.timedelta | _datetime.date | _datetime.datetime
:rtype: T
"""
pass
def __sub__(self, other):
"""Subtract timedelta, date or datetime.
:type other: _datetime.timedelta | _datetime.date | _datetime.datetime
:rtype: _datetime.timedelta | _datetime.date | _datetime.datetime
"""
pass
def __rsub__(self, other):
"""Subtract timedelta, date or datetime.
:type other: _datetime.timedelta | _datetime.date | _datetime.datetime
:rtype: _datetime.timedelta | _datetime.date | _datetime.datetime
"""
pass
def __mul__(self, other):
"""Multiply by an integer.
:type other: numbers.Integral
:rtype: _datetime.timedelta
"""
return _datetime.timedelta()
def __rmul__(self, other):
"""Multiply by an integer.
:type other: numbers.Integral
:rtype: _datetime.timedelta
"""
return _datetime.timedelta()
def __floordiv__(self, other):
"""Divide by an integer or a timedelta.
:type other: numbers.Integral | _datetime.timedelta
:rtype: _datetime.timedelta | int
"""
pass
def __div__(self, other):
"""Divide by an integer.
:type other: numbers.Integral
:rtype: _datetime.timedelta
"""
pass
def __truediv__(self, other):
"""Divide by a float or a timedelta.
:type other: numbers.Real | _datetime.timedelta
:rtype: _datetime.timedelta | float
"""
pass
if sys.version_info >= (2, 7):
def total_seconds(self):
"""Return the total number of seconds contained in the duration.
:rtype: int
"""
return 0
min = _datetime.timedelta()
max = _datetime.timedelta()
resoultion = _datetime.timedelta()
class date(object):
"""An idealized naive date, assuming the current Gregorian calendar always
was, and always will be, in effect."""
def __init__(self, year, month, day):
"""Create a date object.
:type year: numbers.Integral
:type month: numbers.Integral
:type day: numbers.Integral
"""
self.year = year
self.month = month
self.day = day
@classmethod
def today(cls):
"""Return the current local date.
:rtype: _datetime.date
"""
return _datetime.date(0, 0, 0)
@classmethod
def fromtimestamp(cls, timestamp):
"""Return the local date corresponding to the POSIX timestamp, such as
is returned by time.time().
:type timestamp: numbers.Real
:rtype: _datetime.date
"""
return _datetime.date(0, 0, 0)
@classmethod
def fromordinal(cls, ordinal):
"""Return the date corresponding to the proleptic Gregorian ordinal,
where January 1 of year 1 has ordinal 1.
:type ordinal: numbers.Integral
:rtype: _datetime.date
"""
return _datetime.date(0, 0, 0)
def __add__(self, other):
"""Add timedelta.
:type other: _datetime.timedelta
:rtype: _datetime.date
"""
return _datetime.date(0, 0, 0)
def __radd__(self, other):
"""Add timedelta.
:type other: _datetime.timedelta
:rtype: _datetime.date
"""
return _datetime.date(0, 0, 0)
def __sub__(self, other):
"""Subtract date or timedelta.
:type other: _datetime.date | _datetime.timedelta
:rtype: _datetime.timedelta | _datetime.date
"""
pass
def __rsub__(self, other):
"""Subtract date.
:type other: _datetime.date
:rtype: _datetime.timedelta
"""
return _datetime.timedelta()
def replace(self, year=None, month=None, day=None):
"""Return a date with the same value, except for those parameters given
new values by whichever keyword arguments are specified.
:type year: numbers.Integral
:type month: numbers.Integral
:type day: numbers.Integral
:rtype: _datetime.date
"""
return _datetime.date(0, 0, 0)
def timetuple(self):
"""Return a time.struct_time such as returned by time.localtime().
:rtype: struct_time
"""
return struct_time()
def toordinal(self):
"""Return the proleptic Gregorian ordinal of the date, where January 1
of year 1 has ordinal 1.
:rtype: int
"""
return 0
def weekday(self):
"""Return the day of the week as an integer, where Monday is 0 and
Sunday is 6.
:rtype: int
"""
return 0
def isoweekday(self):
"""Return the day of the week as an integer, where Monday is 1 and
Sunday is 7.
:rtype: int
"""
return 0
def isocalendar(self):
"""Return a 3-tuple, (ISO year, ISO week number, ISO weekday).
:rtype: (int, int, int)
"""
return (0, 0, 0)
def isoformat(self):
"""Return a string representing the date in ISO 8601 format,
'YYYY-MM-DD'.
:rtype: string
"""
return str()
def ctime(self):
"""Return a string representing the date.
:rtype: string
"""
return str()
def strftime(self, format):
"""Return a string representing the date, controlled by an explicit
format string.
:type format: string
:rtype: string
"""
return str()
min = _datetime.date(0, 0, 0)
max = _datetime.date(0, 0, 0)
resoultion = _datetime.timedelta()
class datetime(object):
"""A datetime object is a single object containing all the information from
a date object and a time object."""
def __init__(self, year, month, day, hour=0, minute=0, second=0,
microsecond=0, tzinfo=None):
"""Create a datetime object.
:type year: numbers.Integral
:type month: numbers.Integral
:type day: numbers.Integral
:type hour: numbers.Integral
:type minute: numbers.Integral
:type second: numbers.Integral
:type microsecond: numbers.Integral
:type tzinfo: _datetime.tzinfo | None
"""
self.year = year
self.month = month
self.day = day
self.hour = hour
self.minute = minute
self.second = second
self.microsecond = microsecond
self.tzinfo = tzinfo
@classmethod
def today(cls):
"""Return the current local datetime, with tzinfo None.
:rtype: _datetime.datetime
"""
return _datetime.datetime(0, 0, 0)
@classmethod
def now(cls, tz=None):
"""Return the current local date and time.
:type tz: _datetime.tzinfo | None
:rtype: _datetime.datetime
"""
return _datetime.datetime(0, 0, 0)
@classmethod
def utcnow(cls):
"""Return the current UTC date and time, with tzinfo None.
:rtype: _datetime.datetime
"""
return _datetime.datetime(0, 0, 0)
@classmethod
def fromtimestamp(cls, timestamp, tz=None):
"""Return the local date and time corresponding to the POSIX timestamp,
such as is returned by time.time().
:type timestamp: numbers.Real
:type tz: _datetime.tzinfo | None
:rtype: _datetime.datetime
"""
return _datetime.datetime(0, 0, 0)
@classmethod
def utcfromtimestamp(cls, timestamp):
"""Return the UTC datetime corresponding to the POSIX timestamp, with
tzinfo None.
:type timestamp: numbers.Real
:rtype: _datetime.datetime
"""
return _datetime.datetime(0, 0, 0)
@classmethod
def fromordinal(cls, ordinal):
"""Return the datetime corresponding to the proleptic Gregorian
ordinal.
:type ordinal: numbers.Integral
:rtype: _datetime.datetime
"""
return _datetime.datetime(0, 0, 0)
@classmethod
def combine(cls, date, time):
"""Return a new datetime object whose date components are equal to the
given date object's, and whose time components and tzinfo attributes
are equal to the given time object's.
:type date: _datetime.date
:type time: _datetime.time
:rtype: _datetime.datetime
"""
return _datetime.datetime(0, 0, 0)
@classmethod
def strptime(cls, date_string, format):
"""Return a datetime corresponding to date_string, parsed according to
format.
:type date_string: string
:type format: string
:rtype: _datetime.datetime
"""
return _datetime.datetime(0, 0, 0)
def __add__(self, other):
"""Add timedelta.
:type other: _datetime.timedelta
:rtype: _datetime.datetime
"""
return _datetime.datetime(0, 0, 0)
def __radd__(self, other):
"""Add timedelta.
:type other: _datetime.timedelta
:rtype: _datetime.datetime
"""
return _datetime.datetime(0, 0, 0)
def __sub__(self, other):
"""Subtract timedelta or datetime.
:type other: _datetime.timedelta | _datetime.datetime
:rtype: _datetime.datetime | _datetime.timedelta
"""
pass
def __rsub__(self, other):
"""Subtract datetime.
:type other: _datetime.datetime
:rtype: _datetime.timedelta
"""
return _datetime.timedelta()
def date(self):
"""Return date object with same year, month and day.
:rtype: _datetime.date
"""
return _datetime.date(0, 0, 0)
def time(self):
"""Return time object with same hour, minute, second and microsecond.
:rtype: _datetime.time
"""
return _datetime.time()
def timetz(self):
"""Return time object with same hour, minute, second, microsecond, and
tzinfo attributes.
:rtype: _datetime.time
"""
return _datetime.time()
def replace(self, year=None, month=None, day=None, hour=None, minute=None,
second=None, microsecond=None, tzinfo=None):
"""Return a datetime with the same attributes, except for those
attributes given new values by whichever keyword arguments are
specified.
:type year: numbers.Integral
:type month: numbers.Integral
:type day: numbers.Integral
:type hour: numbers.Integral
:type minute: numbers.Integral
:type second: numbers.Integral
:type microsecond: numbers.Integral
:type tzinfo: _datetime.tzinfo | None
:rtype: _datetime.datetime
"""
return _datetime.datetime(0, 0, 0)
def astimezone(self, tz):
"""Return a datetime object with new tzinfo attribute tz, adjusting the
date and time data so the result is the same UTC time as self, but in
tz's local time.
:type tz: _datetime.tzinfo
:rtype: _datetime.datetime
"""
return _datetime.datetime(0, 0, 0)
def utcoffset(self):
"""If tzinfo is None, returns None, else returns
self.tzinfo.utcoffset(self).
:rtype: _datetime.timedelta | None
"""
return _datetime.timedelta()
def dst(self):
"""If tzinfo is None, returns None, else returns self.tzinfo.dst(self).
:rtype: _datetime.timedelta | None
"""
return _datetime.timedelta()
def tzname(self):
"""If tzinfo is None, returns None, else returns
self.tzinfo.tzname(self).
:rtype: string | None
"""
return str()
def timetuple(self):
"""Return a time.struct_time such as returned by time.localtime().
:rtype: struct_time
"""
return struct_time()
def utctimetuple(self):
"""If datetime instance d is naive, this is the same as d.timetuple()
except that tm_isdst is forced to 0 regardless of what d.dst() returns.
:rtype: struct_time
"""
return struct_time()
def toordinal(self):
"""Return the proleptic Gregorian ordinal of the date.
:rtype: int
"""
return 0
def weekday(self):
"""Return the day of the week as an integer, where Monday is 0 and
Sunday is 6.
:rtype: int
"""
return 0
def isoweekday(self):
"""Return the day of the week as an integer, where Monday is 1 and
Sunday is 7.
:rtype: int
"""
return 0
def isocalendar(self):
"""Return a 3-tuple, (ISO year, ISO week number, ISO weekday).
:rtype: (int, int, int)
"""
return (0, 0, 0)
def isoformat(self, sep='T'):
"""Return a string representing the date and time in ISO 8601 format.
:type sep: string
:rtype: string
"""
return str()
def ctime(self):
"""Return a string representing the date and time.
:rtype: string
"""
return str()
def strftime(self, format):
"""Return a string representing the date and time, controlled by an
explicit format string.
:type format: string
:rtype: string
"""
return str()
min = _datetime.datetime(0, 0, 0)
max = _datetime.datetime(0, 0, 0)
resoultion = _datetime.timedelta()
class time(object):
"""A time object represents a (local) time of day, independent of any
particular day, and subject to adjustment via a tzinfo object."""
def __init__(self, hour=0, minute=0, second=0, microsecond=0, tzinfo=None):
"""Create a time object.
:type hour: numbers.Integral
:type minute: numbers.Integral
:type second: numbers.Integral
:type microsecond: numbers.Integral
:type tzinfo: _datetime.tzinfo | None
"""
self.hour = hour
self.minute = minute
self.second = second
self.microsecond = microsecond
sefl.tzinfo = tzinfo
def replace(self, hour=None, minute=None, second=None, microsecond=None,
tzinfo=None):
"""Return a time with the same value, except for those attributes given
new values by whichever keyword arguments are specified.
:type hour: numbers.Integral
:type minute: numbers.Integral
:type second: numbers.Integral
:type microsecond: numbers.Integral
:type tzinfo: _datetime.tzinfo | None
:rtype: _datetime.time
"""
return _datetime.time()
def isoformat(self):
"""Return a string representing the time in ISO 8601 format.
:rtype: string
"""
return str()
def strftime(self, format):
"""Return a string representing the time, controlled by an explicit
format string.
:type format: string
:rtype: string
"""
return str()
def utcoffset(self):
"""If tzinfo is None, returns None, else returns
self.tzinfo.utcoffset(self).
:rtype: _datetime.timedelta | None
"""
return _datetime.timedelta()
def dst(self):
"""If tzinfo is None, returns None, else returns self.tzinfo.dst(self).
:rtype: _datetime.timedelta | None
"""
return _datetime.timedelta()
def tzname(self):
"""If tzinfo is None, returns None, else returns
self.tzinfo.tzname(self).
:rtype: string | None
"""
return str()
min = _datetime.time()
max = _datetime.time()
resoultion = _datetime.timedelta()
@@ -0,0 +1,82 @@
"""Skeleton for 'decimal' stdlib module."""
import decimal
def getcontext():
"""Returns this thread's context.
:rtype: decimal.Context
"""
return decimal.Context()
def setcontext(context):
"""Set this thread's context to context.
:type context: decimal.Context
:rtype: None
"""
pass
class Decimal(object):
"""Floating point class for decimal arithmetic."""
def __add__(self, other, context=None):
"""Returns self + other.
:type other: numbers.Number
:type context: decimal.Context | None
:rtype: decimal.Decimal
"""
return decimal.Decimal()
def __sub__(self, other, context=None):
"""Return self - other.
:type other: numbers.Number
:type context: decimal.Context | None
:rtype: decimal.Decimal
"""
return decimal.Decimal()
def __mul__(self, other, context=None):
"""Return self * other.
:type other: numbers.Number
:type context: decimal.Context | None
:rtype: decimal.Decimal
"""
return decimal.Decimal()
def __truediv__(self, other, context=None):
"""Return self / other.
:type other: numbers.Number
:type context: decimal.Context | None
:rtype: decimal.Decimal
"""
return decimal.Decimal()
def __floordiv__(self, other, context=None):
"""Return self // other.
:type other: numbers.Number
:type context: decimal.Context | None
:rtype: decimal.Decimal
"""
return decimal.Decimal()
def __pow__(self, other, modulo=None, context=None):
"""Return self ** other [ % modulo].
:type other: numbers.Number
:type modulo: numbers.Number
:type context: decimal.Context | None
:rtype: decimal.Decimal
"""
return decimal.Decimal()
@@ -0,0 +1,16 @@
"""Skeleton for 'functools' stdlib module."""
def reduce(function, sequence, initial=None):
"""Apply a function of two arguments cumulatively to the items of a
sequence, from left to right, so as to reduce the sequence to a single
value.
:type function: collections.Callable
:type sequence: collections.Iterable
:type initial: T
:rtype: T | unknown
"""
return initial
+622
View File
@@ -0,0 +1,622 @@
"""Skeleton for 'io' stdlib module."""
from __future__ import unicode_literals
import sys
import io
def open(file, mode='r', buffering=-1, encoding=None, errors=None, newline=None,
closefd=True, opener=None):
"""This is an alias for the builtin open() function.
:type file: string
:type mode: string
:type buffering: numbers.Integral
:type encoding: string | None
:type errors: string | None
:type newline: string | None
:type closefd: bool
:type opener: ((string, int) -> int) | None
:rtype: io.FileIO[bytes] | io.TextIOWrapper[unicode]
"""
pass
class IOBase(object):
"""The abstract base class for all I/O classes, acting on streams of
bytes.
:type closed: bool
"""
def __init__(self, *args, **kwargs):
"""Private constructor of IOBase.
:rtype: io.IOBase[T <= bytes | unicode]
"""
self.closed = False
def __iter__(self):
"""Iterate over lines.
:rtype: collections.Iterator[T]
"""
return []
def close(self):
"""Flush and close this stream.
:rtype: None
"""
pass
def fileno(self):
"""Return the underlying file descriptor (an integer) of the stream if
it exists.
:rtype: int
"""
return 0
def flush(self):
"""Flush the write buffers of the stream if applicable.
:rtype: None
"""
pass
def isatty(self):
"""Return True if the stream is interactive (i.e., connected to a
terminal/tty device).
:rtype: bool
"""
return False
def readable(self):
"""Return True if the stream can be read from.
:rtype: bool
"""
return False
def readline(self, limit=-1):
"""Read and return one line from the stream.
:type limit: numbers.Integral
:rtype: T
"""
pass
def readlines(self, hint=-1):
"""Read and return a list of lines from the stream.
:type hint: numbers.Integral
:rtype: list[T]
"""
return []
def seek(self, offset, whence=io.SEEK_SET):
"""Change the stream position to the given byte offset.
:type offset: numbers.Integral
:type whence: numbers.Integral
:rtype: None
"""
pass
def seekable(self):
"""Return True if the stream supports random access.
:rtype: bool
"""
return False
def tell(self):
"""Return the current stream position.
:rtype: int
"""
return 0
def truncate(self, size=None):
"""Resize the stream to the given size in bytes (or the current
position if size is not specified).
:type size: numbers.Integral | None
:rtype: None
"""
pass
def writable(self):
"""Return True if the stream supports writing.
:rtype: bool
"""
return False
def writelines(self, lines):
"""Write a list of lines to the stream.
:type lines: collections.Iterable[T]
:rtype: None
"""
pass
class RawIOBase(io.IOBase):
"""Base class for raw binary I/O."""
def __init__(self, *args, **kwargs):
"""Private constructor of RawIOBase.
:rtype: io.RawIOBase[bytes]
"""
pass
def read(self, n=1):
"""Read up to n bytes from the object and return them.
:type n: numbers.Integral
:rtype: bytes
"""
return b''
def readall(self):
"""Read and return all the bytes from the stream until EOF, using
multiple calls to the stream if necessary.
:rtype: bytes
"""
return b''
def readinto(self, b):
"""Read up to len(b) bytes into bytearray b and return the number of
bytes read.
:type b: bytearray
:rtype: int
"""
return 0
def write(self, b):
"""Write the given bytes or bytearray object, b, to the underlying raw
stream and return the number of bytes written.
:type b: bytes | bytearray
:rtype: int
"""
return 0
class BufferedIOBase(io.IOBase):
"""Base class for binary streams that support some kind of buffering."""
def __init__(self, *args, **kwargs):
"""Private constructor of BufferedIOBase.
:rtype: io.BufferedIOBase[bytes]
"""
pass
if sys.version_info >= (2, 7):
def detach(self):
"""Separate the underlying raw stream from the buffer and return
it.
:rtype: None
"""
pass
def read1(self, n=-1):
"""Read and return up to n bytes, with at most one call to the
underlying raw stream's read() method.
:type n: numbers.Integral
:rtype: bytes
"""
return b''
class FileIO(io.RawIOBase):
"""FileIO represents an OS-level file containing bytes data.
:type name: string
:type mode: string
:type closefd: bool
:type closed: bool
"""
def __init__(self, name, mode='r', closefd=True):
"""Create a FileIO object.
:type name: string
:type mode: string
:type closefd: bool
:rtype: io.FileIO[bytes]
"""
self.name = name
self.mode = mode
self.closefd = closefd
self.closed = False
pass
def __iter__(self):
"""Iterate over lines.
:rtype: collections.Iterator[bytes]
"""
return []
def close(self):
"""Flush and close this stream.
:rtype: None
"""
pass
def fileno(self):
"""Return the underlying file descriptor (an integer) of the stream if
it exists.
:rtype: int
"""
return 0
def flush(self):
"""Flush the write buffers of the stream if applicable.
:rtype: None
"""
pass
def isatty(self):
"""Return True if the stream is interactive (i.e., connected to a
terminal/tty device).
:rtype: bool
"""
return False
def readable(self):
"""Return True if the stream can be read from.
:rtype: bool
"""
return False
def readline(self, limit=-1):
"""Read and return one line from the stream.
:type limit: numbers.Integral
:rtype: bytes
"""
return b''
def readlines(self, hint=-1):
"""Read and return a list of lines from the stream.
:type hint: numbers.Integral
:rtype: list[bytes]
"""
return []
def seek(self, offset, whence=io.SEEK_SET):
"""Change the stream position to the given byte offset.
:type offset: numbers.Integral
:type whence: numbers.Integral
:rtype: None
"""
pass
def seekable(self):
"""Return True if the stream supports random access.
:rtype: bool
"""
return False
def tell(self):
"""Return the current stream position.
:rtype: int
"""
return 0
def truncate(self, size=None):
"""Resize the stream to the given size in bytes (or the current
position if size is not specified).
:type size: numbers.Integral | None
:rtype: None
"""
pass
def writable(self):
"""Return True if the stream supports writing.
:rtype: bool
"""
return False
def writelines(self, lines):
"""Write a list of lines to the stream.
:type lines: collections.Iterable[bytes]
:rtype: None
"""
pass
def read(self, n=1):
"""Read up to n bytes from the object and return them.
:type n: numbers.Integral
:rtype: bytes
"""
return b''
def readall(self):
"""Read and return all the bytes from the stream until EOF, using
multiple calls to the stream if necessary.
:rtype: bytes
"""
return b''
def readinto(self, b):
"""Read up to len(b) bytes into bytearray b and return the number of
bytes read.
:type b: bytearray
:rtype: int
"""
return 0
def write(self, b):
"""Write the given bytes or bytearray object, b, to the underlying raw
stream and return the number of bytes written.
:type b: bytes | bytearray
:rtype: int
"""
return 0
class BytesIO(io.BufferedIOBase):
"""A stream implementation using an in-memory bytes buffer."""
def __init__(self, initial_bytes=None):
"""Create a BytesIO object.
:rtype: io.BytesIO[bytes]
"""
pass
if sys.version_info >= (3, 2):
def getbuffer(self):
"""Return a readable and writable view over the contents of the
buffer without copying them.
:rtype: bytearray
"""
return bytearray()
def getvalue(self):
"""Return bytes containing the entire contents of the buffer.
:rtype: bytes
"""
return b''
class TextIOBase(io.IOBase):
"""Base class for text streams.
:type encoding: string
:type errors: string
:type newlines: string | tuple | None
:type buffer: BufferedIOBase
"""
def __init__(self, *args, **kwargs):
"""Private constructor of TextIOBase.
:rtype: TextIOBase[unicode]
"""
self.encoding = str()
self.errors = str()
self.newlines = None
self.buffer = BufferedIOBase()
if sys.version_info >= (2, 7):
def detach(self):
"""Separate the underlying raw stream from the buffer and return
it.
:rtype: None
"""
pass
def read(self, n=None):
"""Read and return at most n characters from the stream as a single
unicode.
:type n: numbers.Integral | None
:rtype: unicode
"""
return ''
def write(self, s):
"""Write the unicode string s to the stream and return the number of
characters written.
:type b: unicode
:rtype: int
"""
return 0
class TextIOWrapper(io.TextIOBase):
"""A buffered text stream over a BufferedIOBase binary stream.
:type buffer: io.BufferedIOBase
:type encoding: string
:type errors: string
:type newlines: string
:type line_buffering: bool
:type name: string
"""
def __init__(self, buffer, encoding=None, errors=None, newline=None,
line_buffering=False):
"""Creat a TextIOWrapper object.
:type buffer: io.BufferedIOBase
:type encoding: string | None
:type errors: string | None
:type newline: string | None
:type line_buffering: bool
:rtype: io.TextIOWrapper[unicode]
"""
self.name = ''
self.buffer = buffer
self.encoding = encoding
self.errors = errors
self.newlines = newline
self.line_buffering = line_buffering
def __iter__(self):
"""Iterate over lines.
:rtype: collections.Iterator[unicode]
"""
return []
def close(self):
"""Flush and close this stream.
:rtype: None
"""
pass
def fileno(self):
"""Return the underlying file descriptor (an integer) of the stream if
it exists.
:rtype: int
"""
return 0
def flush(self):
"""Flush the write buffers of the stream if applicable.
:rtype: None
"""
pass
def isatty(self):
"""Return True if the stream is interactive (i.e., connected to a
terminal/tty device).
:rtype: bool
"""
return False
def readable(self):
"""Return True if the stream can be read from.
:rtype: bool
"""
return False
def readline(self, limit=-1):
"""Read and return one line from the stream.
:type limit: numbers.Integral
:rtype: unicode
"""
pass
def readlines(self, hint=-1):
"""Read and return a list of lines from the stream.
:type hint: numbers.Integral
:rtype: list[unicode]
"""
return []
def seek(self, offset, whence=io.SEEK_SET):
"""Change the stream position to the given byte offset.
:type offset: numbers.Integral
:type whence: numbers.Integral
:rtype: None
"""
pass
def seekable(self):
"""Return True if the stream supports random access.
:rtype: bool
"""
return False
def tell(self):
"""Return the current stream position.
:rtype: int
"""
return 0
def truncate(self, size=None):
"""Resize the stream to the given size in bytes (or the current
position if size is not specified).
:type size: numbers.Integral | None
:rtype: None
"""
pass
def writable(self):
"""Return True if the stream supports writing.
:rtype: bool
"""
return False
def writelines(self, lines):
"""Write a list of lines to the stream.
:type lines: collections.Iterable[unicode]
:rtype: None
"""
pass
if sys.version_info >= (2, 7):
def detach(self):
"""Separate the underlying raw stream from the buffer and return
it.
:rtype: None
"""
pass
def read(self, n=None):
"""Read and return at most n characters from the stream as a single
unicode.
:type n: numbers.Integral | None
:rtype: unicode
"""
return ''
def write(self, s):
"""Write the unicode string s to the stream and return the number of
characters written.
:type b: unicode
:rtype: int
"""
return 0
@@ -0,0 +1,2 @@
# coding=utf-8
__author__ = 'Ilya.Kazakevich'
@@ -0,0 +1,68 @@
# coding=utf-8
"""
Lettuce terrain hooks: http://lettuce.it/reference/terrain.html
"""
__author__ = 'Ilya.Kazakevich'
class __When(object):
@staticmethod
def all(function):
"""
Runs before/after all features, scenarios and steps
"""
pass
@staticmethod
def each_step(function):
"""
Runs before/after each step
"""
pass
@staticmethod
def each_scenario(function):
"""
Runs before/after each scenario
"""
pass
@staticmethod
def each_background(function):
"""
Runs before/after each background
"""
pass
@staticmethod
def each_feature(function):
"""
Runs before/after each feature
"""
pass
@staticmethod
def each_app(function):
"""
Runs before/after each Django app.
"""
pass
@staticmethod
def runserver(function):
"""
Runs before/after lettuce starts up the built-in http server.
"""
pass
@staticmethod
def handle_request(function):
"""
Runs before/after lettuce’s built-in HTTP server responds to a request.
"""
pass
before = __When()
after = __When()
+381
View File
@@ -0,0 +1,381 @@
"""Skeleton for 'math' stdlib module."""
import sys
import math
def ceil(x):
"""Return the ceiling of x as a float, the smallest integer value greater
than or equal to x.
:type x: numbers.Real
:rtype: float
"""
return 0.0
if sys.version_info >= (2, 6):
def copysign(x, y):
"""Return x with the sign of y. On a platform that supports signed
zeros, copysign(1.0, -0.0) returns -1.0.
:type x: numbers.Real
:type y: numbers.Real
:rtype: float
"""
return 0.0
def fabs(x):
"""Return the absolute value of x.
:type x: numbers.Real
:rtype: float
"""
return 0.0
if sys.version_info >= (2, 6):
def factorial(x):
"""Return x factorial.
:type x: numbers.Integral
:rtype: int
"""
return 0
def floor(x):
"""Return the floor of x as a float, the largest integer value less than or
equal to x.
:type x: numbers.Real
:rtype: float
"""
return 0.0
def fmod(x, y):
"""Return fmod(x, y), as defined by the platform C library.
:type x: numbers.Real
:type y: numbers.Real
:rtype: float
"""
return 0.0
def frexp(x):
"""Return the mantissa and exponent of x as the pair (m, e).
:type x: numbers.Real
:rtype: (float, int)
"""
return 0.0, 0
if sys.version_info >= (2, 6):
def fsum(iterable):
"""Return an accurate floating point sum of values in the iterable.
:type iterable: collections.Iterable[numbers.Real]
:rtype: float
"""
return 0.0
def isinf(x):
"""Check if the float x is positive or negative infinity.
:type x: numbers.Real
:rtype: bool
"""
return False
def isnan(x):
"""Check if the float x is a NaN (not a number).
:type x: numbers.Real
:rtype: bool
"""
return False
def ldexp(x, i):
"""Return x * (2**i).
:type x: numbers.Real
:type i: numbers.Integral
:rtype: float
"""
return 0.0
def modf(x):
"""Return the fractional and integer parts of x.
:type x: numbers.Real
:rtype: (float, float)
"""
return 0.0, 0.0
if sys.version_info >= (2, 6):
def trunc(x):
"""Return the Real value x truncated to an Integral (usually a long
integer).
:type x: numbers.Real
:rtype: int
"""
return 0
def exp(x):
"""Return e**x.
:type x: numbers.Real
:rtype: float
"""
return 0.0
if sys.version_info >= (2, 7):
def expm1(x):
"""Return e**x - 1.
:type x: numbers.Real
:rtype: float
"""
return 0.0
def log(x, base=math.e):
"""With one argument, return the natural logarithm of x (to base e).
With two arguments, return the logarithm of x to the given base, calculated
as log(x)/log(base).
:type x: numbers.Real
:type base: numbers.Real
:rtype: float
"""
return 0.0
if sys.version_info >= (2, 6):
def log1p(x):
"""Return the natural logarithm of 1+x (base e).
:type x: numbers.Real
:rtype: float
"""
return 0.0
def log10(x):
"""Return the base-10 logarithm of x.
:type x: numbers.Real
:rtype: float
"""
return 0.0
def pow(x, y):
"""Return x raised to the power y.
:type x: numbers.Real
:type y: numbers.Real
:rtype: float
"""
return 0.0
def sqrt(x):
"""Return the square root of x.
:type x: numbers.Real
:rtype: float
"""
return 0.0
def acos(x):
"""Return the arc cosine of x, in radians.
:type x: numbers.Real
:rtype: float
"""
return 0.0
def asin(x):
"""Return the arc sine of x, in radians.
:type x: numbers.Real
:rtype: float
"""
return 0.0
def atan(x):
"""Return the arc tangent of x, in radians.
:type x: numbers.Real
:rtype: float
"""
return 0.0
def atan2(y, x):
"""Return atan(y / x), in radians.
:type y: numbers.Real
:type x: numbers.Real
:rtype: float
"""
return 0.0
def cos(x):
"""Return the cosine of x radians.
:type x: numbers.Real
:rtype: float
"""
return 0.0
def hypot(x, y):
"""Return the Euclidean norm, sqrt(x*x + y*y).
:type x: numbers.Real
:type y: numbers.Real
:rtype: float
"""
return 0.0
def sin(x):
"""Return the sine of x radians.
:type x: numbers.Real
:rtype: float
"""
return 0.0
def tan(x):
"""Return the tangent of x radians.
:type x: numbers.Real
:rtype: float
"""
return 0.0
def degrees(x):
"""Converts angle x from radians to degrees.
:type x: numbers.Real
:rtype: float
"""
return 0.0
def radians(x):
"""Converts angle x from degrees to radians.
:type x: numbers.Real
:rtype: float
"""
return 0.0
if sys.version_info >= (2, 6):
def acosh(x):
"""Return the inverse hyperbolic cosine of x.
:type x: numbers.Real
:rtype: float
"""
return 0.0
def asinh(x):
"""Return the inverse hyperbolic sine of x.
:type x: numbers.Real
:rtype: float
"""
return 0.0
def atanh(x):
"""Return the inverse hyperbolic tangent of x.
:type x: numbers.Real
:rtype: float
"""
return 0.0
def cosh(x):
"""Return the hyperbolic cosine of x.
:type x: numbers.Real
:rtype: float
"""
return 0.0
def sinh(x):
"""Return the hyperbolic sine of x.
:type x: numbers.Real
:rtype: float
"""
return 0.0
def tanh(x):
"""Return the hyperbolic tangent of x.
:type x: numbers.Real
:rtype: float
"""
return 0.0
if sys.version_info >= (2, 7):
def erf(x):
"""Return the error function at x.
:type x: numbers.Real
:rtype: float
"""
return 0.0
def erfc(x):
"""Return the complementary error function at x.
:type x: numbers.Real
:rtype: float
"""
return 0.0
def gamma(x):
"""Return the Gamma function at x.
:type x: numbers.Real
:rtype: float
"""
return 0.0
def lgamma(x):
"""Return the natural logarithm of the absolute value of the Gamma
function at x.
:type x: numbers.Real
:rtype: float
"""
return 0.0
@@ -0,0 +1,280 @@
"""Skeleton for 'multiprocessing' stdlib module."""
from multiprocessing.pool import Pool
class Process(object):
def __init__(self, group=None, target=None, name=None, args=(), kwargs={}):
self.name = ''
self.daemon = False
self.authkey = None
self.exitcode = None
self.ident = 0
self.pid = 0
self.sentinel = None
def run(self):
pass
def start(self):
pass
def terminate(self):
pass
def join(self, timeout=None):
pass
def is_alive(self):
return False
class ProcessError(Exception):
pass
class BufferTooShort(ProcessError):
pass
class AuthenticationError(ProcessError):
pass
class TimeoutError(ProcessError):
pass
class Connection(object):
def send(self, obj):
pass
def recv(self):
pass
def fileno(self):
return 0
def close(self):
pass
def poll(self, timeout=None):
pass
def send_bytes(self, buffer, offset=-1, size=-1):
pass
def recv_bytes(self, maxlength=-1):
pass
def recv_bytes_into(self, buffer, offset=-1):
pass
def __enter__(self):
pass
def __exit__(self, exc_type, exc_val, exc_tb):
pass
def Pipe(duplex=True):
return Connection(), Connection()
class Queue(object):
def __init__(self, maxsize=-1):
self._maxsize = maxsize
def qsize(self):
return 0
def empty(self):
return False
def full(self):
return False
def put(self, obj, block=True, timeout=None):
pass
def put_nowait(self, obj):
pass
def get(self, block=True, timeout=None):
pass
def get_nowait(self):
pass
def close(self):
pass
def join_thread(self):
pass
def cancel_join_thread(self):
pass
class SimpleQueue(object):
def empty(self):
return False
def get(self):
pass
def put(self, item):
pass
class JoinableQueue(multiprocessing.Queue):
def task_done(self):
pass
def join(self):
pass
def active_childern():
"""
:rtype: list[multiprocessing.Process]
"""
return []
def cpu_count():
return 0
def current_process():
"""
:rtype: multiprocessing.Process
"""
return Process()
def freeze_support():
pass
def get_all_start_methods():
return []
def get_context(method=None):
pass
def get_start_method(allow_none=False):
pass
def set_executable(path):
pass
def set_start_method(method):
pass
class Barrier(object):
def __init__(self, parties, action=None, timeout=None):
self.parties = parties
self.n_waiting = 0
self.broken = False
def wait(self, timeout=None):
pass
def reset(self):
pass
def abort(self):
pass
class Semaphore(object):
def __init__(self, value=1):
pass
def acquire(self, blocking=True, timeout=None):
pass
def release(self):
pass
class BoundedSemaphore(multiprocessing.Semaphore):
pass
class Condition(object):
def __init__(self, lock=None):
pass
def acquire(self, *args):
pass
def release(self):
pass
def wait(self, timeout=None):
pass
def wait_for(self, predicate, timeout=None):
pass
def notify(self, n=1):
pass
def notify_all(self):
pass
class Event(object):
def is_set(self):
return False
def set(self):
pass
def clear(self):
pass
def wait(self, timeout=None):
pass
class Lock(object):
def acquire(self, blocking=True, timeout=-1):
pass
def release(self):
pass
class RLock(object):
def acquire(self, blocking=True, timeout=-1):
pass
def release(self):
pass
def __enter__(self):
pass
def __exit__(self, exc_type, exc_val, exc_tb):
pass
def Value(typecode_or_type, *args, **kwargs):
pass
def Array(typecode_or_type, size_or_initializer, lock=True):
pass
def Manager():
return multiprocessing.SyncManager()
@@ -0,0 +1,76 @@
"""Skeleton for 'multiprocessing.managers' stdlib module."""
import threading
import queue
import multiprocessing
import multiprocessing.managers
class BaseManager(object):
def __init__(self, address=None, authkey=None):
self.address = address
def start(self, initializer=None, initargs=None):
pass
def get_server(self):
pass
def connect(self):
pass
def shutdown(self):
pass
@classmethod
def register(cls, typeid, callable=None, proxytype=None, exposed=None,
method_to_typeid=None, create_method=None):
pass
def __enter__(self):
pass
def __exit__(self, exc_type, exc_val, exc_tb):
pass
class SyncManager(multiprocessing.managers.BaseManager):
def Barrier(self, parties, action=None, timeout=None):
return threading.Barrier(parties, action, timeout)
def BoundedSemaphore(self, value=None):
return threading.BoundedSemaphore(value)
def Condition(self, lock=None):
return threading.Condition(lock)
def Event(self):
return threading.Event()
def Lock(self):
return threading.Lock()
def Namespace(self):
pass
def Queue(self, maxsize=None):
return queue.Queue()
def RLock(self):
return threading.RLock()
def Semaphore(self, value=None):
return threading.Semaphore(value)
def Array(self, typecode, sequence):
pass
def Value(self, typecode, value):
pass
def dict(self, mapping_or_sequence):
pass
def list(self, sequence):
pass
@@ -0,0 +1,5 @@
"""Skeleton for 'nose' module.
Project: nose 1.3 <https://nose.readthedocs.org/>
Skeleton by: Andrey Vlasovskikh <andrey.vlasovskikh@jetbrains.com>
"""
@@ -0,0 +1,181 @@
"""Skeleton for 'nose.tools' module.
Project: nose 1.3 <https://nose.readthedocs.org/>
Skeleton by: Andrey Vlasovskikh <andrey.vlasovskikh@jetbrains.com>
"""
import sys
def assert_equal(first, second, msg=None):
"""Fail if the two objects are unequal as determined by the '==' operator.
"""
pass
def assert_not_equal(first, second, msg=None):
"""Fail if the two objects are equal as determined by the '==' operator.
"""
pass
def assert_true(expr, msg=None):
"""Check that the expression is true."""
pass
def assert_false(expr, msg=None):
"""Check that the expression is false."""
pass
if sys.version_info >= (2, 7):
def assert_is(expr1, expr2, msg=None):
"""Just like assert_true(a is b), but with a nicer default message."""
pass
def assert_is_not(expr1, expr2, msg=None):
"""Just like assert_true(a is not b), but with a nicer default message.
"""
pass
def assert_is_none(obj, msg=None):
"""Same as assert_true(obj is None), with a nicer default message.
"""
pass
def assert_is_not_none(obj, msg=None):
"""Included for symmetry with assert_is_none."""
pass
def assert_in(member, container, msg=None):
"""Just like assert_true(a in b), but with a nicer default message."""
pass
def assert_not_in(member, container, msg=None):
"""Just like assert_true(a not in b), but with a nicer default message.
"""
pass
def assert_is_instance(obj, cls, msg=None):
"""Same as assert_true(isinstance(obj, cls)), with a nicer default
message.
"""
pass
def assert_not_is_instance(obj, cls, msg=None):
"""Included for symmetry with assert_is_instance."""
pass
def assert_raises(excClass, callableObj=None, *args, **kwargs):
"""Fail unless an exception of class excClass is thrown by callableObj when
invoked with arguments args and keyword arguments kwargs.
If called with callableObj omitted or None, will return a
context object used like this::
with assert_raises(SomeException):
do_something()
:rtype: unittest.case._AssertRaisesContext | None
"""
pass
if sys.version_info >= (2, 7):
def assert_raises_regexp(expected_exception, expected_regexp,
callable_obj=None, *args, **kwargs):
"""Asserts that the message in a raised exception matches a regexp.
:rtype: unittest.case._AssertRaisesContext | None
"""
pass
def assert_almost_equal(first, second, places=None, msg=None, delta=None):
"""Fail if the two objects are unequal as determined by their difference
rounded to the given number of decimal places (default 7) and comparing to
zero, or by comparing that the between the two objects is more than the
given delta.
"""
pass
def assert_not_almost_equal(first, second, places=None, msg=None, delta=None):
"""Fail if the two objects are equal as determined by their difference
rounded to the given number of decimal places (default 7) and comparing to
zero, or by comparing that the between the two objects is less than the
given delta.
"""
pass
if sys.version_info >= (2, 7):
def assert_greater(a, b, msg=None):
"""Just like assert_true(a > b), but with a nicer default message."""
pass
def assert_greater_equal(a, b, msg=None):
"""Just like assert_true(a >= b), but with a nicer default message."""
pass
def assert_less(a, b, msg=None):
"""Just like assert_true(a < b), but with a nicer default message."""
pass
def assert_less_equal(a, b, msg=None):
"""Just like self.assertTrue(a <= b), but with a nicer default
message.
"""
pass
def assert_regexp_matches(text, expected_regexp, msg=None):
"""Fail the test unless the text matches the regular expression."""
pass
def assert_not_regexp_matches(text, unexpected_regexp, msg=None):
"""Fail the test if the text matches the regular expression."""
pass
def assert_items_equal(expected_seq, actual_seq, msg=None):
"""An unordered sequence specific comparison. It asserts that
actual_seq and expected_seq have the same element counts.
"""
pass
def assert_dict_contains_subset(expected, actual, msg=None):
"""Checks whether actual is a superset of expected."""
pass
def assert_multi_line_equal(first, second, msg=None):
"""Assert that two multi-line strings are equal."""
pass
def assert_sequence_equal(seq1, seq2, msg=None, seq_type=None):
"""An equality assertion for ordered sequences (like lists and tuples).
"""
pass
def assert_list_equal(list1, list2, msg=None):
"""A list-specific equality assertion."""
pass
def assert_tuple_equal(tuple1, tuple2, msg=None):
"""A tuple-specific equality assertion."""
pass
def assert_set_equal(set1, set2, msg=None):
"""A set-specific equality assertion."""
pass
def assert_dict_equal(d1, d2, msg=None):
"""A dict-specific equality assertion."""
pass
assert_equals = assert_equal
assert_not_equals = assert_not_equal
assert_almost_equals = assert_almost_equal
assert_not_almost_equals = assert_not_almost_equal
@@ -0,0 +1,10 @@
"""Skeleton for 'numpy' module.
Project: NumPy 1.8.0 <http://www.numpy.org//>
"""
from . import core
from .core import *
__all__ = []
__all__.extend(core.__all__)
@@ -0,0 +1,3 @@
from . import multiarray
__all__ = []
@@ -0,0 +1,202 @@
class ndarray(object):
"""
ndarray(shape, dtype=float, buffer=None, offset=0,
strides=None, order=None)
An array object represents a multidimensional, homogeneous array
of fixed-size items. An associated data-type object describes the
format of each element in the array (its byte-order, how many bytes it
occupies in memory, whether it is an integer, a floating point number,
or something else, etc.)
Arrays should be constructed using `array`, `zeros` or `empty` (refer
to the See Also section below). The parameters given here refer to
a low-level method (`ndarray(...)`) for instantiating an array.
For more information, refer to the `numpy` module and examine the
the methods and attributes of an array.
Parameters
----------
(for the __new__ method; see Notes below)
shape : tuple of ints
Shape of created array.
dtype : data-type, optional
Any object that can be interpreted as a numpy data type.
buffer : object exposing buffer interface, optional
Used to fill the array with data.
offset : int, optional
Offset of array data in buffer.
strides : tuple of ints, optional
Strides of data in memory.
order : {'C', 'F'}, optional
Row-major or column-major order.
Attributes
----------
T : ndarray
Transpose of the array.
data : buffer
The array's elements, in memory.
dtype : dtype object
Describes the format of the elements in the array.
flags : dict
Dictionary containing information related to memory use, e.g.,
'C_CONTIGUOUS', 'OWNDATA', 'WRITEABLE', etc.
flat : numpy.flatiter object
Flattened version of the array as an iterator. The iterator
allows assignments, e.g., ``x.flat = 3`` (See `ndarray.flat` for
assignment examples; TODO).
imag : ndarray
Imaginary part of the array.
real : ndarray
Real part of the array.
size : int
Number of elements in the array.
itemsize : int
The memory use of each array element in bytes.
nbytes : int
The total number of bytes required to store the array data,
i.e., ``itemsize * size``.
ndim : int
The array's number of dimensions.
shape : tuple of ints
Shape of the array.
strides : tuple of ints
The step-size required to move from one element to the next in
memory. For example, a contiguous ``(3, 4)`` array of type
``int16`` in C-order has strides ``(8, 2)``. This implies that
to move from element to element in memory requires jumps of 2 bytes.
To move from row-to-row, one needs to jump 8 bytes at a time
(``2 * 4``).
ctypes : ctypes object
Class containing properties of the array needed for interaction
with ctypes.
base : ndarray
If the array is a view into another array, that array is its `base`
(unless that array is also a view). The `base` array is where the
array data is actually stored.
See Also
--------
array : Construct an array.
zeros : Create an array, each element of which is zero.
empty : Create an array, but leave its allocated memory unchanged (i.e.,
it contains "garbage").
dtype : Create a data-type.
Notes
-----
There are two modes of creating an array using ``__new__``:
1. If `buffer` is None, then only `shape`, `dtype`, and `order`
are used.
2. If `buffer` is an object exposing the buffer interface, then
all keywords are interpreted.
No ``__init__`` method is needed because the array is fully initialized
after the ``__new__`` method.
Examples
--------
These examples illustrate the low-level `ndarray` constructor. Refer
to the `See Also` section above for easier ways of constructing an
ndarray.
First mode, `buffer` is None:
>>> np.ndarray(shape=(2,2), dtype=float, order='F')
array([[ -1.13698227e+002, 4.25087011e-303],
[ 2.88528414e-306, 3.27025015e-309]]) #random
Second mode:
>>> np.ndarray((2,), buffer=np.array([1,2,3]),
... offset=np.int_().itemsize,
... dtype=int) # offset = 1*itemsize, i.e. skip first element
array([2, 3])
"""
pass
def __mul__(self, y): # real signature unknown; restored from __doc__
"""
x.__mul__(y) <==> x*y
Returns
-------
out : ndarray
"""
pass
def __rmul__(self, y): # real signature unknown; restored from __doc__
"""
x.__rmul__(y) <==> x*y
Returns
-------
out : ndarray
"""
pass
def __abs__(self): # real signature unknown; restored from __doc__
"""
x.__abs__() <==> abs(x)
Returns
-------
out : ndarray
"""
pass
def __add__(self, y): # real signature unknown; restored from __doc__
"""
x.__add__(y) <==> x+y
Returns
-------
out : ndarray
"""
pass
def __copy__(self, order=None): # real signature unknown; restored from __doc__
"""
a.__copy__([order])
Return a copy of the array.
Parameters
----------
order : {'C', 'F', 'A'}, optional
If order is 'C' (False) then the result is contiguous (default).
If order is 'Fortran' (True) then the result has fortran order.
If order is 'Any' (None) then the result has fortran order
only if the array already is in fortran order.
Returns
-------
out : ndarray
"""
pass
def __div__(self, y): # real signature unknown; restored from __doc__
"""
x.__div__(y) <==> x/y
Returns
-------
out : ndarray
"""
pass
def __sub__(self, y): # real signature unknown; restored from __doc__
"""
x.__sub__(y) <==> x-y
Returns
-------
out : ndarray
"""
pass
File diff suppressed because it is too large Load Diff
+293
View File
@@ -0,0 +1,293 @@
"""Skeleton for 'os.path' stdlib module."""
import sys
import os
def abspath(path):
"""Return a normalized absolutized version of the pathname path.
:type path: T <= bytes | unicode
:rtype: T
"""
return path
def basename(path):
"""Return the base name of pathname path.
:type path: T <= bytes | unicode
:rtype: T
"""
return path
def commonprefix(list):
"""Return the longest path prefix (taken character-by-character) that is a
prefix of all paths in list.
:type list: collections.Iterable[T <= bytes | unicode]
:rtype T
"""
pass
def dirname(path):
"""Return the directory name of pathname path.
:type path: T <= bytes | unicode
:rtype: T
"""
return path
def exists(path):
"""Return True if path refers to an existing path. Returns False for broken
symbolic links.
:type path: bytes | unicode
:rtype: bool
"""
return False
def lexists(path):
"""Return True if path refers to an existing path. Returns True for broken
symbolic links.
:type path: bytes | unicode
:rtype: bool
"""
return False
def expanduser(path):
"""On Unix and Windows, return the argument with an initial component of ~
or ~user replaced by that user's home directory.
:type path: T <= bytes | unicode
:rtype: T
"""
return path
def expandvars(path):
"""Return the argument with environment variables expanded.
:type path: T <= bytes | unicode
:rtype: T
"""
return path
def getatime(path):
"""Return the time of last access of path.
:type path: bytes | unicode
:rtype: float
"""
return 0.0
def getmtime(path):
"""Return the time of last modification of path.
:type path: bytes | unicode
:rtype: float
"""
return 0.0
def getctime(path):
"""Return the system's ctime.
:type path: bytes | unicode
:rtype: float
"""
return 0.0
def getsize(path):
"""Return the size, in bytes, of path.
:type path: bytes | unicode
:rtype: int
"""
return 0
def isabs(path):
"""Return True if path is an absolute pathname.
:type path: bytes | unicode
:rtype: bool
"""
return False
def isfile(path):
"""Return True if path is an existing regular file.
:type path: bytes | unicode
:rtype: bool
"""
return False
def isdir(path):
"""Return True if path is an existing directory.
:type path: bytes | unicode
:rtype: bool
"""
return False
def islink(path):
"""Return True if path refers to a directory entry that is a symbolic link.
:type path: bytes | unicode
:rtype: bool
"""
return False
def ismount(path):
"""Return True if pathname path is a mount point: a point in a file system
where a different file system has been mounted.
:type path: bytes | unicode
:rtype: bool
"""
return False
def join(path, *paths):
"""Join one or more path components intelligently.
:type path: T <= bytes | unicode
:type paths: collections.Iterable[T]
:rtype: T
"""
return path
def normcase(path):
"""Normalize the case of a pathname.
:type path: T <= bytes | unicode
:rtype: T
"""
return path
def normpath(path):
"""Normalize a pathname by collapsing redundant separators and up-level
references.
:type path: T <= bytes | unicode
:rtype: T
"""
return path
def realpath(path):
"""Return the canonical path of the specified filename, eliminating any
symbolic links encountered in the path.
:type path: T <= bytes | unicode
:rtype: T
"""
return path
def relpath(path, start=os.curdir):
"""Return a relative filepath to path either from the current directory or
from an optional start directory.
:type path: T <= bytes | unicode
:type start: T
:rtype: T
"""
return path
def samefile(path1, path2):
"""Return True if both pathname arguments refer to the same file or
directory.
:type path1: bytes | unicode
:type path2: bytes | unicode
:rtype: bool
"""
return False
def sameopenfile(fp1, fp2):
"""Return True if the file descriptors fp1 and fp2 refer to the same file.
:type fp1: int
:type fp2: int
:rtype: bool
"""
return False
def samestat(stat1, stat2):
"""Return True if the stat tuples stat1 and stat2 refer to the same file.
:type stat1: os.stat_result | tuple
:type stat2: os.stat_result | tuple
:rtype: bool
"""
return False
def split(path):
"""Split the pathname path into a pair, (head, tail).
:type path: T <= bytes | unicode
:rtype: (T, T)
"""
return path, path
def splitdrive(path):
"""Split the pathname path into a pair (drive, tail).
:type path: T <= bytes | unicode
:rtype: (T, T)
"""
return path, path
def splitext(path):
"""Split the pathname path into a pair (root, ext).
:type path: T <= bytes | unicode
:rtype: (T, T)
"""
return path, path
def splitunc(path):
"""Split the pathname path into a pair (unc, rest).
:type path: T <= bytes | unicode
:rtype: (T, T)
"""
return path, path
if sys.version_info < (3, 0):
def walk(path, visit, arg):
"""Calls the function visit with arguments (arg, dirname, names) for
each directory in the directory tree rooted at path.
:type path: T <= bytes | unicode
:type visit: (V, T, list[T]) -> None
:type arg: V
:rtype: None
"""
pass
+373
View File
@@ -0,0 +1,373 @@
"""Skeleton for 'pathlib' stdlib module."""
import pathlib
class PurePath(object):
def __new__(cls, *pathsegments):
"""
:rtype: pathlib.PurePath
"""
return cls.__new__(*pathsegments)
def __truediv__(self, key):
"""
:type key: string | pathlib.PurePath
:rtype: pathlib.PurePath
"""
return pathlib.PurePath()
def __rtruediv__(self, key):
"""
:type key: string | pathlib.PurePath
:rtype: pathlib.PurePath
"""
return pathlib.PurePath()
@property
def parts(self):
"""
:rtype: tuple[str]
"""
return ()
@property
def drive(self):
"""
:rtype: str
"""
return ''
@property
def root(self):
"""
:rtype: str
"""
return ''
@property
def anchor(self):
"""
:rtype: str
"""
return ''
@property
def parent(self):
"""
:rtype: pathlib.PurePath | unknown
"""
return pathlib.PurePath()
@property
def name(self):
"""
:rtype: str
"""
return ''
@property
def suffix(self):
"""
:rtype: str
"""
return ''
@property
def suffixes(self):
"""
:rtype: list[str]
"""
return []
@property
def stem(self):
"""
:rtype: str
"""
return ''
def as_posix(self):
"""
:rtype: str
"""
return ''
def as_uri(self):
"""
:rtype: str
"""
return ''
def is_absolute(self):
"""
:rtype: bool
"""
return False
def is_reserved(self):
"""
:rtype: bool
"""
return False
def joinpath(self, *other):
"""
:rtype: pathlib.PurePath
"""
return pathlib.PurePath()
def match(self, pattern):
"""
:type pattern: string
:rtype: bool
"""
return False
def relative_to(self, *other):
"""
:rtype: pathlib.PurePath
"""
return pathlib.PurePath()
class PurePosixPath(pathlib.PurePath):
pass
class PureWindowsPath(pathlib.PurePath):
pass
class Path(pathlib.PurePath):
def __new__(cls, *pathsegments):
"""
:rtype: pathlib.Path
"""
return cls.__new__(*pathsegments)
def __truediv__(self, key):
"""
:type key: string | pathlib.Path
:rtype: pathlib.Path
"""
return pathlib.Path()
def __rtruediv__(self, key):
"""
:type key: string | pathlib.Path
:rtype: pathlib.Path
"""
return pathlib.Path()
@property
def parents(self):
"""
:rtype: collections.Sequence[pathlib.Path]
"""
return []
@property
def parent(self):
"""
:rtype: pathlib.Path
"""
return pathlib.Path()
def joinpath(self, *other):
"""
:rtype: pathlib.Path
"""
return pathlib.Path()
def relative_to(self, *other):
"""
:rtype: pathlib.Path
"""
return pathlib.Path()
@classmethod
def cwd(cls):
"""
:rtype: pathlib.Path
"""
return pathlib.Path()
def stat(self):
"""
:rtype: os.stat_result
"""
pass
def chmod(self, mode):
"""
:rtype mode: int
:rtype: None
"""
pass
def exists(self):
"""
:rtype: bool
"""
return False
def glob(self, pattern):
"""
:type pattern: string
:rtype: collections.Iterable[pathlib.Path]
"""
return []
def group(self):
"""
:rtype: str
"""
return ''
def is_dir(self):
"""
:rtype: bool
"""
return False
def is_file(self):
"""
:rtype: bool
"""
return False
def is_file(self):
"""
:rtype: bool
"""
return False
def is_symlink(self):
"""
:rtype: bool
"""
return False
def is_socket(self):
"""
:rtype: bool
"""
return False
def is_fifo(self):
"""
:rtype: bool
"""
return False
def is_block_device(self):
"""
:rtype: bool
"""
return False
def is_char_device(self):
"""
:rtype: bool
"""
return False
def iterdir(self):
"""
:rtype: collections.Iterable[pathlib.Path]
"""
return []
def lchmod(self, mode):
"""
:rtype mode: int
:rtype: None
"""
pass
def lstat(self):
"""
:rtype: os.stat_result
"""
pass
def mkdir(self, mode=0o777, parents=False):
"""
:type mode: int
:type parents: bool
:rtype: None
"""
pass
def open(self, mode='r', buffering=-1, encoding=None, errors=None,
newline=None):
"""
:type mode: string
:type buffering: numbers.Integral
:type encoding: string | None
:type errors: string | None
:type newline: string | None
:rtype: io.FileIO[bytes] | io.TextIOWrapper[unicode]
"""
pass
def owner(self):
"""
:rtype: str
"""
return ''
def rename(self, target):
"""
:type target: string | pathlib.Path
:rtype: None
"""
pass
def replace(self, target):
"""
:type target: string | pathlib.Path
:rtype: None
"""
pass
def resolve(self):
"""
:rtype: pathlib.Path
"""
return pathlib.Path()
def rglob(self, pattern):
"""
:type pattern: string
:rtype: collections.Iterable[pathlib.Path]
"""
return []
def rmdir(self):
"""
:rtype: None
"""
pass
def symlink_to(self, target, target_is_directory=False):
"""
:type target: string | pathlib.Path
:type target_is_directory: bool
:rtype: None
"""
pass
def touch(self, mode=0o777, exist_ok=True):
"""
:type mode: int
:type exist_ok: bool
:rtype: None
"""
pass
def unlink(self):
"""
:rtype: None
"""
pass
+81
View File
@@ -0,0 +1,81 @@
"""Skeleton for 'pickle' stdlib module."""
HIGHEST_PROTOCOL = 0
DEFAULT_PROTOCOL = 0
def dump(obj, file, protocol=None, fix_imports=True):
"""Write a pickled representation of obj to the open file object file.
:type protocol: numbers.Integral | None
:rtype: None
"""
pass
def dumps(obj, protocol=None, fix_imports=True):
"""Return the pickled representation of the object as a bytes object,
instead of writing it to a file.
:type protocol: numbers.Integral | None
:rtype: bytes
"""
return b''
def load(file, fix_imports=True, encoding='ASCII', errors='strict'):
"""Read a pickled object representation from the open file object file and
return the reconstituted object hierarchy specified therein.
"""
pass
def loads(bytes_object, fix_imports=True, encoding='ASCII', errors='strict'):
"""Read a pickled object representation from the open file object file and
return the reconstituted object hierarchy specified therein.
"""
pass
class PickleError(Exception):
pass
class PicklingError(PickleError):
pass
class UnpicklingError(PickleError):
pass
class Pickler(object):
"""This takes a binary file for writing a pickle data stream."""
def __init__(self, file, protocol=None, fix_imports=True):
self.dispatch_table = None
self.fast = False
def dump(self, obj):
pass
def persistent_id(self, obj):
pass
class Unpickler(object):
"""This takes a binary file for reading a pickle data stream."""
def __init__(self, file, fix_imports=True, encoding='ASCII',
errors='strict'):
pass
def load(self):
pass
def persistent_load(self, pid):
pass
def find_class(self, module, name):
pass
+277
View File
@@ -0,0 +1,277 @@
"""Skeleton for 're' stdlib module."""
def compile(pattern, flags=0):
"""Compile a regular expression pattern, returning a pattern object.
:type pattern: bytes | unicode
:type flags: int
:rtype: __Regex
"""
pass
def search(pattern, string, flags=0):
"""Scan through string looking for a match, and return a corresponding
match instance. Return None if no position in the string matches.
:type pattern: bytes | unicode | __Regex
:type string: T <= bytes | unicode
:type flags: int
:rtype: __Match[T] | None
"""
pass
def match(pattern, string, flags=0):
"""Matches zero or more characters at the beginning of the string.
:type pattern: bytes | unicode | __Regex
:type string: T <= bytes | unicode
:type flags: int
:rtype: __Match[T] | None
"""
pass
def split(pattern, string, maxsplit=0, flags=0):
"""Split string by the occurrences of pattern.
:type pattern: bytes | unicode | __Regex
:type string: T <= bytes | unicode
:type maxsplit: int
:type flags: int
:rtype: list[T]
"""
pass
def findall(pattern, string, flags=0):
"""Return a list of all non-overlapping matches of pattern in string.
:type pattern: bytes | unicode | __Regex
:type string: T <= bytes | unicode
:type flags: int
:rtype: list[T]
"""
pass
def finditer(pattern, string, flags=0):
"""Return an iterator over all non-overlapping matches for the pattern in
string. For each match, the iterator returns a match object.
:type pattern: bytes | unicode | __Regex
:type string: T <= bytes | unicode
:type flags: int
:rtype: collections.Iterable[__Match[T]]
"""
pass
def sub(pattern, repl, string, count=0, flags=0):
"""Return the string obtained by replacing the leftmost non-overlapping
occurrences of pattern in string by the replacement repl.
:type pattern: bytes | unicode | __Regex
:type repl: bytes | unicode | collections.Callable
:type string: T <= bytes | unicode
:type count: int
:type flags: int
:rtype: T
"""
pass
def subn(pattern, repl, string, count=0, flags=0):
"""Return the tuple (new_string, number_of_subs_made) found by replacing
the leftmost non-overlapping occurrences of pattern with the
replacement repl.
:type pattern: bytes | unicode | __Regex
:type repl: bytes | unicode | collections.Callable
:type string: T <= bytes | unicode
:type count: int
:type flags: int
:rtype: (T, int)
"""
pass
def escape(string):
"""Escape all the characters in pattern except ASCII letters and numbers.
:type string: T <= bytes | unicode
:type: T
"""
pass
class __Regex(object):
"""Mock class for a regular expression pattern object."""
def __init__(self, flags, groups, groupindex, pattern):
"""Create a new pattern object.
:type flags: int
:type groups: int
:type groupindex: dict[bytes | unicode, int]
:type pattern: bytes | unicode
"""
self.flags = flags
self.groups = groups
self.groupindex = groupindex
self.pattern = pattern
def search(self, string, pos=0, endpos=-1):
"""Scan through string looking for a match, and return a corresponding
match instance. Return None if no position in the string matches.
:type string: T <= bytes | unicode
:type pos: int
:type endpos: int
:rtype: __Match[T] | None
"""
pass
def match(self, string, pos=0, endpos=-1):
"""Matches zero | more characters at the beginning of the string.
:type string: T <= bytes | unicode
:type pos: int
:type endpos: int
:rtype: __Match[T] | None
"""
pass
def split(self, string, maxsplit=0):
"""Split string by the occurrences of pattern.
:type string: T <= bytes | unicode
:type maxsplit: int
:rtype: list[T]
"""
pass
def findall(self, string, pos=0, endpos=-1):
"""Return a list of all non-overlapping matches of pattern in string.
:type string: T <= bytes | unicode
:type pos: int
:type endpos: int
:rtype: list[T]
"""
pass
def finditer(self, string, pos=0, endpos=-1):
"""Return an iterator over all non-overlapping matches for the
pattern in string. For each match, the iterator returns a
match object.
:type string: T <= bytes | unicode
:type pos: int
:type endpos: int
:rtype: collections.Iterable[__Match[T]]
"""
pass
def sub(self, repl, string, count=0):
"""Return the string obtained by replacing the leftmost non-overlapping
occurrences of pattern in string by the replacement repl.
:type repl: bytes | unicode | collections.Callable
:type string: T <= bytes | unicode
:type count: int
:rtype: T
"""
pass
def subn(self, repl, string, count=0):
"""Return the tuple (new_string, number_of_subs_made) found by replacing
the leftmost non-overlapping occurrences of pattern with the
replacement repl.
:type repl: bytes | unicode | collections.Callable
:type string: T <= bytes | unicode
:type count: int
:rtype: (T, int)
"""
pass
class __Match(object):
"""Mock class for a match object."""
def __init__(self, pos, endpos, lastindex, lastgroup, re, string):
"""Create a new match object.
:type pos: int
:type endpos: int
:type lastindex: int | None
:type lastgroup: int | bytes | unicode | None
:type re: __Regex
:type string: bytes | unicode
:rtype: __Match[T]
"""
self.pos = pos
self.endpos = endpos
self.lastindex = lastindex
self.lastgroup = lastgroup
self.re = re
self.string = string
def expand(self, template):
"""Return the string obtained by doing backslash substitution on the
template string template.
:type template: T
:rtype: T
"""
pass
def group(self, *args):
"""Return one or more subgroups of the match.
:rtype: T | tuple
"""
pass
def groups(self, default=None):
"""Return a tuple containing all the subgroups of the match, from 1 up
to however many groups are in the pattern.
:rtype: tuple
"""
pass
def groupdict(self, default=None):
"""Return a dictionary containing all the named subgroups of the match,
keyed by the subgroup name.
:rtype: dict[bytes | unicode, T]
"""
pass
def start(self, group=0):
"""Return the index of the start of the substring matched by group.
:type group: int | bytes | unicode
:rtype: int
"""
pass
def end(self, group=0):
"""Return the index of the end of the substring matched by group.
:type group: int | bytes | unicode
:rtype: int
"""
pass
def span(self, group=0):
"""Return a 2-tuple (start, end) for the substring matched by group.
:type group: int | bytes | unicode
:rtype: (int, int)
"""
pass
+99
View File
@@ -0,0 +1,99 @@
"""Skeleton for 'shutil' stdlib module."""
import sys
def copyfile(src, dst):
"""Copy the contents (no metadata) of the file named src to a file named
dst.
:type src: bytes | unicode
:type dst: bytes | unicode
:rtype: None
"""
pass
def copymode(src, dst):
"""Copy the permission bits from src to dst.
:type src: bytes | unicode
:type dst: bytes | unicode
:rtype: None
"""
pass
def copystat(src, dst):
"""Copy the permission bits, last access time, last modification time, and
flags from src to dst.
:type src: bytes | unicode
:type dst: bytes | unicode
:rtype: None
"""
pass
def copy(src, dst):
"""Copy the file src to the file or directory dst.
:type src: bytes | unicode
:type dst: bytes | unicode
:rtype: None
"""
pass
def copy2(src, dst):
"""Similar to shutil.copy(), but metadata is copied as well.
:type src: bytes | unicode
:type dst: bytes | unicode
:rtype: None
"""
pass
def ignore_patterns(*patterns):
"""This factory function creates a function that can be used as a callable
for copytree()'s ignore argument, ignoring files and directories that match
one of the glob-style patterns provided.
:type patterns: collections.Iterable[bytes | unicode]
:rtype: (bytes | unicode, list[bytes | unicode]) -> collections.Iterable[bytes | unicode]
"""
return lambda path, files: []
def copytree(src, dst, symlinks=False, ignore=None):
"""Recursively copy an entire directory tree rooted at src.
:type src: bytes | unicode
:type dst: bytes | unicode
:type symlinks: bool
:type ignore: ((bytes | unicode, list[bytes | unicode]) -> collections.Iterable[bytes | unicode]) | None
:rtype: None
"""
pass
def rmtree(path, ignore_errors=False, onerror=None):
"""Delete an entire directory tree.
:type path: bytes | unicode
:type ignore_errors: bool
:type onerror: (unknown, bytes | unicode, unknown) -> None
:rtype: None
"""
def move(src, dst):
"""Recursively move a file or directory (src) to another location (dst).
:type src: bytes | unicode
:type dst: bytes | unicode
:rtype: None
"""
pass
+190
View File
@@ -0,0 +1,190 @@
"""Skeleton for 'sqlite3' stdlib module."""
import sqlite3
def connect(database, timeout=5.0, detect_types=0, isolation_level=None,
check_same_thread=False, factory=None, cached_statements=100):
"""Opens a connection to the SQLite database file database.
:type database: bytes | unicode
:type timeout: float
:type detect_types: int
:type isolation_level: string | None
:type check_same_thread: bool
:type factory: (() -> sqlite3.Connection) | None
:rtype: sqlite3.Connection
"""
return sqlite3.Connection()
def register_converter(typename, callable):
"""Registers a callable to convert a bytestring from the database into a
custom Python type.
:type typename: string
:type callable: (bytes) -> unknown
:rtype: None
"""
pass
def register_adapter(type, callable):
"""Registers a callable to convert the custom Python type type into one of
SQLite's supported types.
:type type: type
:type callable: (unknown) -> unknown
:rtype: None
"""
pass
def complete_statement(sql):
"""Returns True if the string sql contains one or more complete SQL
statements terminated by semicolons.
:type sql: string
:rtype: bool
"""
return False
def enable_callback_tracebacks(flag):
"""By default you will not get any tracebacks in user-defined functions,
aggregates, converters, authorizer callbacks etc.
:type flag: bool
:rtype: None
"""
pass
class Connection(object):
"""A SQLite database connection."""
def cursor(self, cursorClass=None):
"""
:type cursorClass: type | None
:rtype: sqlite3.Cursor
"""
return sqlite3.Cursor()
def execute(self, sql, parameters=()):
"""This is a nonstandard shortcut that creates an intermediate cursor
object by calling the cursor method, then calls the cursor's execute
method with the parameters given.
:type sql: string
:type parameters: collections.Iterable
:rtype: sqlite3.Cursor
"""
pass
def executemany(self, sql, seq_of_parameters=()):
"""This is a nonstandard shortcut that creates an intermediate cursor
object by calling the cursor method, then calls the cursor's
executemany method with the parameters given.
:type sql: string
:type seq_of_parameters: collections.Iterable[collections.Iterable]
:rtype: sqlite3.Cursor
"""
pass
def executescript(self, sql_script):
"""This is a nonstandard shortcut that creates an intermediate cursor
object by calling the cursor method, then calls the cursor's
executescript method with the parameters given.
:type sql_script: bytes | unicode
:rtype: sqlite3.Cursor
"""
pass
def create_function(self, name, num_params, func):
"""Creates a user-defined function that you can later use from within
SQL statements under the function name name.
:type name: string
:type num_params: int
:type func: collections.Callable
:rtype: None
"""
pass
def create_aggregate(self, name, num_params, aggregate_class):
"""Creates a user-defined aggregate function.
:type name: string
:type num_params: int
:type aggregate_class: type
:rtype: None
"""
pass
def create_collation(self, name, callable):
"""Creates a collation with the specified name and callable.
:type name: string
:type callable: collections.Callable
:rtype: None
"""
pass
class Cursor(object):
"""A SQLite database cursor."""
def execute(self, sql, parameters=()):
"""Executes an SQL statement.
:type sql: string
:type parameters: collections.Iterable
:rtype: sqlite3.Cursor
"""
pass
def executemany(self, sql, seq_of_parameters=()):
"""Executes an SQL command against all parameter sequences or mappings
found in the sequence.
:type sql: string
:type seq_of_parameters: collections.Iterable[collections.Iterable]
:rtype: sqlite3.Cursor
"""
pass
def executescript(self, sql_script):
"""This is a nonstandard convenience method for executing multiple SQL
statements at once.
:type sql_script: bytes | unicode
:rtype: sqlite3.Cursor
"""
pass
def fetchone(self):
"""Fetches the next row of a query result set, returning a single
sequence, or None when no more data is available.
:rtype: tuple | None
"""
pass
def fetchmany(self, size=-1):
"""Fetches the next set of rows of a query result, returning a list.
:type size: numbers.Integral
:rtype: list[tuple]
"""
return []
def fetchall(self):
"""Fetches all (remaining) rows of a query result, returning a list.
:rtype: list[tuple]
"""
return []
+106
View File
@@ -0,0 +1,106 @@
"""Skeleton for 'struct' stdlib module."""
from __future__ import unicode_literals
import sys
def pack(fmt, *values):
"""Return a string containing the values packed according to the given
format.
:type fmt: bytes | unicode
:rtype: bytes
"""
return b''
def unpack(fmt, string):
"""Unpack the string according to the given format.
:type fmt: bytes | unicode
:type string: bytestring
:rtype: tuple
"""
pass
def pack_into(fmt, buffer, offset, *values):
""""Pack the values according to the given format, write the packed
bytes into the writable buffer starting at offset.
:type fmt: bytes | unicode
:type offset: int | long
:rtype: bytes
"""
return b''
def unpack_from(fmt, buffer, offset=0):
"""Unpack the buffer according to the given format.
:type fmt: bytes | unicode
:type offset: int | long
:rtype: tuple
"""
pass
def calcsize(fmt):
"""Return the size of the struct (and hence of the string) corresponding to
the given format.
:type fmt: bytes | unicode
:rtype: int
"""
return 0
class Struct(object):
"""Struct object which writes and reads binary data according to the format
string.
:param format: The format string used to construct this Struct object.
:type format: bytes | unicode
:param size: The calculated size of the struct corresponding to format.
:type size: int
"""
def __init__(self, format):
"""Create a new Struct object.
:type format: bytes | unicode
"""
self.format = format
self.size = 0
def pack(self, *values):
"""Identical to the pack() function, using the compiled format.
:rtype: bytes
"""
return b''
def pack_into(self, buffer, offset, *values):
"""Identical to the pack_into() function, using the compiled format.
:type offset: int | long
:rtype: bytes
"""
return b''
def unpack(self, string):
"""Identical to the unpack() function, using the compiled format.
:type string: bytestring
:rtype: tuple
"""
pass
def unpack_from(self, buffer, offset=0):
"""Identical to the unpack_from() function, using the compiled format.
:type offset: int | long
:rtype: tuple
"""
pass
@@ -0,0 +1,140 @@
"""Skeleton for 'subprocess' stdlib module."""
def call(args, bufsize=0, executable=None, stdin=None, stdout=None, stderr=None,
preexec_fn=None, close_fds=False, shell=False, cwd=None, env=None,
universal_newlines=False, startupinfo=None, creationflags=0,
timeout=None, restore_signals=True, start_new_session=False,
pass_fds=()):
"""Run the command described by args.
:type args: collections.Iterable[bytes | unicode]
:type bufsize: int
:type executable: bytes | unicode | None
:type close_fds: bool
:type shell: bool
:type cwd: bytes | unicode | None
:type env: collections.Mapping | None
:type universal_newlines: bool
:type creationflags: int
:rtype: int
"""
return 0
def check_call(args, bufsize=0, executable=None, stdin=None, stdout=None,
stderr=None, preexec_fn=None, close_fds=False, shell=False,
cwd=None, env=None, universal_newlines=False, startupinfo=None,
creationflags=0, timeout=None, restore_signals=True,
start_new_session=False, pass_fds=()):
"""Run command with arguments. Wait for command to complete. If the return
code was zero then return, otherwise raise CalledProcessError.
:type args: collections.Iterable[bytes | unicode]
:type bufsize: int
:type executable: bytes | unicode | None
:type close_fds: bool
:type shell: bool
:type cwd: bytes | unicode | None
:type env: collections.Mapping | None
:type universal_newlines: bool
:type creationflags: int
:rtype: int
"""
return 0
def check_output(args, bufsize=0, executable=None, stdin=None, stderr=None,
preexec_fn=None, close_fds=False, shell=False, cwd=None,
env=None, universal_newlines=False, startupinfo=None,
creationflags=0, timeout=None, restore_signals=True,
start_new_session=False, pass_fds=()):
"""Run command with arguments and return its output as a byte string.
:type args: collections.Iterable[bytes | unicode]
:type bufsize: int
:type executable: bytes | unicode | None
:type close_fds: bool
:type shell: bool
:type cwd: bytes | unicode | None
:type env: collections.Mapping | None
:type universal_newlines: bool
:type creationflags: int
:rtype: bytes
"""
pass
class Popen(object):
"""Execute a child program in a new process.
:type returncode: int
"""
def __init__(self, args, bufsize=0, executable=None, stdin=None,
stdout=None, stderr=None, preexec_fn=None, close_fds=False,
shell=False, cwd=None, env=None, universal_newlines=False,
startupinfo=None, creationflags=0, timeout=None,
restore_signals=True, start_new_session=False, pass_fds=()):
"""Popen constructor.
:type args: collections.Iterable[bytes | unicode]
:type bufsize: int
:type executable: bytes | unicode | None
:type close_fds: bool
:type shell: bool
:type cwd: bytes | unicode | None
:type env: collections.Mapping | None
:type universal_newlines: bool
:type creationflags: int
"""
self.stdin = stdin
self.stdout = stdout
self.stderr = stderr
self.pid = 0
self.returncode = 0
def poll(self):
"""Check if child process has terminated.
:rtype: int
"""
return 0
def wait(self, timeout=None):
"""Wait for child process to terminate.
:rtype: int
"""
return 0
def communicate(self, input=None, timeout=None):
"""Interact with process: Send data to stdin. Read data from stdout and
stderr, until end-of-file is reached.
:type input: bytes | unicode | None
:rtype: (bytes, bytes)
"""
return b'', b''
def send_signal(self, signal):
"""Sends the signal signal to the child.
:type signal: int
:rtype: None
"""
pass
def terminate(self):
"""Stop the child.
:rtype: None
"""
pass
def kill(self):
"""Kills the child.
:rtype: None
"""
pass