Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Remove sort imports from command palette and context menu #22057

Closed
wants to merge 1 commit into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 0 additions & 17 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -430,11 +430,6 @@
"command": "python.setInterpreter",
"title": "%python.command.python.setInterpreter.title%"
},
{
"category": "Python Refactor",
"command": "python.sortImports",
"title": "%python.command.python.sortImports.title%"
},
{
"category": "Python",
"command": "python.startREPL",
Expand Down Expand Up @@ -1870,12 +1865,6 @@
"title": "%python.command.python.setInterpreter.title%",
"when": "!virtualWorkspace && shellExecutionSupported"
},
{
"category": "Python Refactor",
"command": "python.sortImports",
"title": "%python.command.python.sortImports.title%",
"when": "!virtualWorkspace && shellExecutionSupported && editorLangId == python"
},
{
"category": "Python",
"command": "python.startREPL",
Expand Down Expand Up @@ -1914,12 +1903,6 @@
"group": "Python",
"when": "editorLangId == python && !virtualWorkspace && shellExecutionSupported && isWorkspaceTrusted"
},
{
"command": "python.sortImports",
"group": "Refactor",
"title": "%python.command.python.sortImports.title%",
"when": "editorLangId == python && !notebookEditorFocused && !virtualWorkspace && shellExecutionSupported"
},
{
"submenu": "python.runFileInteractive",
"group": "Jupyter2",
Expand Down
10 changes: 8 additions & 2 deletions src/client/common/utils/multiStepInput.ts
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,7 @@ export interface IQuickPickParameters<T extends QuickPickItem, E = any> {
totalSteps?: number;
canGoBack?: boolean;
items: T[];
activeItem?: T | Promise<T>;
activeItem?: T | ((quickPick: QuickPick<T>) => Promise<T>);
placeholder: string | undefined;
customButtonSetups?: QuickInputButtonSetup[];
matchOnDescription?: boolean;
Expand Down Expand Up @@ -156,7 +156,13 @@ export class MultiStepInput<S> implements IMultiStepInput<S> {
initialize(input);
}
if (activeItem) {
input.activeItems = [await activeItem];
if (typeof activeItem === 'function') {
activeItem(input).then((item) => {
if (input.activeItems.length === 0) {
input.activeItems = [item];
}
});
}
} else {
input.activeItems = [];
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,7 @@ import { EnvironmentVariables } from '../../common/variables/types';
import { TerminalShellType } from '../../common/terminal/types';
import { OSType } from '../../common/utils/platform';
import { normCase } from '../../common/platform/fs-paths';
import { PythonEnvType } from '../../pythonEnvironments/base/info';

@injectable()
export class TerminalEnvVarCollectionService implements IExtensionActivationService, ITerminalEnvVarCollectionService {
Expand All @@ -63,6 +64,8 @@ export class TerminalEnvVarCollectionService implements IExtensionActivationServ
*/
private processEnvVars: EnvironmentVariables | undefined;

private separator: string;

constructor(
@inject(IPlatformService) private readonly platform: IPlatformService,
@inject(IInterpreterService) private interpreterService: IInterpreterService,
Expand All @@ -75,7 +78,9 @@ export class TerminalEnvVarCollectionService implements IExtensionActivationServ
@inject(IWorkspaceService) private workspaceService: IWorkspaceService,
@inject(IConfigurationService) private readonly configurationService: IConfigurationService,
@inject(IPathUtils) private readonly pathUtils: IPathUtils,
) {}
) {
this.separator = platform.osType === OSType.Windows ? ';' : ':';
}

public async activate(resource: Resource): Promise<void> {
try {
Expand Down Expand Up @@ -196,6 +201,9 @@ export class TerminalEnvVarCollectionService implements IExtensionActivationServ
applyAtProcessCreation: true,
});
} else {
if (!value.endsWith(this.separator)) {
value = value.concat(this.separator);
}
traceVerbose(`Prepending environment variable ${key} in collection to ${value}`);
envVarCollection.prepend(key, value, {
applyAtShellIntegration: true,
Expand Down Expand Up @@ -257,8 +265,8 @@ export class TerminalEnvVarCollectionService implements IExtensionActivationServ
if (this.platform.osType !== OSType.Windows) {
// These shells are expected to set PS1 variable for terminal prompt for virtual/conda environments.
const interpreter = await this.interpreterService.getActiveInterpreter(resource);
const shouldPS1BeSet = interpreter?.type !== undefined;
if (shouldPS1BeSet && !env.PS1) {
const shouldSetPS1 = shouldPS1BeSet(interpreter?.type, env);
if (shouldSetPS1 && !env.PS1) {
// PS1 should be set but no PS1 was set.
return;
}
Expand All @@ -284,8 +292,8 @@ export class TerminalEnvVarCollectionService implements IExtensionActivationServ
if (this.platform.osType !== OSType.Windows) {
// These shells are expected to set PS1 variable for terminal prompt for virtual/conda environments.
const interpreter = await this.interpreterService.getActiveInterpreter(resource);
const shouldPS1BeSet = interpreter?.type !== undefined;
if (shouldPS1BeSet && !env.PS1) {
const shouldSetPS1 = shouldPS1BeSet(interpreter?.type, env);
if (shouldSetPS1 && !env.PS1) {
// PS1 should be set but no PS1 was set.
return getPromptForEnv(interpreter);
}
Expand Down Expand Up @@ -360,6 +368,22 @@ export class TerminalEnvVarCollectionService implements IExtensionActivationServ
}
}

function shouldPS1BeSet(type: PythonEnvType | undefined, env: EnvironmentVariables): boolean {
if (type === PythonEnvType.Virtual) {
const promptDisabledVar = env.VIRTUAL_ENV_DISABLE_PROMPT;
const isPromptDisabled = promptDisabledVar && promptDisabledVar !== undefined;
return !isPromptDisabled;
}
if (type === PythonEnvType.Conda) {
// Instead of checking config value using `conda config --get changeps1`, simply check
// `CONDA_PROMPT_MODIFER` to avoid the cost of launching the conda binary.
const promptEnabledVar = env.CONDA_PROMPT_MODIFIER;
const isPromptEnabled = promptEnabledVar && promptEnabledVar !== '';
return !!isPromptEnabled;
}
return type !== undefined;
}

function shouldSkip(env: string) {
return ['_', 'SHLVL'].includes(env);
}
Expand Down
13 changes: 12 additions & 1 deletion src/client/interpreter/autoSelection/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -181,6 +181,11 @@ export class InterpreterAutoSelectionService implements IInterpreterAutoSelectio
return this.stateFactory.createWorkspacePersistentState(key, undefined);
}

private getAutoSelectionQueriedOnceState(): IPersistentState<boolean | undefined> {
const key = `autoSelectionInterpretersQueriedOnce`;
return this.stateFactory.createWorkspacePersistentState(key, undefined);
}

/**
* Auto-selection logic:
* 1. If there are cached interpreters (not the first session in this workspace)
Expand All @@ -200,7 +205,12 @@ export class InterpreterAutoSelectionService implements IInterpreterAutoSelectio
});
}

await this.interpreterService.refreshPromise;
const globalQueriedState = this.getAutoSelectionQueriedOnceState();
if (!globalQueriedState.value) {
// Global interpreters are loaded the first time an extension loads, after which we don't need to
// wait on global interpreter promise refresh.
await this.interpreterService.refreshPromise;
}
const interpreters = this.interpreterService.getInterpreters(resource);
const workspaceUri = this.interpreterHelper.getActiveWorkspaceUri(resource);

Expand All @@ -215,6 +225,7 @@ export class InterpreterAutoSelectionService implements IInterpreterAutoSelectio
}

queriedState.updateValue(true);
globalQueriedState.updateValue(true);

this.didAutoSelectedInterpreterEmitter.fire();
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,7 @@ import { BaseInterpreterSelectorCommand } from './base';
const untildify = require('untildify');

export type InterpreterStateArgs = { path?: string; workspace: Resource };
type QuickPickType = IInterpreterQuickPickItem | ISpecialQuickPickItem | QuickPickItem;
export type QuickPickType = IInterpreterQuickPickItem | ISpecialQuickPickItem | QuickPickItem;

function isInterpreterQuickPickItem(item: QuickPickType): item is IInterpreterQuickPickItem {
return 'interpreter' in item;
Expand Down Expand Up @@ -177,7 +177,7 @@ export class SetInterpreterCommand extends BaseInterpreterSelectorCommand implem
items: suggestions,
sortByLabel: !preserveOrderWhenFiltering,
keepScrollPosition: true,
activeItem: this.getActiveItem(state.workspace, suggestions), // Use a promise here to ensure quickpick is initialized synchronously.
activeItem: (quickPick) => this.getActiveItem(state.workspace, quickPick), // Use a promise here to ensure quickpick is initialized synchronously.
matchOnDetail: true,
matchOnDescription: true,
title,
Expand Down Expand Up @@ -277,8 +277,9 @@ export class SetInterpreterCommand extends BaseInterpreterSelectorCommand implem
return getGroupedQuickPickItems(items, recommended, workspaceFolder?.uri.fsPath);
}

private async getActiveItem(resource: Resource, suggestions: QuickPickType[]) {
private async getActiveItem(resource: Resource, quickPick: QuickPick<QuickPickType>) {
const interpreter = await this.interpreterService.getActiveInterpreter(resource);
const suggestions = quickPick.items;
const activeInterpreterItem = suggestions.find(
(i) => isInterpreterQuickPickItem(i) && i.interpreter.id === interpreter?.id,
);
Expand Down Expand Up @@ -339,7 +340,9 @@ export class SetInterpreterCommand extends BaseInterpreterSelectorCommand implem
return false;
})
: undefined;
quickPick.activeItems = activeItem ? [activeItem] : [];
if (activeItem) {
quickPick.activeItems = [activeItem];
}
}

/**
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -115,9 +115,9 @@ export class EnvsCollectionService extends PythonEnvsWatcher<PythonEnvCollection
// Do not trigger another refresh if a refresh has previously finished.
return Promise.resolve();
}
refreshPromise = this.startRefresh(query);
refreshPromise = this.startRefresh(query).then(() => this.sendTelemetry(query, stopWatch));
}
return refreshPromise.then(() => this.sendTelemetry(query, stopWatch));
return refreshPromise;
}

private startRefresh(query: PythonLocatorQuery | undefined): Promise<void> {
Expand Down
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.

import { uniq } from 'lodash';
import { toLower, uniq, uniqBy } from 'lodash';
import * as path from 'path';
import { chain, iterable } from '../../../../common/utils/async';
import { getEnvironmentVariable, getOSType, getUserHomeDir, OSType } from '../../../../common/utils/platform';
Expand Down Expand Up @@ -39,19 +39,22 @@ async function getGlobalVirtualEnvDirs(): Promise<string[]> {

const homeDir = getUserHomeDir();
if (homeDir && (await pathExists(homeDir))) {
const subDirs = ['Envs', '.direnv', '.venvs', '.virtualenvs', path.join('.local', 'share', 'virtualenvs')];
if (![OSType.Windows, OSType.OSX].includes(getOSType())) {
// Not a case insensitive platform, push both upper and lower cases.
subDirs.push('envs');
}
const subDirs = [
'envs',
'Envs',
'.direnv',
'.venvs',
'.virtualenvs',
path.join('.local', 'share', 'virtualenvs'),
];
const filtered = await asyncFilter(
subDirs.map((d) => path.join(homeDir, d)),
pathExists,
);
filtered.forEach((d) => venvDirs.push(d));
}

return uniq(venvDirs);
return [OSType.Windows, OSType.OSX].includes(getOSType()) ? uniqBy(venvDirs, toLower) : uniq(venvDirs);
}

/**
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@ import {
import {
EnvGroups,
InterpreterStateArgs,
QuickPickType,
SetInterpreterCommand,
} from '../../../../client/interpreter/configuration/interpreterSelector/commands/setInterpreter';
import {
Expand Down Expand Up @@ -265,8 +266,14 @@ suite('Set Interpreter Command', () => {
delete actualParameters!.initialize;
delete actualParameters!.customButtonSetups;
delete actualParameters!.onChangeItem;
const activeItem = await actualParameters!.activeItem;
assert.deepStrictEqual(activeItem, recommended);
if (typeof actualParameters!.activeItem === 'function') {
const activeItem = await actualParameters!.activeItem(({ items: suggestions } as unknown) as QuickPick<
QuickPickType
>);
assert.deepStrictEqual(activeItem, recommended);
} else {
assert(false, 'Not a function');
}
delete actualParameters!.activeItem;
assert.deepStrictEqual(actualParameters, expectedParameters, 'Params not equal');
});
Expand Down Expand Up @@ -308,8 +315,14 @@ suite('Set Interpreter Command', () => {
delete actualParameters!.initialize;
delete actualParameters!.customButtonSetups;
delete actualParameters!.onChangeItem;
const activeItem = await actualParameters!.activeItem;
assert.deepStrictEqual(activeItem, noPythonInstalled);
if (typeof actualParameters!.activeItem === 'function') {
const activeItem = await actualParameters!.activeItem(({ items: suggestions } as unknown) as QuickPick<
QuickPickType
>);
assert.deepStrictEqual(activeItem, noPythonInstalled);
} else {
assert(false, 'Not a function');
}
delete actualParameters!.activeItem;
assert.deepStrictEqual(actualParameters, expectedParameters, 'Params not equal');
});
Expand Down Expand Up @@ -666,8 +679,14 @@ suite('Set Interpreter Command', () => {
delete actualParameters!.initialize;
delete actualParameters!.customButtonSetups;
delete actualParameters!.onChangeItem;
const activeItem = await actualParameters!.activeItem;
assert.deepStrictEqual(activeItem, recommended);
if (typeof actualParameters!.activeItem === 'function') {
const activeItem = await actualParameters!.activeItem(({ items: suggestions } as unknown) as QuickPick<
QuickPickType
>);
assert.deepStrictEqual(activeItem, recommended);
} else {
assert(false, 'Not a function');
}
delete actualParameters!.activeItem;

assert.deepStrictEqual(actualParameters, expectedParameters, 'Params not equal');
Expand Down
Loading