publish-wechat-new.js 9.09 KB
const fs = require("fs");
const child_process = require("child_process");
const path = require("path");

function getJenkinsConfig() {
    const debug = process.argv[2] === "dev";
    const disableDebugTool = process.argv[3] === "noDebugTool";
    const bucketPath = process.argv[4];
    const ossPath = process.argv[5];
    const emptyRecord = process.argv[6] == "true";
    const isCompressScript = process.argv[7] == "true";

    
    const gameConfigPath = path.join(__dirname, "..", "assets", "script", "GameConfig.ts");
    const fileContent = fs.readFileSync(gameConfigPath, { encoding: "utf-8" });
    let re = /const\s+gameId\s+=\s+\"([a-zA-Z_0-9]+)\"/g;
    let match = re.exec(fileContent);
    let gameid;
    if (match) {
        gameid = match[1];
    }
    re = /const\s+gameVersion\s+=\s+\"([0-9\.]+)\"/g;
    match = re.exec(fileContent);
    let version;
    if (match) {
        version = match[1];
    }

    const wechatSeverResPath = `${bucketPath}/${debug ? "dev" : "release"}/wechat/${version}/`;


    const wechatjsonpath = path.join(__dirname, '..', 'settings', 'wechatgame.json');
    let wechatSetting = JSON.parse(fs.readFileSync(wechatjsonpath));
    const appid = wechatSetting.appid;
    return [gameid, version, debug, disableDebugTool, wechatSeverResPath, appid, bucketPath, ossPath, emptyRecord,isCompressScript];
}

if (!process.env.CREATOR_242_PATH)
    throw new Error("evn CREATOR_242_PATH not set")

const [gGameID, gVersion, gDebug, gDisableDebugTool, gWechatSeverResPath, gAppId, bucketPath, ossPath, emptyRecord,isCompressScript] = getJenkinsConfig();

console.log("current JenkinsInfo is gGameID = " + gGameID + " gVersion=" + gVersion + " gDisableDebugTool=" + gDisableDebugTool + " gWechatSeverResPath=" + gWechatSeverResPath + " gAppId=" + gAppId + "  bucketPath=" + bucketPath + "  ossPath" + ossPath + "  emptyRecord = " + emptyRecord + 'isCompressScript = ' + isCompressScript);

function buildConfig() {

    if (!gDebug || gDisableDebugTool) {//重新设置GameConfig
        const gameConfigPath = path.join(__dirname, "..", "assets", "script", "GameConfig.ts");
        let fileContent = fs.readFileSync(gameConfigPath, { encoding: 'utf-8' });
        if (!gDebug) {
            fileContent = fileContent.replace("debug = true", "debug = false");
            fileContent = fileContent.replace("showFPS = true", "showFPS = false");
        }
        if (gDisableDebugTool) {
            fileContent = fileContent.replace("showDebugTool = true", "showDebugTool = false");
        }
        fileContent = fileContent.replace("simba-sdk-dummy", "simba-sdk-wechat");
        fs.writeFileSync(gameConfigPath, fileContent);
    }
    else {
        const gameConfigPath = path.join(__dirname, "..", "assets", "script", "GameConfig.ts");
        let fileContent = fs.readFileSync(gameConfigPath, { encoding: 'utf-8' });
        fileContent = fileContent.replace("simba-sdk-dummy", "simba-sdk-wechat");
        fs.writeFileSync(gameConfigPath, fileContent);
    }
    {
        const gameConfigPath = path.join(__dirname, "..", "assets", "script", "GameConfig.ts");
        let fileContent = fs.readFileSync(gameConfigPath, { encoding: 'utf-8' });
        if (emptyRecord) {
            console.log("modify EMPTY_RECORD_WHEN_LOGIN value to true");
            fileContent = fileContent.replace("EMPTY_RECORD_WHEN_LOGIN = false", "EMPTY_RECORD_WHEN_LOGIN = true");
            fs.writeFileSync(gameConfigPath, fileContent);
        } else {
            console.log("modify EMPTY_RECORD_WHEN_LOGIN value to false");
            fileContent = fileContent.replace("EMPTY_RECORD_WHEN_LOGIN = true", "EMPTY_RECORD_WHEN_LOGIN = false");
            fs.writeFileSync(gameConfigPath, fileContent);
        }
        console.log("current GameConfig.ts is " + fileContent);
    }

    {
        //重新设置wechatJson里面的额REMOTE_SERVER_ROOT
        const wechatjsonpath = path.join(__dirname, '..', 'settings', 'wechatgame.json');
        let wechatSetting = JSON.parse(fs.readFileSync(wechatjsonpath), { encoding: "utf-8" });
        wechatSetting.REMOTE_SERVER_ROOT = gWechatSeverResPath;
        fs.writeFileSync(wechatjsonpath, JSON.stringify(wechatSetting));
    }

    {
        //重新设置game.js中的变量值
        const gameJsPath = path.join(__dirname, '..', 'build-templates', 'wechatgame', 'game.js');
        let fileContent = fs.readFileSync(gameJsPath, { encoding: "utf-8" });

        if (gDebug && !isCompressScript) {
            fileContent = fileContent.replace("debug = false", "debug = true");
        } else {
            fileContent = fileContent.replace("debug = true", "debug = false");
        }
        console.log("current game.js is " + fileContent);
        fs.writeFileSync(gameJsPath, fileContent);
    }

}

async function rmdir(dir) {
    return new Promise((resolve, reject) => {
        fs.readdir(dir, (err, files) => {
            if (err) reject(err);
            else {
                function next(index) {
                    if (index == files.length) return fs.rmdir(dir, () => {
                        resolve();
                    });
                    let newPath = path.join(dir, files[index]);
                    fs.stat(newPath, (err, stat) => {
                        if (err) reject(err);
                        else {
                            if (stat.isDirectory()) {
                                rmdir(newPath).then(() => {
                                    next(index + 1);
                                }).catch((e) => {
                                    reject(e);
                                });
                            } else {
                                fs.unlink(newPath, (err) => {
                                    if (err) reject(err);
                                    else next(index + 1);
                                });
                            }
                        }
                    });
                }
                next(0);
            }
        });
    });
}

function buildProject() {
    let buildDebug = false;
    if(gDebug) buildDebug = !isCompressScript;
   
    const buildProcess = child_process.spawn(process.env.CREATOR_242_PATH, ["--path", path.join(__dirname, '..'), "--build", `platform=wechatgame;debug=${buildDebug}`, "--force"]);
    buildProcess.stdout.on('data', function (data) {
        console.log('stdout: ' + data);
    });
    buildProcess.on('close', (code) => {
        if (code === 0) {
            console.log("==========================================begin upLoadProcess====================================================");
            upLoadProcess();
            console.log("==========================================end upLoadProcess====================================================");
        } else {
            console.error("Build failed.");
            process.exit(1);
        }
    });
}

async function upLoadProcess() {
    await upLoadOss();
    await upLoadWechat();
}

async function upLoadOss() {
    const cdnAddress = `${ossPath}/${gDebug ? "dev" : "release"}/wechat/${gVersion}/remote`;
    console.log("Upload remote to cdn", cdnAddress);
    const resPath = path.join(__dirname, "..", "build", "wechatgame", "remote");
    await new Promise((resolve, reject) => {
        const uploadProcess = child_process.spawn(path.join(__dirname, "..", "tools", "rss_uploader", "ossutilmac64"), [
            "cp", resPath, cdnAddress, "--recursive", "-f", "-u", "--config-file", path.join(__dirname, "..", "tools", "rss_uploader", ".ossutilconfig")
        ]);
        uploadProcess.stdout.on('data', function (data) {
            console.log('stdout: ' + data);
        });
        uploadProcess.on('close', (code) => {
            if (code === 0) {
                resolve();
            } else {
                reject();
            }
        });
    });
    await rmdir(resPath);
}

async function upLoadWechat() {
    // publish to wechat
    const pubMsg = process.argv[2] + "-" + process.env.BUILD_NUMBER;

    const ci = require('miniprogram-ci');
    const project = new ci.Project({
        appid: gAppId,
        type: 'miniGame',
        projectPath: path.join(__dirname, '..', 'build', 'wechatgame'),
        privateKeyPath: path.join(__dirname, 'private.key'),
    });
    try {
        let uploadResult = await ci.upload({
            project,
            version: gVersion,
            desc: pubMsg,
            setting: {
                es6: false,
                minify: true
            },
            onProgressUpdate: console.log
        });
        console.log("miniprogram-ci upload result", uploadResult);
    } catch (e) {
        console.error("miniprogram-ci upload error", e);
        process.exit(1);
    }
}

console.log("==========================================begin buildConfig====================================================");
buildConfig();
console.log("==========================================end buildConfig====================================================");
console.log("==========================================begin buildProject====================================================");
buildProject();
console.log("==========================================end buildProject====================================================");