chore: rewrite some logs message and add not-chinese-message commit rule (#2542)

* chore: use English as the default language in the code

* chore: add not-chinese-message rules

* chore: use unicode

* chore: fix build
This commit is contained in:
Dan 2023-04-06 10:38:30 +08:00 committed by GitHub
parent 95c83d5c4d
commit ec4dea43c2
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
32 changed files with 107 additions and 88 deletions

16
commitlint.config.js Normal file
View File

@ -0,0 +1,16 @@
module.exports = {
extends: ['@commitlint/config-conventional'],
rules: {
'not-chinese-message-rule': [2, 'always'],
},
plugins: [
{
rules: {
'not-chinese-message-rule': ({ subject }) => {
const regex = /[\u4e00-\u9fa5]+/;
return [!regex.test(subject), 'Please use english to rewrite your commit message'];
},
},
},
],
};

View File

@ -76,11 +76,6 @@
"path": "node_modules/cz-conventional-changelog"
}
},
"commitlint": {
"extends": [
"@commitlint/config-conventional"
]
},
"repository": {
"type": "git",
"url": "git@github.com:opensumi/core.git"

View File

@ -86,7 +86,7 @@ describe('comment service test', () => {
const [thread] = createTestThreads(uri);
expect(thread.uri.isEqual(uri));
expect(thread.range.startLineNumber).toBe(1);
expect(thread.comments[0].body).toBe('评论内容1');
expect(thread.comments[0].body).toBe('评论内容');
});
it('get commentsThreads', () => {
@ -152,7 +152,7 @@ describe('comment service test', () => {
author: {
name: 'User',
},
body: '评论内容1',
body: '评论内容',
},
],
});
@ -171,7 +171,7 @@ describe('comment service test', () => {
author: {
name: 'User',
},
body: '评论内容1',
body: '评论内容',
},
],
});
@ -245,7 +245,7 @@ describe('comment service test', () => {
author: {
name: 'User',
},
body: '评论内容1',
body: '评论内容',
},
],
}),

View File

@ -39,7 +39,7 @@ export function getSlotLocation(moduleName: string, layoutConfig: LayoutConfig)
return location;
}
}
getDebugLogger().warn(`没有找到${moduleName}所对应的位置!`);
logger.warn(`Cannot find the location with ${moduleName}`);
return '';
}
@ -97,14 +97,14 @@ export class ErrorBoundary extends React.Component {
export const allSlot: { slot: string; dom: HTMLElement }[] = [];
export const SlotDecorator: React.FC<{ slot: string; backgroundColor?: string }> = ({ slot, ...props }) => {
const ref = React.useRef<HTMLElement>();
const ref = React.useRef<HTMLElement | null>();
React.useEffect(() => {
if (ref.current) {
allSlot.push({ slot, dom: ref.current });
}
}, [ref]);
return (
<div ref={(ele) => (ref.current = ele!)} className='resize-wrapper'>
<div ref={(ele) => (ref.current = ele)} className='resize-wrapper'>
{props.children}
</div>
);
@ -163,12 +163,13 @@ export class SlotRendererRegistry {
export const slotRendererRegistry = new SlotRendererRegistry();
export interface SlotProps {
// Name of the slot view
slot: string;
/**
* slot
*/
// Background color of the slot view
backgroundColor?: string;
// Is tabbar slot renderer or not
isTabbar?: boolean;
// Optional props
[key: string]: any;
}
@ -181,7 +182,7 @@ export function SlotRenderer({ slot, isTabbar, ...props }: SlotProps) {
slotRendererRegistry.addTabbar(slot);
}
if (!componentKeys || !componentKeys.length) {
getDebugLogger().warn(`No ${slot} view declared by location.`);
logger.warn(`No ${slot} view declared by location.`);
}
const [componentInfos, setInfos] = React.useState<ComponentRegistryInfo[]>([]);
const updateComponentInfos = React.useCallback(() => {
@ -189,7 +190,7 @@ export function SlotRenderer({ slot, isTabbar, ...props }: SlotProps) {
componentKeys.forEach((token) => {
const info = componentRegistry.getComponentRegistryInfo(token);
if (!info) {
getDebugLogger().warn(`${token} view isn't registered, please check.`);
logger.warn(`${token} view isn't registered, please check.`);
} else {
infos.push(info);
}

View File

@ -41,7 +41,7 @@ export function getDomainConstructors(...domains: Domain[]) {
constructorSet.add(constructor);
} else {
// eslint-disable-next-line no-console
console.error(`没有获取到 ${String(domain)} 对应的Constructor`);
console.error(`Unable to retrieve the Constructor for ${String(domain)}`);
}
}
return Array.from(constructorSet);

View File

@ -16,16 +16,14 @@ export class ElectronMainApiRegistryImpl implements ElectronMainApiRegistry {
private apis: Map<string, ElectronMainApiProxy> = new Map();
@Autowired(INJECTOR_TOKEN)
injector: Injector;
constructor() {}
private readonly injector: Injector;
registerMainApi(name: string, api: IElectronMainApiProvider): IDisposable {
if (this.apis.has(name)) {
this.apis.get(name)!.dispose();
this.apis.get(name)?.dispose();
}
const proxy = this.injector.get(ElectronMainApiProxy, [name, api]);
getDebugLogger().log('注册Electron Main Api: ' + name);
getDebugLogger().log(`Register Electron Main Api: ${name}`);
this.apis.set(name, proxy);
return {

View File

@ -175,7 +175,7 @@ export class CodeWindow extends Disposable implements ICodeWindow {
async start() {
if (this.isRemote) {
getDebugLogger().log('Remote 模式,停止创建 Server 进程');
getDebugLogger().log('[Remote mode] stop creating Server process');
} else {
this.startNode();
}

View File

@ -401,7 +401,7 @@ export class EditorDocumentModel extends Disposable implements IEditorDocumentMo
this.compareAndSave();
}
});
this.logger.error('文件无法保存,版本和磁盘不一致');
this.logger.error('The file cannot be saved, the version is inconsistent with the disk');
return false;
}
return false;

View File

@ -435,7 +435,7 @@ export class TextmateService extends WithEventBus implements ITextmateTokenizerS
json = parseWithComments(content);
return json;
} catch (error) {
this.logger.error('语言配置文件解析出错!', content);
this.logger.error(`Language configuration file parsing error, ${error.stack}`);
return;
}
}

View File

@ -209,9 +209,9 @@ export class UntitledSchemeResourceProvider extends WithEventBus implements IRes
}
// 询问用户是否保存
const buttons = {
[localize('file.prompt.dontSave', '不保存')]: AskSaveResult.REVERT,
[localize('file.prompt.save', '保存')]: AskSaveResult.SAVE,
[localize('file.prompt.cancel', '取消')]: AskSaveResult.CANCEL,
[localize('file.prompt.dontSave', "Don't Save")]: AskSaveResult.REVERT,
[localize('file.prompt.save', 'Save')]: AskSaveResult.SAVE,
[localize('file.prompt.cancel', 'Cancel')]: AskSaveResult.CANCEL,
};
const selection = await this.dialogService.open(
formatLocalize('saveChangesMessage', resource.name),

View File

@ -518,9 +518,9 @@ export class WorkbenchEditorServiceImpl extends WithEventBus implements Workbenc
// 询问用户是否保存
const buttons = {
[localize('file.prompt.dontSave', '不保存')]: AskSaveResult.REVERT,
[localize('file.prompt.save', '保存')]: AskSaveResult.SAVE,
[localize('file.prompt.cancel', '取消')]: AskSaveResult.CANCEL,
[localize('file.prompt.dontSave', "Don't Save")]: AskSaveResult.REVERT,
[localize('file.prompt.save', 'Save')]: AskSaveResult.SAVE,
[localize('file.prompt.cancel', 'Cancel')]: AskSaveResult.CANCEL,
};
const files = toClose.slice(0, MAX_CONFIRM_RESOURCES);
let filesDetail = files.map((v) => v.resource.name).join('、');

View File

@ -21,7 +21,7 @@ describe('packages/express-file-server/__tests__/browser/index.test.ts', () => {
createContributionProvider(injector, StaticResourceContribution);
// 手动执行 staticResource 的 contribution
staticResourceClientAppContribution.initialize();
it('express 模块提供 file schema 的 uri 转换', () => {
it('User express module to transform URI', () => {
const uri = staticResourceService.resolveStaticResource(URI.file('test'));
expect(uri.toString()).toEqual('http://127.0.0.1:8000/assets/test');
});

View File

@ -92,8 +92,8 @@ describe('extension browser test', () => {
extension.initialize();
// 注入语言包后
expect(extension.toJSON().displayName).toEqual('哈哈哈哈啊哈哈');
expect(extension.localize('displayName')).toEqual('哈哈哈哈啊哈哈');
expect(extension.toJSON().displayName).toEqual('中文测试');
expect(extension.localize('displayName')).toEqual('中文测试');
}, 0);
});

View File

@ -147,7 +147,7 @@ describe('vscode extHostEnv Test', () => {
},
});
it('用户首次访问时间大于一天', async () => {
it("The user's first visit is more than a day old", async () => {
const envApi = createEnvApiFactory(
rpcProtocolExt,
extensionService,
@ -158,7 +158,7 @@ describe('vscode extHostEnv Test', () => {
expect(envApi.isNewAppInstall).toBe(false);
});
it('用户首次访问时间小于一天', () => {
it("The user's first visit is less than a day old", () => {
const envApi = createEnvApiFactory(
rpcProtocolExt,
extensionService,

View File

@ -32,38 +32,38 @@ export class MainThreadLayout extends Disposable implements IMainThreadLayout {
}
$setTitle(id: string, title: string): void {
this.getHandler(id).updateTitle(title);
this.getHandler(id)?.updateTitle(title);
}
$setIcon(id: string, iconPath: string): void {
const iconClass = this.iconService.fromIcon('', iconPath, IconType.Background, IconShape.Square);
this.getHandler(id).setIconClass(iconClass!);
this.getHandler(id)?.setIconClass(iconClass!);
}
$setSize(id: string, size: number): void {
this.getHandler(id).setSize(size);
this.getHandler(id)?.setSize(size);
}
$activate(id: string): void {
this.getHandler(id).activate();
this.getHandler(id)?.activate();
}
$deactivate(id: string): void {
this.getHandler(id).deactivate();
this.getHandler(id)?.deactivate();
}
$setBadge(id: string, badge: string): void {
this.getHandler(id).setBadge(badge);
this.getHandler(id)?.setBadge(badge);
}
async $setVisible(id: string, visible: boolean) {
if (visible) {
this.getHandler(id).show();
this.getHandler(id)?.show();
} else {
if (this.getHandler(id).isActivated()) {
this.getHandler(id).deactivate();
if (this.getHandler(id)?.isActivated()) {
this.getHandler(id)?.deactivate();
}
this.getHandler(id).hide();
this.getHandler(id)?.hide();
}
}
@ -75,8 +75,10 @@ export class MainThreadLayout extends Disposable implements IMainThreadLayout {
} else {
const disposer = this.eventBus.on(TabBarRegistrationEvent, (e) => {
if (e.payload.tabBarId === id) {
const handle = this.layoutService.getTabbarHandler(id);
this.bindHandleEvents(handle!);
const handler = this.layoutService.getTabbarHandler(id);
if (handler) {
this.bindHandleEvents(handler);
}
disposer.dispose();
}
});
@ -103,8 +105,8 @@ export class MainThreadLayout extends Disposable implements IMainThreadLayout {
protected getHandler(id: string) {
const handler = this.layoutService.getTabbarHandler(id);
if (!handler) {
this.logger.warn(`MainThreaLayout:没有找到${id}对应的handler`);
this.logger.warn(`Could not find a handler with \`${id}\``);
}
return handler!;
return handler;
}
}

View File

@ -69,7 +69,7 @@ export class LocalizationsContributionPoint extends VSCodeContributePoint<Locali
json = parseWithComments(content);
return json;
} catch (error) {
return this.logger.error('语言配置文件解析出错!', content);
return this.logger.error(`Language configuration file parsing error, ${error.stack}`);
}
}

View File

@ -426,7 +426,7 @@ export class FileServiceClient implements IFileServiceClient {
registerProvider(scheme: string, provider: FileSystemProvider): IDisposable {
if (this.fsProviders.has(scheme)) {
throw new Error(`'${scheme}' 的文件系统 provider 已存在`);
throw new Error(`The file system provider for \`${scheme}\` already registered`);
}
const disposables: IDisposable[] = [];
@ -513,7 +513,7 @@ export class FileServiceClient implements IFileServiceClient {
const _uri = new URI(uri);
if (!_uri.scheme) {
throw new Error(`没有设置 scheme: ${uri}`);
throw new Error(`Unsupported convert Uri with non-scheme Uri: ${uri}`);
}
return _uri;

View File

@ -388,7 +388,7 @@ export class FileService implements IFileService {
const _uri = new URI(uri);
if (!_uri.scheme) {
throw new Error(`没有设置 scheme: ${uri}`);
throw new Error(`Unsupported to get Uri from non-scheme Uri: ${uri}`);
}
return _uri;

View File

@ -1361,6 +1361,9 @@ export const localizationBundle = {
// #endregion merge editor
'workbench.quickOpen.preserveInput':
'Controls whether the last typed input to Quick Open(include Command Palette) should be preserved.',
'webview.webviewTagUnavailable': 'Webview is unsupported on non-electron env, please use iframe instead',
...browserViews,
},
};

View File

@ -1079,6 +1079,9 @@ export const localizationBundle = {
'mergeEditor.conflict.action.apply.confirm.complete': '确认保存并更改',
'mergeEditor.button.apply': '应用更改',
'workbench.quickOpen.preserveInput': '是否在 QuickOpen 的输入框(包括命令面板)中保留上次输入的内容',
'webview.webviewTagUnavailable': '非 Electron 环境不支持 Webview 标签,请使用 Iframe 标签',
...browserViews,
},
};

View File

@ -64,7 +64,7 @@ describe('LogService', () => {
console.log('text', text);
if (text.trim().length < 1) {
// eslint-disable-next-line no-console
return console.warn('spdlog 写入文件可能失败了、或者 spdlog 初始化失败!');
return console.warn('Spdlog may have failed to write to file, or initialization failed');
}
expect(text.indexOf(LogLevelMessageMap[LogLevel.Verbose]) < 0).toBe(true);
expect(text.indexOf(LogLevelMessageMap[LogLevel.Debug]) < 0).toBe(true);

View File

@ -156,7 +156,7 @@ export class TabBarHandler {
targetView.name = title;
this.accordionService.updateViewTitle(viewId, title);
} else {
this.logger.error('没有找到目标视图,无法更新手风琴标题!');
this.logger.error(`No target view \`${viewId}\` found, unable to update accordion title`);
}
}
@ -169,7 +169,7 @@ export class TabBarHandler {
targetView.description = desciption;
this.accordionService.updateViewDesciption(viewId, desciption);
} else {
this.logger.error('没有找到目标视图,无法更新手风琴描述!');
this.logger.error(`No target view \`${viewId}\` found, unable to update accordion description`);
}
}
@ -182,7 +182,7 @@ export class TabBarHandler {
targetView.message = message;
this.accordionService.updateViewMessage(viewId, message);
} else {
this.logger.error('没有找到目标视图,无法更新手风琴 message!');
this.logger.error(`No target view \`${viewId}\` found, unable to update accordion message`);
}
}
/**

View File

@ -1,14 +1,12 @@
import { localize } from '@opensumi/ide-core-browser';
export default class Messages {
public static markerTitle = () => localize('markers.title', '问题');
public static markerPanelContentEmpty = () => localize('markers.panel.content.empty', '目前尚未在工作区检测到问题。');
public static markerPanelFilterInputPlaceholder = () =>
localize('markers.filter.placeholder', '筛选器例如text、**/*.ts、!**/node_modules/**');
public static markerTitle = () => localize('markers.title');
public static markerPanelContentEmpty = () => localize('markers.panel.content.empty');
public static markerPanelFilterInputPlaceholder = () => localize('markers.filter.placeholder');
public static markerPanelFilterErrors = () => localize('markers.panel.filter.errors', 'errors');
public static markerPanelFilterWarnings = () => localize('markers.panel.filter.warnings', 'warnings');
public static markerPanelFilterInfos = () => localize('markers.panel.filter.infos', 'infos');
public static markerPanelFilterContentEmpty = () =>
localize('markers.filter.content.empty', '在给定的筛选条件下,没有找到结果。');
public static markerPanelFilterReset = () => localize('markers.filter.reset', '清除筛选器');
public static markerPanelFilterContentEmpty = () => localize('markers.filter.content.empty');
public static markerPanelFilterReset = () => localize('markers.filter.reset');
}

View File

@ -80,7 +80,7 @@ export class OutputContribution
component: Output,
},
{
title: localize('output.tabbar.title', '输出'),
title: localize('output.tabbar.title'),
priority: 9,
containerId: OUTPUT_CONTAINER_ID,
activateKeyBinding: 'ctrlcmd+shift+u',

View File

@ -79,7 +79,7 @@ export class OutputChannel extends Disposable {
this.documentService.createModelReference(uri).then((model) => {
this.outputModel = model;
this.monacoModel = this.outputModel.instance.getMonacoModel();
this.monacoModel.setValue(localize('output.channel.none', '还没有任何输出'));
this.monacoModel.setValue(localize('output.channel.none', '<no output yet>'));
if (this.enableHighlight) {
this.outputModel.instance.languageId = 'log';

View File

@ -777,7 +777,7 @@ function StringArrayPreferenceItem({
onValueChange={handleInputValueChange}
/>
<Button className={styles.add_button} onClick={addItem}>
{localize('preference.array.additem', '添加')}
{localize('preference.array.additem', 'Add')}
</Button>
</div>
</div>

View File

@ -58,7 +58,7 @@ export class QuickOpenHandlerRegistry extends Disposable implements IQuickOpenHa
registerHandler(handler: QuickOpenHandler, tabConfig?: QuickOpenTabConfig): IDisposable {
if (this.handlers.has(handler.prefix)) {
this.logger.warn(`前缀是 ${handler.prefix} 的处理函数已经存在`);
this.logger.warn(`The handler function of the \`${handler.prefix}\` is already registered`);
return Disposable.NULL;
}
this.handlers.set(handler.prefix, handler);

View File

@ -22,7 +22,7 @@ class MockRecentStorage {
}
}
describe('测试 SearchHistory', () => {
describe('SearchHistory test', () => {
const searchServiceClient: any = new MockSearchServiceClient();
const mockRecentStorage = new MockRecentStorage();
const searchHistory = new SearchHistory(searchServiceClient, mockRecentStorage as any);
@ -47,7 +47,7 @@ describe('测试 SearchHistory', () => {
expect(spy).toHaveBeenCalled();
});
test('method: setRecentSearchWord 前进到底', () => {
test('method: setRecentSearchWord', () => {
searchHistory.setRecentSearchWord();
searchHistory.setRecentSearchWord();
searchHistory.setRecentSearchWord();
@ -66,7 +66,7 @@ describe('测试 SearchHistory', () => {
expect(spy).toHaveBeenCalled();
});
test('method: setBackRecentSearchWord 后退到底', () => {
test('method: setBackRecentSearchWord', () => {
searchHistory.setBackRecentSearchWord();
searchHistory.setBackRecentSearchWord();
searchHistory.setBackRecentSearchWord();

View File

@ -1,7 +1,7 @@
import { cutShortSearchResult } from '../../src/common/content-search';
describe('cutShortSearchResult', () => {
test('内容超出长度的结果, matchStart 未达到截取位置', () => {
describe('The long search results should be cropped', () => {
test('[0] The result of the content exceeding the length, matchStart did not reach the interception position', () => {
const result = cutShortSearchResult({
fileUri: 'file://root.txt',
matchStart: 10,
@ -16,7 +16,7 @@ describe('cutShortSearchResult', () => {
expect(result.renderLineText![9]).toEqual('M');
});
test('内容超出长度的结果, matchStart 未达到截取位置', () => {
test('[1] The result of the content exceeding the length, matchStart did not reach the interception position', () => {
const result = cutShortSearchResult({
fileUri: 'file://root.txt',
matchStart: 21,
@ -30,7 +30,7 @@ describe('cutShortSearchResult', () => {
expect(result.renderLineText!.length).toEqual(500);
});
test('内容超出长度的结果, matchStart 达到截取位置, matchLength达到截取长度', () => {
test('The matchStart and matchLength reaches the interception position', () => {
const result = cutShortSearchResult({
fileUri: 'file://root.txt',
matchStart: 21,
@ -45,7 +45,7 @@ describe('cutShortSearchResult', () => {
expect(result.matchLength).toEqual(500);
});
test('内容未超出长度, matchStart 未达到截取位置', () => {
test('[0] Content does not exceed length', () => {
const insertResult = {
fileUri: 'file://root.txt',
matchStart: 21,
@ -60,7 +60,7 @@ describe('cutShortSearchResult', () => {
expect(result.matchLength).toEqual(insertResult.matchLength);
});
test('内容未超出长度, matchStart 达到截取位置', () => {
test('[1] Content does not exceed length', () => {
const insertResult = {
fileUri: 'file://root.txt',
matchStart: 41,

View File

@ -128,7 +128,10 @@ export class WebviewServiceImpl implements IWebviewService {
} else {
if (options.preferredImpl && options.preferredImpl === 'webview') {
getDebugLogger().warn(
localize('webview.webviewTagUnavailable', '无法在非Electron环境使用Webview标签。回退至使用iframe。'),
localize(
'webview.webviewTagUnavailable',
'Webview is unsupported on non-electron env, please use iframe instead.',
),
);
}
return new IframePlainWebview();

View File

@ -130,7 +130,7 @@ export class ResourceTextEditTask {
const monacoModel = documentModel.getMonacoModel();
if (this.versionId) {
if (monacoModel.getVersionId() !== this.versionId) {
throw new Error('文档版本不一致,无法执行变更');
throw new Error('Unable to perform changes due to inconsistent document versions');
}
}
const edits: monaco.editor.IIdentifiedSingleEditOperation[] = [];

View File

@ -17,14 +17,14 @@ describe('mock-injector test', () => {
fn2 = jest.fn();
});
describe('手动创建 injector', () => {
describe('Manually create Injector', () => {
let injector: MockInjector;
beforeEach(() => {
injector = new MockInjector();
});
it('能够正常 mock 一个依赖注入的对象', () => {
it('Can mock a injected service', () => {
injector.mock(A, 'log', fn2);
const args = [1, '2', true];
@ -36,7 +36,7 @@ describe('mock-injector test', () => {
expect(fn2).toBeCalledWith(...args);
});
it('先创建对象,能够正常 mock', () => {
it('Can mock a created service', () => {
const args = [1, '2', true];
const a = injector.get(A);
@ -48,7 +48,7 @@ describe('mock-injector test', () => {
expect(fn2).toBeCalledWith(...args);
});
it('不 mock 的时候正常运行', () => {
it('Work as expected', () => {
const args = [1, '2', true];
const a = injector.get(A);
a.log(...args);
@ -58,8 +58,8 @@ describe('mock-injector test', () => {
});
});
describe('通过辅助函数创建 injector', () => {
it('能够使用 Browser 环境的 Injector 进行 mock', () => {
describe('User helper to create Injector', () => {
it('Can mock service with the Injector created by `createBrowserInjector` method', () => {
const injector = createBrowserInjector([]);
injector.mock(A, 'log', fn2);
@ -72,7 +72,7 @@ describe('mock-injector test', () => {
expect(fn2).toBeCalledWith(...args);
});
it('能够使用 Node 环境的 Injector 进行 mock', () => {
it('Can mock service with the Injector created by `createNodeInjector` method', () => {
const injector = createNodeInjector([]);
injector.mock(A, 'log', fn2);