Add capability for Pylance to override strings (#5497)

This commit is contained in:
Rich Chiodo 2023-07-14 10:17:10 -07:00 committed by GitHub
parent 6a15a6dc6d
commit b865a45061
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 34 additions and 2 deletions

View File

@ -50,7 +50,7 @@ type StringLookupMap = { [key: string]: string | StringLookupMap };
let localizedStrings: StringLookupMap | undefined = undefined;
let defaultStrings: StringLookupMap = {};
function getRawString(key: string): string {
function getRawStringDefault(key: string): string {
if (localizedStrings === undefined) {
localizedStrings = initialize();
}
@ -65,6 +65,16 @@ function getRawString(key: string): string {
fail(`Missing localized string for key "${key}"`);
}
let getRawString = getRawStringDefault;
// Function allowing different strings to be used for messages.
// Returns the previous function used for getting messages.
export function setGetRawString(func: (key: string) => string): (key: string) => string {
const oldLookup = getRawString;
getRawString = func;
return oldLookup;
}
export function getRawStringFromMap(map: StringLookupMap, keyParts: string[]): string | undefined {
let curObj: any = map;

View File

@ -9,7 +9,7 @@
import * as assert from 'assert';
import { Localizer, ParameterizedString } from '../localization/localize';
import { Localizer, ParameterizedString, setGetRawString } from '../localization/localize';
const namespaces = [Localizer.Diagnostic, Localizer.DiagnosticAddendum, Localizer.CodeAction];
@ -45,3 +45,25 @@ test('Raw strings present', () => {
});
});
});
test('Override a specific string', () => {
// eslint-disable-next-line prefer-const
let originalRawString: ((key: string) => string) | undefined;
function overrideImportResolve(key: string): string {
if (key === 'Diagnostic.importResolveFailure') {
return 'Import is {importName}';
}
return originalRawString!(key);
}
originalRawString = setGetRawString(overrideImportResolve);
const value = Localizer.Diagnostic.importResolveFailure().format({ importName: 'foo' });
try {
assert.equal(value, 'Import is foo');
const nonMovedValue = Localizer.Diagnostic.abstractMethodInvocation().format({ method: 'foo' });
assert.equal(nonMovedValue, 'Method "foo" cannot be called because it is abstract');
} finally {
setGetRawString(originalRawString);
}
});