Skip to content

Commit

Permalink
配置:默认 ignore 文件列表添加: .formatignore
Browse files Browse the repository at this point in the history
  • Loading branch information
xiaohuohumax committed Mar 25, 2024
1 parent ee66c70 commit 299f882
Show file tree
Hide file tree
Showing 15 changed files with 95 additions and 43 deletions.
5 changes: 5 additions & 0 deletions .changeset/thick-boats-trade.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"format-files-by-ignores": minor
---

默认 ignore 文件列表添加: .formatignore
14 changes: 14 additions & 0 deletions .formatignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
.changeset
.github
.editorconfig
images

.vscode*
.git*

.env*
.eslint*
.formatignore
LICENSE
*.png
*.md
1 change: 1 addition & 0 deletions .vscodeignore
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ images/**
env/**
types/**
.gitignore
.formatignore
.yarnrc
vsc-extension-quickstart.md
**/tsconfig.json
Expand Down
12 changes: 7 additions & 5 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -21,11 +21,13 @@ VSCode Extensions Select `Format Files By Ignores`
## 📄 Usage

- **Format Workspace**
- Open command pallette (Ctrl + Shift + P)
- Enter "Start Format Workspace By Ignores 📂"
- Open command pallette (`Ctrl + Shift + P`)
- Enter `Start Format Workspace By Ignores 📂`
- **Format Folder**
- Right click a folder
- Select "Start Format Folder By Ignores 📂"
- `Right` click a folder
- Select `Start Format Folder By Ignores 📂`
- **Custom Ignore File**
- Create a file called `.formatignore` under the folder, and then write the ignore rules (like `.gitignore`)

## ⚙ Options

Expand All @@ -34,7 +36,7 @@ VSCode Extensions Select `Format Files By Ignores`
- `formatFilesByIgnores.ignoreExtension`: Ignore extension rules (root folder)
- `default`: [ "node_modules", ".vscode", ".git", "dist" ]
- `formatFilesByIgnores.ignoreFileNames`: Ignore files name
- `default`: [ ".gitignore" ]
- `default`: [ ".gitignore", ".formatignore" ]

## 📹 Demo

Expand Down
10 changes: 6 additions & 4 deletions README_CN.md
Original file line number Diff line number Diff line change
Expand Up @@ -22,13 +22,15 @@ VSCode 插件搜索 `Format Files By Ignores`

## 使用

+ 格式文件夹(folder)
+ **格式文件夹(folder)**
+ 文件夹上 `右键`
+ 选择 `Start Format Folder By Ignores 📂`
+ 格式工作空间(workspace)
+ **格式工作空间(workspace)**
+ 调用命令面板 `ctrl + shift + p`
+ 搜索 `Start Format Workspace By Ignores 📂`
+ 选择需要批量格式的 `工作空间(workspace)`
+ **自定义ignore文件**
+ 文件夹下创建名叫 `.formatignore` 的文件, 接着写入过滤规则(规则和 `.gitignore` 相同)

## 配置

Expand All @@ -37,8 +39,8 @@ VSCode 插件搜索 `Format Files By Ignores`
- `formatFilesByIgnores.ignoreExtension`: 文件夹根目录 `ignore` 过滤规则扩展
- `default`: [ "node_modules", ".vscode", ".git", "dist" ]
- `formatFilesByIgnores.ignoreFileNames`: `Ignore` 文件的名称
- `default`: [ ".gitignore" ]
- `default`: [ ".gitignore", ".formatignore" ]

## 演示

![folder.gif](https://cdn.jsdelivr.net/gh/xiaohuohumax/format-files-by-ignores/images/folder.gif)
Expand Down
2 changes: 1 addition & 1 deletion env/.env
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
# 日志等级
VITE_LOG_LEVEL = Debug
# 日志打印格式
VITE_LOG_FORMAT = :time :level: :msg
VITE_LOG_FORMAT = :time :level [:caller]: :msg
# 输出窗口名称
VITE_OUTPUT_CHANNEL_NAME = Format Files By Ignores
4 changes: 3 additions & 1 deletion env/.env.production
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
# 生产发布

# 日志打印格式
VITE_LOG_LEVEL = Info
VITE_LOG_LEVEL = Info
# 日志打印格式
VITE_LOG_FORMAT = :time :level: :msg
6 changes: 4 additions & 2 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -60,7 +60,8 @@
},
"description": "Ignore files name",
"default": [
".gitignore"
".gitignore",
".formatignore"
]
}
}
Expand Down Expand Up @@ -94,7 +95,8 @@
"pretest": "npm run compile && npm run lint:fix",
"lint:fix": "eslint --ext .ts,.mts,.d.ts --fix .",
"changeset": "changeset",
"vsce-publish": "vsce publish"
"vsce-publish": "vsce publish",
"vsce-package": "vsce package"
},
"devDependencies": {
"@changesets/changelog-github": "^0.5.0",
Expand Down
14 changes: 6 additions & 8 deletions src/commands/command.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,8 +25,7 @@ export abstract class Command {
* 命令回调
* @param _args 任意回调参数
*/
// eslint-disable-next-line @typescript-eslint/no-explicit-any
async callback(..._args: any[]): Promise<void> { }
async callback(..._args: unknown[]): Promise<void> { }

/**
* 回调抛出异常时执行
Expand All @@ -46,12 +45,11 @@ export abstract class Command {
* @param context 上下文
*/
async activate(context: vscode.ExtensionContext) {
Logger.debug(`Register command: ${this.options.key}`);
Logger.debug('Register command:', this.options.key);

// eslint-disable-next-line @typescript-eslint/no-explicit-any
const callback = async (...args: any[]) => {
Logger.info(JSON.stringify(FormatConfig.config));
Logger.debug(`Command '${this.options.key}' callback args: ${args}`);
const callback = async (...args: unknown[]) => {
Logger.debug(JSON.stringify(FormatConfig.config));
Logger.debug('Command:', this.options.key, 'callback args:', args);
try {
return await this.callback(...args);
} catch (error) {
Expand All @@ -68,6 +66,6 @@ export abstract class Command {
* 注销指令
*/
async deactivate() {
Logger.debug('Deactivate command: ' + this.options.key);
Logger.debug('Deactivate command:', this.options.key);
}
}
6 changes: 4 additions & 2 deletions src/commands/formatFolder.ts
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ export class FormatFolder extends Command {
}

async callback(folder: Uri): Promise<void> {
Logger.debug('Format folder root: ' + folder);
Logger.debug('Format folder root:', folder);

// 工作空间存在多个文件夹时根目录右键选择异常 {}
// 修正为:让用户自行选择工作空间文件夹
Expand All @@ -60,7 +60,9 @@ export class FormatFolder extends Command {
);

// 供用户检查
Logger.info('Format files:');
Logger.info('Format files (please check):');
const maxLength = Math.max(...files.map(f => f.length));
Logger.info(''.padEnd(maxLength, '-'));
files.forEach(files => Logger.info(files));

// 用户确认
Expand Down
2 changes: 1 addition & 1 deletion src/commands/formatWorkspace.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ import { Logger } from '../util/logger';
export class FilterWorkspace extends FormatFolder {
async callback(): Promise<void> {
const wp = await selectWorkspace();
Logger.debug('Format workspace root: ' + wp.uri);
Logger.debug('Format workspace root:', wp.uri);
// 开始格式化
await super.callback(wp.uri);
}
Expand Down
2 changes: 1 addition & 1 deletion src/util/doc.ts
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,7 @@ export async function formatDocs(docs: Uri[]) {
throw new OperationAborted('Format cancelled');
}
progress.report({ message: file.fsPath, increment });
Logger.debug('Format: ' + file);
Logger.debug('Format:', file);
await formatDoc(file);
}
progress.report({ increment: 100 });
Expand Down
6 changes: 3 additions & 3 deletions src/util/folder.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ export function filterFolderByignore(
const res: string[] = [];

if (!fs.existsSync(root)) {
Logger.debug('Folder not exists: ' + root);
Logger.debug('Folder not exists:', root);
return res;
}

Expand All @@ -27,7 +27,7 @@ export function filterFolderByignore(
for (const ignoreFileName of ignoreFileNames) {
const ignoreFile = path.resolve(root, ignoreFileName);
if (fs.existsSync(ignoreFile)) {
Logger.debug('Find ignore file: ' + ignoreFile);
Logger.debug('Find ignore file:', ignoreFile);
filter.add(fs.readFileSync(ignoreFile, 'utf-8'));
}
}
Expand All @@ -38,7 +38,7 @@ export function filterFolderByignore(
for (const file of files.map(f => path.join(root, f))) {
// 文件可能不存在异常
if (!fs.existsSync(file)) {
Logger.debug('File not exists: ' + file);
Logger.debug('File not exists:', file);
continue;
}
const fileStat = fs.statSync(file);
Expand Down
47 changes: 35 additions & 12 deletions src/util/logger.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,38 +13,61 @@ export class Logger {
// 日志级别
public static logLevel: LogLevel = LogLevel[import.meta.env.VITE_LOG_LEVEL];

public static info(msg: string) {
Logger.log(LogLevel.Info, msg);
public static info(...msgs: unknown[]) {
Logger.print(LogLevel.Info, ...msgs);
}

public static debug(msg: string) {
Logger.log(LogLevel.Debug, msg);
public static debug(...msgs: unknown[]) {
Logger.print(LogLevel.Debug, ...msgs);
}

public static warning(msg: string) {
Logger.log(LogLevel.Warning, msg);
public static warning(...msgs: unknown[]) {
Logger.print(LogLevel.Warning, ...msgs);
}

public static error(msg: string) {
Logger.log(LogLevel.Error, msg);
public static error(...msgs: unknown[]) {
Logger.print(LogLevel.Error, ...msgs);
}

public static log(level: LogLevel, msg: string) {
public static log(level: LogLevel, ...msgs: unknown[]) {
Logger.print(level, ...msgs);
}

private static print(level: LogLevel, ...msgs: unknown[]) {
if (Logger.logLevel > level || Logger.logLevel === LogLevel.Off) {
return;
}

// 简单获取调用信息
let caller = '';
const stack = new Error().stack;
if (stack) {
caller = stack.split('\n')[3]?.replace(/\s*at\s*/i, '');
}

const replaces: [string, string][] = [
// 时间
[':time', new Date().toLocaleString()],
[':msg', msg],
[':level', LogLevel[level].padStart(6, ' ')]
// 消息主体
[':msg', msgs.join(' ')],
// 日志等级
[':level', LogLevel[level].padStart(7, ' ')],
// 调用者信息
[':caller', caller],
];

const line = replaces.reduce(
(f, r) => f.replace(r[0], r[1]),
(f, [key, value]) => f.replace(key, value),
import.meta.env.VITE_LOG_FORMAT
);

Logger.outputChannel.appendLine(line);
}

private static stack() {

}

public static show(preserveFocus?: boolean) {
Logger.outputChannel.show(preserveFocus);
}
Expand Down
7 changes: 4 additions & 3 deletions types/env.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,9 +8,10 @@ interface ImportMetaEnv {
* 日志打印格式
*
* ```
* :time 时间戳
* :level 等级
* :msg 消息
* :time 时间戳
* :level 等级
* :msg 消息
* :caller 调用者信息
* ```
*/
readonly VITE_LOG_FORMAT: string
Expand Down

0 comments on commit 299f882

Please sign in to comment.