Skip to content

Commit

Permalink
feat: 新增配置 include 和 exclude 控制更新范围
Browse files Browse the repository at this point in the history
Co-authored-by: ygqygq2 <[email protected]>
  • Loading branch information
ygqygq2 committed Mar 16, 2024
1 parent f43d438 commit 246c2f9
Show file tree
Hide file tree
Showing 23 changed files with 410 additions and 212 deletions.
6 changes: 6 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,12 @@

All notable changes to the "turbo-file-header" extension will be documented in this file.

# [0.0.8]

## 新增功能 🌱

- feat: 新增配置 `include``exclude` 控制更新范围

# [0.0.7]

## 新增功能 🌱
Expand Down
39 changes: 22 additions & 17 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -18,23 +18,28 @@ Turbo file header, sets file header information globally or for a project.

Properties:

| Feature | Description | Setting | Default |
| --------------------------------- | ---------------------------------------------------------------- | -------------------------------- | --------------------- |
| Custom user name | The fixed user name. The default is from your VCS | userName | `` |
| Custom user email | The fixed user email. The default is from your VCS | userEmail | `` |
| Custom company name | Company name | companyName | `YourCompanyName` |
| Date format | The [date format](https://momentjs.com/docs/#/displaying/format) | dateFormat | `YYYY-MM-DD HH:mm:ss` |
| Auto insert on create file | When create file, auto insert file header | autoInsertOnCreateFile | `false` |
| Auto update on save file | When save file, auto update file header | autoUpdateOnSave | `false` |
| Disable fields in file header | The fields that you want to disable in file header | disableFields | `[]` |
| Only dirty file or not to support | Only dirty file to support update file header | updateHeaderForModifiedFilesOnly | `false` |
| Extra languages support | To support new or unknown languages | languages | the below |
| JSDoc style for js/ts | File header user JSDoc style comments | useJSDocStyle | `false` |
| Multiline comment highlighter | Whether the multiline comment highlighter should be active | multilineComments | `true` |
| plaintext comment highlighter | Whether the plaintext comment highlighter should be active | highlightPlainText | `false` |
| Use tags to color the comments | Tags which are used to color the comments | tags | the below |
| Tags for light themes | Overwrite tags options for light themes | tagsLight | `[]` |
| Tags for dark themes | Overwrite tags options for dark themes | tagsDark | `[]` |
| Feature | Description | Setting | Default |
| --------------------------------- | -------------------------------------------------------------------- | -------------------------------- | ------------------------ |
| Custom user name | The fixed user name. The default is from your VCS | userName | `` |
| Custom user email | The fixed user email. The default is from your VCS | userEmail | `` |
| Custom company name | Company name | companyName | `YourCompanyName` |
| Date format | The [date format](https://momentjs.com/docs/#/displaying/format) | dateFormat | `YYYY-MM-DD HH:mm:ss` |
| Auto insert on create file | When create file, auto insert file header | autoInsertOnCreateFile | `false` |
| Auto update on save file | When save file, auto update file header | autoUpdateOnSave | `false` |
| Include glob | "include glob" for `autoInsertOnCreateFile` and batch update command | include | `**/this-default-glob/*` |
| Exclude glob | "exclude glob" for `autoInsertOnCreateFile` and batch update command | exclude | `` |
| Disable fields in file header | The fields that you want to disable in file header | disableFields | `[]` |
| Only dirty file or not to support | Only dirty file to support update file header | updateHeaderForModifiedFilesOnly | `false` |
| Extra languages support | To support new or unknown languages | languages | the below |
| JSDoc style for js/ts | File header user JSDoc style comments | useJSDocStyle | `false` |
| Multiline comment highlighter | Whether the multiline comment highlighter should be active | multilineComments | `true` |
| plaintext comment highlighter | Whether the plaintext comment highlighter should be active | highlightPlainText | `false` |
| Use tags to color the comments | Tags which are used to color the comments | tags | the below |
| Tags for light themes | Overwrite tags options for light themes | tagsLight | `[]` |
| Tags for dark themes | Overwrite tags options for dark themes | tagsDark | `[]` |

**Note**:
- `include` and `exclude` are used to control the scope of the file header update, except for `addFileheader` command.

## Default settings list

Expand Down
13 changes: 12 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
"name": "turbo-file-header",
"displayName": "Turbo File Header",
"description": "Sets file header information globally or for a project.",
"version": "0.0.7",
"version": "0.0.8",
"icon": "resources/icons/icon.png",
"repository": {
"type": "git",
Expand Down Expand Up @@ -96,6 +96,16 @@
"default": false,
"description": "%turboFileHeader.autoUpdateOnSave.description%"
},
"turboFileHeader.include": {
"type": "string",
"description": "%turboFileHeader.include.description%",
"default": "**/this-default-glob/*"
},
"turboFileHeader.exclude": {
"type": "string",
"description": "%turboFileHeader.exclude.description%",
"default": ""
},
"turboFileHeader.disableFields": {
"type": "array",
"default": [],
Expand Down Expand Up @@ -468,6 +478,7 @@
"handlebars": "^4.7.8",
"json5": "^2.2.3",
"lodash": "^4.17.21",
"minimatch": "^9.0.3",
"upath": "^2.0.1",
"yaml": "^2.4.1"
}
Expand Down
2 changes: 2 additions & 0 deletions package.nls.json
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,8 @@
"turboFileHeader.dateFormat.markdownDescription": "The date format, see [Dayjs Document](https://momentjs.com/docs/#/displaying/format)",
"turboFileHeader.autoInsertOnCreateFile.description": "Auto insert fileheader when create file",
"turboFileHeader.autoUpdateOnSave.description": "Auto update fileheader when save file",
"turboFileHeader.include.description": "Insert header to files which match the glob pattern. Affects batchUpdateFileheader command and while autoInsertOnCreateFile is true",
"turboFileHeader.exclude.description": "Do not insert header to files which match the glob pattern",
"turboFileHeader.disableFields.items.enum.birthtime": "file create time. will get it from VCS or fallback to filesystem when it is not available.",
"turboFileHeader.disableFields.items.enum.mtime": "file last modified time. will get it from VCS or fallback to filesystem when it is not available.",
"turboFileHeader.disableFields.items.enum.authorName": "file author name. if the file is tracked by VCS, it will get the author name from VCS, else it will get it from current user name.",
Expand Down
2 changes: 2 additions & 0 deletions package.nls.zh-cn.json
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,8 @@
"turboFileHeader.dateFormat.markdownDescription": "时间格式, 查看[格式文档](https://momentjs.com/docs/#/displaying/format)",
"turboFileHeader.autoInsertOnCreateFile.description": "创建文件时自动插入文件头",
"turboFileHeader.autoUpdateOnSave.description": "保存文件时自动更新文件头",
"turboFileHeader.include.description": "匹配到的 glob 模式将被插入文件头,影响批量操作命令和新文件自动插入文件头",
"turboFileHeader.exclude.description": "匹配到的 glob 模式将被排除插入文件头",
"turboFileHeader.disableFields.items.enum.birthtime": "文件创建时间. 来自 VCS 或文件系统",
"turboFileHeader.disableFields.items.enum.mtime": "文件最后修改时间. 来自 VCS 或文件系统",
"turboFileHeader.disableFields.items.enum.authorName": "文件作者名. 如果文件被 VCS 跟踪, 则从 VCS 中获取作者名, 否则从当前用户名中获取",
Expand Down
6 changes: 3 additions & 3 deletions pnpm-lock.yaml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

5 changes: 2 additions & 3 deletions resources/fileheader.config.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ providers:
# * 必填
template: |
* @file {{filePath}}
* @description
* @description
* @author {{authorName}} <{{authorEmail}}>
* @createTime {{birthtime}}
* @lastModified {{mtime}}
Expand All @@ -39,7 +39,6 @@ findFilesConfig:
# * 必填,Glob 模式
include: '**/*.{js,ts,java}'
# * 必填,Glob 模式
exclude:
- '**/{node_modules,dist}/**'
exclude: '**/{node_modules,dist}/**'
# 选填
# maxResults: 1000
23 changes: 21 additions & 2 deletions src/configuration/ConfigManager.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,19 +6,33 @@ import { ConfigSection, ConfigTag } from '../constants';
import { Configuration, ConfigurationFlatten, Tag, TagFlatten } from './types';
import { errorHandler } from '@/extension';
import { ConfigReader } from './ConfigReader';
import { ConfigYaml } from '@/typings/types';

export class ConfigManager {
private static instance: ConfigManager;
private configReader: ConfigReader;
private configuration: Configuration & vscode.WorkspaceConfiguration;
private configFlatten: ConfigurationFlatten;
private configYaml: ConfigYaml | undefined;

private constructor(configReader: ConfigReader) {
this.configReader = configReader;
this.configuration = this.getConfiguration();
this.configFlatten = this.getConfigurationFlatten();
}

// 用于执行实例初始化的异步方法
private async initialize() {
this.configYaml = await this.configReader.getConfigYaml();
}

// 静态异步初始化方法
public static async createInstance(configReader: ConfigReader): Promise<ConfigManager> {
const manager = new ConfigManager(configReader);
await manager.initialize();
return manager;
}

public static getInstance(configReader: ConfigReader): ConfigManager {
return ConfigManager?.instance || new ConfigManager(configReader);
}
Expand Down Expand Up @@ -62,6 +76,8 @@ export class ConfigManager {
dateFormat: orig?.dateFormat || 'YYYY-MM-DD HH:mm:ss',
autoInsertOnCreateFile: orig?.autoInsertOnCreateFile || true,
autoUpdateOnSave: orig?.autoUpdateOnSave || true,
include: orig?.include || '',
exclude: orig?.exclude || '',
disableFields: orig?.disableFields || [],
languages: orig?.language || {},
updateHeaderForModifiedFilesOnly: orig?.updateHeaderForModifiedFilesOnly || true,
Expand Down Expand Up @@ -93,7 +109,10 @@ export class ConfigManager {
return flatTags;
}

public async getConfigurationFromCustomConfig() {
return this.configReader?.getConfigYaml();
public async getConfigurationFromCustomConfig(forceRefresh = false) {
if (!this.configYaml || forceRefresh) {
this.configYaml = await this.configReader.getConfigYaml();
}
return this.configYaml;
}
}
32 changes: 19 additions & 13 deletions src/configuration/ConfigReader.ts
Original file line number Diff line number Diff line change
@@ -1,21 +1,20 @@
import path from 'path';
import fs from 'fs';
import YAML from 'yaml';
// import * as vscode from 'vscode';
import { CUSTOM_CONFIG_FILE_NAME } from '@/constants';
import { ConfigYaml } from '@/typings/types';
import { getActiveDocumentWorkspace } from '@/utils/vscode-utils';
import { errorHandler } from '@/extension';
import { CustomError, ErrorCode } from '@/error';

export class ConfigReader {
private static instance: ConfigReader;
private configYaml: ConfigYaml;

private constructor() {
this.configYaml = this.getConfigYaml() as unknown as ConfigYaml;
}

public static getInstance(): ConfigReader {
return ConfigReader?.instance || new ConfigReader();
if (!this.instance) {
this.instance = new ConfigReader();
}
return this.instance;
}

public getConfigYaml = async (): Promise<ConfigYaml> => {
Expand All @@ -37,13 +36,20 @@ export class ConfigReader {
return defaultConfig;
}

// 读取 yaml 配置
const configContent = fs.readFileSync(configPath, 'utf8');
const config: ConfigYaml = YAML.parse(configContent);
return { ...defaultConfig, ...config };
try {
// 读取 yaml 配置
const configContent = fs.readFileSync(configPath, 'utf8');
const config: ConfigYaml = YAML.parse(configContent);
return { ...defaultConfig, ...config };
} catch (error) {
errorHandler.handle(new CustomError(ErrorCode.GetCustomConfigFail));
}
return defaultConfig;
};

public getAllLanguages = (): string[] => {
return this.configYaml?.providers.flatMap((provider) => provider.languages) || [];
public getAllLanguages = async (): Promise<string[]> => {
const config = await this.getConfigYaml();
const languages = config?.providers.flatMap((provider) => provider.languages) || [];
return languages;
};
}
2 changes: 2 additions & 0 deletions src/configuration/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,8 @@ export interface Configuration {
dateFormat: string;
autoInsertOnCreateFile: boolean;
autoUpdateOnSave: boolean;
include: string;
exclude: string;
disableFields: string[];
languages: LanguagesConfig;
updateHeaderForModifiedFilesOnly: boolean;
Expand Down
4 changes: 2 additions & 2 deletions src/error/ErrorHandler.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ export class CustomError extends Error {
} else if (arg instanceof Error) {
// 如果是 Error 对象,设置 originError 为这个对象
super(errorCodeMessages[code]);
this.originalError = args;
this.originalError = arg;
} else {
super(errorCodeMessages[code]);
}
Expand All @@ -25,7 +25,7 @@ export class CustomError extends Error {
const errorObj = args.find((arg) => arg instanceof Error) as Error | undefined;
// 过滤掉Error对象,只留下其它类型的参数
const otherArgs = args.filter((arg) => !(arg instanceof Error));
super(`${errorCodeMessages[code]}${log(otherArgs)}`);
super(`${errorCodeMessages[code]}${log(otherArgs.join(', '))}`);
this.originalError = errorObj;
} else {
super(errorCodeMessages[code]);
Expand Down
8 changes: 6 additions & 2 deletions src/extension-operate/DocumentHandler.ts
Original file line number Diff line number Diff line change
Expand Up @@ -26,15 +26,20 @@ export class DocumentHandler {
}

for (const file of e.files) {
const fileStat = await vscode.workspace.fs.stat(file);
if (fileStat.type === vscode.FileType.Directory) {
return;
}

const document = await vscode.workspace.openTextDocument(file);
if (document.lineCount > 1 || document.lineAt(0).text.trim().length !== 0) {
return;
}

await this.fileheaderManager.updateFileheader(document, {
allowInsert: true,
silent: true,
addSelection: true,
newFile: true,
});
}
};
Expand All @@ -54,7 +59,6 @@ export class DocumentHandler {
async () => {
await this.fileheaderManager.updateFileheader(e.document, {
allowInsert: false,
silent: true,
});
},
2000,
Expand Down
Loading

0 comments on commit 246c2f9

Please sign in to comment.