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是用于构建配置的TypeScript文件。要在hvigorfile.ts中执行类似git rev-list HEAD --count的CMD命令,可以使用Node.js的child_process模块。具体步骤如下:

  1. 导入child_process模块: 在hvigorfile.ts文件中,首先需要导入Node.js的child_process模块,该模块提供了执行外部命令的功能。

    import { execSync } from 'child_process';
    
  2. 执行CMD命令: 使用execSync函数可以同步执行CMD命令,并获取命令的输出结果。例如,执行git rev-list HEAD --count可以如下实现:

    const commitCount = execSync('git rev-list HEAD --count').toString().trim();
    

    这里,execSync会执行git rev-list HEAD --count命令,并将输出结果转换为字符串,使用trim()去除多余的空白字符。

  3. 使用命令结果: 获取到命令的输出结果后,可以将其用于构建配置或其他逻辑中。例如,可以将提交次数作为版本号的一部分:

    const version = `1.0.${commitCount}`;
    
  4. 完整示例: 以下是一个完整的示例,展示了如何在hvigorfile.ts中执行CMD命令并使用其结果:

    import { execSync } from 'child_process';
    
    const commitCount = execSync('git rev-list HEAD --count').toString().trim();
    const version = `1.0.${commitCount}`;
    
    export default {
      // 其他配置项
      version: version,
    };
    

通过上述步骤,你可以在hvigorfile.ts中执行CMD命令并利用其输出结果。

在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命令并输出结果。

回到顶部