Remove unneeded files (#3221)

* remove unneeded files

* remove submodule cocos2d-console
This commit is contained in:
minggo
2021-01-14 14:36:37 +08:00
committed by GitHub
parent 3e03612fbb
commit 39b2c940ae
25 changed files with 0 additions and 5701 deletions
-3
View File
@@ -1,3 +0,0 @@
[submodule "tools/cocos2d-console"]
path = tools/cocos2d-console
url = https://github.com/cocos-creator/cocos2d-console.git
-4
View File
@@ -1,4 +0,0 @@
node_modules/
package.json
package-lock.json
**/*.map.js
-17
View File
@@ -1,17 +0,0 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const fs = require("fs");
const util_1 = require("util");
exports.afs = {
readFile: util_1.promisify(fs.readFile),
readdir: util_1.promisify(fs.readdir),
stat: util_1.promisify(fs.stat),
exists: util_1.promisify(fs.exists),
copyFile: util_1.promisify(fs.copyFile),
writeFile: util_1.promisify(fs.writeFile),
mkdir: util_1.promisify(fs.mkdir),
mkdtemp: util_1.promisify(fs.mkdtemp),
unlink: util_1.promisify(fs.unlink),
rmdir: util_1.promisify(fs.rmdir)
};
//# sourceMappingURL=afs.js.map
-15
View File
@@ -1,15 +0,0 @@
import * as fs from "fs";
import {promisify} from "util";
export const afs = {
readFile: promisify(fs.readFile),
readdir: promisify(fs.readdir),
stat: promisify(fs.stat),
exists: promisify(fs.exists),
copyFile: promisify(fs.copyFile),
writeFile: promisify(fs.writeFile),
mkdir: promisify(fs.mkdir),
mkdtemp: promisify(fs.mkdtemp),
unlink: promisify(fs.unlink),
rmdir: promisify(fs.rmdir)
};
-8
View File
@@ -1,8 +0,0 @@
#!/bin/bash -l
COCOS_CONSOLE_BIN_DIRECTORY=$(dirname "$0")
COCOS_CONSOLE_BIN_DIRECTORY=$(cd "$COCOS_CONSOLE_BIN_DIRECTORY" && pwd -P)
#python "$COCOS_CONSOLE_BIN_DIRECTORY/cocos.py" "$@"
node $COCOS_CONSOLE_BIN_DIRECTORY/cocos_cli.js "$@"
-2
View File
@@ -1,2 +0,0 @@
@echo off
@node "%~dp0/cocos_cli.js" %*
-789
View File
@@ -1,789 +0,0 @@
"use strict";
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
Object.defineProperty(exports, "__esModule", { value: true });
const fs = require("fs");
const path = require("path");
const ml = require("./multi_language");
const cocos_cfg = require("./cocos_config.json");
const os = require("os");
const afs_1 = require("./afs");
const child_process = require("child_process");
var ArgumentItemType;
(function (ArgumentItemType) {
ArgumentItemType[ArgumentItemType["BOOL_FLAG"] = 0] = "BOOL_FLAG";
ArgumentItemType[ArgumentItemType["STRING_VALUE"] = 1] = "STRING_VALUE";
ArgumentItemType[ArgumentItemType["ACTION"] = 2] = "ACTION";
ArgumentItemType[ArgumentItemType["ENUM"] = 3] = "ENUM";
})(ArgumentItemType || (ArgumentItemType = {}));
/** pre-defined arguments */
exports.pa = {
help: { short: "-h", long: "--help", help: "show this message", arg_type: ArgumentItemType.ACTION },
src_dir: { short: "-s", long: "--src", help: ml.get_string("COCOS_HELP_ARG_SRC"), arg_type: ArgumentItemType.STRING_VALUE },
quiet: { short: '-q', long: "--quiet", help: ml.get_string("COCOS_HELP_ARG_PLATFORM"), arg_type: ArgumentItemType.BOOL_FLAG },
platform: { short: "-p", long: "--platform", help: ml.get_string("COCOS_HELP_ARG_PLATFORM"), arg_type: ArgumentItemType.ENUM, enum_values: cocos_cfg.platforms },
do_list_platforms: { short: "", long: "--list-platforms", help: "list available platforms", arg_type: ArgumentItemType.ACTION },
proj_dir: { short: "", long: "--proj-dir", help: ml.get_string("COCOS_HELP_ARG_PROJ_DIR"), arg_type: ArgumentItemType.STRING_VALUE },
build_dir: { short: "", long: "--build-dir", help: "specify directory where to build project", arg_type: ArgumentItemType.STRING_VALUE },
package_name: { short: "-p", long: "--package", help: ml.get_string("NEW_ARG_PACKAGE"), arg_type: ArgumentItemType.STRING_VALUE },
directory: { short: "-d", long: "--directory", help: ml.get_string("NEW_ARG_DIR"), arg_type: ArgumentItemType.STRING_VALUE },
ios_bundleid: { short: "", long: "--ios-bundleid", help: ml.get_string("NEW_ARG_IOS_BUNDLEID"), arg_type: ArgumentItemType.STRING_VALUE },
mac_bundleid: { short: "", long: "--mac-bundleid", help: ml.get_string("NEW_ARG_MAC_BUNDLEID"), arg_type: ArgumentItemType.STRING_VALUE },
engine_path: { short: "-e", long: "--engine-path", help: ml.get_string("NEW_ARG_ENGINE_PATH"), arg_type: ArgumentItemType.STRING_VALUE },
portrait: { short: "", long: "--portrait", help: ml.get_string("NEW_ARG_PORTRAIT"), arg_type: ArgumentItemType.BOOL_FLAG },
no_native: { short: "", long: "--no-native", help: ml.get_string("NEW_ARG_NO_NATIVE"), arg_type: ArgumentItemType.BOOL_FLAG },
language: { short: "-l", long: "--language", help: ml.get_string("NEW_ARG_LANG"), arg_type: ArgumentItemType.ENUM, enum_values: cocos_cfg.languages },
do_list_templates: { short: "", long: "--list-templates", help: "List available templates. To be used with --template option.", arg_type: ArgumentItemType.ACTION },
template_name: { short: "-k", long: "--template-name", help: 'Name of the template to be used to create the game. To list available names, use --list-templates.', arg_type: ArgumentItemType.STRING_VALUE },
cmake_generator: { short: "-G", long: "--cmake-generator", help: "Set cmake generator", arg_type: ArgumentItemType.STRING_VALUE },
cmake_path: { short: "", long: "--cmake-path", help: "path to cmake.exe or cmake", arg_type: ArgumentItemType.STRING_VALUE },
ios_simulator: { short: "", long: "--ios-simulator", help: "enable iOS simulator support", arg_type: ArgumentItemType.BOOL_FLAG },
teamid: { short: "", long: "--team-id", help: "Apple developer team id", arg_type: ArgumentItemType.STRING_VALUE },
shared_dir: { short: "", long: "--shared-dir", help: "Shared source directory", arg_type: ArgumentItemType.STRING_VALUE },
};
class ArgumentParser {
constructor() {
this.definations = [];
this.values = {};
this.other_values = [];
}
add_argument(short, long, field, arg_type, help, enum_values, required, action, default_value) {
if (short.length != 0 && (!short.startsWith("-") || short.length != 2)) {
console.error(`short argument ${short} format incorrect!`);
}
if (!long.startsWith("--")) {
console.error(`long argument ${long} format incorrect!`);
}
let item = { short, long, help, arg_type, field, enum_values, action, required, default_value };
this.definations.push(item);
return item;
}
add_predefined_argument(field, action) {
let item = exports.pa[field];
if (item) {
return this.add_argument(item.short, item.long, field, item.arg_type, item.help, item.enum_values, false, action);
}
else {
console.error(`Predefiend argument "${field}" is not found!`);
}
}
add_predefined_argument_with_default(field, default_value) {
let item = exports.pa[field];
if (item) {
return this.add_argument(item.short, item.long, field, item.arg_type, item.help, item.enum_values, false, undefined, default_value);
}
else {
console.error(`Predefiend argument "${field}" is not found!`);
}
}
add_required_predefined_argument(field, action) {
let item = exports.pa[field];
if (item) {
return this.add_argument(item.short, item.long, field, item.arg_type, item.help, item.enum_values, true, action);
}
else {
console.error(`Predefiend argument "${field}" is not found!`);
}
}
parse(list) {
let cfgs = [];
for (let i = 0; i < list.length; i++) {
let line = list[i];
cfgs.length = 0;
let prefix;
if (line.startsWith("--")) {
let p1 = line;
if (line.match(/^--[-_a-z]+=/)) { // contains `=` --template-name=
p1 = line.split("=")[0];
}
cfgs = this.definations.filter(x => x.long == p1).sort((a, b) => a.long.length - b.long.length);
if (cfgs.length > 0)
prefix = cfgs[0].long;
}
else if (line.startsWith("-")) {
cfgs = this.definations.filter(x => x.short.length > 0 && line == x.short);
if (cfgs.length > 0)
prefix = cfgs[0].short;
}
else {
this.other_values.push(line);
continue;
}
if (cfgs.length > 0) {
if (cfgs.length > 1) {
console.error(`multiple argument match ${line}`);
break;
}
const cfg = cfgs[0];
if (cfg.arg_type == ArgumentItemType.BOOL_FLAG) {
this.values[cfg.field] = true;
if (line.length > prefix.length) {
console.warn(`argument ${line} too long?`);
}
}
else if (cfg.arg_type == ArgumentItemType.STRING_VALUE || cfg.arg_type == ArgumentItemType.ENUM) {
if (line.length == prefix.length) {
if (list[i + 1] == undefined || list[i + 1].startsWith("-")) {
console.warn(`argument "${prefix}" is not provided with value?`);
}
this.values[cfg.field] = list[i + 1];
i++;
continue;
}
if (line.length > prefix.length) {
let value = line.substr(prefix.length);
this.values[cfg.field] = value[0] === "=" ? value.substr(1) : value;
continue;
}
}
else if (cfg.arg_type == ArgumentItemType.ACTION) {
this.values[cfg.field] = cfg.action;
}
}
else {
console.warn(`unknown argument: ${line}`);
}
}
}
defination_for(key) {
let list = this.definations.filter(x => x.field == key);
if (list.length > 1) {
console.warn(`multiply command line argument definations for "${key}"`);
}
else if (list.length == 0) {
console.error(`no command line argument defination for "${key}" found!`);
return null;
}
return list[0];
}
get_bool(key) {
return this.values[key] === true;
}
set_bool(key, value) {
this.values[key] = value;
}
get_path(key) {
if (!(key in this.values)) {
console.log(`[warn] argument ${key} not set!`);
}
return (key in this.values) ? this.values[key] : this.defination_for(key).default_value;
}
get_string(key) {
if (!(key in this.values)) {
console.log(`[warn] argument ${key} not set!`);
}
return this.get_path(key);
}
set_string(key, v) {
this.values[key] = v;
}
exist_key(key) {
return key in this.values;
}
call(key) {
if (typeof this.values[key] === "function") {
this.values[key].apply();
}
else {
console.log(`[warn] argument value of ${key} is not a function`);
}
}
call_all() {
for (let key in this.values) {
let f = this.values[key];
if (typeof (f) === "function") {
f.call();
return true;
}
}
return false;
}
get_otherargs() {
return this.other_values;
}
print() {
console.log("Usage:");
for (let i of this.definations) {
console.log(` ${i.short.length == 0 ? "" : i.short + ", "}${i.long} \t: ${i.help}`);
}
}
validate() {
for (let key in this.values) {
// validate enums
let v = this.values[key];
let defs = this.definations.filter(x => x.field == key);
if (defs.length > 0) {
if (defs[0].arg_type == ArgumentItemType.ENUM) {
if (!defs[0].enum_values.includes(v)) {
console.error(` incorrect argument "${defs[0].long} ${v}", expect "${defs[0].enum_values.join(",")}"`);
}
}
}
}
for (let d of this.definations) {
if (d.required && !(d.field in this.values)) {
console.error(` required argument ${d.long} is not provided!`);
}
}
}
}
class CCPlugin {
constructor() {
this._cocos2d_path = null;
this._template_path = null;
this._plugin_name = null;
this.ext_args = [];
this.parser = new ArgumentParser();
}
extend_argv(args) {
this.ext_args = this.ext_args.concat(args);
}
get_cocos_root() {
let engine_path = this.get_engine_path();
if (!!engine_path) {
return engine_path;
}
if (!this._cocos2d_path) {
this._cocos2d_path = path.join(__dirname, "../../..");
if (!fs.existsSync(path.join(this._cocos2d_path, "cocos"))) {
console.warn(ml.get_string("COCOS_WARNING_ENGINE_NOT_FOUND"));
this._cocos2d_path = null;
}
}
return this._cocos2d_path;
}
get_consle_root() {
let engine_path = this.get_engine_path();
if (!!engine_path) {
return path.join(engine_path, "tools/cocos-console");
}
return path.join(__dirname, "..");
}
get_templates_root_path() {
let engine_path = this.get_engine_path();
if (!!engine_path) {
return path.join(engine_path, "templates");
}
if (!this._template_path) {
let cocos2d_path = this.get_cocos_root();
if (cocos2d_path) {
this._template_path = path.join(cocos2d_path, "templates");
}
else {
this._template_path = null;
}
}
return this._template_path;
}
get project_dir() {
let dir = this.args.get_path("directory");
return cchelper.replace_env_variables(dir);
}
get_cmake_generator() {
return this.args.get_string("cmake_generator");
}
get_build_dir() {
let dir = this.args.get_string("build_dir");
let ext = "";
if (this.enable_ios_simulator()) {
ext = "-simulator";
}
return cchelper.replace_env_variables(path.join(dir, `build-${this.get_platform()}${ext}`));
}
get_cmake_path() {
let cp = this.args.get_string("cmake_path");
return !!cp ? cp : "cmake";
}
enable_ios_simulator() {
return this.args.get_bool("ios_simulator");
}
get_app_team_id() {
return this.args.get_string("teamid");
}
run_cmake(args) {
return __awaiter(this, void 0, void 0, function* () {
return new Promise((resolve, reject) => {
console.log(`run cmake with ${args.join(" ")}`);
let cp = child_process.spawn(this.get_cmake_path(), args, {
stdio: ["pipe", "pipe", "pipe"],
env: process.env,
shell: true
});
cp.stdout.on("data", (data) => {
console.log(`[cmake] ${data}`);
});
cp.stderr.on("data", (data) => {
console.error(`[cmake-err] ${data}`);
});
cp.on("close", (code, sig) => {
if (code !== 0) {
reject(new Error(`run cmake failed "cmake ${args.join(" ")}", code: ${code}, signal: ${sig}`));
return;
}
resolve();
});
});
});
}
do_list_platforms() {
console.log("support platforms:");
for (let p of cocos_cfg.platforms) {
console.log(` - ${p}`);
}
}
do_show_help() {
let parser = this.parser;
parser.print();
}
set_env(key, value) {
process.env[key] = value;
}
get_env(key) {
return process.env[key];
}
get_current_platform() {
let p = os.platform();
if (p === "darwin") {
return "mac";
}
else if (p == "win32") {
return "win32";
}
console.warn(`platform ${p} is not supported!`);
return p;
}
parse_args() {
let parser = this.parser;
parser.add_predefined_argument("src_dir");
parser.add_predefined_argument("quiet");
parser.add_predefined_argument("platform");
parser.add_predefined_argument("do_list_platforms", this.do_list_platforms.bind(this));
parser.add_predefined_argument("proj_dir");
parser.add_predefined_argument("help", this.do_show_help.bind(this));
this.define_args();
let args = process.argv.slice(3);
this.parser.parse(args.concat(this.ext_args));
//expose enviroment variables
this.set_env("COCOS_X_ROOT", this.get_cocos_root());
}
get_engine_path() {
return null;
}
///////////////// helper methods
get_templates_dir_names() {
let template_dir = this.get_templates_root_path();
let dirs = [];
if (template_dir) {
dirs = fs.readdirSync(template_dir).filter(x => !x.startsWith("."));
dirs = dirs.filter(d => {
let p = path.join(template_dir, d);
let stat = fs.statSync(p);
return stat.isDirectory();
});
}
return dirs;
}
get_template_dir_paths() {
let template_dir = this.get_templates_root_path();
return this.get_templates_dir_names().map(x => path.join(template_dir, x));
}
get_platform() {
let p = this.parser.get_string("platform");
if (!p) {
p = this.get_current_platform();
console.log(`platform not specified, use current platform ${p}`);
}
return p;
}
set_platform(p) {
this.parser.set_string("platform", p);
}
get_plugin_name() { return this._plugin_name; }
set_plugin_name(name) { this._plugin_name = name; }
exec() {
return __awaiter(this, void 0, void 0, function* () {
this.parse_args();
if (this.parser.call_all())
return;
this.parser.validate();
console.log(`[plugin ${this.get_plugin_name()}]: running ...`);
this.init();
yield this.run();
console.log(` [plugin ${this.get_plugin_name()}]: done!`);
});
}
get args() {
return this.parser;
}
}
exports.CCPlugin = CCPlugin;
class cchelper {
static replace_env_variables(str) {
return str.replace(/\$\{([^\}]*)\}/g, (_, n) => process.env[n] == undefined ? _ : process.env[n]).
replace(/(\~)/g, (_, n) => process.env["HOME"]);
}
static fix_path(p) {
p = this.replace_env_variables(p);
if (os.platform() == "win32") {
if (p.indexOf(" ") >= 0) {
console.error(`space found in path "${p}"`);
}
return p.replace(/\\/g, "/").replace(/\/+/, "/");
}
return p;
}
static delay(ms) {
return __awaiter(this, void 0, void 0, function* () {
return new Promise((resolve, reject) => {
setTimeout(() => __awaiter(this, void 0, void 0, function* () {
resolve();
}), ms);
});
});
}
static join(p1, ...p2) {
let l = p2.map(x => this.replace_env_variables(x));
if (path.isAbsolute(l[l.length - 1]))
return l[l.length - 1];
return path.join(this.replace_env_variables(p1), ...p2);
}
static copy_file_sync(src_root, src_file, dst_root, dst_file) {
// console.log(`copy_file_sync args: ${JSON.stringify(arguments)}`);
src_root = this.replace_env_variables(src_root);
src_file = this.replace_env_variables(src_file);
dst_root = this.replace_env_variables(dst_root);
dst_file = this.replace_env_variables(dst_file);
let src = path.isAbsolute(src_file) ? src_file : path.join(src_root, src_file);
let dst = path.isAbsolute(dst_file) ? dst_file : path.join(dst_root, dst_file);
// console.error(`copy_file_sync ${src} -> ${dst}`);
this.make_directory_recursive(path.dirname(dst));
fs.copyFileSync(src, dst);
}
static copy_file_async(src, dst) {
return __awaiter(this, void 0, void 0, function* () {
// console.log(`[async] copy_file ${src} -> ${dst}`);
this.make_directory_recursive(path.parse(dst).dir);
yield afs_1.afs.copyFile(src, dst);
});
}
static copy_recursive_async(src_dir, dst) {
return __awaiter(this, void 0, void 0, function* () {
src_dir = this.replace_env_variables(src_dir);
dst = this.replace_env_variables(dst);
let tasks = [];
let src_stat = yield afs_1.afs.stat(src_dir);
if (!src_stat) {
console.error(`failed to stat ${src_dir}`);
return;
}
if (src_stat.isDirectory()) {
this.make_directory_recursive(dst);
let files = yield afs_1.afs.readdir(src_dir);
for (let f of files) {
if (f == "." || f == "..")
continue;
let fp = path.join(src_dir, f);
let tsk = this.copy_recursive_async(fp, path.join(dst, f));
tasks.push(tsk);
}
yield Promise.all(tasks);
}
else if (src_stat.isFile()) {
try {
yield this.copy_file_async(src_dir, dst);
}
catch (e) {
yield this.delay(10);
console.error(`error: retry copying ${src_dir} -> to ${dst} ... ${e}`);
yield this.copy_file_async(src_dir, dst);
}
}
});
}
static prepare_dirs_for_files(src_root, files, dst_dir) {
let tree = {};
for (let f of files) {
let parts = f.split("/");
let p = tree;
for (let i of parts) {
if (i in p) {
p = p[i];
}
else {
p = p[i] = {};
}
}
}
let mkdirs = (src_dir, attrs, dst_dir) => {
let src_stat = fs.statSync(src_dir);
if (!src_stat.isDirectory())
return;
if (!fs.existsSync(dst_dir)) {
// console.log(`prepere_dir ${dst_dir}`);
fs.mkdirSync(dst_dir);
}
for (let i in attrs) {
if (i !== "." && i !== "..") {
mkdirs(path.join(src_dir, i), attrs[i], path.join(dst_dir, i));
}
}
};
mkdirs(src_root, tree, dst_dir);
}
static parallel_copy_files(par, src_root, files, dst_dir) {
let running_tasks = 0;
dst_dir = this.replace_env_variables(dst_dir);
cchelper.prepare_dirs_for_files(src_root, files, dst_dir);
return new Promise((resolve, reject) => {
let copy_async = (src, dst) => __awaiter(this, void 0, void 0, function* () {
running_tasks += 1;
yield this.copy_recursive_async(src, dst);
running_tasks -= 1;
schedule_copy();
});
let schedule_copy = () => {
if (files.length > 0 && running_tasks < par) {
let f = files.shift();
let src_file = path.join(src_root, f);
if (fs.existsSync(src_file)) {
copy_async(src_file, path.join(dst_dir, f));
}
else {
console.warn(`warning: copy_file: ${src_file} not exists!`);
}
}
if (files.length == 0 && running_tasks == 0) {
resolve();
}
};
for (let i = 0; i < par; i++)
schedule_copy();
});
}
static make_directory_recursive(dir) {
if (dir.length == 0)
return;
let dirs = [];
let p = dir;
while (!fs.existsSync(p)) {
dirs.push(p);
p = path.join(p, "..");
}
while (dirs.length > 0) {
fs.mkdirSync(dirs[dirs.length - 1]);
dirs.length = dirs.length - 1;
}
}
static remove_directory_recursive(dir) {
return __awaiter(this, void 0, void 0, function* () {
let stat = yield afs_1.afs.stat(dir);
if (stat.isFile()) {
yield afs_1.afs.unlink(dir);
}
else if (stat.isDirectory()) {
let list = yield afs_1.afs.readdir(dir);
let tasks = [];
for (let f of list) {
if (f == "." || f == "..")
continue;
let fp = path.join(dir, f);
tasks.push(this.remove_directory_recursive(fp));
}
yield Promise.all(tasks);
yield afs_1.afs.rmdir(dir);
}
});
}
static copy_files_with_config(cfg, src_root, dst_root) {
return __awaiter(this, void 0, void 0, function* () {
if (!fs.existsSync(src_root)) {
console.error(`copy file src_root ${src_root} is not exists!`);
return;
}
src_root = this.replace_env_variables(src_root);
dst_root = this.replace_env_variables(dst_root);
let from = this.replace_env_variables(cfg.from);
let to = this.replace_env_variables(cfg.to);
if (path.isAbsolute(from)) {
src_root = from;
from = ".";
}
if (path.isAbsolute(to)) {
dst_root = to;
to = ".";
}
// console.log(`copy ${JSON.stringify(cfg)}, ${from} -> ${to} from ${src_root} -> ${dst_root}`);
let build_prefix_tree = (list0) => {
let tree = {};
let list = list0.map(x => Array.from(x));
while (list.length > 0) {
let t = list.shift();
let p = tree;
while (t.length > 0) {
let c = t.shift();
if (!(c in p)) {
p[c] = {};
}
p = p[c];
}
}
return tree;
};
let match_prefix_tree = (str, tree) => {
if (tree == null) {
return false;
}
let arr = Array.from(str);
let i = 0;
let p = tree;
while (arr[i] in p) {
p = p[arr[i]];
i++;
}
return i == arr.length && Object.keys(p).length == 0;
};
let include_prefix = cfg.include ? build_prefix_tree(cfg.include) : null;
let exclude_prefix = cfg.exclude ? build_prefix_tree(cfg.exclude) : null;
let cp_r_async = (src_root, src_dir, dst_root) => __awaiter(this, void 0, void 0, function* () {
let curr_full_dir = path.join(src_root, src_dir);
let stat = yield afs_1.afs.stat(curr_full_dir);
if (stat.isDirectory()) {
let files = yield afs_1.afs.readdir(curr_full_dir);
let subcopies = [];
for (let f of files) {
if (f == "." || f == "..")
continue;
let path_in_src_root = path.join(src_dir, f);
if (exclude_prefix && match_prefix_tree(path_in_src_root, exclude_prefix)) {
if (include_prefix && match_prefix_tree(path_in_src_root, include_prefix)) {
//include
}
else {
console.log(` - skip copy ${src_root} ${path_in_src_root} to ${dst_root}`);
continue;
}
}
subcopies.push(cp_r_async(src_root, path_in_src_root, dst_root));
}
yield Promise.all(subcopies);
}
else if (stat.isFile()) {
// let dst_file_abs = path.isAbsolute(src_dir) ? src_dir : path.join(dst_root, src_dir);
yield this.copy_file_async(curr_full_dir, path.join(dst_root, src_dir));
}
});
let copy_from = this.replace_env_variables(path.normalize(path.join(src_root, from)));
let copy_to = this.replace_env_variables(path.normalize(path.join(dst_root, to)));
yield cp_r_async(src_root, from, copy_to);
});
}
static replace_in_file(patterns, filepath) {
return __awaiter(this, void 0, void 0, function* () {
filepath = this.replace_env_variables(filepath);
if (!fs.existsSync(filepath)) {
console.log(`warning: file ${filepath} not exists while replacing content!`);
return;
}
// console.log(`replace ${filepath} with ${JSON.stringify(patterns)}`);
let lines = (yield afs_1.afs.readFile(filepath)).toString("utf8").split("\n");
let new_content = lines.map(l => {
patterns.forEach(p => {
l = l.replace(new RegExp(p.reg), this.replace_env_variables(p.text));
});
return l;
}).join("\n");
yield afs_1.afs.writeFile(filepath, new_content);
});
}
static exact_value_from_file(regexp, filename, idx) {
if (!(fs.existsSync(filename))) {
console.error(`file ${filename} not exist!`);
return;
}
let lines = fs.readFileSync(filename).toString("utf-8").split("\n");
for (let l of lines) {
let r = l.match(regexp);
if (r) {
return r[idx];
}
}
}
static run_cmd(cmd, args, slient, cwd) {
return __awaiter(this, void 0, void 0, function* () {
return new Promise((resolve, reject) => {
console.log(`[run_cmd]: ${cmd} ${args.join(" ")}`);
let cp = child_process.spawn(cmd, args, {
shell: true,
env: process.env,
cwd: cwd || process.cwd()
});
if (!slient) {
cp.stdout.on(`data`, (chunk) => {
console.log(`[run_cmd ${cmd}] ${chunk}`);
});
cp.stderr.on(`data`, (chunk) => {
console.log(`[run_cmd ${cmd} - error] ${chunk}`);
});
}
cp.on("close", (code, signal) => {
if (code != 0 && !slient)
return reject(`faile to exec ${cmd} ${args.join(" ")}`);
resolve();
});
});
});
}
}
exports.cchelper = cchelper;
class CCPluginRunner {
load_plugin(plugin_name) {
let p = null;
let script_path = path.join(__dirname, `plugin_${plugin_name}.js`);
if (!fs.existsSync(script_path)) {
console.error(`Plugin ${plugin_name} is not defined!`);
process.exit(1);
}
let exp = require(script_path);
let klsName = `CCPlugin${plugin_name.toUpperCase()}`;
if (klsName in exp) {
p = new exp[klsName];
}
else {
console.error(`${klsName} not defined in plugin_${plugin_name}.js`);
process.exit(1);
}
p.set_plugin_name(plugin_name);
return p;
}
run() {
return __awaiter(this, void 0, void 0, function* () {
let plugin_name = process.argv[2];
let task = [];
let p;
do {
p = this.load_plugin(plugin_name);
task.push(p);
} while ((plugin_name = p.depends()) !== null);
for (let i = task.length - 1; i >= 0; i--) {
yield task[i].exec();
}
});
}
}
process.on("unhandledRejection", (err, promise) => {
console.error(`----unhandledRejection---`);
console.error(err);
});
let runner = new CCPluginRunner();
runner.run().then(() => {
console.log(`[all done!]`);
process.exit(0);
});
//# sourceMappingURL=cocos_cli.js.map
-859
View File
@@ -1,859 +0,0 @@
import * as fs from "fs";
import * as path from "path";
import * as ml from "./multi_language";
import * as cocos_cfg from "./cocos_config.json";
import * as os from "os";
import { afs } from "./afs";
import * as child_process from "child_process";
enum ArgumentItemType {
BOOL_FLAG,
STRING_VALUE,
ACTION,
ENUM,
}
interface ArgumentConfig {
short: string;
long: string;
field?: string;
help: string;
arg_type: ArgumentItemType;
action?: () => void;
enum_values?: string[];
required: boolean;
default_value?: string;
}
/** pre-defined arguments */
export const pa = {
help: { short: "-h", long: "--help", help: "show this message", arg_type: ArgumentItemType.ACTION },
src_dir: { short: "-s", long: "--src", help: ml.get_string("COCOS_HELP_ARG_SRC"), arg_type: ArgumentItemType.STRING_VALUE },
quiet: { short: '-q', long: "--quiet", help: ml.get_string("COCOS_HELP_ARG_PLATFORM"), arg_type: ArgumentItemType.BOOL_FLAG },
platform: { short: "-p", long: "--platform", help: ml.get_string("COCOS_HELP_ARG_PLATFORM"), arg_type: ArgumentItemType.ENUM, enum_values: cocos_cfg.platforms },
do_list_platforms: { short: "", long: "--list-platforms", help: "list available platforms", arg_type: ArgumentItemType.ACTION },
proj_dir: { short: "", long: "--proj-dir", help: ml.get_string("COCOS_HELP_ARG_PROJ_DIR"), arg_type: ArgumentItemType.STRING_VALUE },
build_dir: { short: "", long: "--build-dir", help: "specify directory where to build project", arg_type: ArgumentItemType.STRING_VALUE },
package_name: { short: "-p", long: "--package", help: ml.get_string("NEW_ARG_PACKAGE"), arg_type: ArgumentItemType.STRING_VALUE },
directory: { short: "-d", long: "--directory", help: ml.get_string("NEW_ARG_DIR"), arg_type: ArgumentItemType.STRING_VALUE },
ios_bundleid: { short: "", long: "--ios-bundleid", help: ml.get_string("NEW_ARG_IOS_BUNDLEID"), arg_type: ArgumentItemType.STRING_VALUE },
mac_bundleid: { short: "", long: "--mac-bundleid", help: ml.get_string("NEW_ARG_MAC_BUNDLEID"), arg_type: ArgumentItemType.STRING_VALUE },
engine_path: { short: "-e", long: "--engine-path", help: ml.get_string("NEW_ARG_ENGINE_PATH"), arg_type: ArgumentItemType.STRING_VALUE },
portrait: { short: "", long: "--portrait", help: ml.get_string("NEW_ARG_PORTRAIT"), arg_type: ArgumentItemType.BOOL_FLAG },
no_native: { short: "", long: "--no-native", help: ml.get_string("NEW_ARG_NO_NATIVE"), arg_type: ArgumentItemType.BOOL_FLAG },
language: { short: "-l", long: "--language", help: ml.get_string("NEW_ARG_LANG"), arg_type: ArgumentItemType.ENUM, enum_values: cocos_cfg.languages },
do_list_templates: { short: "", long: "--list-templates", help: "List available templates. To be used with --template option.", arg_type: ArgumentItemType.ACTION },
template_name: { short: "-k", long: "--template-name", help: 'Name of the template to be used to create the game. To list available names, use --list-templates.', arg_type: ArgumentItemType.STRING_VALUE },
cmake_generator: { short: "-G", long: "--cmake-generator", help: "Set cmake generator", arg_type: ArgumentItemType.STRING_VALUE },
cmake_path: { short: "", long: "--cmake-path", help: "path to cmake.exe or cmake", arg_type: ArgumentItemType.STRING_VALUE },
ios_simulator: { short: "", long: "--ios-simulator", help: "enable iOS simulator support", arg_type: ArgumentItemType.BOOL_FLAG },
teamid: { short: "", long: "--team-id", help: "Apple developer team id", arg_type: ArgumentItemType.STRING_VALUE },
shared_dir: { short: "", long: "--shared-dir", help: "Shared source directory", arg_type: ArgumentItemType.STRING_VALUE },
};
class ArgumentParser {
private definations: ArgumentConfig[] = [];
private values: { [key: string]: (string | boolean | { (): void }) } = {};
private other_values: string[] = [];
add_argument(short: string, long: string, field: string, arg_type: ArgumentItemType, help: string, enum_values: string[], required: boolean, action?: () => void, default_value?: string): ArgumentConfig {
if (short.length != 0 && (!short.startsWith("-") || short.length != 2)) {
console.error(`short argument ${short} format incorrect!`);
}
if (!long.startsWith("--")) {
console.error(`long argument ${long} format incorrect!`);
}
let item = { short, long, help, arg_type, field, enum_values, action, required, default_value };
this.definations.push(item);
return item;
}
add_predefined_argument(field: string, action?: () => void): ArgumentConfig | undefined {
let item = (pa as any)[field];
if (item) {
return this.add_argument(item.short, item.long, field, item.arg_type, item.help, item.enum_values, false, action);
} else {
console.error(`Predefiend argument "${field}" is not found!`)
}
}
add_predefined_argument_with_default(field: string, default_value: string): ArgumentConfig | undefined {
let item = (pa as any)[field];
if (item) {
return this.add_argument(item.short, item.long, field, item.arg_type, item.help, item.enum_values, false, undefined, default_value);
} else {
console.error(`Predefiend argument "${field}" is not found!`)
}
}
add_required_predefined_argument(field: string, action?: () => void): ArgumentConfig | undefined {
let item = (pa as any)[field];
if (item) {
return this.add_argument(item.short, item.long, field, item.arg_type, item.help, item.enum_values, true, action);
} else {
console.error(`Predefiend argument "${field}" is not found!`)
}
}
parse(list: string[]) {
let cfgs: ArgumentConfig[] = [];
for (let i = 0; i < list.length; i++) {
let line = list[i];
cfgs.length = 0;
let prefix: string;
if (line.startsWith("--")) {
let p1: string = line;
if (line.match(/^--[-_a-z]+=/)) { // contains `=` --template-name=
p1 = line.split("=")[0];
}
cfgs = this.definations.filter(x => x.long == p1).sort((a, b) => a.long.length - b.long.length);
if (cfgs.length > 0) prefix = cfgs[0].long;
} else if (line.startsWith("-")) {
cfgs = this.definations.filter(x => x.short.length > 0 && line == x.short);
if (cfgs.length > 0) prefix = cfgs[0].short;
} else {
this.other_values.push(line);
continue;
}
if (cfgs.length > 0) {
if (cfgs.length > 1) {
console.error(`multiple argument match ${line}`);
break;
}
const cfg = cfgs[0];
if (cfg.arg_type == ArgumentItemType.BOOL_FLAG) {
this.values[cfg.field!] = true;
if (line.length > prefix!.length) {
console.warn(`argument ${line} too long?`)
}
} else if (cfg.arg_type == ArgumentItemType.STRING_VALUE || cfg.arg_type == ArgumentItemType.ENUM) {
if (line.length == prefix!.length) {
if (list[i + 1] == undefined || list[i + 1].startsWith("-")) {
console.warn(`argument "${prefix!}" is not provided with value?`)
}
this.values[cfg.field!] = list[i + 1];
i++;
continue;
}
if (line.length > prefix!.length) {
let value = line.substr(prefix!.length);
this.values[cfg.field!] = value[0] === "=" ? value.substr(1) : value;
continue;
}
} else if (cfg.arg_type == ArgumentItemType.ACTION) {
this.values[cfg.field!] = cfg.action!;
}
} else {
console.warn(`unknown argument: ${line}`)
}
}
}
private defination_for(key: string): ArgumentConfig | null {
let list = this.definations.filter(x => x.field == key);
if (list.length > 1) {
console.warn(`multiply command line argument definations for "${key}"`);
} else if (list.length == 0) {
console.error(`no command line argument defination for "${key}" found!`);
return null;
}
return list[0];
}
public get_bool(key: string): boolean {
return (this.values[key] as boolean) === true;
}
public set_bool(key:string, value:boolean) {
this.values[key] = value;
}
public get_path(key: string): string {
if (!(key in this.values)) {
console.log(`[warn] argument ${key} not set!`);
}
return (key in this.values) ? this.values[key] as string : this.defination_for(key)!.default_value!;
}
public get_string(key: string): string {
if (!(key in this.values)) {
console.log(`[warn] argument ${key} not set!`);
}
return this.get_path(key);
}
public set_string(key:string, v:string) {
this.values[key] = v;
}
public exist_key(key: string): boolean {
return key in this.values;
}
public call(key: string): void {
if (typeof this.values[key] === "function") {
(this.values[key] as any).apply();
} else {
console.log(`[warn] argument value of ${key} is not a function`)
}
}
public call_all(): boolean {
for (let key in this.values) {
let f = this.values[key];
if (typeof (f) === "function") {
(f as any).call();
return true;
}
}
return false;
}
public get_otherargs(): string[] {
return this.other_values;
}
public print() {
console.log("Usage:")
for (let i of this.definations) {
console.log(` ${i.short.length == 0 ? "" : i.short + ", "}${i.long} \t: ${i.help}`);
}
}
public validate() {
for (let key in this.values) {
// validate enums
let v = this.values[key];
let defs = this.definations.filter(x => x.field == key);
if (defs.length > 0) {
if (defs[0].arg_type == ArgumentItemType.ENUM) {
if (!defs[0].enum_values!.includes(v as string)) {
console.error(` incorrect argument "${defs[0].long} ${v}", expect "${defs[0].enum_values!.join(",")}"`);
}
}
}
}
for (let d of this.definations) {
if (d.required && !(d.field! in this.values)) {
console.error(` required argument ${d.long} is not provided!`);
}
}
}
}
export abstract class CCPlugin {
private _cocos2d_path: string | null = null;
private _template_path: string | null = null;
private _plugin_name: string | null = null;
private ext_args:string[] = [];
parser: ArgumentParser = new ArgumentParser();
extend_argv(args:string[]) {
this.ext_args = this.ext_args.concat(args);
}
get_cocos_root(): string | null {
let engine_path = this.get_engine_path();
if (!!engine_path) {
return engine_path;
}
if (!this._cocos2d_path) {
this._cocos2d_path = path.join(__dirname, "../../..");
if (!fs.existsSync(path.join(this._cocos2d_path, "cocos"))) {
console.warn(ml.get_string("COCOS_WARNING_ENGINE_NOT_FOUND"));
this._cocos2d_path = null;
}
}
return this._cocos2d_path;
}
get_consle_root(): string {
let engine_path = this.get_engine_path();
if (!!engine_path) {
return path.join(engine_path, "tools/cocos-console");
}
return path.join(__dirname, "..");
}
get_templates_root_path(): string | null {
let engine_path = this.get_engine_path();
if (!!engine_path) {
return path.join(engine_path, "templates");
}
if (!this._template_path) {
let cocos2d_path = this.get_cocos_root();
if (cocos2d_path) {
this._template_path = path.join(cocos2d_path, "templates");
} else {
this._template_path = null;
}
}
return this._template_path;
}
get project_dir(): string | undefined {
let dir = this.args.get_path("directory");
return cchelper.replace_env_variables(dir);
}
get_cmake_generator(): string | undefined {
return this.args.get_string("cmake_generator");
}
get_build_dir(): string {
let dir = this.args.get_string("build_dir");
let ext = "";
if (this.enable_ios_simulator()) {
ext = "-simulator";
}
return cchelper.replace_env_variables(path.join(dir, `build-${this.get_platform()}${ext}`));
}
get_cmake_path(): string {
let cp = this.args.get_string("cmake_path");
return !!cp ? cp : "cmake";
}
enable_ios_simulator(): boolean {
return this.args.get_bool("ios_simulator");
}
get_app_team_id(): string | undefined {
return this.args.get_string("teamid");
}
async run_cmake(args: string[]) {
return new Promise((resolve, reject) => {
console.log(`run cmake with ${args.join(" ")}`);
let cp = child_process.spawn(this.get_cmake_path(), args, {
stdio: ["pipe", "pipe", "pipe"],
env: process.env,
shell: true
});
cp.stdout.on("data", (data) => {
console.log(`[cmake] ${data}`);
});
cp.stderr.on("data", (data) => {
console.error(`[cmake-err] ${data}`);
});
cp.on("close", (code, sig) => {
if (code !== 0) {
reject(new Error(`run cmake failed "cmake ${args.join(" ")}", code: ${code}, signal: ${sig}`));
return;
}
resolve();
});
});
}
private do_list_platforms() {
console.log("support platforms:");
for (let p of cocos_cfg.platforms) {
console.log(` - ${p}`);
}
}
private do_show_help() {
let parser = this.parser;
parser.print();
}
protected set_env(key: string, value: string) {
process.env[key] = value;
}
protected get_env(key: string): string {
return process.env[key]!;
}
get_current_platform(): string {
let p = os.platform();
if (p === "darwin") {
return "mac";
} else if (p == "win32") {
return "win32";
}
console.warn(`platform ${p} is not supported!`);
return p;
}
parse_args() {
let parser = this.parser;
parser.add_predefined_argument("src_dir");
parser.add_predefined_argument("quiet");
parser.add_predefined_argument("platform");
parser.add_predefined_argument("do_list_platforms", this.do_list_platforms.bind(this));
parser.add_predefined_argument("proj_dir");
parser.add_predefined_argument("help", this.do_show_help.bind(this));
this.define_args();
let args = process.argv.slice(3);
this.parser.parse(args.concat(this.ext_args));
//expose enviroment variables
this.set_env("COCOS_X_ROOT", this.get_cocos_root()!);
}
abstract define_args(): void;
abstract init(): boolean;
abstract async run(): Promise<boolean>;
abstract depends(): string | null;
get_engine_path(): string | null {
return null;
}
///////////////// helper methods
get_templates_dir_names(): string[] {
let template_dir = this.get_templates_root_path();
let dirs: string[] = [];
if (template_dir) {
dirs = fs.readdirSync(template_dir).filter(x => !x.startsWith("."));
dirs = dirs.filter(d => {
let p = path.join(template_dir!, d);
let stat = fs.statSync(p);
return stat.isDirectory();
});
}
return dirs;
}
get_template_dir_paths(): string[] {
let template_dir = this.get_templates_root_path();
return this.get_templates_dir_names().map(x => path.join(template_dir!, x));
}
get_platform(): string {
let p = this.parser.get_string("platform");
if (!p) {
p = this.get_current_platform();
console.log(`platform not specified, use current platform ${p}`);
}
return p;
}
set_platform(p:string) {
this.parser.set_string("platform", p);
}
get_plugin_name(): string { return this._plugin_name!; }
set_plugin_name(name: string) { this._plugin_name = name; }
async exec() {
this.parse_args();
if (this.parser.call_all()) return;
this.parser.validate();
console.log(`[plugin ${this.get_plugin_name()}]: running ...`);
this.init();
await this.run();
console.log(` [plugin ${this.get_plugin_name()}]: done!`);
}
get args(): ArgumentParser {
return this.parser;
}
}
export class cchelper {
static replace_env_variables(str: string): string {
return str.replace(/\$\{([^\}]*)\}/g, (_, n) => process.env[n] == undefined ? _ : process.env[n]!).
replace(/(\~)/g, (_, n) => process.env["HOME"]!);
}
static fix_path(p: string): string {
p = this.replace_env_variables(p);
if (os.platform() == "win32") {
if(p.indexOf(" ") >= 0) {
console.error(`space found in path "${p}"`);
}
return p.replace(/\\/g, "/").replace(/\/+/, "/");
}
return p;
}
static async delay<T>(ms: number): Promise<T> {
return new Promise((resolve, reject) => {
setTimeout(async () => {
resolve();
}, ms);
});
}
static join(p1:string, ...p2:string[]) :string {
let l = p2.map(x=> this.replace_env_variables(x));
if(path.isAbsolute(l[l.length - 1])) return l[l.length -1];
return path.join(this.replace_env_variables(p1), ...p2);
}
static copy_file_sync(src_root: string, src_file: string, dst_root: string, dst_file: string) {
// console.log(`copy_file_sync args: ${JSON.stringify(arguments)}`);
src_root = this.replace_env_variables(src_root);
src_file = this.replace_env_variables(src_file);
dst_root = this.replace_env_variables(dst_root);
dst_file = this.replace_env_variables(dst_file);
let src = path.isAbsolute(src_file) ? src_file: path.join(src_root, src_file);
let dst = path.isAbsolute(dst_file)? dst_file: path.join(dst_root, dst_file);
// console.error(`copy_file_sync ${src} -> ${dst}`);
this.make_directory_recursive(path.dirname(dst));
fs.copyFileSync(src, dst);
}
static async copy_file_async(src: string, dst: string) {
// console.log(`[async] copy_file ${src} -> ${dst}`);
this.make_directory_recursive(path.parse(dst).dir);
await afs.copyFile(src, dst);
}
static async copy_recursive_async(src_dir: string, dst: string) {
src_dir = this.replace_env_variables(src_dir);
dst = this.replace_env_variables(dst);
let tasks: Promise<any>[] = [];
let src_stat = await afs.stat(src_dir);
if (!src_stat) {
console.error(`failed to stat ${src_dir}`);
return;
}
if (src_stat.isDirectory()) {
this.make_directory_recursive(dst);
let files = await afs.readdir(src_dir);
for (let f of files) {
if (f == "." || f == "..") continue;
let fp = path.join(src_dir, f);
let tsk = this.copy_recursive_async(fp, path.join(dst, f));
tasks.push(tsk);
}
await Promise.all(tasks);
} else if (src_stat.isFile()) {
try {
await this.copy_file_async(src_dir, dst);
} catch (e) {
await this.delay(10);
console.error(`error: retry copying ${src_dir} -> to ${dst} ... ${e}`);
await this.copy_file_async(src_dir, dst);
}
}
}
static prepare_dirs_for_files(src_root:string, files: string[], dst_dir:string) {
let tree: any = {};
for(let f of files) {
let parts = f.split("/");
let p = tree;
for(let i of parts) {
if(i in p) {
p = p[i];
}else {
p = p[i] = {};
}
}
}
let mkdirs = ( src_dir:string, attrs:any, dst_dir:string) => {
let src_stat = fs.statSync(src_dir);
if(!src_stat.isDirectory()) return;
if(!fs.existsSync(dst_dir)) {
// console.log(`prepere_dir ${dst_dir}`);
fs.mkdirSync(dst_dir);
}
for(let i in attrs) {
if(i !== "." && i !== "..") {
mkdirs(path.join(src_dir, i), attrs[i], path.join(dst_dir, i));
}
}
}
mkdirs(src_root, tree, dst_dir);
}
static parallel_copy_files(par: number, src_root: string, files: string[], dst_dir: string) {
let running_tasks = 0;
dst_dir = this.replace_env_variables(dst_dir);
cchelper.prepare_dirs_for_files(src_root, files, dst_dir);
return new Promise((resolve, reject) => {
let copy_async = async (src: string, dst: string) => {
running_tasks += 1;
await this.copy_recursive_async(src, dst);
running_tasks -= 1;
schedule_copy();
};
let schedule_copy = () => {
if (files.length > 0 && running_tasks < par) {
let f = files.shift()!;
let src_file = path.join(src_root, f);
if(fs.existsSync(src_file)){
copy_async(src_file, path.join(dst_dir, f))
}else{
console.warn(`warning: copy_file: ${src_file} not exists!`);
}
}
if (files.length == 0 && running_tasks == 0) {
resolve();
}
}
for (let i = 0; i < par; i++) schedule_copy();
});
}
static make_directory_recursive(dir: string) {
if (dir.length == 0) return;
let dirs: string[] = [];
let p = dir;
while (!fs.existsSync(p)) {
dirs.push(p);
p = path.join(p, "..");
}
while (dirs.length > 0) {
fs.mkdirSync(dirs[dirs.length - 1]);
dirs.length = dirs.length - 1;
}
}
static async remove_directory_recursive(dir: string) {
let stat = await afs.stat(dir);
if (stat.isFile()) {
await afs.unlink(dir);
} else if (stat.isDirectory()) {
let list = await afs.readdir(dir);
let tasks: Promise<any>[] = [];
for (let f of list) {
if (f == "." || f == "..") continue;
let fp = path.join(dir, f);
tasks.push(this.remove_directory_recursive(fp));
}
await Promise.all(tasks);
await afs.rmdir(dir);
}
}
static async copy_files_with_config(cfg: { from: string, to: string, include?: string[], exclude?: string[] }, src_root: string, dst_root: string) {
if (!fs.existsSync(src_root)) {
console.error(`copy file src_root ${src_root} is not exists!`);
return;
}
src_root = this.replace_env_variables(src_root);
dst_root = this.replace_env_variables(dst_root);
let from = this.replace_env_variables(cfg.from)
let to = this.replace_env_variables(cfg.to);
if (path.isAbsolute(from)) {
src_root = from;
from = ".";
}
if (path.isAbsolute(to)) {
dst_root = to;
to = ".";
}
// console.log(`copy ${JSON.stringify(cfg)}, ${from} -> ${to} from ${src_root} -> ${dst_root}`);
let build_prefix_tree = (list0: string[]) => {
let tree: any = {};
let list = list0.map(x => Array.from(x));
while (list.length > 0) {
let t = list.shift()!;
let p = tree;
while (t.length > 0) {
let c = t.shift()!;
if (!(c in p)) {
p[c] = {};
}
p = p[c];
}
}
return tree;
};
let match_prefix_tree = (str: string, tree: any): boolean => {
if (tree == null) {
return false;
}
let arr = Array.from(str);
let i = 0;
let p = tree;
while (arr[i] in p) {
p = p[arr[i]];
i++;
}
return i == arr.length && Object.keys(p).length == 0;
}
let include_prefix = cfg.include ? build_prefix_tree(cfg.include) : null;
let exclude_prefix = cfg.exclude ? build_prefix_tree(cfg.exclude) : null;
let cp_r_async = async (src_root: string, src_dir: string, dst_root: string) => {
let curr_full_dir = path.join(src_root, src_dir);
let stat = await afs.stat(curr_full_dir);
if (stat.isDirectory()) {
let files = await afs.readdir(curr_full_dir);
let subcopies: Promise<any>[] = [];
for (let f of files) {
if (f == "." || f == "..") continue;
let path_in_src_root = path.join(src_dir, f);
if (exclude_prefix && match_prefix_tree(path_in_src_root, exclude_prefix)) {
if (include_prefix && match_prefix_tree(path_in_src_root, include_prefix)) {
//include
} else {
console.log(` - skip copy ${src_root} ${path_in_src_root} to ${dst_root}`);
continue;
}
}
subcopies.push(cp_r_async(src_root, path_in_src_root, dst_root));
}
await Promise.all(subcopies);
} else if (stat.isFile()) {
// let dst_file_abs = path.isAbsolute(src_dir) ? src_dir : path.join(dst_root, src_dir);
await this.copy_file_async(curr_full_dir, path.join(dst_root, src_dir));
}
}
let copy_from = this.replace_env_variables(path.normalize(path.join(src_root, from)));
let copy_to = this.replace_env_variables(path.normalize(path.join(dst_root, to)));
await cp_r_async(src_root, from, copy_to);
}
static async replace_in_file(patterns: { reg: string, text: string }[], filepath: string) {
filepath = this.replace_env_variables(filepath);
if (!fs.existsSync(filepath)) {
console.log(`warning: file ${filepath} not exists while replacing content!`);
return;
}
// console.log(`replace ${filepath} with ${JSON.stringify(patterns)}`);
let lines = (await afs.readFile(filepath)).toString("utf8").split("\n");
let new_content = lines.map(l => {
patterns.forEach(p => {
l = l.replace(new RegExp(p.reg), this.replace_env_variables(p.text));
});
return l;
}).join("\n");
await afs.writeFile(filepath, new_content);
}
static exact_value_from_file(regexp: RegExp, filename: string, idx: number): string | undefined {
if (!(fs.existsSync(filename))) {
console.error(`file ${filename} not exist!`);
return;
}
let lines = fs.readFileSync(filename).toString("utf-8").split("\n");
for (let l of lines) {
let r = l.match(regexp);
if (r) {
return r[idx];
}
}
}
static async run_cmd(cmd: string, args: string[], slient: boolean, cwd?: string) {
return new Promise<any>((resolve, reject) => {
console.log(`[run_cmd]: ${cmd} ${args.join(" ")}`);
let cp = child_process.spawn(cmd, args, {
shell: true,
env: process.env,
cwd: cwd! || process.cwd()
});
if (!slient) {
cp.stdout.on(`data`, (chunk) => {
console.log(`[run_cmd ${cmd}] ${chunk}`);
});
cp.stderr.on(`data`, (chunk) => {
console.log(`[run_cmd ${cmd} - error] ${chunk}`);
});
}
cp.on("close", (code, signal) => {
if (code != 0 && !slient) return reject(`faile to exec ${cmd} ${args.join(" ")}`);
resolve();
});
});
}
}
class CCPluginRunner {
private load_plugin(plugin_name: string): CCPlugin {
let p: CCPlugin | null = null;
let script_path = path.join(__dirname, `plugin_${plugin_name}.js`);
if (!fs.existsSync(script_path)) {
console.error(`Plugin ${plugin_name} is not defined!`);
process.exit(1);
}
let exp = require(script_path);
let klsName = `CCPlugin${plugin_name.toUpperCase()}`;
if (klsName in exp) {
p = new exp[klsName];
} else {
console.error(`${klsName} not defined in plugin_${plugin_name}.js`);
process.exit(1);
}
p!.set_plugin_name(plugin_name);
return p!;
}
public async run() {
let plugin_name = process.argv[2];
let task: CCPlugin[] = [];
let p: CCPlugin;
do {
p = this.load_plugin(plugin_name);
task.push(p);
} while ((plugin_name = p.depends()!) !== null);
for (let i = task.length - 1; i >= 0; i--) {
await task[i].exec();
}
}
}
process.on("unhandledRejection", (err, promise) => {
console.error(`----unhandledRejection---`);
console.error(err);
});
let runner = new CCPluginRunner();
runner.run().then(() => {
console.log(`[all done!]`);
process.exit(0);
});
@@ -1,59 +0,0 @@
{
"languages": [
"js"
],
"platforms": [
"ios",
"mac",
"win32",
"android",
"ios-simulator"
],
"support_templates":["link", "default"],
"default": {
"project_name": "MyGame"
},
"availableTargetPlatforms": {
"mac": [
"mac",
"ios",
"android"
],
"win32": [
"win32",
"android"
]
},
"defaultGeneratePlatforms": {
"mac":["mac", "ios-simulator"],
"win32":["win32"]
},
"cmake": {
"win32": {
"generators": [
{
"G": "Visual Studio 16 2019",
"A": "win32"
},
{
"G": "Visual Studio 15 2017"
},
{
"G": "Visual Studio 14 2015"
},
{
"G": "Visual Studio 12 2013"
},
{
"G": "Visual Studio 11 2012"
},
{
"G": "Visual Studio 10 2010"
},
{
"G": "Visual Studio 9 2008"
}
]
}
}
}
@@ -1,4 +0,0 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.CONFIG = '.cocos-project.json';
//# sourceMappingURL=cocos_project_config.js.map
@@ -1,4 +0,0 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.CONFIG = '.cocos-project.json';
//# sourceMappingURL=cocos_project_types.js.map
@@ -1,63 +0,0 @@
export interface CocosProject{
project_type:string;
has_native:boolean;
custom_step_script:string;
engine_version:string;
pre_build:string;
post_build:string;
}
export const CONFIG: string = '.cocos-project.json';
export interface CocosProjectTasks {
exclude_from_template?: string[],
append_from_template: {
from:string;
to:string;
exclude?:string[];
},
append_file: {from:string, to:string}[],
append_x_engine?:{
from:string; to:string
},
project_rename:{
src_project_name:string;
files:[]
},
project_replace_project_name: {
src_project_name:string,
files:string[];
},
project_replace_package_name: {
src_package_name:string;
files:string[]
},
project_replace_mac_bundleid: {
src_bundle_id: string;
files:string[]
},
project_replace_ios_bundleid: {
src_bundle_id:string,
files:string[]
},
project_replace_cocos_x_root: {
pattern: string;
files:(string|{file:string, default?:string, link?:string, needFix?:boolean})[];
},
project_replace_projec_common: {
pattern: string;
files:(string|{file:string, default?:string, link?:string, needFix?:boolean})[];
}
common_replace?: {pattern:string, value:string, files:string[]}[];
}
export interface CocosProjecConfig {
do_default:CocosProjectTasks,
do_add_native_support: CocosProjectTasks
}
@@ -1,120 +0,0 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const path = require("path");
const fs = require("fs");
const cfg_info = require("./strings.json");
// const CONFIG_FILE_NAME = "strings.json";
const DEFAULT_LANGUAGE = "en";
let locale = null;
let cur_lang_string = null;
let default_lang_string = null;
function get_env_locale() {
const default_ret = { lang: "en" };
let env = process.env;
let lang_encoding = env.LC_ALL || env.LC_MESSAGES || env.LANG || env.LANGUAGE || Intl.DateTimeFormat().resolvedOptions().locale;
if (!lang_encoding) {
return default_ret;
}
let p2 = lang_encoding.split(".");
return { lang: p2[0] || default_ret.lang };
}
function get_avaiable_langs() {
if (!!cfg_info) {
return Object.keys(cfg_info);
}
return [];
}
function get_lang_key(lang) {
let p2 = lang.split("_");
if (p2[0] == "zh")
return (p2.length == 1 || p2[1] == "cn") ? "zh" : "zh_tr";
return p2[0];
}
function do_init() {
locale = get_env_locale();
cur_lang_string = cfg_info[get_lang_key(locale.lang)];
if (!cur_lang_string) {
cur_lang_string = cfg_info[DEFAULT_LANGUAGE];
}
default_lang_string = cfg_info[DEFAULT_LANGUAGE];
}
do_init();
function set_current_language(lang) {
let lang_key = get_lang_key(lang);
if (lang in cfg_info) {
cur_lang_string = cfg_info[lang];
locale.lang = lang;
}
else if (lang_key in cfg_info) {
cur_lang_string = cfg_info[lang_key];
locale.lang = lang_key;
}
else {
console.warn();
}
}
exports.set_current_language = set_current_language;
function get_string(key, ...fmts) {
if (cur_lang_string) {
let fmt = cur_lang_string[key];
if (!fmt) {
return `[KEY "${key}" is not found! lang: ${locale.lang}]`;
}
if (fmts.length == 0) {
return fmt;
}
let chars = Array.from(fmt);
let ret = [];
let len = chars.length;
let p = 0;
let ai = 0;
let place_holders = 0;
while (p < len) {
if (chars[p] == "%") {
if (chars[p + 1] == "d" || chars[p + 1] == "f") {
ret.push(fmts[ai++] + ""); // %d | %f
place_holders++;
}
else if (chars[p + 1] == "s") {
ret.push(fmts[ai++] + ""); // %s
place_holders++;
}
else if (chars[p + 1] == "%") {
ret.push("%"); // %%
}
else {
// unknown formatter?
ret.push(fmts[ai++] + ""); // %?
place_holders++;
}
p += 2;
}
else {
ret.push(chars[p]);
p += 1;
}
}
if (place_holders != fmts.length) {
console.error(`format argument mismatch: ${fmt} & ${fmts.join(", ")}`);
}
return ret.join("");
}
return `[language ${locale.lang} not set, key ${key}]`;
}
exports.get_string = get_string;
function has_key(key, data) {
return !!data && (key in data);
}
exports.has_key = has_key;
function get_current_string(key) {
let ret;
if (has_key(key, cur_lang_string)) {
ret = cur_lang_string[key];
}
else if (has_key(key, default_lang_string)) {
ret = default_lang_string[key];
}
return ret || key;
}
exports.get_current_string = get_current_string;
//# sourceMappingURL=multi_language.js.map
@@ -1,127 +0,0 @@
const path = require("path");
const fs = require("fs");
const cfg_info = require("./strings.json");
// const CONFIG_FILE_NAME = "strings.json";
const DEFAULT_LANGUAGE = "en";
interface LocaleInfo {
lang:string;
encoding?:string;
}
let locale: LocaleInfo | null = null;
let cur_lang_string : {[key:string]:string}|null = null;
let default_lang_string : {[key:string]:string}|null = null;
function get_env_locale() : LocaleInfo {
const default_ret = {lang: "en"};
let env = process.env;
let lang_encoding = env.LC_ALL || env.LC_MESSAGES || env.LANG || env.LANGUAGE || Intl.DateTimeFormat().resolvedOptions().locale;
if(!lang_encoding) {
return default_ret;
}
let p2 = lang_encoding.split(".");
return {lang: p2[0] || default_ret.lang};
}
function get_avaiable_langs() : string[] {
if(!!cfg_info) {
return Object.keys(cfg_info);
}
return [];
}
function get_lang_key(lang: string) : string {
let p2 = lang.split("_");
if(p2[0] == "zh")
return (p2.length == 1 || p2[1] == "cn") ? "zh" : "zh_tr";
return p2[0];
}
function do_init() {
locale = get_env_locale();
cur_lang_string = cfg_info[get_lang_key(locale.lang)];
if(!cur_lang_string) {
cur_lang_string = cfg_info[DEFAULT_LANGUAGE];
}
default_lang_string = cfg_info[DEFAULT_LANGUAGE];
}
do_init();
export function set_current_language(lang:string) {
let lang_key = get_lang_key(lang);
if(lang in cfg_info) {
cur_lang_string = cfg_info[lang];
locale!.lang = lang;
} else if(lang_key in cfg_info) {
cur_lang_string = cfg_info[lang_key];
locale!.lang = lang_key;
} else {
console.warn()
}
}
export function get_string(key:string, ...fmts: (string|number)[]) {
if(cur_lang_string) {
let fmt = cur_lang_string[key];
if(!fmt){
return `[KEY "${key}" is not found! lang: ${locale!.lang}]`
}
if(fmts.length == 0) {
return fmt;
}
let chars = Array.from(fmt);
let ret : string []= [];
let len = chars.length;
let p = 0;
let ai = 0;
let place_holders = 0;
while(p < len) {
if(chars[p] == "%") {
if(chars[p + 1] == "d" || chars[p+1] == "f") {
ret.push(fmts[ai++] + ""); // %d | %f
place_holders ++;
} else if(chars[p + 1] == "s") {
ret.push(fmts[ai++] + ""); // %s
place_holders ++;
} else if(chars[p + 1] == "%") {
ret.push("%"); // %%
} else {
// unknown formatter?
ret.push(fmts[ai++] + ""); // %?
place_holders++;
}
p +=2;
}else {
ret.push(chars[p]);
p += 1;
}
}
if(place_holders != fmts.length) {
console.error(`format argument mismatch: ${fmt} & ${fmts.join(", ")}`)
}
return ret.join("");
}
return `[language ${locale!.lang} not set, key ${key}]`
}
export function has_key(key:string, data: {[key:string]:string}|null):boolean {
return !!data && (key in data);
}
export function get_current_string(key:string):string {
let ret:string|undefined;
if(has_key(key, cur_lang_string)) {
ret = cur_lang_string![key];
} else if(has_key(key, default_lang_string)) {
ret = default_lang_string![key];
}
return ret || key;
}
@@ -1,140 +0,0 @@
"use strict";
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
Object.defineProperty(exports, "__esModule", { value: true });
const cocos_cli_1 = require("./cocos_cli");
const path = require("path");
const cocos_cfg = require("./cocos_config.json");
const fs = require("fs");
const PackageNewConfig = "cocos-project-template.json";
class CCPluginCOMPILE extends cocos_cli_1.CCPlugin {
depends() {
return "generate";
}
define_args() {
this.parser.add_predefined_argument("build_dir");
this.parser.add_predefined_argument("cmake_path");
this.parser.add_predefined_argument("ios_simulator");
this.parser.add_predefined_argument("directory");
}
init() {
if (cocos_cfg.platforms.indexOf(this.get_platform()) < 0) {
console.error(`invalidate platform "${this.get_platform()}"`);
}
return true;
}
run() {
return __awaiter(this, void 0, void 0, function* () {
yield this.compile_platform(this.get_platform());
return true;
});
}
compile_platform(p) {
return __awaiter(this, void 0, void 0, function* () {
let c = this.get_current_platform();
let allow_targets = cocos_cfg.availableTargetPlatforms[c];
if (!!!allow_targets) {
console.error(`current host platform ${c} is not supported.`);
process.exit(1);
return;
}
if (allow_targets.indexOf(p) < 0) {
console.error(`target platform "${p}" is not listed [${allow_targets.join(", ")}]`);
process.exit(1);
return;
}
if (p === "mac") {
yield this.compile_mac();
}
else if (p == "ios") {
yield this.compile_ios();
}
else if (p == "win32") {
yield this.compile_win32();
}
else if (p == "android") {
yield this.compile_android();
}
});
}
compile_android() {
return __awaiter(this, void 0, void 0, function* () {
yield (new AndroidCompileCMD(this)).compile();
});
}
compile_ios() {
return __awaiter(this, void 0, void 0, function* () {
yield (new IOSCompileCMD(this)).compile();
});
}
compile_mac() {
return __awaiter(this, void 0, void 0, function* () {
yield (new MacCompileCMD(this)).compile();
});
}
compile_win32() {
return __awaiter(this, void 0, void 0, function* () {
yield (new Win32CompileCMD(this)).compile();
});
}
}
exports.CCPluginCOMPILE = CCPluginCOMPILE;
class PlatformCompileCmd {
constructor(plugin) {
this.plugin = plugin;
}
}
class IOSCompileCMD extends PlatformCompileCmd {
compile() {
return __awaiter(this, void 0, void 0, function* () {
let build_dir = this.plugin.get_build_dir();
yield this.plugin.run_cmake(["--build", `${build_dir}`, "--config", "Debug", "--", "-allowProvisioningUpdates", "-quiet"]);
return true;
});
}
}
class MacCompileCMD extends PlatformCompileCmd {
compile() {
return __awaiter(this, void 0, void 0, function* () {
let build_dir = this.plugin.get_build_dir();
yield this.plugin.run_cmake(["--build", `${build_dir}`, "--config", "Debug", "--", "-quiet"]);
return true;
});
}
}
class Win32CompileCMD extends PlatformCompileCmd {
compile() {
return __awaiter(this, void 0, void 0, function* () {
let build_dir = this.plugin.get_build_dir();
yield this.plugin.run_cmake(["--build", `${cocos_cli_1.cchelper.fix_path(build_dir)}`, "--config", "Debug", "--", "-verbosity:quiet"]);
return true;
});
}
}
class AndroidCompileCMD extends PlatformCompileCmd {
compile() {
return __awaiter(this, void 0, void 0, function* () {
let build_dir = this.plugin.get_build_dir();
let proj_dir = path.join(this.plugin.project_dir, "frameworks/runtime-src/proj.android-studio");
if (!fs.existsSync(proj_dir)) {
console.error(`dir ${proj_dir} not exits`);
return false;
}
let gradle = "gradlew";
if (this.plugin.get_current_platform() == "win32") {
gradle += ".bat";
}
gradle = path.join(proj_dir, gradle);
yield cocos_cli_1.cchelper.run_cmd(gradle, ["assembleDebug", "--quiet", "--build-cache", "--project-cache-dir", build_dir], false, proj_dir);
return true;
});
}
}
//# sourceMappingURL=plugin_compile.js.map
@@ -1,133 +0,0 @@
import { CCPlugin, pa, cchelper } from "./cocos_cli";
import * as path from "path";
import * as os from "os";
import * as cocos_cfg from "./cocos_config.json";
import * as child_process from "child_process";
import { afs } from "./afs";
import * as fs from "fs";
const PackageNewConfig = "cocos-project-template.json";
export class CCPluginCOMPILE extends CCPlugin {
depends():string |null {
return "generate";
}
define_args(): void {
this.parser.add_predefined_argument("build_dir");
this.parser.add_predefined_argument("cmake_path");
this.parser.add_predefined_argument("ios_simulator");
this.parser.add_predefined_argument("directory");
}
init(): boolean {
if (cocos_cfg.platforms.indexOf(this.get_platform()) < 0) {
console.error(`invalidate platform "${this.get_platform()}"`);
}
return true;
}
async run(): Promise<boolean> {
await this.compile_platform(this.get_platform()!);
return true;
}
async compile_platform(p: string) {
let c = this.get_current_platform();
let allow_targets = (cocos_cfg.availableTargetPlatforms as any)[c];
if (!!!allow_targets) {
console.error(`current host platform ${c} is not supported.`);
process.exit(1);
return;
}
if (allow_targets.indexOf(p) < 0) {
console.error(`target platform "${p}" is not listed [${allow_targets.join(", ")}]`);
process.exit(1);
return;
}
if (p === "mac") {
await this.compile_mac();
} else if (p == "ios") {
await this.compile_ios();
} else if (p == "win32") {
await this.compile_win32();
} else if (p == "android") {
await this.compile_android();
}
}
async compile_android() {
await (new AndroidCompileCMD(this)).compile();
}
async compile_ios() {
await (new IOSCompileCMD(this)).compile();
}
async compile_mac() {
await (new MacCompileCMD(this)).compile();
}
async compile_win32() {
await (new Win32CompileCMD(this)).compile();
}
}
abstract class PlatformCompileCmd {
plugin: CCPluginCOMPILE;
constructor(plugin: CCPluginCOMPILE) {
this.plugin = plugin;
}
abstract async compile(): Promise<boolean>;
}
class IOSCompileCMD extends PlatformCompileCmd {
async compile() {
let build_dir = this.plugin.get_build_dir();
await this.plugin.run_cmake(["--build", `${build_dir}`, "--config", "Debug", "--", "-allowProvisioningUpdates", "-quiet"]);
return true;
}
}
class MacCompileCMD extends PlatformCompileCmd {
async compile() {
let build_dir = this.plugin.get_build_dir();
await this.plugin.run_cmake(["--build", `${build_dir}`, "--config", "Debug", "--", "-quiet"]);
return true;
}
}
class Win32CompileCMD extends PlatformCompileCmd {
async compile() {
let build_dir = this.plugin.get_build_dir();
await this.plugin.run_cmake(["--build", `${cchelper.fix_path(build_dir)}`, "--config", "Debug", "--", "-verbosity:quiet"]);
return true;
}
}
class AndroidCompileCMD extends PlatformCompileCmd {
async compile() {
let build_dir = this.plugin.get_build_dir();
let proj_dir:string = path.join(this.plugin.project_dir!, "frameworks/runtime-src/proj.android-studio");
if(!fs.existsSync(proj_dir)) {
console.error(`dir ${proj_dir} not exits`);
return false;
}
let gradle = "gradlew";
if(this.plugin.get_current_platform() == "win32") {
gradle += ".bat";
}
gradle = path.join(proj_dir, gradle);
await cchelper.run_cmd(gradle, ["assembleDebug", "--quiet", "--build-cache", "--project-cache-dir",build_dir], false, proj_dir);
return true;
}
}
@@ -1,276 +0,0 @@
"use strict";
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
Object.defineProperty(exports, "__esModule", { value: true });
const cocos_cli_1 = require("./cocos_cli");
const os = require("os");
const cocos_cfg = require("./cocos_config.json");
const child_process = require("child_process");
const afs_1 = require("./afs");
const PackageNewConfig = "cocos-project-template.json";
class CCPluginGENERATE extends cocos_cli_1.CCPlugin {
depends() {
// return "new"; // recreate project file will override everything
return null;
}
define_args() {
this.parser.add_required_predefined_argument("build_dir");
this.parser.add_required_predefined_argument("directory");
this.parser.add_predefined_argument("cmake_generator");
this.parser.add_predefined_argument("cmake_path");
this.parser.add_predefined_argument("ios_simulator");
this.parser.add_predefined_argument("teamid");
this.parser.add_predefined_argument_with_default("template_name", "link");
}
init() {
if (cocos_cfg.platforms.indexOf(this.get_platform()) < 0) {
console.error(`invalidate platform "${this.get_platform()}"`);
}
return true;
}
run() {
return __awaiter(this, void 0, void 0, function* () {
let arg_p = this.parser.get_string("platform");
if (!arg_p) {
let ps = cocos_cfg["defaultGeneratePlatforms"][this.get_current_platform()];
for (let p of ps) {
yield this.generate_platform(p);
}
}
else {
yield this.generate_platform(arg_p);
}
return true;
});
}
generate_platform(p) {
return __awaiter(this, void 0, void 0, function* () {
let c = this.get_current_platform();
if (p == "ios-simulator") {
p = "ios";
this.set_platform("ios");
this.extend_argv(["--ios-simulator"]);
this.args.set_bool("ios_simulator", true);
}
let allow_targets = cocos_cfg.availableTargetPlatforms[c];
if (!!!allow_targets) {
console.error(`current host platform ${c} is not supported.`);
process.exit(1);
return;
}
if (allow_targets.indexOf(p) < 0) {
console.error(`target platform "${p}" is not listed [${allow_targets.join(", ")}]`);
process.exit(1);
return;
}
if (p === "mac") {
yield this.generate_mac();
}
else if (p == "ios") {
yield this.generate_ios();
}
else if (p == "win32") {
yield this.generate_win32();
}
else if (p == "android") {
yield this.generate_android();
}
});
}
generate_android() {
return __awaiter(this, void 0, void 0, function* () {
});
}
generate_ios() {
return __awaiter(this, void 0, void 0, function* () {
yield (new IOSGenerateCMD(this)).generate();
});
}
generate_mac() {
return __awaiter(this, void 0, void 0, function* () {
yield (new MacGenerateCMD(this)).generate();
});
}
generate_win32() {
return __awaiter(this, void 0, void 0, function* () {
yield (new Win32GenerateCMD(this)).generate();
});
}
}
exports.CCPluginGENERATE = CCPluginGENERATE;
class PlatformGenerateCmd {
constructor(plugin) {
this.plugin = plugin;
}
get project_src_dir() {
return cocos_cli_1.cchelper.join(this.plugin.project_dir, "..", `common-${this.plugin.args.get_string("template_name")}`);
}
append_cmake_res_dir_args(args) {
args.push(`-DRES_DIR="${cocos_cli_1.cchelper.fix_path(this.plugin.project_dir)}"`);
}
}
class IOSGenerateCMD extends PlatformGenerateCmd {
generate() {
return __awaiter(this, void 0, void 0, function* () {
let build_dir = this.plugin.get_build_dir();
if (!(yield afs_1.afs.exists(cocos_cli_1.cchelper.join(this.project_src_dir, "CMakelists.txt")))) {
throw new Error(`CMakeLists.txt not found in ${this.project_src_dir}`);
}
if (!(yield afs_1.afs.exists(build_dir))) {
cocos_cli_1.cchelper.make_directory_recursive(build_dir);
}
let osx_sysroot = "iphoneos";
let ext = [];
if (this.plugin.enable_ios_simulator()) {
osx_sysroot = "iphonesimulator";
ext.push("-DCMAKE_OSX_ARCHITECTURES=x86_64");
}
else {
ext.push("-DCMAKE_OSX_ARCHITECTURES=arm64");
}
let teamid = this.plugin.get_app_team_id();
if (teamid) {
ext.push(`-DDEVELOPMENT_TEAM=${teamid}`);
}
this.append_cmake_res_dir_args(ext);
const do_build = false;
if (do_build) {
if (!this.plugin.enable_ios_simulator() && !teamid) {
console.error(`can not build ios without teamid`);
process.exit(1);
}
}
yield this.plugin.run_cmake(["-S", `${this.project_src_dir}`, "-GXcode", `-B${build_dir}`, "-DCMAKE_SYSTEM_NAME=iOS", `-DCMAKE_OSX_SYSROOT=${osx_sysroot}`].concat(ext));
if (do_build) {
yield this.plugin.run_cmake(["--build", `${build_dir}`, "--config", "Debug", "--", "-allowProvisioningUpdates"]);
}
return true;
});
}
}
class MacGenerateCMD extends PlatformGenerateCmd {
generate() {
return __awaiter(this, void 0, void 0, function* () {
let build_dir = this.plugin.get_build_dir();
if (!(yield afs_1.afs.exists(cocos_cli_1.cchelper.join(this.project_src_dir, "CMakelists.txt")))) {
throw new Error(`CMakeLists.txt not found in ${this.project_src_dir}`);
}
if (!(yield afs_1.afs.exists(build_dir))) {
cocos_cli_1.cchelper.make_directory_recursive(build_dir);
}
let cmake_args = ["-S", `${this.project_src_dir}`, "-GXcode", `-B${build_dir}`, "-DCMAKE_SYSTEM_NAME=Darwin"];
this.append_cmake_res_dir_args(cmake_args);
yield this.plugin.run_cmake(cmake_args);
return true;
});
}
}
class Win32GenerateCMD extends PlatformGenerateCmd {
win32_select_cmake_generator_args() {
return __awaiter(this, void 0, void 0, function* () {
console.log(`selecting visual studio generator ...`);
const visualstudio_generators = cocos_cfg.cmake.win32.generators;
let test_proj_dir = yield afs_1.afs.mkdtemp(cocos_cli_1.cchelper.join(os.tmpdir(), "cmake_test_"));
let test_cmake_lists_path = cocos_cli_1.cchelper.join(test_proj_dir, "CMakeLists.txt");
let test_cpp_file = cocos_cli_1.cchelper.join(test_proj_dir, "test.cpp");
{
let cmake_content = `
cmake_minimum_required(VERSION 3.8)
set(APP_NAME test-cmake)
project(\${APP_NAME} CXX)
add_library(\${APP_NAME} test.cpp)
`;
let cpp_src = `
#include<iostream>
int main(int argc, char **argv)
{
std::cout << "Hello World" << std::endl;
return 0;
}
`;
yield afs_1.afs.writeFile(test_cmake_lists_path, cmake_content);
yield afs_1.afs.writeFile(test_cpp_file, cpp_src);
}
let try_run_cmake_with_arguments = (args, workdir) => {
return new Promise((resolve, reject) => {
let cp = child_process.spawn(this.plugin.get_cmake_path(), args, {
cwd: workdir,
env: process.env,
shell: true
});
cp.on("close", (code, sig) => {
if (code != 0) {
resolve(false);
return;
}
resolve(true);
});
});
};
let available_generators = [];
for (let cfg of visualstudio_generators) {
let build_dir = cocos_cli_1.cchelper.join(test_proj_dir, `build_${cfg.G.replace(/ /g, "_")}`);
let args = [`-S"${test_proj_dir}"`, `-G"${cfg.G}"`, `-B"${build_dir}"`];
if ("A" in cfg) {
args.push("-A", cfg.A);
}
yield afs_1.afs.mkdir(build_dir);
if (yield try_run_cmake_with_arguments(args, build_dir)) {
available_generators.push(cfg.G);
break;
}
yield cocos_cli_1.cchelper.remove_directory_recursive(build_dir);
}
yield cocos_cli_1.cchelper.remove_directory_recursive(test_proj_dir);
let ret = [];
if (available_generators.length == 0) {
return []; // use cmake default option -G
}
let opt = visualstudio_generators.filter(x => x.G == available_generators[0])[0];
for (let k in opt) {
ret.push(`-${k}"${opt[k]}"`);
}
console.log(` using ${opt.G}`);
return ret;
});
}
generate() {
return __awaiter(this, void 0, void 0, function* () {
let build_dir = this.plugin.get_build_dir();
if (!(yield afs_1.afs.exists(cocos_cli_1.cchelper.join(this.project_src_dir, "CMakelists.txt")))) {
throw new Error(`CMakeLists.txt not found in ${this.project_src_dir}`);
}
if (!(yield afs_1.afs.exists(build_dir))) {
cocos_cli_1.cchelper.make_directory_recursive(build_dir);
}
let g = this.plugin.get_cmake_generator();
let generate_args = [];
if (g) {
let optlist = cocos_cfg.cmake.win32.generators.filter(x => x.G.toLowerCase() == g.toLowerCase());
if (optlist.length == 0) {
generate_args.push(`-G"${g}"`);
}
else {
let opt = optlist[0];
for (let t of opt) {
generate_args.push(`-${t}"${opt[t]}"`);
}
}
}
else {
generate_args = generate_args.concat(yield this.win32_select_cmake_generator_args());
}
this.append_cmake_res_dir_args(generate_args);
yield this.plugin.run_cmake([`-S"${cocos_cli_1.cchelper.fix_path(this.project_src_dir)}"`, `-B"${cocos_cli_1.cchelper.fix_path(build_dir)}"`].concat(generate_args));
return true;
});
}
}
//# sourceMappingURL=plugin_generate.js.map
@@ -1,288 +0,0 @@
import { CCPlugin, pa, cchelper } from "./cocos_cli";
import * as path from "path";
import * as os from "os";
import * as cocos_cfg from "./cocos_config.json";
import * as child_process from "child_process";
import { afs } from "./afs";
const PackageNewConfig = "cocos-project-template.json";
export class CCPluginGENERATE extends CCPlugin {
depends():string |null {
// return "new"; // recreate project file will override everything
return null;
}
define_args(): void {
this.parser.add_required_predefined_argument("build_dir");
this.parser.add_required_predefined_argument("directory");
this.parser.add_predefined_argument("cmake_generator");
this.parser.add_predefined_argument("cmake_path");
this.parser.add_predefined_argument("ios_simulator");
this.parser.add_predefined_argument("teamid");
this.parser.add_predefined_argument_with_default("template_name", "link");
}
init(): boolean {
if (cocos_cfg.platforms.indexOf(this.get_platform()) < 0) {
console.error(`invalidate platform "${this.get_platform()}"`);
}
return true;
}
async run(): Promise<boolean> {
let arg_p = this.parser.get_string("platform");
if(!arg_p) {
let ps = (cocos_cfg as any)["defaultGeneratePlatforms"][this.get_current_platform()];
for(let p of ps){
await this.generate_platform(p);
}
}else{
await this.generate_platform(arg_p);
}
return true;
}
async generate_platform(p: string) {
let c = this.get_current_platform();
if(p == "ios-simulator") {
p = "ios";
this.set_platform("ios");
this.extend_argv(["--ios-simulator"]);
this.args.set_bool("ios_simulator", true);
}
let allow_targets = (cocos_cfg.availableTargetPlatforms as any)[c];
if (!!!allow_targets) {
console.error(`current host platform ${c} is not supported.`);
process.exit(1);
return;
}
if (allow_targets.indexOf(p) < 0) {
console.error(`target platform "${p}" is not listed [${allow_targets.join(", ")}]`);
process.exit(1);
return;
}
if (p === "mac") {
await this.generate_mac();
} else if (p == "ios") {
await this.generate_ios();
} else if (p == "win32") {
await this.generate_win32();
} else if (p == "android") {
await this.generate_android();
}
}
async generate_android() {
}
async generate_ios() {
await (new IOSGenerateCMD(this)).generate();
}
async generate_mac() {
await (new MacGenerateCMD(this)).generate();
}
async generate_win32() {
await (new Win32GenerateCMD(this)).generate();
}
}
abstract class PlatformGenerateCmd {
plugin: CCPluginGENERATE;
constructor(plugin: CCPluginGENERATE) {
this.plugin = plugin;
}
abstract async generate(): Promise<boolean>;
get project_src_dir():string {
return cchelper.join(this.plugin.project_dir!, "..", `common-${this.plugin.args.get_string("template_name")}`);
}
append_cmake_res_dir_args(args:string[]) {
args.push(`-DRES_DIR="${cchelper.fix_path(this.plugin.project_dir!)}"`);
}
}
class IOSGenerateCMD extends PlatformGenerateCmd {
async generate() {
let build_dir = this.plugin.get_build_dir();
if (!(await afs.exists(cchelper.join(this.project_src_dir, "CMakelists.txt")))) {
throw new Error(`CMakeLists.txt not found in ${this.project_src_dir}`);
}
if (!(await afs.exists(build_dir))) {
cchelper.make_directory_recursive(build_dir);
}
let osx_sysroot = "iphoneos";
let ext:string[] = [];
if(this.plugin.enable_ios_simulator()){
osx_sysroot = "iphonesimulator";
ext.push("-DCMAKE_OSX_ARCHITECTURES=x86_64")
}else{
ext.push("-DCMAKE_OSX_ARCHITECTURES=arm64")
}
let teamid = this.plugin.get_app_team_id();
if(teamid) {
ext.push(`-DDEVELOPMENT_TEAM=${teamid}`);
}
this.append_cmake_res_dir_args(ext);
const do_build = false;
if(do_build) {
if(!this.plugin.enable_ios_simulator() && !teamid) {
console.error(`can not build ios without teamid`);
process.exit(1);
}
}
await this.plugin.run_cmake(["-S", `${this.project_src_dir}`, "-GXcode", `-B${build_dir}`, "-DCMAKE_SYSTEM_NAME=iOS", `-DCMAKE_OSX_SYSROOT=${osx_sysroot}`].concat(ext));
if(do_build) {
await this.plugin.run_cmake(["--build", `${build_dir}`, "--config", "Debug", "--", "-allowProvisioningUpdates"]);
}
return true;
}
}
class MacGenerateCMD extends PlatformGenerateCmd {
async generate() {
let build_dir = this.plugin.get_build_dir();
if (!(await afs.exists(cchelper.join(this.project_src_dir, "CMakelists.txt")))) {
throw new Error(`CMakeLists.txt not found in ${this.project_src_dir}`);
}
if (!(await afs.exists(build_dir))) {
cchelper.make_directory_recursive(build_dir);
}
let cmake_args = ["-S", `${this.project_src_dir}`, "-GXcode", `-B${build_dir}`, "-DCMAKE_SYSTEM_NAME=Darwin"];
this.append_cmake_res_dir_args(cmake_args);
await this.plugin.run_cmake(cmake_args);
return true;
}
}
class Win32GenerateCMD extends PlatformGenerateCmd {
async win32_select_cmake_generator_args(): Promise<string[]> {
console.log(`selecting visual studio generator ...`);
const visualstudio_generators = cocos_cfg.cmake.win32.generators;
let test_proj_dir = await afs.mkdtemp(cchelper.join(os.tmpdir(), "cmake_test_"));
let test_cmake_lists_path = cchelper.join(test_proj_dir, "CMakeLists.txt");
let test_cpp_file = cchelper.join(test_proj_dir, "test.cpp");
{
let cmake_content = `
cmake_minimum_required(VERSION 3.8)
set(APP_NAME test-cmake)
project(\${APP_NAME} CXX)
add_library(\${APP_NAME} test.cpp)
`;
let cpp_src = `
#include<iostream>
int main(int argc, char **argv)
{
std::cout << "Hello World" << std::endl;
return 0;
}
`
await afs.writeFile(test_cmake_lists_path, cmake_content);
await afs.writeFile(test_cpp_file, cpp_src);
}
let try_run_cmake_with_arguments = (args: string[], workdir: string) => {
return new Promise<boolean>((resolve, reject) => {
let cp = child_process.spawn(this.plugin.get_cmake_path(), args, {
cwd: workdir,
env: process.env,
shell: true
});
cp.on("close", (code, sig) => {
if (code != 0) {
resolve(false);
return;
}
resolve(true);
});
});
}
let available_generators: string[] = [];
for (let cfg of visualstudio_generators) {
let build_dir = cchelper.join(test_proj_dir, `build_${cfg.G.replace(/ /g, "_")}`);
let args: string[] = [`-S"${test_proj_dir}"`, `-G"${cfg.G}"`, `-B"${build_dir}"`];
if ("A" in cfg) {
args.push("-A", cfg.A!)
}
await afs.mkdir(build_dir);
if (await try_run_cmake_with_arguments(args, build_dir)) {
available_generators.push(cfg.G);
break;
}
await cchelper.remove_directory_recursive(build_dir);
}
await cchelper.remove_directory_recursive(test_proj_dir);
let ret: string[] = [];
if (available_generators.length == 0) {
return []; // use cmake default option -G
}
let opt = visualstudio_generators.filter(x => x.G == available_generators[0])[0];
for (let k in opt) {
ret.push(`-${k}"${(opt as any)[k]}"`);
}
console.log(` using ${opt.G}`)
return ret;
}
async generate() {
let build_dir = this.plugin.get_build_dir();
if (!(await afs.exists(cchelper.join(this.project_src_dir, "CMakelists.txt")))) {
throw new Error(`CMakeLists.txt not found in ${this.project_src_dir}`);
}
if (!(await afs.exists(build_dir))) {
cchelper.make_directory_recursive(build_dir);
}
let g = this.plugin.get_cmake_generator();
let generate_args: string[] = [];
if (g) {
let optlist = cocos_cfg.cmake.win32.generators.filter(x => x.G.toLowerCase() == g!.toLowerCase());
if (optlist.length == 0) {
generate_args.push(`-G"${g}"`);
} else {
let opt = optlist[0] as any;
for (let t of opt) {
generate_args.push(`-${t}"${opt[t]}"`);
}
}
} else {
generate_args = generate_args.concat(await this.win32_select_cmake_generator_args());
}
this.append_cmake_res_dir_args(generate_args);
await this.plugin.run_cmake([`-S"${cchelper.fix_path(this.project_src_dir)}"`, `-B"${cchelper.fix_path(build_dir)}"`].concat(generate_args));
return true;
}
}
@@ -1,556 +0,0 @@
"use strict";
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
Object.defineProperty(exports, "__esModule", { value: true });
const cocos_cli_1 = require("./cocos_cli");
const path = require("path");
const fs = require("fs");
const cocos_project = require("./cocos_project_types");
const cocos2dx_files = require("../../../templates/cocos2dx_files.json");
const cocos_cfg = require("./cocos_config.json");
const afs_1 = require("./afs");
const PackageNewConfig = "cocos-project-template.json";
let project_CONFIG = {
project_type: "js",
has_native: true,
engine_version: "",
custom_step_script: null /* script path*/
};
class CCPluginNEW extends cocos_cli_1.CCPlugin {
depends() {
return null;
}
define_args() {
let parser = this.parser;
parser.add_predefined_argument_with_default("package_name", "CocosGame");
parser.add_required_predefined_argument("directory");
parser.add_predefined_argument_with_default("ios_bundleid", "org.cocos2dx.ios");
parser.add_predefined_argument_with_default("mac_bundleid", "org.cocos2dx.mac");
parser.add_predefined_argument("engine_path");
parser.add_predefined_argument("portrait");
parser.add_predefined_argument("no_native");
parser.add_predefined_argument("build_dir");
parser.add_predefined_argument_with_default("language", "js");
parser.add_predefined_argument("do_list_templates", this.do_list_templates.bind(this));
parser.add_predefined_argument_with_default("template_name", "link");
parser.add_predefined_argument("shared_dir");
}
init() {
this.set_env("PROJECT_NAME", this.project_name);
this.set_env("COMMON_DIR", cocos_cli_1.cchelper.join(this.shared_dir, this.common_dir));
let parser = this.parser;
// console.log(`PROJECT_NAME name ${this.project_name}`);
let cocos_dir = this.get_cocos_root();
if (!fs.existsSync(cocos_cli_1.cchelper.join(cocos_dir, "cocos/cocos2d.h"))) {
console.error(`cocos2d.h not found in ${cocos_dir}, path incorrect!`);
return false;
}
if (this.project_dir && !fs.existsSync(this.project_dir)) {
cocos_cli_1.cchelper.make_directory_recursive(this.project_dir);
}
return true;
}
get common_dir() {
return `common-${this.args.get_string("template_name")}`;
}
run() {
return __awaiter(this, void 0, void 0, function* () {
let tp = new TemplateCreator(this);
yield tp.run(); // async
return true;
});
}
/* override */
get_engine_path() {
return this.args.get_path("engine_path");
}
do_list_templates() {
console.log(`templates:`);
let dirs = this.get_templates_dir_names();
for (let d of dirs) {
console.log(` - ${d}/`);
}
}
get project_name() {
if (this.args.get_otherargs().length == 0) {
console.error(`argument project name is not set!`);
}
let pname = this.args.get_otherargs()[0];
if (!pname.match(/^[a-zA-Z0-9-_]+$/)) {
console.error(`project name "${pname}" seems to be a bad argument!`);
}
return pname;
}
get project_dir() {
let dir = this.args.get_path("directory");
if (!dir || !this.project_name)
return;
return cocos_cli_1.cchelper.join(dir, this.project_name);
}
get shared_dir() {
let dir = this.args.get_path("shared_dir");
if (!dir)
return cocos_cli_1.cchelper.join(this.project_dir, "..");
return dir;
}
get engine_path() {
return this.args.get_path("engine_path");
}
get selected_template_dir_name() {
let tpn = this.args.get_path("template_name");
let template_names = this.get_templates_dir_names();
if (template_names.length == 1) {
return template_names[0];
}
let dirs = template_names.filter(x => x === `template-${tpn}`);
if (dirs.length == 0) {
console.error(`can not find template ${tpn} in ${template_names.join(",")}`);
}
return dirs[0];
}
get selected_template_path() {
if (!this.selected_template_dir_name)
return null;
let dir = cocos_cli_1.cchelper.join(this.get_templates_root_path(), this.selected_template_dir_name);
if (!fs.existsSync(dir)) {
console.error(`selected template path not exists: ${dir}`);
}
let st = fs.statSync(dir);
if (!st.isDirectory()) {
console.error(`selected template path is not directory: ${dir}`);
}
let check_files = ["main.js", "project.json", PackageNewConfig, "frameworks"];
for (let f of check_files) {
if (!fs.existsSync(cocos_cli_1.cchelper.join(dir, f))) {
console.warn(`warning: file "${f}" does not exists in ${dir}, template path can be incorrect setting!`);
}
}
return dir;
}
}
exports.CCPluginNEW = CCPluginNEW;
class TemplateCreator {
constructor(plugin) {
this.excludes = [];
this.plugin = plugin;
let args = plugin.args;
let template_dir = cocos_cli_1.cchelper.join(plugin.get_templates_root_path(), plugin.selected_template_dir_name);
this.lang = args.get_path("language");
this.cocos_root = plugin.get_cocos_root();
this.project_name = plugin.project_name;
this.project_dir = plugin.project_dir;
this.package_name = args.get_string("package_name");
this.mac_bundleid = args.get_string("mac_bundleid");
this.ios_bundleid = args.get_string("ios_bundleid");
this.tp_name = args.get_path("template_name");
this.tp_dir = template_dir;
if (cocos_cfg.support_templates.indexOf(this.tp_name) < 0) {
console.error(`template name "${this.tp_name}" is not supported!`);
}
if (!fs.existsSync(cocos_cli_1.cchelper.join(this.tp_dir, PackageNewConfig))) {
console.error(`can not find ${PackageNewConfig} in ${this.tp_dir}`);
return;
}
this.template_info = JSON.parse(fs.readFileSync(cocos_cli_1.cchelper.join(this.tp_dir, PackageNewConfig)).toString("utf8"));
if (!("do_default" in this.template_info)) {
console.error(`can not find "do_default" in ${PackageNewConfig}`);
return;
}
}
do_post_steps() {
return __awaiter(this, void 0, void 0, function* () {
yield this.set_orientation();
yield this.update_android_gradle_values();
});
}
get_config_path() {
return cocos_cli_1.cchelper.join(this.project_dir, cocos_project.CONFIG);
}
run() {
return __awaiter(this, void 0, void 0, function* () {
let shared_dir = this.plugin.shared_dir;
{
let dir = cocos_cli_1.cchelper.join(shared_dir, this.plugin.common_dir);
if (!fs.existsSync(dir)) {
yield cocos_cli_1.cchelper.copy_files_with_config({
from: cocos_cli_1.cchelper.join(this.tp_dir, "common"),
to: dir,
}, this.tp_dir, this.project_dir);
}
}
cocos_cli_1.cchelper.copy_file_sync(this.tp_dir, "project.json", this.project_dir, "project.json");
// copy by platform
let plat = this.plugin.args.get_string("platform");
{
let dir = cocos_cli_1.cchelper.join(this.project_dir, "proj");
if (plat && !fs.existsSync(dir)) {
yield cocos_cli_1.cchelper.copy_files_with_config({
from: cocos_cli_1.cchelper.join(this.tp_dir, "platforms", plat),
to: dir,
}, this.tp_dir, this.project_dir);
}
}
delete this.template_info.do_default;
for (let key in this.template_info) {
// console.log(`other commands ${key}`)
yield this.execute(this.template_info[key]);
}
yield this.do_post_steps();
project_CONFIG.engine_version = this.get_cocos_version();
let cfg = {};
let cfgPath = this.get_config_path();
if (fs.existsSync(cfgPath)) {
cfg = JSON.parse(fs.readFileSync(cfgPath).toString("utf-8"));
}
cfg = Object.assign(cfg, project_CONFIG);
fs.writeFileSync(cfgPath, JSON.stringify(cfg, undefined, 2));
});
}
get_cocos_version() {
const cocos2d_h = cocos_cli_1.cchelper.join(this.cocos_root, "cocos/cocos2d.h");
if (!fs.existsSync(cocos2d_h)) {
return "unknown";
}
else {
let lines = fs.readFileSync(cocos2d_h).toString("utf-8").split("\n").filter(x => x.indexOf("COCOS2D_VERSION") >= 0);
if (lines.length > 0) {
let ps = lines[0].split(" ");
let v = parseInt(ps[ps.length - 1]);
return `${v >> 16}.${(v & 0x0000FF00) >> 8}.${v & 0x000000FF}`;
}
}
return "unknown";
}
get_project_pkg_config(platform) {
if (!fs.existsSync(this.get_config_path())) {
return undefined;
}
let p = JSON.parse(fs.readFileSync(this.get_config_path()).toString("utf-8"));
if (!p.packages) {
return undefined;
}
return p.packages[platform];
}
set_orientation() {
return __awaiter(this, void 0, void 0, function* () {
let cfgPath = this.get_config_path();
if (fs.existsSync(cfgPath)) {
let json = JSON.parse(fs.readFileSync(cfgPath).toString("utf-8"));
if (json.ios) {
let cfg = json.ios.orientation;
let infoPlist = cocos_cli_1.cchelper.join(this.project_dir, 'proj/Info.plist');
if (fs.existsSync(infoPlist)) {
let orientations = [];
if (cfg.landscapeRight) {
orientations.push('UIInterfaceOrientationLandscapeRight');
}
if (cfg.landscapeLeft) {
orientations.push('UIInterfaceOrientationLandscapeLeft');
}
if (cfg.portrait) {
orientations.push('UIInterfaceOrientationPortrait');
}
if (cfg.upsideDown) {
orientations.push('UIInterfaceOrientationPortraitUpsideDown');
}
let replacement = `\t<key>UISupportedInterfaceOrientations</key>\t<array>${orientations.map(x => `\t\t<string>${x}</string>`)}\t</array>`;
let newlines = [];
let lines = fs.readFileSync(infoPlist).toString("utf-8").split("\n");
let found_key = 0;
let found_values = 0;
for (let i = 0; i < lines.length; i++) {
if (lines[i].indexOf("UISupportedInterfaceOrientations") >= 0) {
found_key += 1;
newlines.push(lines[i]);
i++;
while (i < lines.length && lines[i].indexOf("</array>") < 0) {
i++;
}
if (lines[i].indexOf("</array>") >= 0) {
found_values += 1;
}
i++;
newlines.push(replacement);
}
else {
newlines.push(lines[i]);
}
}
if (found_key != 1 || found_values != 1) {
console.error(`error occurs while setting orientations for iOS`);
}
else {
yield afs_1.afs.writeFile(infoPlist, newlines.join("\n"));
}
}
else {
console.error(`file ${infoPlist} not exist!`);
}
}
if (json.android) {
let cfg = json.android.orientation;
let manifestPath = cocos_cli_1.cchelper.join(this.project_dir, 'proj/app/AndroidManifest.xml');
if (fs.existsSync(manifestPath)) {
let pattern = /android:screenOrientation=\"[^"]*\"/;
let replaceString = 'android:screenOrientation="unspecified"';
if (cfg.landscapeRight && cfg.landscapeLeft && cfg.portrait && cfg.upsideDown) {
replaceString = 'android:screenOrientation="fullSensor"';
}
else if (cfg.landscapeRight && !cfg.landscapeLeft) {
replaceString = 'android:screenOrientation="landscape"';
}
else if (!cfg.landscapeRight && cfg.landscapeLeft) {
replaceString = 'android:screenOrientation="reverseLandscape"';
}
else if (cfg.landscapeRight && cfg.landscapeLeft) {
replaceString = 'android:screenOrientation="sensorLandscape"';
}
else if (cfg.portrait && !cfg.upsideDown) {
replaceString = 'android:screenOrientation="portrait"';
}
else if (!cfg.portrait && cfg.upsideDown) {
let oriValue = 'reversePortrait';
replaceString = `android:screenOrientation="${oriValue}"`;
}
else if (cfg.portrait && cfg.upsideDown) {
let oriValue = 'sensorPortrait';
replaceString = `android:screenOrientation="${oriValue}"`;
}
let content = yield afs_1.afs.readFile(manifestPath, 'utf8');
content = content.replace(pattern, replaceString);
yield afs_1.afs.writeFile(manifestPath, content);
}
else {
console.error(`file ${manifestPath} not exist!`);
}
}
}
else {
console.error(`file ${cfgPath} not found!`);
}
});
}
update_android_gradle_values() {
return __awaiter(this, void 0, void 0, function* () {
let cfg = this.get_project_pkg_config("android");
if (!cfg)
return;
// android-studio gradle.properties
console.log(`update gradle.prperties`);
let gradlePropertyPath = cocos_cli_1.cchelper.join(this.project_dir, 'proj/gradle.properties');
if (fs.existsSync(gradlePropertyPath)) {
let keystorePath = cfg.keystorePath;
if (this.plugin.get_current_platform() == "win32") {
keystorePath = cocos_cli_1.cchelper.fix_path(keystorePath);
}
let apiLevel = cfg.apiLevel;
if (!apiLevel) {
apiLevel = 27;
}
console.log(`AndroidAPI level ${apiLevel}`);
let content = fs.readFileSync(gradlePropertyPath, 'utf-8');
if (keystorePath) {
content = content.replace(/.*RELEASE_STORE_FILE=.*/, `RELEASE_STORE_FILE=${keystorePath}`);
content = content.replace(/.*RELEASE_STORE_PASSWORD=.*/, `RELEASE_STORE_PASSWORD=${cfg.keystorePassword}`);
content = content.replace(/.*RELEASE_KEY_ALIAS=.*/, `RELEASE_KEY_ALIAS=${cfg.keystoreAlias}`);
content = content.replace(/.*RELEASE_KEY_PASSWORD=.*/, `RELEASE_KEY_PASSWORD=${cfg.keystoreAliasPassword}`);
}
else {
content = content.replace(/.*RELEASE_STORE_FILE=.*/, `# RELEASE_STORE_FILE=${keystorePath}`);
content = content.replace(/.*RELEASE_STORE_PASSWORD=.*/, `# RELEASE_STORE_PASSWORD=${cfg.keystorePassword}`);
content = content.replace(/.*RELEASE_KEY_ALIAS=.*/, `# RELEASE_KEY_ALIAS=${cfg.keystoreAlias}`);
content = content.replace(/.*RELEASE_KEY_PASSWORD=.*/, `# RELEASE_KEY_PASSWORD=${cfg.keystoreAliasPassword}`);
}
let SDK_VERSION = typeof apiLevel === "string" ? apiLevel.match(/\d+/)[0] : apiLevel;
content = content.replace(/PROP_TARGET_SDK_VERSION=.*/, `PROP_TARGET_SDK_VERSION=${SDK_VERSION}`);
content = content.replace(/PROP_COMPILE_SDK_VERSION=.*/, `PROP_COMPILE_SDK_VERSION=${SDK_VERSION}`);
let abis = (cfg.appABIs && cfg.appABIs.length > 0) ? cfg.appABIs.join(':') : 'armeabi-v7a';
//todo:新的template里面有个注释也是这个字段,所以要加个g
content = content.replace(/PROP_APP_ABI=.*/g, `PROP_APP_ABI=${abis}`);
fs.writeFileSync(gradlePropertyPath, content);
// generate local.properties
content = '';
content += `ndk.dir=${process.env.NDK_ROOT}\n`;
content += `sdk.dir=${process.env.ANDROID_SDK_ROOT}`;
//windows 需要使用的这样的格式 e\:\\aa\\bb\\cc
if (process.platform === 'win32') {
content = content.replace(/\\/g, '\\\\');
content = content.replace(/:/g, '\\:');
}
fs.writeFileSync(cocos_cli_1.cchelper.join(path.dirname(gradlePropertyPath), 'local.properties'), content);
}
else {
console.log(`warning: ${gradlePropertyPath} not found!`);
}
});
}
execute(cmds) {
return __awaiter(this, void 0, void 0, function* () {
if (cmds.append_file) {
cmds.append_file.forEach(cmd => {
cocos_cli_1.cchelper.copy_file_sync(this.cocos_root, cmd.from, this.project_dir, cmd.to);
});
delete cmds.append_file;
}
if (cmds.exclude_from_template) {
// do nothing
delete cmds.exclude_from_template;
}
/// only in link mode
let project_x_root = cmds.append_x_engine;
if (cmds.append_x_engine && this.tp_name != "link") {
let common = cocos2dx_files.common;
let engine_to = cocos_cli_1.cchelper.replace_env_variables(cmds.append_x_engine.to);
let to = path.isAbsolute(engine_to) ? engine_to : cocos_cli_1.cchelper.join(this.project_dir, engine_to);
yield cocos_cli_1.cchelper.parallel_copy_files(20, this.cocos_root, common, to);
if (this.lang == "js") {
let fileList = cocos2dx_files.js;
yield cocos_cli_1.cchelper.parallel_copy_files(20, this.cocos_root, fileList, to);
}
}
delete cmds.append_x_engine;
if (cmds.append_from_template) {
let cmd = cmds.append_from_template;
// console.log(`append-from-template ${JSON.stringify(cmd)}`);
yield cocos_cli_1.cchelper.copy_files_with_config({
from: cmd.from,
to: cmd.to,
exclude: cmd.exclude
}, this.tp_dir, this.project_dir);
delete cmds.append_from_template;
}
let replace_files_delay = {};
;
if (cmds.project_replace_project_name) {
let cmd = cmds.project_replace_project_name;
cmd.files.forEach(file => {
let fp = cocos_cli_1.cchelper.join(this.project_dir, file);
replace_files_delay[fp] = replace_files_delay[fp] || [];
replace_files_delay[fp].push({
reg: cmd.src_project_name,
content: this.project_name
});
});
delete cmds.project_replace_project_name;
}
if (cmds.project_replace_package_name) {
let cmd = cmds.project_replace_package_name;
let name = cmd.src_package_name.replace(/\./g, "\\.");
cmd.files.forEach(file => {
let fp = cocos_cli_1.cchelper.join(this.project_dir, file);
replace_files_delay[fp] = replace_files_delay[fp] || [];
replace_files_delay[fp].push({
reg: name,
content: this.package_name
});
});
delete cmds.project_replace_package_name;
}
if (cmds.project_replace_mac_bundleid) {
let cmd = cmds.project_replace_mac_bundleid;
let bundle_id = cmd.src_bundle_id.replace(/\./g, "\\.");
cmd.files.forEach(file => {
let fp = cocos_cli_1.cchelper.join(this.project_dir, file);
replace_files_delay[fp] = replace_files_delay[fp] || [];
replace_files_delay[fp].push({
reg: bundle_id,
content: this.mac_bundleid
});
});
delete cmds.project_replace_mac_bundleid;
}
if (cmds.project_replace_ios_bundleid) {
let cmd = cmds.project_replace_ios_bundleid;
let bundle_id = cmd.src_bundle_id.replace(/\./g, "\\.");
cmd.files.forEach(file => {
let fp = cocos_cli_1.cchelper.join(this.project_dir, file);
replace_files_delay[fp] = replace_files_delay[fp] || [];
replace_files_delay[fp].push({
reg: bundle_id,
content: this.ios_bundleid
});
});
delete cmds.project_replace_ios_bundleid;
}
if (cmds.project_replace_cocos_x_root) {
let cmd = cmds.project_replace_cocos_x_root;
let cocos_x_root = path.normalize(this.cocos_root);
let proj_cocos_path = path.normalize(cocos_cli_1.cchelper.join(this.project_dir, project_x_root.to));
for (let f of cmd.files) {
let p = typeof (f) == "string" ? f : f.file;
// console.log(`warning: project dir ${this.project_dir!} + ${p}`);
let fp = cocos_cli_1.cchelper.join(this.project_dir, p);
let list = replace_files_delay[fp] = replace_files_delay[fp] || [];
if (this.tp_name == "link") {
let v = typeof f.link == "string" ? f.link : cocos_x_root;
v = cocos_cli_1.cchelper.fix_path(v);
list.push({
reg: cmd.pattern,
content: v
});
}
else {
// use relative path
let rel_path = path.relative(fp, proj_cocos_path);
let v = !!f.default ? f.default : rel_path;
v = cocos_cli_1.cchelper.fix_path(v);
list.push({
reg: cmd.pattern,
content: v
});
}
}
delete cmds.project_replace_cocos_x_root;
}
if (cmds.project_replace_projec_common) {
let cmd = cmds.project_replace_projec_common;
let cocos_x_root = path.normalize(this.cocos_root);
let proj_common_dir = cocos_cli_1.cchelper.join(this.project_dir, this.plugin.common_dir);
for (let f of cmd.files) {
let p = typeof (f) == "string" ? f : f.file;
let fp = cocos_cli_1.cchelper.join(this.project_dir, p);
let list = replace_files_delay[fp] = replace_files_delay[fp] || [];
let rel_path = path.relative(fp, proj_common_dir);
list.push({
reg: cmd.pattern,
content: cocos_cli_1.cchelper.fix_path(rel_path)
});
}
delete cmds.project_replace_projec_common;
}
if (cmds.common_replace) {
for (let cmd of cmds.common_replace) {
for (let f of cmd.files) {
let fp = cocos_cli_1.cchelper.join(this.project_dir, f);
replace_files_delay[fp] = replace_files_delay[fp] || [];
replace_files_delay[fp].push({
reg: cmd.pattern,
content: cmd.value
});
}
}
delete cmds.common_replace;
}
for (let fullpath in replace_files_delay) {
let cfg = replace_files_delay[fullpath];
yield cocos_cli_1.cchelper.replace_in_file(cfg.map(x => {
return { reg: x.reg, text: x.content };
}), fullpath);
}
if (Object.keys(cmds).length > 0) {
for (let f in cmds) {
console.error(`command "${f}" is not parsed in ${PackageNewConfig}`);
}
}
});
}
}
exports.TemplateCreator = TemplateCreator;
//# sourceMappingURL=plugin_new.js.map
@@ -1,610 +0,0 @@
import { CCPlugin, pa, cchelper as ccutils } from "./cocos_cli";
import * as path from "path";
import * as fs from "fs";
import * as cocos_project from "./cocos_project_types";
import * as cocos2dx_files from "../../../templates/cocos2dx_files.json";
import * as cocos_cfg from "./cocos_config.json";
import { afs } from "./afs";
const PackageNewConfig = "cocos-project-template.json";
import { CCPluginGENERATE } from "./plugin_generate";
import { CCPluginRUN } from "./plugin_run";
let project_CONFIG =
{
project_type: "js",
has_native: true,
engine_version: "",
custom_step_script: null /* script path*/
};
export class CCPluginNEW extends CCPlugin {
depends(): string | null {
return null;
}
define_args(): void {
let parser = this.parser;
parser.add_predefined_argument_with_default("package_name", "CocosGame");
parser.add_required_predefined_argument("directory");
parser.add_predefined_argument_with_default("ios_bundleid", "org.cocos2dx.ios");
parser.add_predefined_argument_with_default("mac_bundleid", "org.cocos2dx.mac");
parser.add_predefined_argument("engine_path");
parser.add_predefined_argument("portrait");
parser.add_predefined_argument("no_native");
parser.add_predefined_argument("build_dir");
parser.add_predefined_argument_with_default("language", "js");
parser.add_predefined_argument("do_list_templates", this.do_list_templates.bind(this));
parser.add_predefined_argument_with_default("template_name", "link");
parser.add_predefined_argument("shared_dir");
}
init(): boolean {
this.set_env("PROJECT_NAME", this.project_name!);
this.set_env("COMMON_DIR", ccutils.join(this.shared_dir!, this.common_dir));
let parser = this.parser;
// console.log(`PROJECT_NAME name ${this.project_name}`);
let cocos_dir = this.get_cocos_root();
if (!fs.existsSync(ccutils.join(cocos_dir!, "cocos/cocos2d.h"))) {
console.error(`cocos2d.h not found in ${cocos_dir}, path incorrect!`);
return false;
}
if (this.project_dir && !fs.existsSync(this.project_dir)) {
ccutils.make_directory_recursive(this.project_dir);
}
return true;
}
get common_dir() {
return `common-${this.args.get_string("template_name")}`;
}
async run(): Promise<boolean> {
let tp = new TemplateCreator(this);
await tp.run(); // async
return true;
}
/* override */
get_engine_path(): string | null {
return this.args.get_path("engine_path");
}
private do_list_templates() {
console.log(`templates:`)
let dirs = this.get_templates_dir_names();
for (let d of dirs) {
console.log(` - ${d}/`);
}
}
get project_name(): string | undefined {
if (this.args.get_otherargs().length == 0) {
console.error(`argument project name is not set!`);
}
let pname = this.args.get_otherargs()[0];
if (!pname.match(/^[a-zA-Z0-9-_]+$/)) {
console.error(`project name "${pname}" seems to be a bad argument!`)
}
return pname;
}
get project_dir(): string | undefined {
let dir = this.args.get_path("directory");
if (!dir || !this.project_name) return;
return ccutils.join(dir, this.project_name!);
}
get shared_dir(): string | undefined {
let dir = this.args.get_path("shared_dir");
if (!dir) return ccutils.join(this.project_dir!, "..");
return dir;
}
get engine_path(): string {
return this.args.get_path("engine_path");
}
get selected_template_dir_name(): string {
let tpn = this.args.get_path("template_name");
let template_names = this.get_templates_dir_names();
if (template_names.length == 1) {
return template_names[0];
}
let dirs = template_names.filter(x => x === `template-${tpn}`);
if (dirs.length == 0) {
console.error(`can not find template ${tpn} in ${template_names.join(",")}`);
}
return dirs[0];
}
get selected_template_path(): string | null {
if (!this.selected_template_dir_name) return null;
let dir = ccutils.join(this.get_templates_root_path()!, this.selected_template_dir_name);
if (!fs.existsSync(dir)) {
console.error(`selected template path not exists: ${dir}`);
}
let st = fs.statSync(dir);
if (!st.isDirectory()) {
console.error(`selected template path is not directory: ${dir}`);
}
let check_files: string[] = ["main.js", "project.json", PackageNewConfig, "frameworks"];
for (let f of check_files) {
if (!fs.existsSync(ccutils.join(dir, f))) {
console.warn(`warning: file "${f}" does not exists in ${dir}, template path can be incorrect setting!`);
}
}
return dir;
}
}
export class TemplateCreator {
lang?: string;
cocos_root?: string;
project_name?: string;
project_dir?: string;
tp_name?: string;
tp_dir?: string;
package_name?: string;
mac_bundleid?: string;
ios_bundleid?: string;
template_info?: cocos_project.CocosProjecConfig;
excludes: string[] = [];
plugin: CCPluginNEW;
constructor(plugin: CCPluginNEW) {
this.plugin = plugin;
let args = plugin.args;
let template_dir = ccutils.join(plugin.get_templates_root_path()!, plugin.selected_template_dir_name);
this.lang = args.get_path("language");
this.cocos_root = plugin.get_cocos_root()!;
this.project_name = plugin.project_name;
this.project_dir = plugin.project_dir;
this.package_name = args.get_string("package_name");
this.mac_bundleid = args.get_string("mac_bundleid");
this.ios_bundleid = args.get_string("ios_bundleid");
this.tp_name = args.get_path("template_name");
this.tp_dir = template_dir;
if (cocos_cfg.support_templates.indexOf(this.tp_name) < 0) {
console.error(`template name "${this.tp_name}" is not supported!`);
}
if (!fs.existsSync(ccutils.join(this.tp_dir, PackageNewConfig))) {
console.error(`can not find ${PackageNewConfig} in ${this.tp_dir}`);
return;
}
this.template_info = JSON.parse(fs.readFileSync(ccutils.join(this.tp_dir, PackageNewConfig)).toString("utf8"));
if (!("do_default" in this.template_info!)) {
console.error(`can not find "do_default" in ${PackageNewConfig}`);
return;
}
}
async do_post_steps() {
await this.set_orientation();
await this.update_android_gradle_values();
}
get_config_path(): string {
return ccutils.join(this.project_dir!, cocos_project.CONFIG);
}
async run() {
let shared_dir = this.plugin.shared_dir!;
{
let dir = ccutils.join(shared_dir, this.plugin.common_dir);
if(!fs.existsSync(dir)) {
await ccutils.copy_files_with_config(
{
from: ccutils.join(this.tp_dir!, "common"),
to: dir,
}, this.tp_dir!, this.project_dir!);
}
}
ccutils.copy_file_sync(this.tp_dir!, "project.json", this.project_dir!, "project.json");
// copy by platform
let plat = this.plugin.args.get_string("platform");
{
let dir = ccutils.join(this.project_dir!, "proj");
if (plat && !fs.existsSync(dir)) {
await ccutils.copy_files_with_config(
{
from: ccutils.join(this.tp_dir!, "platforms", plat),
to: dir,
}, this.tp_dir!, this.project_dir!);
}
}
delete this.template_info!.do_default;
for (let key in this.template_info!) {
// console.log(`other commands ${key}`)
await this.execute((this.template_info as any)[key] as any);
}
await this.do_post_steps();
project_CONFIG.engine_version = this.get_cocos_version();
let cfg: any = {};
let cfgPath = this.get_config_path();
if (fs.existsSync(cfgPath)) {
cfg = JSON.parse(fs.readFileSync(cfgPath).toString("utf-8"));
}
cfg = Object.assign(cfg, project_CONFIG);
fs.writeFileSync(cfgPath, JSON.stringify(cfg, undefined, 2));
}
get_cocos_version(): string {
const cocos2d_h = ccutils.join(this.cocos_root!, "cocos/cocos2d.h");
if (!fs.existsSync(cocos2d_h)) {
return "unknown";
} else {
let lines = fs.readFileSync(cocos2d_h).toString("utf-8").split("\n").filter(x => x.indexOf("COCOS2D_VERSION") >= 0);
if (lines.length > 0) {
let ps = lines[0].split(" ");
let v = parseInt(ps[ps.length - 1]);
return `${v >> 16}.${(v & 0x0000FF00) >> 8}.${v & 0x000000FF}`;
}
}
return "unknown";
}
get_project_pkg_config(platform: string): any {
if (!fs.existsSync(this.get_config_path())) {
return undefined;
}
let p = JSON.parse(fs.readFileSync(this.get_config_path()).toString("utf-8"));
if (!p.packages) {
return undefined;
}
return p.packages[platform];
}
async set_orientation() {
let cfgPath = this.get_config_path();
if (fs.existsSync(cfgPath)) {
let json = JSON.parse(fs.readFileSync(cfgPath).toString("utf-8"));
if (json.ios) {
let cfg = json.ios.orientation;
let infoPlist = ccutils.join(this.project_dir!, 'proj/Info.plist');
if (fs.existsSync(infoPlist)) {
let orientations: string[] = [];
if (cfg.landscapeRight) {
orientations.push('UIInterfaceOrientationLandscapeRight');
}
if (cfg.landscapeLeft) {
orientations.push('UIInterfaceOrientationLandscapeLeft');
}
if (cfg.portrait) {
orientations.push('UIInterfaceOrientationPortrait');
}
if (cfg.upsideDown) {
orientations.push('UIInterfaceOrientationPortraitUpsideDown');
}
let replacement: string = `\t<key>UISupportedInterfaceOrientations</key>\t<array>${orientations.map(x => `\t\t<string>${x}</string>`)}\t</array>`;
let newlines: string[] = [];
let lines = fs.readFileSync(infoPlist).toString("utf-8").split("\n");
let found_key = 0;
let found_values = 0;
for (let i = 0; i < lines.length; i++) {
if (lines[i].indexOf("UISupportedInterfaceOrientations") >= 0) {
found_key += 1;
newlines.push(lines[i]);
i++;
while (i < lines.length && lines[i].indexOf("</array>") < 0) {
i++;
}
if (lines[i].indexOf("</array>") >= 0) {
found_values += 1;
}
i++;
newlines.push(replacement);
} else {
newlines.push(lines[i]);
}
}
if (found_key != 1 || found_values != 1) {
console.error(`error occurs while setting orientations for iOS`);
} else {
await afs.writeFile(infoPlist, newlines.join("\n"));
}
} else {
console.error(`file ${infoPlist} not exist!`);
}
}
if (json.android) {
let cfg = json.android.orientation;
let manifestPath = ccutils.join(this.project_dir!, 'proj/app/AndroidManifest.xml');
if (fs.existsSync(manifestPath)) {
let pattern = /android:screenOrientation=\"[^"]*\"/;
let replaceString = 'android:screenOrientation="unspecified"';
if (cfg.landscapeRight && cfg.landscapeLeft && cfg.portrait && cfg.upsideDown) {
replaceString = 'android:screenOrientation="fullSensor"';
}
else if (cfg.landscapeRight && !cfg.landscapeLeft) {
replaceString = 'android:screenOrientation="landscape"';
}
else if (!cfg.landscapeRight && cfg.landscapeLeft) {
replaceString = 'android:screenOrientation="reverseLandscape"';
}
else if (cfg.landscapeRight && cfg.landscapeLeft) {
replaceString = 'android:screenOrientation="sensorLandscape"';
}
else if (cfg.portrait && !cfg.upsideDown) {
replaceString = 'android:screenOrientation="portrait"';
}
else if (!cfg.portrait && cfg.upsideDown) {
let oriValue = 'reversePortrait';
replaceString = `android:screenOrientation="${oriValue}"`;
}
else if (cfg.portrait && cfg.upsideDown) {
let oriValue = 'sensorPortrait';
replaceString = `android:screenOrientation="${oriValue}"`;
}
let content = await afs.readFile(manifestPath, 'utf8');
content = content.replace(pattern, replaceString);
await afs.writeFile(manifestPath, content);
} else {
console.error(`file ${manifestPath} not exist!`);
}
}
} else {
console.error(`file ${cfgPath} not found!`)
}
}
async update_android_gradle_values() {
let cfg = this.get_project_pkg_config("android");
if (!cfg) return;
// android-studio gradle.properties
console.log(`update gradle.prperties`)
let gradlePropertyPath = ccutils.join(this.project_dir!, 'proj/gradle.properties');
if (fs.existsSync(gradlePropertyPath)) {
let keystorePath = cfg.keystorePath;
if (this.plugin.get_current_platform() == "win32") {
keystorePath = ccutils.fix_path(keystorePath);
}
let apiLevel = cfg.apiLevel;
if (!apiLevel) {
apiLevel = 27;
}
console.log(`AndroidAPI level ${apiLevel}`);
let content = fs.readFileSync(gradlePropertyPath, 'utf-8');
if (keystorePath) {
content = content.replace(/.*RELEASE_STORE_FILE=.*/, `RELEASE_STORE_FILE=${keystorePath}`);
content = content.replace(/.*RELEASE_STORE_PASSWORD=.*/, `RELEASE_STORE_PASSWORD=${cfg.keystorePassword}`);
content = content.replace(/.*RELEASE_KEY_ALIAS=.*/, `RELEASE_KEY_ALIAS=${cfg.keystoreAlias}`);
content = content.replace(/.*RELEASE_KEY_PASSWORD=.*/, `RELEASE_KEY_PASSWORD=${cfg.keystoreAliasPassword}`);
} else {
content = content.replace(/.*RELEASE_STORE_FILE=.*/, `# RELEASE_STORE_FILE=${keystorePath}`);
content = content.replace(/.*RELEASE_STORE_PASSWORD=.*/, `# RELEASE_STORE_PASSWORD=${cfg.keystorePassword}`);
content = content.replace(/.*RELEASE_KEY_ALIAS=.*/, `# RELEASE_KEY_ALIAS=${cfg.keystoreAlias}`);
content = content.replace(/.*RELEASE_KEY_PASSWORD=.*/, `# RELEASE_KEY_PASSWORD=${cfg.keystoreAliasPassword}`);
}
let SDK_VERSION = typeof apiLevel === "string"? apiLevel.match(/\d+/)![0] : apiLevel;
content = content.replace(/PROP_TARGET_SDK_VERSION=.*/, `PROP_TARGET_SDK_VERSION=${SDK_VERSION}`);
content = content.replace(/PROP_COMPILE_SDK_VERSION=.*/, `PROP_COMPILE_SDK_VERSION=${SDK_VERSION}`);
let abis = (cfg.appABIs && cfg.appABIs.length > 0) ? cfg.appABIs.join(':') : 'armeabi-v7a';
//todo:新的template里面有个注释也是这个字段,所以要加个g
content = content.replace(/PROP_APP_ABI=.*/g, `PROP_APP_ABI=${abis}`);
fs.writeFileSync(gradlePropertyPath, content);
// generate local.properties
content = '';
content += `ndk.dir=${process.env.NDK_ROOT}\n`;
content += `sdk.dir=${process.env.ANDROID_SDK_ROOT}`;
//windows 需要使用的这样的格式 e\:\\aa\\bb\\cc
if (process.platform === 'win32') {
content = content.replace(/\\/g, '\\\\');
content = content.replace(/:/g, '\\:');
}
fs.writeFileSync(ccutils.join(path.dirname(gradlePropertyPath), 'local.properties'), content);
} else {
console.log(`warning: ${gradlePropertyPath} not found!`);
}
}
private async execute(cmds: cocos_project.CocosProjectTasks) {
if (cmds.append_file) {
cmds.append_file.forEach(cmd => {
ccutils.copy_file_sync(this.cocos_root!, cmd.from, this.project_dir!, cmd.to);
});
delete cmds.append_file;
}
if (cmds.exclude_from_template) {
// do nothing
delete cmds.exclude_from_template;
}
/// only in link mode
let project_x_root = cmds.append_x_engine!;
if (cmds.append_x_engine && this.tp_name != "link") {
let common = cocos2dx_files.common;
let engine_to = ccutils.replace_env_variables(cmds.append_x_engine.to);
let to = path.isAbsolute(engine_to) ? engine_to : ccutils.join(this.project_dir!, engine_to);
await ccutils.parallel_copy_files(20, this.cocos_root!, common, to);
if (this.lang == "js") {
let fileList = cocos2dx_files.js;
await ccutils.parallel_copy_files(20, this.cocos_root!, fileList, to);
}
}
delete cmds.append_x_engine;
if (cmds.append_from_template) {
let cmd = cmds.append_from_template;
// console.log(`append-from-template ${JSON.stringify(cmd)}`);
await ccutils.copy_files_with_config({
from: cmd.from,
to: cmd.to,
exclude: cmd.exclude
}, this.tp_dir!, this.project_dir!);
delete cmds.append_from_template;
}
let replace_files_delay: { [key: string]: { reg: string, content: string }[] } = {};;
if (cmds.project_replace_project_name) {
let cmd = cmds.project_replace_project_name;
cmd.files.forEach(file => {
let fp = ccutils.join(this.project_dir!, file);
replace_files_delay[fp] = replace_files_delay[fp] || [];
replace_files_delay[fp].push({
reg: cmd.src_project_name,
content: this.project_name!
});
});
delete cmds.project_replace_project_name;
}
if (cmds.project_replace_package_name) {
let cmd = cmds.project_replace_package_name;
let name = cmd.src_package_name.replace(/\./g, "\\.");
cmd.files.forEach(file => {
let fp = ccutils.join(this.project_dir!, file);
replace_files_delay[fp] = replace_files_delay[fp] || [];
replace_files_delay[fp].push({
reg: name,
content: this.package_name!
});
});
delete cmds.project_replace_package_name;
}
if (cmds.project_replace_mac_bundleid) {
let cmd = cmds.project_replace_mac_bundleid;
let bundle_id = cmd.src_bundle_id.replace(/\./g, "\\.");
cmd.files.forEach(file => {
let fp = ccutils.join(this.project_dir!, file);
replace_files_delay[fp] = replace_files_delay[fp] || [];
replace_files_delay[fp].push({
reg: bundle_id,
content: this.mac_bundleid!
});
});
delete cmds.project_replace_mac_bundleid;
}
if (cmds.project_replace_ios_bundleid) {
let cmd = cmds.project_replace_ios_bundleid;
let bundle_id = cmd.src_bundle_id.replace(/\./g, "\\.");
cmd.files.forEach(file => {
let fp = ccutils.join(this.project_dir!, file);
replace_files_delay[fp] = replace_files_delay[fp] || [];
replace_files_delay[fp].push({
reg: bundle_id,
content: this.ios_bundleid!
});
});
delete cmds.project_replace_ios_bundleid;
}
if (cmds.project_replace_cocos_x_root) {
let cmd = cmds.project_replace_cocos_x_root!;
let cocos_x_root = path.normalize(this.cocos_root!);
let proj_cocos_path = path.normalize(ccutils.join(this.project_dir!, project_x_root.to));
for (let f of cmd.files) {
let p = typeof (f) == "string" ? f : f.file;
// console.log(`warning: project dir ${this.project_dir!} + ${p}`);
let fp = ccutils.join(this.project_dir!, p);
let list = replace_files_delay[fp] = replace_files_delay[fp] || [];
if (this.tp_name == "link") {
let v = typeof f.link == "string" ? f.link as string : cocos_x_root;
v = ccutils.fix_path(v);
list.push({
reg: cmd.pattern,
content: v
});
} else {
// use relative path
let rel_path = path.relative(fp, proj_cocos_path);
let v = !!(f as any).default ? (f as any).default : rel_path;
v = ccutils.fix_path(v);
list.push({
reg: cmd.pattern,
content: v
});
}
}
delete cmds.project_replace_cocos_x_root;
}
if (cmds.project_replace_projec_common) {
let cmd = cmds.project_replace_projec_common!;
let cocos_x_root = path.normalize(this.cocos_root!);
let proj_common_dir = ccutils.join(this.project_dir!, this.plugin.common_dir);
for (let f of cmd.files) {
let p = typeof (f) == "string" ? f : f.file;
let fp = ccutils.join(this.project_dir!, p);
let list = replace_files_delay[fp] = replace_files_delay[fp] || [];
let rel_path = path.relative(fp, proj_common_dir);
list.push({
reg: cmd.pattern,
content: ccutils.fix_path(rel_path)
});
}
delete cmds.project_replace_projec_common;
}
if (cmds.common_replace) {
for (let cmd of cmds.common_replace) {
for (let f of cmd.files) {
let fp = ccutils.join(this.project_dir!, f);
replace_files_delay[fp] = replace_files_delay[fp] || [];
replace_files_delay[fp].push({
reg: cmd.pattern,
content: cmd.value
});
}
}
delete cmds.common_replace;
}
for (let fullpath in replace_files_delay) {
let cfg = replace_files_delay[fullpath];
await ccutils.replace_in_file(cfg.map(x => {
return { reg: x.reg, text: x.content };
}), fullpath);
}
if (Object.keys(cmds).length > 0) {
for (let f in cmds) {
console.error(`command "${f}" is not parsed in ${PackageNewConfig}`);
}
}
}
}
@@ -1,252 +0,0 @@
"use strict";
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
Object.defineProperty(exports, "__esModule", { value: true });
const cocos_cli_1 = require("./cocos_cli");
const path = require("path");
const fs = require("fs");
const os = require("os");
const child_process = require("child_process");
const PackageNewConfig = "cocos-project-template.json";
class CCPluginRUN extends cocos_cli_1.CCPlugin {
depends() {
return "compile";
}
define_args() {
this.parser.add_required_predefined_argument("build_dir");
this.parser.add_predefined_argument("cmake_path");
this.parser.add_predefined_argument("ios_simulator");
}
init() {
return true;
}
run() {
return __awaiter(this, void 0, void 0, function* () {
let platform = this.get_platform();
let build_dir = this.get_build_dir();
let project_name = this.get_project_name_from_cmake();
if (platform == "mac") {
return (new MacRunCMD(this)).run();
}
else if (platform == "ios") {
return (new IOSRunCMD(this)).run();
}
else if (platform == "android") {
return (new AndroidRunCMD(this)).run();
}
else if (platform == "win32") {
return (new Win32RunCMD(this)).run();
}
return true;
});
}
get_project_name_from_cmake() {
let cmake_cache = path.join(this.get_build_dir(), "CMakeCache.txt");
if (!fs.existsSync(cmake_cache)) {
console.error(`can not find "CMakeCache.txt" in ${this.get_build_dir()}, please run "cmake -G" first`);
}
let project_name = cocos_cli_1.cchelper.exact_value_from_file(/CMAKE_PROJECT_NAME:\w+=(.*)/, cmake_cache, 1);
return project_name;
}
}
exports.CCPluginRUN = CCPluginRUN;
class PlatformRunCmd {
constructor(plugin) {
this.plugin = plugin;
}
get project_name() {
return this.plugin.get_project_name_from_cmake();
}
}
class MacRunCMD extends PlatformRunCmd {
run() {
return __awaiter(this, void 0, void 0, function* () {
this.mac_run(this.project_name);
return true;
});
}
mac_open(app) {
console.log(`open ${app}`);
let cp = child_process.spawn(`open`, [app], {
shell: true,
env: process.env
});
cp.stdout.on("data", (data) => {
console.log(`[open app] ${data}`);
});
cp.stderr.on(`data`, (data) => {
console.error(`[open app error] ${data}`);
});
cp.on("close", (code, sig) => {
console.log(`${app} exit with ${code}, sig: ${sig}`);
});
}
mac_run(project_name) {
let debug_dir = path.join(this.plugin.get_build_dir(), "Debug");
if (!fs.existsSync(debug_dir)) {
console.log(`[mac run] ${debug_dir} is not exist!`);
process.exit(1);
}
let app_path;
if (project_name) {
app_path = path.join(debug_dir, `${project_name}-desktop.app`);
if (fs.existsSync(app_path)) {
this.mac_open(app_path);
return;
}
}
let app_list = fs.readdirSync(debug_dir).filter(x => x.endsWith(".app"));
if (app_list.length == 1) {
return this.mac_open(path.join(debug_dir, app_list[0]));
}
console.error(`found ${app_list.length} apps, failed to open.`);
process.exit(1);
}
}
class IOSRunCMD extends PlatformRunCmd {
run() {
if (this.plugin.enable_ios_simulator()) {
return this.run_ios_simulator();
}
else {
return this.run_ios_device();
}
}
select_simulator_id() {
let iphones = child_process.execSync("xcrun instruments -s").toString("utf-8").split("\n").filter(x => x.startsWith("iPhone") && x.indexOf("Simulator") >= 0);
const exact = (l) => {
l = l.split("[")[0].substr(6);
return parseInt(l) * 100 + l.length;
};
let ret = iphones.filter(x => x.indexOf("Apple Watch") < 0).sort((a, b) => {
return exact(b) - exact(a);
})[0];
let m = ret.match(/iPhone\s*[^\[]*\[([^\]]*)\].*/);
console.log(`selected simualtor ${ret}`);
return m[1];
}
select_ios_devices() {
let lines = child_process.execSync(`xcrun simctl list`).toString("utf-8").split("\n");
let readDevices = (lines, idx) => {
while (idx < lines.length && !lines[idx].match(/== Devices ==/)) {
idx++;
}
return idx < lines.length ? idx : -1;
};
let readIOSDevices = (list, idx) => {
let ret = [];
while (!list[idx].match(/-- iOS [^ ]* --/)) {
idx++;
}
if (list[idx].indexOf("iOS") < 0) {
console.error(`can not find iOS section!`);
return ret;
}
idx++;
while (list[idx].startsWith(" ")) {
ret.push(list[idx++]);
}
return ret.map(x => x.trim());
};
let idx = readDevices(lines, 0);
if (idx < 0) {
console.error(`can not find devices section!`);
return [];
}
let list = readIOSDevices(lines, idx);
let ret = list.filter(x => x.startsWith("iPhone"));
return ret;
}
read_bundle_id() {
let prj_name = this.project_name;
let cmake_tmp_dir = fs.readdirSync(path.join(this.plugin.get_build_dir(), "CMakeFiles")).filter(x => x.startsWith(prj_name))[0];
let infoPlist = path.join(this.plugin.get_build_dir(), "CMakeFiles", cmake_tmp_dir, "Info.plist");
if (fs.existsSync(infoPlist)) {
let lines = fs.readFileSync(infoPlist).toString("utf-8").split("\n");
for (let i = 0; i < lines.length; i++) {
if (lines[i].match(/CFBundleIdentifier/)) {
i++;
while (!lines[i].match(/<string>/)) {
i++;
}
let m = lines[i].match(/<string>([^<]*)<\/string>/);
return m[1];
}
}
}
else {
console.error(`Info.plist not found ${infoPlist}`);
}
return null;
}
query_ios_device() {
let lines = child_process.execSync(`xcrun instruments -s devices`).toString("utf-8").split("\n");
let ret = [];
//skip first line
for (let i = 1; i < lines.length; i++) {
if (lines[i].endsWith("(Simulator)")) {
continue;
}
else if (lines[i].match(/iPhone|iPad|iPod/)) {
ret.push(lines[i]);
}
}
if (ret.length > 0) {
console.log(`select ios device ${ret[0]}`);
return ret[0].match(/[^\[]]*\[([^\]]*)\]/)[1];
}
return null;
}
run_ios_device() {
return __awaiter(this, void 0, void 0, function* () {
let build_dir = this.plugin.get_build_dir();
let foudn_aps = child_process.execSync(`find ${build_dir} -name "*.app"`).toString("utf-8").split("\n").filter(x => x.trim().length > 0);
let device_id = this.query_ios_device();
if (!device_id) {
console.error(`no connected device found!`);
return false;
}
if (foudn_aps.length > 0) {
let cwd = fs.mkdtempSync(path.join(os.tmpdir(), this.project_name));
yield cocos_cli_1.cchelper.run_cmd(`xcrun`, ["instruments", "-t", "Blank", "-w", device_id, foudn_aps[0]], false, cwd);
}
return true;
});
}
run_ios_simulator() {
return __awaiter(this, void 0, void 0, function* () {
let sim_id = this.select_simulator_id();
let build_dir = this.plugin.get_build_dir();
let bundle_id = this.read_bundle_id();
console.log(` - build dir ${build_dir} - sim_id ${sim_id}`);
console.log(` - bundle id ${bundle_id}`);
let found_apps = child_process.execSync(`find ${build_dir} -name "*.app"`).toString("utf-8").split("\n").filter(x => x.trim().length > 0);
if (found_apps.length > 0 && bundle_id) {
yield cocos_cli_1.cchelper.run_cmd("xcrun", ["simctl", "boot", sim_id], true);
yield cocos_cli_1.cchelper.run_cmd("open", ["`xcode-select -p`/Applications/Simulator.app"], true);
yield cocos_cli_1.cchelper.run_cmd("xcrun", ["simctl", "boot", sim_id], true);
yield cocos_cli_1.cchelper.run_cmd("xcrun", ["simctl", "install", sim_id, found_apps[0].trim()], false);
yield cocos_cli_1.cchelper.run_cmd("xcrun", ["simctl", "launch", sim_id, `"${bundle_id}"`], false);
}
return false;
});
}
}
class Win32RunCMD extends PlatformRunCmd {
run() {
throw new Error("Method not implemented.");
}
}
class AndroidRunCMD extends PlatformRunCmd {
run() {
throw new Error("Method not implemented.");
}
}
//# sourceMappingURL=plugin_run.js.map
@@ -1,267 +0,0 @@
import { CCPlugin, pa, cchelper } from "./cocos_cli";
import * as path from "path";
import * as fs from "fs";
import * as os from "os";
import * as cocos_cfg from "./cocos_config.json";
import * as cocos_project from "./cocos_project_types";
import * as cocos2dx_files from "../../../templates/cocos2dx_files.json";
import * as child_process from "child_process";
import { afs } from "./afs";
const PackageNewConfig = "cocos-project-template.json";
export class CCPluginRUN extends CCPlugin {
depends(): string | null {
return "compile";
}
define_args(): void {
this.parser.add_required_predefined_argument("build_dir");
this.parser.add_predefined_argument("cmake_path");
this.parser.add_predefined_argument("ios_simulator");
}
init(): boolean {
return true;
}
async run(): Promise<boolean> {
let platform: string = this.get_platform();
let build_dir: string = this.get_build_dir();
let project_name: string | undefined = this.get_project_name_from_cmake();
if (platform == "mac") {
return (new MacRunCMD(this)).run()
} else if (platform == "ios") {
return (new IOSRunCMD(this)).run();
} else if (platform == "android") {
return (new AndroidRunCMD(this)).run();
} else if (platform == "win32") {
return (new Win32RunCMD(this)).run();
}
return true;
}
get_project_name_from_cmake(): string | undefined {
let cmake_cache = path.join(this.get_build_dir(), "CMakeCache.txt");
if (!fs.existsSync(cmake_cache)) {
console.error(`can not find "CMakeCache.txt" in ${this.get_build_dir()}, please run "cmake -G" first`);
}
let project_name = cchelper.exact_value_from_file(/CMAKE_PROJECT_NAME:\w+=(.*)/, cmake_cache, 1);
return project_name;
}
}
abstract class PlatformRunCmd {
plugin: CCPluginRUN;
constructor(plugin: CCPluginRUN) {
this.plugin = plugin;
}
abstract async run(): Promise<boolean>;
get project_name(): string | undefined {
return this.plugin.get_project_name_from_cmake();
}
}
class MacRunCMD extends PlatformRunCmd {
async run(): Promise<boolean> {
this.mac_run(this.project_name!);
return true;
}
private mac_open(app: string) {
console.log(`open ${app}`);
let cp = child_process.spawn(`open`, [app], {
shell: true,
env: process.env
});
cp.stdout.on("data", (data) => {
console.log(`[open app] ${data}`);
});
cp.stderr.on(`data`, (data) => {
console.error(`[open app error] ${data}`);
});
cp.on("close", (code, sig) => {
console.log(`${app} exit with ${code}, sig: ${sig}`);
});
}
private mac_run(project_name?: string) {
let debug_dir = path.join(this.plugin.get_build_dir(), "Debug");
if (!fs.existsSync(debug_dir)) {
console.log(`[mac run] ${debug_dir} is not exist!`);
process.exit(1);
}
let app_path: string;
if (project_name) {
app_path = path.join(debug_dir, `${project_name}-desktop.app`);
if (fs.existsSync(app_path)) {
this.mac_open(app_path);
return;
}
}
let app_list = fs.readdirSync(debug_dir).filter(x => x.endsWith(".app"));
if (app_list.length == 1) {
return this.mac_open(path.join(debug_dir, app_list[0]));
}
console.error(`found ${app_list.length} apps, failed to open.`);
process.exit(1);
}
}
class IOSRunCMD extends PlatformRunCmd {
run(): Promise<boolean> {
if (this.plugin.enable_ios_simulator()) {
return this.run_ios_simulator();
} else {
return this.run_ios_device();
}
}
select_simulator_id(): string {
let iphones = child_process.execSync("xcrun instruments -s").toString("utf-8").split("\n").filter(x => x.startsWith("iPhone") && x.indexOf("Simulator") >= 0);
const exact = (l: string) => {
l = l.split("[")[0].substr(6);
return parseInt(l) * 100 + l.length;
}
let ret = iphones.filter(x => x.indexOf("Apple Watch") < 0).sort((a, b) => {
return exact(b) - exact(a);
})[0];
let m = ret.match(/iPhone\s*[^\[]*\[([^\]]*)\].*/);
console.log(`selected simualtor ${ret}`);
return m![1];
}
select_ios_devices(): string[] {
let lines = child_process.execSync(`xcrun simctl list`).toString("utf-8").split("\n");
let readDevices = (lines: string[], idx: number): number => {
while (idx < lines.length && !lines[idx].match(/== Devices ==/)) {
idx++;
}
return idx < lines.length ? idx : -1;
}
let readIOSDevices = (list: string[], idx: number): string[] => {
let ret: string[] = [];
while (!list[idx].match(/-- iOS [^ ]* --/)) {
idx++;
}
if (list[idx].indexOf("iOS") < 0) {
console.error(`can not find iOS section!`);
return ret;
}
idx++;
while (list[idx].startsWith(" ")) {
ret.push(list[idx++]);
}
return ret.map(x => x.trim());
};
let idx = readDevices(lines, 0);
if (idx < 0) {
console.error(`can not find devices section!`);
return [];
}
let list = readIOSDevices(lines, idx);
let ret = list.filter(x => x.startsWith("iPhone"));
return ret;
}
read_bundle_id():string|null {
let prj_name = this.project_name!;
let cmake_tmp_dir = fs.readdirSync(path.join(this.plugin.get_build_dir(), "CMakeFiles")).filter(x=>x.startsWith(prj_name))[0];
let infoPlist = path.join(this.plugin.get_build_dir(), "CMakeFiles", cmake_tmp_dir, "Info.plist");
if(fs.existsSync(infoPlist)) {
let lines = fs.readFileSync(infoPlist).toString("utf-8").split("\n");
for(let i = 0;i< lines.length;i++) {
if (lines[i].match(/CFBundleIdentifier/)) {
i++;
while(!lines[i].match(/<string>/)){
i++;
}
let m = lines[i].match(/<string>([^<]*)<\/string>/);
return m![1];
}
}
}else{
console.error(`Info.plist not found ${infoPlist}`);
}
return null;
}
query_ios_device():string|null {
let lines = child_process.execSync(`xcrun instruments -s devices`).toString("utf-8").split("\n");
let ret:string[] = [];
//skip first line
for(let i = 1; i< lines.length; i++) {
if(lines[i].endsWith("(Simulator)")){
continue;
}else if(lines[i].match(/iPhone|iPad|iPod/)) {
ret.push(lines[i]);
}
}
if(ret.length > 0) {
console.log(`select ios device ${ret[0]}`);
return ret[0].match(/[^\[]]*\[([^\]]*)\]/)![1];
}
return null;
}
async run_ios_device(): Promise<boolean> {
let build_dir = this.plugin.get_build_dir();
let foudn_aps = child_process.execSync(`find ${build_dir} -name "*.app"`).toString("utf-8").split("\n").filter(x => x.trim().length > 0);
let device_id = this.query_ios_device();
if(!device_id) {
console.error(`no connected device found!`);
return false;
}
if(foudn_aps.length > 0) {
let cwd = fs.mkdtempSync(path.join(os.tmpdir(), this.project_name!));
await cchelper.run_cmd(`xcrun`, ["instruments", "-t", "Blank", "-w", device_id, foudn_aps[0]], false,
cwd);
}
return true;
}
async run_ios_simulator(): Promise<boolean> {
let sim_id = this.select_simulator_id();
let build_dir = this.plugin.get_build_dir();
let bundle_id = this.read_bundle_id();
console.log(` - build dir ${build_dir} - sim_id ${sim_id}`);
console.log(` - bundle id ${bundle_id}`);
let found_apps = child_process.execSync(`find ${build_dir} -name "*.app"`).toString("utf-8").split("\n").filter(x => x.trim().length > 0);
if (found_apps.length > 0 && bundle_id) {
await cchelper.run_cmd("xcrun", ["simctl", "boot", sim_id], true);
await cchelper.run_cmd("open", ["`xcode-select -p`/Applications/Simulator.app"], true);
await cchelper.run_cmd("xcrun", ["simctl", "boot", sim_id], true);
await cchelper.run_cmd("xcrun", ["simctl", "install", sim_id, found_apps[0].trim()], false);
await cchelper.run_cmd("xcrun", ["simctl", "launch", sim_id, `"${bundle_id}"`], false);
}
return false;
}
}
class Win32RunCMD extends PlatformRunCmd {
run(): Promise<boolean> {
throw new Error("Method not implemented.");
}
}
class AndroidRunCMD extends PlatformRunCmd {
run(): Promise<boolean> {
throw new Error("Method not implemented.");
}
}
File diff suppressed because it is too large Load Diff
-66
View File
@@ -1,66 +0,0 @@
{
"compilerOptions": {
/* Basic Options */
// "incremental": true, /* Enable incremental compilation */
"target": "es6", /* Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017', 'ES2018', 'ES2019', 'ES2020', or 'ESNEXT'. */
"module": "commonjs", /* Specify module code generation: 'none', 'commonjs', 'amd', 'system', 'umd', 'es2015', 'es2020', or 'ESNext'. */
// "lib": [], /* Specify library files to be included in the compilation. */
// "allowJs": true, /* Allow javascript files to be compiled. */
// "checkJs": true, /* Report errors in .js files. */
// "jsx": "preserve", /* Specify JSX code generation: 'preserve', 'react-native', or 'react'. */
// "declaration": true, /* Generates corresponding '.d.ts' file. */
// "declarationMap": true, /* Generates a sourcemap for each corresponding '.d.ts' file. */
"sourceMap": true, /* Generates corresponding '.map' file. */
// "outFile": "./", /* Concatenate and emit output to single file. */
// "outDir": "./", /* Redirect output structure to the directory. */
// "rootDir": "./", /* Specify the root directory of input files. Use to control the output directory structure with --outDir. */
// "composite": true, /* Enable project compilation */
// "tsBuildInfoFile": "./", /* Specify file to store incremental compilation information */
// "removeComments": true, /* Do not emit comments to output. */
// "noEmit": true, /* Do not emit outputs. */
// "importHelpers": true, /* Import emit helpers from 'tslib'. */
// "downlevelIteration": true, /* Provide full support for iterables in 'for-of', spread, and destructuring when targeting 'ES5' or 'ES3'. */
// "isolatedModules": true, /* Transpile each file as a separate module (similar to 'ts.transpileModule'). */
/* Strict Type-Checking Options */
"strict": true, /* Enable all strict type-checking options. */
// "noImplicitAny": true, /* Raise error on expressions and declarations with an implied 'any' type. */
"strictNullChecks": true, /* Enable strict null checks. */
// "strictFunctionTypes": true, /* Enable strict checking of function types. */
"strictBindCallApply": true, /* Enable strict 'bind', 'call', and 'apply' methods on functions. */
// "strictPropertyInitialization": true, /* Enable strict checking of property initialization in classes. */
// "noImplicitThis": true, /* Raise error on 'this' expressions with an implied 'any' type. */
"alwaysStrict": true, /* Parse in strict mode and emit "use strict" for each source file. */
"resolveJsonModule":true,
/* Additional Checks */
// "noUnusedLocals": true, /* Report errors on unused locals. */
// "noUnusedParameters": true, /* Report errors on unused parameters. */
// "noImplicitReturns": true, /* Report error when not all code paths in function return a value. */
// "noFallthroughCasesInSwitch": true, /* Report errors for fallthrough cases in switch statement. */
/* Module Resolution Options */
"moduleResolution": "node", /* Specify module resolution strategy: 'node' (Node.js) or 'classic' (TypeScript pre-1.6). */
// "baseUrl": "./", /* Base directory to resolve non-absolute module names. */
// "paths": {}, /* A series of entries which re-map imports to lookup locations relative to the 'baseUrl'. */
// "rootDirs": [], /* List of root folders whose combined content represents the structure of the project at runtime. */
// "typeRoots": [], /* List of folders to include type definitions from. */
// "types": [], /* Type declaration files to be included in compilation. */
// "allowSyntheticDefaultImports": true, /* Allow default imports from modules with no default export. This does not affect code emit, just typechecking. */
// "esModuleInterop": true, /* Enables emit interoperability between CommonJS and ES Modules via creation of namespace objects for all imports. Implies 'allowSyntheticDefaultImports'. */
// "preserveSymlinks": true, /* Do not resolve the real path of symlinks. */
// "allowUmdGlobalAccess": true, /* Allow accessing UMD globals from modules. */
/* Source Map Options */
// "sourceRoot": "", /* Specify the location where debugger should locate TypeScript files instead of source locations. */
// "mapRoot": "", /* Specify the location where debugger should locate map files instead of generated locations. */
// "inlineSourceMap": true, /* Emit a single file with source maps instead of having a separate file. */
// "inlineSources": true, /* Emit the source alongside the sourcemaps within a single file; requires '--inlineSourceMap' or '--sourceMap' to be set. */
/* Experimental Options */
// "experimentalDecorators": true, /* Enables experimental support for ES7 decorators. */
// "emitDecoratorMetadata": true, /* Enables experimental support for emitting type metadata for decorators. */
/* Advanced Options */
"forceConsistentCasingInFileNames": true /* Disallow inconsistently-cased references to the same file. */
}
}
Submodule native/tools/cocos2d-console deleted from 36c1480f5b