HarmonyOS鸿蒙Next中hvigorfile.ts如何执行cmd命令 类似这种 git rev-list HEAD --count
HarmonyOS鸿蒙Next中hvigorfile.ts如何执行cmd命令 类似这种 git rev-list HEAD --count
想在打包时候根据git rev-list HEAD --count 获取一下当前的 commit 总数。作为应用的 VersionCode,这个有什么办法获取?
4 回复
这个是属于node.js领域的,可以参考如下demo:
import { hapTasks } from '@ohos/hvigor-ohos-plugin';
import * as fs from 'fs';
import * as path from 'path';
import { exec } from 'child_process';
export function customPluginFunction1(str?: string) {
return {
pluginId: 'CustomPluginID1',
apply(pluginContext) {
pluginContext.registerTask({
// 编写自定义任务
name: 'customTask1',
run: (taskContext) => {
// 插件主体
// 执行git命令获取提交id
exec('git rev-parse --short HEAD', (error, stdout, stderr) => {
if (error) {
console.error(`执行命令出错: ${error.message}`);
return;
}
console.log(`命令输出: ${stdout}`);
const filePath = path.join(__dirname, 'src/main/ets/pages/GitTestClass.ets');
console.log('filePath = ', filePath)
const newValue = '123456'
// 读取ets文件内容
fs.readFile(filePath, 'utf8', (err, data) => {
console.log('fs.readFile')
if (err) {
console.log('读取文件时发生错误')
console.error('读取文件时发生错误:', err);
return;
}
// 使用正则表达式替换内容
// const pattern = /@State test: string = '[^']*';/g
// if (pattern.test(data)) {
// console.log("匹配成功!");
// } else {
// console.log("匹配失败!");
// }
// 将git命令返回的id写入ets代码
const updatedContent = data.replace(/@State test: string = '[^']*';/g, `@State test: string = '${newValue}';`);
console.log('updatedContent = ', updatedContent)
// 写入文件
fs.writeFile(filePath, updatedContent, 'utf8', (err) => {
if (err) {
console.error('写入文件时发生错误:', err);
return;
}
console.log('文件已更新');
});
});
});
},
// 确认自定义任务插入位置
dependencies: ['default@BuildJS'],
postDependencies: ['default@CompileArkTS']
})
}
}
}
export default {
system: hapTasks, /* Built-in plugin of Hvigor. It cannot be modified. */
plugins:[
customPluginFunction1()
]/* Custom plugin to extend the functionality of Hvigor. */
}
更多关于HarmonyOS鸿蒙Next中hvigorfile.ts如何执行cmd命令 类似这种 git rev-list HEAD --count的实战系列教程也可以访问 https://www.itying.com/category-93-b0.html
直接用命令行执行,然后修改json文件,
在HarmonyOS鸿蒙Next的hvigorfile.ts中,你可以通过exec方法来执行命令行命令。以下是一个示例,展示如何执行git rev-list HEAD --count命令:
import { exec } from 'hvigor';
task('getGitCommitCount', () => {
exec('git rev-list HEAD --count', (error, stdout, stderr) => {
if (error) {
console.error(`执行命令出错: ${error.message}`);
return;
}
if (stderr) {
console.error(`命令错误输出: ${stderr}`);
return;
}
console.log(`Git commit count: ${stdout.trim()}`);
});
});
这样,当你运行hvigor getGitCommitCount时,就会执行git rev-list HEAD --count命令并输出结果。


