publish_xmgame.js 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518
  1. // v1.1.1
  2. // publish 2.x 也是用这个文件,需要做兼容
  3. let isPublish2 = process.argv[2].includes("publish_xmgame.js") && process.argv[3].includes("--evn=publish2");
  4. // 获取Node插件和工作路径
  5. let ideModuleDir, workSpaceDir;
  6. if (isPublish2) {
  7. //是否使用IDE自带的node环境和插件,设置false后,则使用自己环境(使用命令行方式执行)
  8. const useIDENode = process.argv[0].indexOf("LayaAir") > -1 ? true : false;
  9. ideModuleDir = useIDENode ? process.argv[1].replace("gulp\\bin\\gulp.js", "").replace("gulp/bin/gulp.js", "") : "";
  10. workSpaceDir = useIDENode ? process.argv[2].replace("--gulpfile=", "").replace("\\.laya\\publish_xmgame.js", "").replace("/.laya/publish_xmgame.js", "") + "/" : "./../";
  11. } else {
  12. ideModuleDir = global.ideModuleDir;
  13. workSpaceDir = global.workSpaceDir;
  14. }
  15. //引用插件模块
  16. const gulp = require(ideModuleDir + "gulp");
  17. const fs = require("fs");
  18. const path = require("path");
  19. const childProcess = require("child_process");
  20. const del = require(ideModuleDir + "del");
  21. const revCollector = require(ideModuleDir + 'gulp-rev-collector');
  22. let commandSuffix = ".cmd";
  23. let prevTasks = ["packfile"];
  24. if (isPublish2) {
  25. prevTasks = "";
  26. }
  27. let
  28. config,
  29. platform,
  30. releaseDir,
  31. tempReleaseDir, // 小米临时拷贝目录
  32. projDir; // 小米快游戏工程目录
  33. let IDEXMProjPath,
  34. isUpdateIDEXMProj = false;
  35. let versionCon; // 版本管理version.json
  36. // 创建小米项目前,拷贝小米引擎库、修改index.js
  37. // 应该在publish中的,但是为了方便发布2.0及IDE 1.x,放在这里修改
  38. gulp.task("preCreate_XM", prevTasks, function() {
  39. if (isPublish2) {
  40. let pubsetPath = path.join(workSpaceDir, ".laya", "pubset.json");
  41. let content = fs.readFileSync(pubsetPath, "utf8");
  42. let pubsetJson = JSON.parse(content);
  43. platform = "xmgame";
  44. releaseDir = path.join(workSpaceDir, "release", platform).replace(/\\/g, "/");
  45. releaseDir = tempReleaseDir = path.join(releaseDir, "temprelease");
  46. config = pubsetJson[4]; // 只用到了 config.xmInfo|config.xmSign
  47. } else {
  48. platform = global.platform;
  49. releaseDir = global.releaseDir;
  50. tempReleaseDir = global.tempReleaseDir;
  51. config = global.config;
  52. }
  53. // 如果不是小米快游戏
  54. if (platform !== "xmgame") {
  55. return;
  56. }
  57. if (process.platform === "darwin") {
  58. commandSuffix = "";
  59. }
  60. let copyLibsList = [`${workSpaceDir}/bin/libs/laya.xmmini.js`];
  61. var stream = gulp.src(copyLibsList, { base: `${workSpaceDir}/bin` });
  62. return stream.pipe(gulp.dest(tempReleaseDir));
  63. });
  64. gulp.task("copyPlatformFile_XM", ["preCreate_XM"], function() {
  65. // 如果不是小米快游戏
  66. if (platform !== "xmgame") {
  67. return;
  68. }
  69. let xmAdapterPath = path.join(ideModuleDir, "../", "out", "layarepublic", "LayaAirProjectPack", "lib", "data", "xmfiles");
  70. let copyLibsList = [`${xmAdapterPath}/**/*.*`];
  71. var stream = gulp.src(copyLibsList);
  72. return stream.pipe(gulp.dest(tempReleaseDir));
  73. });
  74. // 新建小米项目-小米项目与其他项目不同,需要新建小米快游戏项目,并打包成.rpk文件
  75. gulp.task("checkIDEProj_XM", ["copyPlatformFile_XM"], function() {
  76. // 如果不是小米快游戏
  77. if (platform !== "xmgame") {
  78. return;
  79. }
  80. if (!ideModuleDir) {
  81. return;
  82. }
  83. IDEXMProjPath = path.join(ideModuleDir, "../", "out", "layarepublic", "xm");
  84. if (process.platform === "darwin") {
  85. return;
  86. }
  87. let ideLastXMProjPath = path.join(IDEXMProjPath, config.xmInfo.projName);
  88. // 如果IDE中没有小米项目,跳过这一步
  89. let isProjExist = fs.existsSync(ideLastXMProjPath + "/node_modules") &&
  90. fs.existsSync(ideLastXMProjPath + "/sign");
  91. if (!isProjExist) {
  92. console.log("IDE中没有小米项目,跳过检查小米项目版本号这一步");
  93. return;
  94. }
  95. // 如果IDE中项目已经存在了,检查版本号
  96. // npm view quickgame-cli version
  97. // npm ls quickgame-cli
  98. let remoteVersion, localVersion;
  99. let isGetRemote, isGetLocal;
  100. return new Promise((resolve, reject) => { // 远程版本号
  101. childProcess.exec("npm view quickgame-cli version", function(error, stdout, stderr) {
  102. if (!stdout) { // 获取 quickgame-cli 远程版本号失败
  103. reject();
  104. return;
  105. }
  106. remoteVersion = stdout;
  107. isGetRemote = true;
  108. if (isGetRemote && isGetLocal) {
  109. resolve();
  110. }
  111. });
  112. childProcess.exec("npm ls quickgame-cli", { cwd: ideLastXMProjPath }, function(error, stdout, stderr) {
  113. if (!stdout) { // 获取 quickgame-cli 本地版本号失败
  114. reject();
  115. return;
  116. }
  117. localVersion = stdout.match(/quickgame-cli@(.+)/);
  118. localVersion = localVersion && localVersion[1];
  119. isGetLocal = true;
  120. if (isGetRemote && isGetLocal) {
  121. resolve();
  122. }
  123. });
  124. setTimeout(() => {
  125. if (!isGetLocal || !isGetRemote) {
  126. console.log("获取远程版本号或本地版本号失败");
  127. reject();
  128. return;
  129. }
  130. }, 10000);
  131. }).then(() => { // 比较两个版本号
  132. if (!remoteVersion || !localVersion) {
  133. console.log("获取远程版本号或本地版本号失败!");
  134. }
  135. console.log("quickgame-cli -> ", localVersion, "|", remoteVersion);
  136. if (remoteVersion.trim() !== localVersion.trim()) { // 仅当两个版本号都获取到并且不相等,置为需要更新(true)
  137. isUpdateIDEXMProj = true;
  138. }
  139. }).catch((e) => {
  140. console.log("获取远程版本号或本地版本号失败 -> ", remoteVersion, "|", localVersion);
  141. console.log(e);
  142. });
  143. });
  144. gulp.task("createIDEProj_XM", ["checkIDEProj_XM"], function() {
  145. // 如果不是小米快游戏
  146. if (platform !== "xmgame") {
  147. return;
  148. }
  149. if (!ideModuleDir) {
  150. return;
  151. }
  152. if (process.platform === "darwin") {
  153. return;
  154. }
  155. let ideLastXMProjPath = path.join(IDEXMProjPath, config.xmInfo.projName);
  156. // 如果有即存项目,不再新建
  157. let isProjExist = fs.existsSync(ideLastXMProjPath + "/node_modules") &&
  158. fs.existsSync(ideLastXMProjPath + "/sign");
  159. if (isProjExist && !isUpdateIDEXMProj) { // 项目存在并且不需要更新IDE中的小米项目
  160. return;
  161. }
  162. return new Promise((resolve, reject) => {
  163. console.log("(IDE)开始创建小米快游戏项目,请耐心等待(预计需要10分钟)...");
  164. let cmd = `npx${commandSuffix}`;
  165. let args = ["create-quickgame", config.xmInfo.projName, `path=${IDEXMProjPath}`,
  166. `package=${config.xmInfo.package}`, `versionName=${config.xmInfo.versionName}`,
  167. `versionCode=${config.xmInfo.versionCode}`, `minPlatformVersion=${config.xmInfo.minPlatformVersion}`,
  168. `icon=/layaicon/${path.basename(config.xmInfo.icon)}`, `name=${config.xmInfo.name}`, `rebuild=true`];
  169. console.log(JSON.stringify(args));
  170. let cp = childProcess.spawn(cmd, args);
  171. cp.stdout.on('data', (data) => {
  172. console.log(`stdout: ${data}`);
  173. });
  174. cp.stderr.on('data', (data) => {
  175. console.log(`stderr: ${data}`);
  176. // reject();
  177. });
  178. cp.on('close', (code) => {
  179. console.log(`子进程退出码:${code}`);
  180. resolve();
  181. });
  182. });
  183. });
  184. gulp.task("createProj_XM", ["createIDEProj_XM"], function() {
  185. // 如果不是小米快游戏
  186. if (platform !== "xmgame") {
  187. return;
  188. }
  189. releaseDir = path.dirname(releaseDir);
  190. projDir = path.join(releaseDir, config.xmInfo.projName);
  191. // 如果有即存项目,不再新建
  192. let isProjExist = fs.existsSync(projDir + "/node_modules") &&
  193. fs.existsSync(projDir + "/sign");
  194. if (isProjExist) {
  195. return;
  196. }
  197. // 如果IDE中有即存项目,不再新建,从IDE中拷贝
  198. let ideLastXMProjPath = path.join(IDEXMProjPath, config.xmInfo.projName);
  199. let isIDEXMProjExist = fs.existsSync(ideLastXMProjPath + "/node_modules") &&
  200. fs.existsSync(ideLastXMProjPath + "/sign");
  201. if (isIDEXMProjExist) { // 如果用的IDE并且有IDEXM目录
  202. console.log("使用IDE中的小米游戏项目,拷贝...");
  203. // node-glob语法中,* 无法匹配 .开头的文件(夹),必须手动匹配
  204. let IDEXMProjPathStr = [`${IDEXMProjPath}/**/*.*`, `${ideLastXMProjPath}/node_modules/.bin/*.*`];
  205. var stream = gulp.src(IDEXMProjPathStr, { base: IDEXMProjPath});
  206. return stream.pipe(gulp.dest(releaseDir));
  207. }
  208. // 在项目中创建小米项目
  209. return new Promise((resolve, reject) => {
  210. console.log("(proj)开始创建小米快游戏项目,请耐心等待(预计需要10分钟)...");
  211. let cmd = `npx${commandSuffix}`;
  212. let args = ["create-quickgame", config.xmInfo.projName, `path=${releaseDir}`,
  213. `package=${config.xmInfo.package}`, `versionName=${config.xmInfo.versionName}`,
  214. `versionCode=${config.xmInfo.versionCode}`, `minPlatformVersion=${config.xmInfo.minPlatformVersion}`,
  215. `icon=/layaicon/${path.basename(config.xmInfo.icon)}`, `name=${config.xmInfo.name}`, `rebuild=true`];
  216. console.log(JSON.stringify(args));
  217. let cp = childProcess.spawn(cmd, args);
  218. cp.stdout.on('data', (data) => {
  219. console.log(`stdout: ${data}`);
  220. });
  221. cp.stderr.on('data', (data) => {
  222. console.log(`stderr: ${data}`);
  223. // reject();
  224. });
  225. cp.on('close', (code) => {
  226. console.log(`子进程退出码:${code}`);
  227. resolve();
  228. });
  229. });
  230. });
  231. // 拷贝文件到小米快游戏
  232. gulp.task("copyFileToProj_XM", ["createProj_XM"], function() {
  233. // 如果不是小米快游戏
  234. if (platform !== "xmgame") {
  235. return;
  236. }
  237. // 将临时文件夹中的文件,拷贝到项目中去
  238. let originalDir = `${tempReleaseDir}/**/*.*`;
  239. let stream = gulp.src(originalDir);
  240. return stream.pipe(gulp.dest(path.join(projDir)));
  241. });
  242. // 拷贝icon到小米快游戏
  243. gulp.task("copyIconToProj_XM", ["copyFileToProj_XM"], function() {
  244. // 如果不是小米快游戏
  245. if (platform !== "xmgame") {
  246. return;
  247. }
  248. let originalDir = config.xmInfo.icon;
  249. let stream = gulp.src(originalDir);
  250. return stream.pipe(gulp.dest(path.join(projDir, "layaicon")));
  251. });
  252. // 清除小米快游戏临时目录
  253. gulp.task("clearTempDir_XM", ["copyIconToProj_XM"], function() {
  254. // 如果不是小米快游戏
  255. if (platform !== "xmgame") {
  256. return;
  257. }
  258. // 删掉临时目录
  259. return del([tempReleaseDir], { force: true });
  260. });
  261. // 生成release签名(私钥文件 private.pem 和证书文件 certificate.pem )
  262. gulp.task("generateSign_XM", ["clearTempDir_XM"], function() {
  263. // 如果不是小米快游戏
  264. if (platform !== "xmgame") {
  265. return;
  266. }
  267. if (!config.xmSign.generateSign) {
  268. return;
  269. }
  270. // https://doc.quickapp.cn/tools/compiling-tools.html
  271. return new Promise((resolve, reject) => {
  272. let cmd = "openssl";
  273. let args = ["req", "-newkey", "rsa:2048", "-nodes", "-keyout", "private.pem",
  274. "-x509", "-days", "3650", "-out", "certificate.pem"];
  275. let opts = {
  276. cwd: projDir,
  277. shell: true
  278. };
  279. let cp = childProcess.spawn(cmd, args, opts);
  280. cp.stdout.on('data', (data) => {
  281. console.log(`stdout: ${data}`);
  282. });
  283. cp.stderr.on('data', (data) => {
  284. console.log(`stderr: ${data}`);
  285. data += "";
  286. if (data.includes("Country Name")) {
  287. cp.stdin.write(`${config.xmSign.countryName}\n`);
  288. console.log(`Country Name: ${config.xmSign.countryName}`);
  289. } else if (data.includes("Province Name")) {
  290. cp.stdin.write(`${config.xmSign.provinceName}\n`);
  291. console.log(`Province Name: ${config.xmSign.provinceName}`);
  292. } else if (data.includes("Locality Name")) {
  293. cp.stdin.write(`${config.xmSign.localityName}\n`);
  294. console.log(`Locality Name: ${config.xmSign.localityName}`);
  295. } else if (data.includes("Organization Name")) {
  296. cp.stdin.write(`${config.xmSign.orgName}\n`);
  297. console.log(`Organization Name: ${config.xmSign.orgName}`);
  298. } else if (data.includes("Organizational Unit Name")) {
  299. cp.stdin.write(`${config.xmSign.orgUnitName}\n`);
  300. console.log(`Organizational Unit Name: ${config.xmSign.orgUnitName}`);
  301. } else if (data.includes("Common Name")) {
  302. cp.stdin.write(`${config.xmSign.commonName}\n`);
  303. console.log(`Common Name: ${config.xmSign.commonName}`);
  304. } else if (data.includes("Email Address")) {
  305. cp.stdin.write(`${config.xmSign.emailAddr}\n`);
  306. console.log(`Email Address: ${config.xmSign.emailAddr}`);
  307. // cp.stdin.end();
  308. }
  309. // reject();
  310. });
  311. cp.on('close', (code) => {
  312. console.log(`子进程退出码:${code}`);
  313. resolve();
  314. });
  315. });
  316. });
  317. // 拷贝sign文件到指定位置
  318. gulp.task("copySignFile_XM", ["generateSign_XM"], function() {
  319. // 如果不是小米快游戏
  320. if (platform !== "xmgame") {
  321. return;
  322. }
  323. if (config.xmSign.generateSign) { // 新生成的签名
  324. // 移动签名文件到项目中(Laya & 小米快游戏项目中)
  325. let
  326. privatePem = path.join(projDir, "private.pem"),
  327. certificatePem = path.join(projDir, "certificate.pem");
  328. let isSignExits = fs.existsSync(privatePem) && fs.existsSync(certificatePem);
  329. if (!isSignExits) {
  330. return;
  331. }
  332. let
  333. xiaomiDest = `${projDir}/sign/release`,
  334. layaDest = `${workSpaceDir}/sign/release`;
  335. let stream = gulp.src([privatePem, certificatePem]);
  336. return stream.pipe(gulp.dest(xiaomiDest))
  337. .pipe(gulp.dest(layaDest));
  338. } else if (config.xmInfo.useReleaseSign && !config.xmSign.generateSign) { // 使用release签名,并且没有重新生成
  339. // 从项目中将签名拷贝到小米快游戏项目中
  340. let
  341. privatePem = path.join(workSpaceDir, "sign", "release", "private.pem"),
  342. certificatePem = path.join(workSpaceDir, "sign", "release", "certificate.pem");
  343. let isSignExits = fs.existsSync(privatePem) && fs.existsSync(certificatePem);
  344. if (!isSignExits) {
  345. return;
  346. }
  347. let
  348. xiaomiDest = `${projDir}/sign/release`;
  349. let stream = gulp.src([privatePem, certificatePem]);
  350. return stream.pipe(gulp.dest(xiaomiDest));
  351. }
  352. });
  353. gulp.task("deleteSignFile_XM", ["copySignFile_XM"], function() {
  354. // 如果不是小米快游戏
  355. if (platform !== "xmgame") {
  356. return;
  357. }
  358. if (config.xmSign.generateSign) { // 新生成的签名
  359. let
  360. privatePem = path.join(projDir, "private.pem"),
  361. certificatePem = path.join(projDir, "certificate.pem");
  362. return del([privatePem, certificatePem], { force: true });
  363. }
  364. });
  365. gulp.task("modifyFile_XM", ["deleteSignFile_XM"], function() {
  366. // 如果不是小米快游戏
  367. if (platform !== "xmgame") {
  368. return;
  369. }
  370. // 修改manifest.json文件
  371. let manifestPath = path.join(projDir, "manifest.json");
  372. if (!fs.existsSync(manifestPath)) {
  373. return;
  374. }
  375. let manifestContent = fs.readFileSync(manifestPath, "utf8");
  376. let manifestJson = JSON.parse(manifestContent);
  377. manifestJson.package = config.xmInfo.package;
  378. manifestJson.name = config.xmInfo.name;
  379. manifestJson.orientation = config.xmInfo.orientation;
  380. manifestJson.versionName = config.xmInfo.versionName;
  381. manifestJson.versionCode = config.xmInfo.versionCode;
  382. manifestJson.minPlatformVersion = config.xmInfo.minPlatformVersion;
  383. manifestJson.icon = `/layaicon/${path.basename(config.xmInfo.icon)}`;
  384. fs.writeFileSync(manifestPath, JSON.stringify(manifestJson, null, 4), "utf8");
  385. if (config.version) {
  386. let versionPath = projDir + "/version.json";
  387. versionCon = fs.readFileSync(versionPath, "utf8");
  388. versionCon = JSON.parse(versionCon);
  389. }
  390. let indexJsStr = (versionCon && versionCon["index.js"]) ? versionCon["index.js"] : "index.js";
  391. // 修改main.js文件
  392. let content = 'require("./qg-adapter.js");\nrequire("./libs/laya.xmmini.js");\nrequire("./index.js");';
  393. let mainJsPath = path.join(projDir, "main.js");
  394. fs.writeFileSync(mainJsPath, content, "utf8");
  395. // 小米项目,修改index.js
  396. let filePath = path.join(projDir, indexJsStr);
  397. if (!fs.existsSync(filePath)) {
  398. return;
  399. }
  400. let fileContent = fs.readFileSync(filePath, "utf8");
  401. fileContent = fileContent.replace(/loadLib(\(['"])/gm, "require$1./");
  402. fs.writeFileSync(filePath, fileContent, "utf8");
  403. })
  404. gulp.task("version_XM", ["modifyFile_XM"], function () {
  405. // 如果不是小米快游戏
  406. if (platform !== "xmgame") {
  407. return;
  408. }
  409. if (config.version) {
  410. let versionPath = projDir + "/version.json";
  411. let mainJSPath = projDir + "/main.js";
  412. let srcList = [versionPath, mainJSPath];
  413. return gulp.src(srcList)
  414. .pipe(revCollector())
  415. .pipe(gulp.dest(projDir));
  416. }
  417. });
  418. // 打包rpk
  419. gulp.task("buildRPK_XM", ["version_XM"], function() {
  420. // 如果不是小米快游戏
  421. if (platform !== "xmgame") {
  422. return;
  423. }
  424. // 在小米轻游戏项目目录中执行:
  425. // npm run build || npm run release
  426. let cmdStr = "build";
  427. if (config.xmInfo.useReleaseSign) {
  428. cmdStr = "release";
  429. }
  430. return new Promise((resolve, reject) => {
  431. let cmd = `npm${commandSuffix}`;
  432. let args = ["run", cmdStr];
  433. let opts = {
  434. cwd: projDir
  435. };
  436. let cp = childProcess.spawn(cmd, args, opts);
  437. // let cp = childProcess.spawn(`npx${commandSuffix}`, ['-v']);
  438. cp.stdout.on('data', (data) => {
  439. console.log(`stdout: ${data}`);
  440. });
  441. cp.stderr.on('data', (data) => {
  442. console.log(`stderr: ${data}`);
  443. // reject();
  444. });
  445. cp.on('close', (code) => {
  446. console.log(`子进程退出码:${code}`);
  447. resolve();
  448. });
  449. });
  450. });
  451. gulp.task("showQRCode_XM", ["buildRPK_XM"], function() {
  452. // 如果不是小米快游戏
  453. if (platform !== "xmgame") {
  454. return;
  455. }
  456. // 在小米轻游戏项目目录中执行:
  457. // npm run server
  458. return new Promise((resolve, reject) => {
  459. let cmd = `npm${commandSuffix}`;
  460. let args = ["run", "server"];
  461. let opts = {
  462. cwd: projDir
  463. };
  464. let cp = childProcess.spawn(cmd, args, opts);
  465. // let cp = childProcess.spawn(`npx${commandSuffix}`, ['-v']);
  466. cp.stdout.on('data', (data) => {
  467. console.log(`${data}`);
  468. // 输出pid,macos要用: macos无法kill进程树,也无法执行命令获取3000端口pid(没有查询权限),导致无法kill这个进程
  469. console.log('xm_qrcode_pid:' + cp.pid);
  470. });
  471. cp.stderr.on('data', (data) => {
  472. console.log(`stderr: ${data}`);
  473. // reject();
  474. });
  475. cp.on('close', (code) => {
  476. console.log(`子进程退出码:${code}`);
  477. resolve();
  478. });
  479. });
  480. });
  481. gulp.task("buildXiaomiProj", ["showQRCode_XM"], function() {
  482. console.log("all tasks completed");
  483. });