前端学习 node 快速入门 系列 —— 项目版权格式化

发布时间 2023-04-10 19:27:22作者: 彭加李

其他章节请看:

前端学习 node 快速入门 系列

项目版权格式化

需求

替换整个项目的版权信息,替换文件为 .c.h 结尾。

分析

版权信息通常都在文件开头,通过是否有 copyright 来判断是替换版权还是新增版权

实现

通过 node 读取文件,过滤出 .c、.h 文件,然后用正则判断是替换版权还是新增。代码如下:

const fs = require('fs');
const path = require('path');
function walkSync(currentDirPath, callback) {
    fs.readdirSync(currentDirPath, { withFileTypes: true }).forEach(function (dirent) {
        var filePath = path.join(currentDirPath, dirent.name);
        if (dirent.isFile()) {
            callback(filePath, dirent);
        } else if (dirent.isDirectory()) {
            walkSync(filePath, callback);
        }
    });
}

const dir = 'c-project';
walkSync(dir, function (filePath, stat) {
    // 输出特定文件: .c
    const fileList = ['.c', '.h'];
    // 取得文件后缀
    const extname = path.extname(filePath)
    if (!fileList.includes(extname)) {
        return
    }
    formatFile(filePath)
});

// 格式化文件
function formatFile(filePath) {
    fs.readFile(filePath, 'utf8', (err, data) => {
        if (err) throw err;
        // 新的版权信息
        const copyright = 
`/*
* 1
* 2
* COPYRIGHT ph
* 4
* 5
*/
`
        if ((/^(\s|\r|\n)*(\/\*)((\s|.|\r|\n)*?)(\*\/)/im).test(data)) {
            data = data.replace(/^(\s|\r|\n)*(\/\*)((\s|.|\r|\n)*?)(\*\/)/im, copyright)
        } else {
            data = copyright + data
        }

        fs.writeFile(filePath, data, (err) => {
            if (err) throw err;
            console.log('The file has been saved!');
        });

    });
    console.log(filePath)
}

Tip:正则表达式可以通过可视化工具帮助理解,例如这个

笔者最初使用的正则表达式是第一个,结果处理项目时迟迟不能结束,换成第二个只花费了几秒钟就处理完成。

乱码

批量处理完成后,合并代码前发现有几个文件出现黑桃A的乱码,按照我的程序,不应该匹配,甚至修改。

以为是node读写文件字符编码设置不对,甚至在 linux 中执行 node。最后发现直接通过 vscode 手动修改版权,保存后提交仍旧在该文件其他地方出现黑桃A的乱码

在vscode 中搜索出有黑桃A乱码的共8个文件,node 程序过滤掉它们,直接交给c语言项目开发同学手动替换版权。

其他章节请看:

前端学习 node 快速入门 系列