需求是从文件夹中遍历检索多层级文件夹,找到其中文件取到上面namespace 后面的名称,在下面代码中自动注入动态代码:
static displayName = "Test";
下面使用node和python两种代码实现一下,方便对照学习
node代码
const fs = require('fs');
const path = require('path');
function traverseFolder(dir, targetString) {
fs.readdirSync(dir).forEach((file) => {
const filePath = path.join(dir, file);
if (fs.statSync(filePath).isDirectory()) {
traverseFolder(filePath, targetString);
} else {
if (fs.readFileSync(filePath, 'utf8').includes(targetString)) {
const fileContent = fs.readFileSync(filePath, 'utf8');
let result = /namespace\b\s*(\w+)\s*\{/.exec(fileContent);
let name = result[1];
let match = /(class Component.*\{)(\s*)/;
let updatedContent = fileContent.replace(match, `$1 \n static displayName = "${name}"; $2`);
fs.writeFileSync(filePath, updatedContent, 'utf8');
}
}
});
}
const targetDirectory = './src'; // 替换为你的目录路径
traverseFolder(targetDirectory, 'namespace ');
python代码
import os
import re
def traverse_folder(dir_path, target_string):
for root, dirs, files in os.walk(dir_path):
# for dir in dirs:
# print("dir", dir)
for file in files:
file_path = os.path.join(root, file)
if "tsx" in file and open(file_path, 'r').read().find(target_string) != -1 :
with open(file_path, 'r') as file:
content = file.read()
match = re.search(r'namespace\b\s*(\w+)\s*\{', content)
if match:
name = match.group(1)
match2 = re.search(r'(class\s+Component.*\{)(\s*)', content)
if match2:
updated_content = content.replace(match2.group(1), f'{match2.group(1)} \n static displayName = "{name}";{match2.group(2)}')
with open(file_path, 'w') as file:
file.write(updated_content)
traverse_folder('./src', 'namespace ') # replace with your directory path