🎩 You're Invited:Meet the Socket team at Black Hat in Las Vegas, August 3-6.RSVP
Sign In

daji

Package Overview
Dependencies
Maintainers
1
Versions
34
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

daji - npm Package Compare versions

Comparing version
1.3.1
to
1.4.0
+148
common/_GitQuestion.js
// host
const utils = require('daji/common/utils');
const inquirer = require('inquirer');
const _gitConfig = require('../data/git/config.json');
// const listJSONRoot = _config.panJSON;
class question {
constructor() {
this.state = {
}
}
async chooseGitAccount() {
const gitList = [];
for (const i in _gitConfig) {
gitList.push(i);
}
const list = [{
type: 'list',
name: 'gitConfig',
message: '请选择要切换的账户',
choices: gitList || [],
filter: (val) => {
return _gitConfig[val];
}
}]
return new Promise((resolve, reject) => {
inquirer.prompt(list).then((answers) => {
resolve(answers);
}).catch(err => {
reject(err);
});
});
}
// 获取配置项
async getConfig() {
// 筛选当前命令所在的目录下的json、js文件,用于 使用当前目录文件 时,进行选择
const file = await utils.file.getFile('./', ['json', 'js']);
const configList = [{
type: 'list',
name: 'type',
message: '选择操作类型',
choices: [{
name: '当前目录导入至工具',
value: 'import'
}, {
name: '导出至当前目录(备份)',
value: 'export'
}, {
name: '修改',
value: 'update'
}],
}, {
type: 'list',
name: 'fileName',
message: '选择要导入的文件',
choices: file || [],
when: (answers) => {
if (answers.type === 'import') {
return answers.type;
}
},
filter: (val) => {
return val;
}
}]
return new Promise((resolve, reject) => {
inquirer.prompt(configList).then((answers) => {
resolve(answers);
}).catch(err => {
reject(err);
});
});
}
async updateGitConfig(json) {
const gitKey = [];
for (const i in _gitConfig) {
gitKey.push(i)
}
const configList = [{
type: 'list',
name: 'gitKey',
message: '选择要需改的git账号',
choices: gitKey || [],
validate: (val) => {
return val
},
}, {
type: 'input',
name: 'name',
default: json.name || null,
message: '请输入git.name',
validate: (val) => {
if (val.trim() === '') {
return '账号不能为空';
}
return true;
}
}, {
type: 'input',
name: 'email',
default: json.email || null,
message: '请输入git.email',
validate: (val) => {
if (val.trim() === '') {
return 'email不能为空';
}
return true;
}
}];
return new Promise((resolve, reject) => {
inquirer.prompt(configList).then((answers) => {
resolve(answers);
}).catch(err => {
reject(err);
});
});
}
}
module.exports = new question();
// host
const utils = require('daji/common/utils');
const inquirer = require('inquirer');
const _hostConfig = require('../data/host/config.json');
const selectedList = require('../data/host/selected.json');
// const listJSONRoot = _config.panJSON;
class question {
constructor() {
this.state = {
}
}
async chooseHost(callback) {
const hostList = [];
for (const i in _hostConfig) {
hostList.push(i);
}
// const list = [{
// type: 'list',
// name: 'hosts',
// message: '请选择Host列表',
// choices: hostList,
// filter: (val) => {
// return _hostConfig[val];
// }
// }]
const configList =[{
type:'checkbox',
name:'hostList',
message:'选择要使用的host列表',
default: selectedList || [],
choices: hostList,
}]
return new Promise((resolve, reject) => {
inquirer.prompt(configList).then((answers) => {
resolve(answers);
}).catch(err => {
reject(err);
});
});
}
// 获取配置项
async getConfig() {
// 筛选当前命令所在的目录下的json、js文件,用于 使用当前目录文件 时,进行选择
const file = await utils.file.getFile('./', ['json', 'js']);
const configList = [{
type: 'list',
name: 'type',
message: '选择操作类型',
choices: [ {
name: '当前目录导入至工具',
value: 'import'
}, {
name: '导出至当前目录(备份)',
value: 'export'
}, {
name:'生成配置文件',
message: '根据当前目录的txt文件,创建Host配置文件(不直接导入)',
value:'createConfig'
}
// {
// name: '自定义配置项目录',
// value: 'userDefined'
// },
// {
// name: '使用当前目录文件',
// value: 'thisRoot'
// }
],
}, {
type: 'list',
name: 'fileName',
message: '选择要导入的文件',
choices: file || [],
when: (answers) => {
if (answers.type === 'import') {
return answers.type;
}
},
filter: (val) => {
return val;
}
}]
return new Promise((resolve, reject) => {
inquirer.prompt(configList).then((answers) => {
resolve(answers);
}).catch(err => {
reject(err);
});
});
}
}
module.exports = new question();
// ios配置文件
const path = require('path');
// const fs = require('fs');
const utils = require('./utils');
const inquirer = require('inquirer');
const _config = require('../data/ios/config.json');
const listJSONRoot = _config.panJSON;
const appJson = require(listJSONRoot);
const process = require('child_process');
const iosTools = require('./iosTools');
class question {
constructor() {
this.state = {
}
this.getAppName = this.getAppName.bind(this);
this.getIphoneList = this.getIphoneList.bind(this);
this.chooseApp = this.chooseApp.bind(this);
this.chooseDevice = this.chooseDevice.bind(this);
this.inputAppInfo = this.inputAppInfo.bind(this);
this.confirm = this.confirm.bind(this);
}
// 获取appName 列表
getAppName() {
let result = [];
const listLength = appJson.list.length;
for (let i = 0; i < listLength; i++) {
result.push(appJson.list[i].cname);
}
return result;
}
// 获取当前设备的模拟器list
getIphoneList() {
return new Promise((resolve, reject) => {
console.log('== 正在获取本地设备清单 =='.x34);
console.log('ps: 首次启动时间较长,请耐心等待... \n');
process.exec("xcrun instruments -w 'iphone'", (err, stdout, stderr) => {
const arr = stderr.split('\n')
const iphoneList = [];
for (let i = 1; i < arr.length; i++) {
if (/^iPhone/.test(arr[i])) {
iphoneList.push(arr[i]);
}
}
resolve(iphoneList.reverse());
});
})
}
/**
* 获取本地的applist,并给与选择
*
* @memberof question
*/
chooseApp(callback) {
const list = this.getAppName();
if (list.length === 0) {
console.log('当前未添加任何app信息,如想添加请查阅文档');
callback(false);
} else {
const appList = [{
type: 'list',
name: 'app',
message: 'choose a app',
choices: this.getAppName() || [],
filter: function (val) {
return val;
}
}];
inquirer.prompt(appList).then(function (answers) {
if (!!callback) {
callback(answers);
}
});
}
}
/**
* 获取本地设备清单,并给与选择
*
* @param {any} callback
* @memberof question
*/
chooseDevice(callback) {
this.getIphoneList().then(data => {
const list = [{
type: 'list',
name: 'iphone',
message: '选择设备',
choices: data,
filter: function (val) {
return val;
}
}];
inquirer.prompt(list).then(function (answers) {
if (!!callback) {
callback(answers);
}
});
})
}
inputAppInfo() {
const _this = this;
return new Promise((resolve, reject) => {
const list = _this.formatInfoList({});
inquirer.prompt(list).then(function (answers) {
const result = _this.formatInfoListForResult(answers);
resolve(result);
});
});
}
/**
* 用于条件判断
*
* @param {any} msg
* @memberof question
*/
confirm(msg, callback) {
const list = [{
type: 'confirm',
name: 'flag',
message: msg
}];
return new Promise((resolve, reject) => {
inquirer.prompt(list).then(function (answers) {
resolve(answers);
});
})
}
/**
* 更新app,并获取更新后的数据
*
* @param {any} appInfo
* @returns
* @memberof question
*/
updateApp(appInfo) {
const _this = this;
// console.log(appInfo);
return new Promise((resolve, reject) => {
const list = _this.formatInfoList(appInfo);
inquirer.prompt(list).then(function (answers) {
const result = _this.formatInfoListForResult(answers);
result.name = appInfo.name; // name为主键,不允许修改
resolve(result);
});
})
}
formatInfoList(appInfo) {
const name = [{
type: 'input',
name: 'name',
message: 'app的英文名(用于启动指令)',
validate: (val) => {
if (val.trim() === '') {
return '请填写app的英文名';
}
return true;
}
}]
const list = [{
type: 'input',
name: 'cname',
default: appInfo.cname || null,
message: 'app的中文名(用于list展示)',
validate: (val) => {
if (val.trim() === '') {
return '请填写app的中文名';
}
return true;
}
}, {
type: 'input',
name: 'packageName',
message: 'app文件名(xxx.app)',
default: appInfo.packageName || null,
validate: (val) => {
if (val.trim() === '') {
return '请填写正确的packageName';
}
return true;
}
}, {
type: 'input',
name: 'boundId',
message: '请填写boundId',
default: appInfo.boundId || null,
validate: (val) => {
if (val.trim() === '') {
return '请填写boundId';
}
return true;
}
}, {
type: 'input',
name: 'scheme',
message: '请填写scheme(用于调用对应app打开H5页面,如:xxx://webview?url=)',
default: appInfo.scheme || null,
validate: (val) => {
if (val.trim() === '') {
return '请填写scheme';
}
return true;
}
},
{
type: 'input',
name: 'url',
message: 'app包仓库地址(git地址),用于存放对应app包,如果不需要安装可以不填写直接回车',
default: !!appInfo.repository ? appInfo.repository.url : null,
// validate: (val) => {
// if (!/^git/.test(val)) {
// return '请填写正确的仓库地址,如 git@xxx';
// }
// return true;
// }
}
];
if (!!appInfo.name) {
return list;
} else {
return [].concat(name, list);
}
}
formatInfoListForResult(answers) {
return Object.assign({}, {
"name": answers.name || '',
"cname": answers.cname,
"packageName": answers.packageName,
"boundId": answers.boundId,
"scheme": answers.scheme,
"repository": {
"type": "git",
"url": answers.url
}
});
}
// 输入地址
async getConfig() {
// 筛选当前命令所在的目录下的json、js文件,用于 使用当前目录文件 时,进行选择
const file = await utils.file.getFile('./', ['json', 'js']);
const configList = [{
type: 'list',
message: '请选择操作类型',
name: 'type',
choices: [{
name: '导出',
value: 'export'
}, {
name: '导入',
value: 'import'
}, {
name: '自定义配置项目录',
value: 'userDefined'
}, {
name: '重置',
value: 'reset'
}, {
name: '使用当前目录文件',
value: 'thisRoot'
}],
}, {
type: 'input',
name: 'url',
message: "请输入地址",
when: (answers) => {
if (answers.type !== 'reset' && answers.type !== 'thisRoot') {
return answers.type;
}
},
validate: (val) => {
let _urlObj = path.parse(val);
if (!!_urlObj.ext.trim() === false) {
return '请填写准确的文件地址(xxx/xxx/xxx.xx)';
}
return true;
}
}, {
type: 'list',
name: 'fileName',
message: '输选择文件名',
choices:file||[],
when: (answers) => {
if (answers.type === 'thisRoot') {
return answers.type;
}
},
filter: function (val) {
return val;
}
}];
return new Promise((resolve, reject) => {
inquirer.prompt(configList).then((answers) => {
resolve(answers);
}).catch(err => {
reject(err);
});
});
}
}
// const a = new question();
module.exports = new question();
// a.chooseApp()
{
"host": "/private/etc/hosts",
"hostConfig":"../data/host/config.json",
"hostSelectDateBase": "../data/host/selected.json",
"panConfig":"../data/ios/config.json",
"defaultConfigRoot": "../data/ios/pan.json",
"gitConfig":"../data/git/config.json"
}
{
"version": "1.0.0",
"panJSON": "../data/ios/pan.json"
}
const path = require('path')
const process = require('child_process');
const getFile = require('getfiles');
const cFile = require('cfiles');
const utils = require('../common/utils');
const _fileList = require('../data/_fileList.json');
const question = require('../common/_gitQuestion');
const appListManage = require('../common/appListManage');
const _gitConfig = require('../data/git/config.json');
const log = utils.msg;
const _defaultConfigFileName = 'gitConfig.json'
const _getFile = new getFile();
// 选择设置、删除、清空
class App {
constructor(props) {
const { cmd, options } = props;
this.state = {
cmd, options
}
}
init() {
const { options, cmd } = this.state;
const { install, backup } = options;
if (install) {
console.log('导入备份')
this.doImportBack();
} else if (backup) {
this.doBackUp()
}
}
// 备份
async doBackUp() {
const _cFile = new cFile();
const fileList = await this.getList({
root: '../data',
absolute: true,
});
const fileListLength = fileList.length
for (let i = 0; i < fileListLength; i += 1) {
const _json = path.parse(fileList[i]);
if (_json.name.indexOf('_') < 0) {
const _url = path.format({
root: './',
dir: `backup/${_json.dir.split('/').pop()}`,
base: _json.base
})
utils.file.readFile({ path: fileList[i] }).then((data) => {
_cFile.create(path.resolve(_url), data)
})
}
}
}
// 导入备份数据
async doImportBack() {
const fileList = await this.getList({ root: './' });
for (let i = 0; i < fileList.length; i += 1) {
const _json = path.parse(fileList[i]);
const root = path.resolve(__dirname, )
utils.file.readFile({ path: fileList[i]}).then((data)=>{
utils.file.reset(`../data/${_json.dir.split('/').pop()}/${_json.base}`,data)
})
}
}
getList(param) {
const { root, absolute } = param;
let _root = root;
if (absolute) {
_root = path.resolve(__dirname, root)
}
return new Promise((resolve) => {
_getFile.getResult({
root: _root,
suffix: ['json'],
callback: function (arr) {
resolve(arr)
}
});
})
}
}
module.exports = (cmd, options) => {
const app = new App({ cmd, options });
app.init();
}
const path = require('path')
const process = require('child_process');
const utils = require('../common/utils');
const _fileList = require('../data/_fileList.json');
const question = require('../common/_gitQuestion');
const appListManage = require('../common/appListManage');
const _gitConfig = require('../data/git/config.json');
const log = utils.msg;
const _defaultConfigFileName = 'gitConfig.json'
// 选择设置、删除、清空
class App {
constructor(props) {
const { cmd, options } = props;
this.state = {
cmd, options
}
}
init() {
const { options, cmd } = this.state;
const { info, switchGit, reset, config } = options;
if (info) {
this.onInfo(info);
} else if (switchGit) {
this.onSwitchGitCofig();
} else if (config) {
this.onConfig()
} else {
log.info('试试 -h?')
}
}
// 查看信息
async onInfo(info) {
if(info === 'all'){
log.info(JSON.stringify(_gitConfig,'',2))
}else {
this.execGet('name');
this.execGet('email');
}
}
// 设置host为制定文本
async resetConfig(param) {
const { name, email } = param;
this.execSet('name', name);
this.execSet('email', email);
}
// 选择git账号
async onSwitchGitCofig() {
const answer = await question.chooseGitAccount();
this.resetConfig(answer.gitConfig);
}
// 配置项操作
async onConfig() {
const answer = await question.getConfig()
const { type } = answer;
if (type === 'import') {
appListManage.useThisDirFile(answer, _fileList.gitConfig);
} else if (type === 'export') {
const url = `${path.resolve('./')}/${_defaultConfigFileName}`
await appListManage.exportsConfig({ url }, _fileList.gitConfig);
} else if (type === 'update') {
const answer = await question.updateGitConfig(_gitConfig);
const { gitKey, name, email} = answer
_gitConfig[gitKey].name = name;
_gitConfig[gitKey].email = email;
utils.file.reset(_fileList.gitConfig, JSON.stringify(_gitConfig,'',2) )
}
}
execSet(type, value) {
process.exec(`git config --global user.${type} ${value}`, (error, stdouts, stderr) => {
if (error) {
console.log(error);
return false;
} else {
console.log(`${type}:${value} is set success`);
}
});
}
execGet(type) {
process.exec(`git config user.${type}`, (error, stdouts, stderr) => {
if (error) {
console.log(error);
return false;
} else {
console.log(stdouts);
}
});
}
}
module.exports = (cmd, options) => {
const app = new App({ cmd, options });
app.init();
}
const path = require('path')
// const process = require('process')
const utils = require('../common/utils');
const _fileList = require('../data/_fileList.json');
const question = require('../common/_HostQuestion');
const appListManage = require('../common/appListManage');
const _hostConfig = require('../data/host/config.json');
const hostRoot = _fileList.host;
const log = utils.msg;
const _defaultConfigFileName = 'hostConfig.json'
// 选择设置、删除、清空
class App {
constructor(props) {
const { cmd, options } = props;
this.state = {
cmd, options
}
}
init() {
const { options, cmd } = this.state;
const { info, switchHost, reset, config } = options;
if (info) {
this.onInfo(info);
} else if (switchHost) {
this.onSwitchHost();
} else if (reset) {
this.onReset();
} else if (config) {
this.onConfig()
} else {
console.log('试试 -h?')
}
}
// 查看信息
async onInfo(info) {
if(!!info && info === 'all'){
for (const i in _hostConfig){
log.tip(`### ${i}`)
log.info(_hostConfig[i])
console.log('=============')
}
}else{
const file = await utils.file.read(hostRoot);
log.info(file);
}
}
// 设置host为制定文本
async setHost(str) {
const _this = this;
try {
log.info('=== 开始修改 ===')
await utils.file.reset(hostRoot, str)
await _this.onInfo();
log.success('=== 修改成功 ===')
} catch (error) {
log.error('=== 修改失败 ===')
}
}
// 选择host
async onSwitchHost() {
const answer = await question.chooseHost();
const str = await this.formatHost(answer.hostList);
// console.log(str);
this.setHost(str);
}
/**
* 获取并格式化host内容
* @param {*} list
*/
async formatHost(list) {
// const text =[];
let text = '### 妲己很高兴为您服务\n\n\n';
for (let i = 0; i < list.length; i += 1) {
// text.push(_hostConfig[list[i]]);
const key = list[i];
const title = `### ${key}\n`
text += `${title}${_hostConfig[key]} \n`
}
utils.file.reset(_fileList.hostSelectDateBase, JSON.stringify(list))
return text;
}
onReset() {
const _this = this
utils.file.reset(hostRoot, '## 已重置').then(() => {
_this.onInfo();
});
}
// 配置项操作
async onConfig() {
const answer = await question.getConfig()
const { type, fileName } = answer;
if (type === 'import') {
// 当前目录文件进行导入
// const url = `./${answer.fileName}`;
appListManage.useThisDirFile(answer, _fileList.hostConfig);
} else if (type === 'export') {
// 导出到当前目录下
// 导出配置文件
const url = `${path.resolve('./')}/${_defaultConfigFileName}`;
const data = await appListManage.exportsConfig({ url }, _fileList.hostConfig);
// 根据配置文件导出host文件
const _json = JSON.parse(data)
const arr = [];
for (const i in _json) {
arr.push(utils.file.reset(`${path.resolve('./')}/${i}.txt`, _json[i]));
}
await Promise.all(arr);
} else if (type === 'createConfig') {
const url = `${path.resolve('./')}/${_defaultConfigFileName}`;
// 获取所有txt文件清单
const file = await utils.file.getFile('./', ['txt']);
const arr = [];
for (let i = 0; i < file.length; i += 1) {
arr.push(utils.file.readFile({ path: `./${file[i]}` }))
}
// 获取所有txt文件内容
const result = await Promise.all(arr);
const configJson = {};
for (let i = 0; i < file.length; i += 1) {
configJson[path.parse(file[i]).name] = result[i]
}
// 生成配置文件
utils.file.reset(url, JSON.stringify(configJson, '', 4));
}
}
}
module.exports = (cmd, options) => {
const app = new App({ cmd, options });
app.init();
}
+63
-35

@@ -7,6 +7,8 @@ #!/usr/bin/env node

ios = require('../lib/ios.js'),
host = require('../lib/host.js');
ip = require('../lib/ip.js'),
gitConfig = require('../lib/gitConfig.js'),
git = require('../lib/git.js'),
test = require('../lib/test.js'),
_path = require('../lib/path.js'),
config = require('../lib/config'),

@@ -20,21 +22,23 @@ color = require('colors-cli/toxic');

// .allowUnknownOption()//不报错误
.version(appInfo.version)
.version(`daji@${appInfo.version}`, '-v, --version')
.usage('妲己是个小能手,什么都可以做,目前还正在学习ing'.x31 + ' [options] <package>')
.description(`目前正在测试ing,而且此工具基本不对外,呵呵`.x33 + `当前版本${appInfo.version}`)
.description(`目前正在测试ing,而且此工具基本不对外`.x33 + `当前版本${appInfo.version}`)
.parse(process.argv);
program
.command('project [cmd]')
.alias('p')
.description('this is my test project '.x29)
.option('-i, --init [type]', '创建工程')
.option('-t, --test [type]', '测试')
.action(function (cmd, options) {
const a = typeof options.name === 'string' ? options.name : ''
project(cmd, options);
}).on('--help', function () {
console.log('welcome for Daji');
// 创建工程 作废
// program
// .command('project [cmd]')
// .alias('p')
// .description('this is my test project '.x29)
// .option('-i, --init [type]', '创建工程')
// .option('-t, --test [type]', '测试')
// .action(function (cmd, options) {
// const a = typeof options.name === 'string' ? options.name : ''
// project(cmd, options);
// }).on('--help', function () {
// console.log('welcome for Daji');
});
// });
// ios 模拟器
program

@@ -65,2 +69,29 @@ .command('ios [cmd]')

program
.command('switchHost [cmd]')
.alias('host')
.option('-s --switchHost [type]', '选择切换Host')
.option('-r --reset [type]', '重置Host文件')
.option('--info [type]', '查看当前Host信息')
.option('--config [type]', '配置文件操作')
.action((cmd, options) => {
host(cmd, options);
}).on('--help', () => {
console.log('SwitchHost'.x29);
})
program
.command('gitConfig [cmd]')
.alias('git')
.option('--info [type]', '查看git当前账户信息')
.option('-s --switchGit [type]', '切换账户')
.option('--config [type]', '操作配置')
.description('git相关指令'.x29)
.action(function (cmd, options) {
git(cmd, options);
}).on('--help', function () {
console.log('切换配置');
})
program
.command('ip [cmd]')

@@ -71,3 +102,3 @@ .option('-p --ip [type]', '获取ip')

ip(cmd, options);
}).on('--help', function () {
}).on('--help', () => {
console.log('获取ip');

@@ -86,26 +117,23 @@ })

program
.command('gitConfig [cmd]')
.alias('git')
.option('-g --get [type]', '查看当前信息')
.option('-m --my [type]', '自己配置')
.option('-w --work [type]', '工作配置')
.description('get this mac\'s ip'.x29)
.command('config [cmd]')
.description('配置项的相关操作'.x29)
.option('-i --install [type]', '将当前目录记录的配置文件全部导入工具')
.option('-b --backup [type]', '将当前配置项全部进行备份')
.action(function (cmd, options) {
gitConfig(cmd, options);
config(cmd, options);
}).on('--help', function () {
console.log('切换配置');
console.log('获取路径信息');
})
program
.command('testCode [cmd]')
.alias('test')
.option('-i --init [type]', '查看当前信息')
// program
// .command('testCode [cmd]')
// .alias('test')
// .option('-i --init [type]', '查看当前信息')
.description('just test code'.x29)
.action(function (cmd, options) {
test(cmd, options);
}).on('--help', function () {
console.log('testCode');
})
// .description('just test code'.x29)
// .action(function (cmd, options) {
// test(cmd, options);
// }).on('--help', function () {
// console.log('testCode');
// })

@@ -112,0 +140,0 @@ //默认不传参数输出help

@@ -1,11 +0,9 @@

const _configRoot = '../data/config.json';
const _defaultConfigRoot = '../data/pan.json';
const _fileList = require('../data/_fileList.json');
const utils = require('./utils');
const question = require('./question');
const _config = require(_configRoot);
const _config = require(_fileList.panConfig);
const listJSONRoot = _config.panJSON;
// const _listJSONRoot = _config.panJSON;
const _configRoot = _fileList.panConfig;
const _defaultConfigRoot = _fileList.defaultConfigRoot;
const fs = require('fs');
const path = require('path');
const log = utils.msg;

@@ -16,2 +14,3 @@

constructor() {
this.state = {

@@ -164,3 +163,4 @@ json: utils.JSON.get(listJSONRoot)

*/
importConfig(answers) {
importConfig(answers, root) {
utils.file.readFile({

@@ -170,3 +170,3 @@ path: answers.url,

}).then((data) => {
utils.file.reset(listJSONRoot, data);
utils.file.reset(root || listJSONRoot, data);
}).catch(err => console.log(err))

@@ -180,10 +180,14 @@ }

*/
exportsConfig(answers) {
utils.file.readFile({
path: listJSONRoot,
isAbsolute: true
}).then((data) => {
utils.file.reset(answers.url, data);
log.success('== success ==');
}).catch(err =>log.error(err));
async exportsConfig(answers, root) {
try {
const data = await utils.file.readFile({
path: root || listJSONRoot,
isAbsolute: true
});
await utils.file.reset(answers.url, data);
log.success('== success ==');
return data;
} catch (error) {
log.error(error)
}
}

@@ -220,4 +224,4 @@ /**

*/
async useThisDirFile(answers) {
async useThisDirFile(answers, root) {
const url = `./${answers.fileName}`;

@@ -227,7 +231,7 @@ utils.file.readFile({

}).then(data => {
utils.file.reset(listJSONRoot, data);
log.success('== success ==');
});
utils.file.reset(root || listJSONRoot, data);
log.success('== success ==');
});
}
}
module.exports = new common();
const fs = require('fs');
const question = require('./question');
const question = require('./_IOSQuestion');
const utils = require('./utils');
const _config = require('../data/config.json');
const _config = require('../data/ios/config.json');
const listJSONRoot = _config.panJSON;

@@ -7,0 +7,0 @@ const appJson = require(listJSONRoot);

@@ -15,149 +15,152 @@ /*

common.prototype.file = {
set: function (file, message, opation) {
return new Promise((resolve, reject) => {
const dir = path.resolve(__dirname, file);
set: function (file, message, opation) {
return new Promise((resolve, reject) => {
const dir = path.resolve(__dirname, file);
fs.appendFile(dir, message, (err) => {
if (err) {
reject(err);
}
resolve();
});
})
},
reset: function (file, message) {
return new Promise((resolve, reject) => {
const dir = path.resolve(__dirname, file);
fs.writeFile(dir, message, (err) => {
if (err) {
reject(err);
}
resolve();
});
});
fs.appendFile(dir, message, (err) => {
if (err) {
reject(err);
}
resolve();
});
})
},
reset: function (file, message) {
return new Promise((resolve, reject) => {
const dir = path.resolve(__dirname, file);
fs.writeFile(dir, message, (err) => {
if (err) {
reject(err);
}
resolve();
});
});
},
},
read: function (file) {
return new Promise((resolve, reject) => {
const dir = path.resolve(__dirname, file);
fs.readFile(dir, 'utf8', (err, data) => {
if (err) {
reject(err);
}
resolve(data);
});
});
},
readdir: function (path) {
return new Promise((resolve, reject) => {
fs.readdir(path, (err, fd) => {
if (err) {
reject(err);
}
resolve();
});
});
},
readdirSync: function (path, callback) {
return new Promise((resolove, reject) => {
const file = fs.readdirSync(path);
resolve(file);
});
read: function (file) {
return new Promise((resolve, reject) => {
const dir = path.resolve(__dirname, file);
fs.readFile(dir, 'utf8', (err, data) => {
if (err) {
reject(err);
}
resolve(data);
});
});
},
readdir: function (path) {
return new Promise((resolve, reject) => {
fs.readdir(path, (err, fd) => {
if (err) {
reject(err);
}
resolve();
});
});
},
readdirSync: function (path, callback) {
return new Promise((resolove, reject) => {
const file = fs.readdirSync(path);
resolve(file);
});
},
},
// 获取指定目录下指定文件合集(内部调用方法)
getFile: function (root, fileType) {
return new Promise((resolve, reject) => {
const file = fs.readdirSync(root);
const array = file.filter((name) => {
const arr = name.split('.');
return fileType.includes(arr[arr.length - 1])
})
resolve(array);
})
},
open: function (file) {
return new Promise((resolve, reject) => {
fs.open(file, 0666, (err, d) => {
if (err) {
throw err
}
resolve()
});
})
// 获取指定目录下指定文件合集(内部调用方法)
getFile: function (root, fileType) {
console.log(root);
return new Promise((resolve, reject) => {
const file = fs.readdirSync(root);
const array = file.filter((name) => {
const arr = name.split('.');
return fileType.includes(arr[arr.length - 1])
})
resolve(array);
})
},
open: function (file) {
return new Promise((resolve, reject) => {
fs.open(file, 0666, (err, d) => {
if (err) {
throw err
}
resolve()
});
})
},
create: function (file, message, callback) {
const _this = this;
const array = file.split('/');
const name = array[array.length - 1];
if (name.indexOf('.') < 0) {
console.error('当前目录地址格式错误');
return false;
},
create: function (file, message, callback) {
const _this = this;
const array = file.split('/');
const name = array[array.length - 1];
if (name.indexOf('.') < 0) {
console.error('当前目录地址格式错误');
return false;
}
var root = file.substring(0, file.indexOf(name));
common.exists({
path: file,
callback: function (data) {
if (data) {
console.error(file + '对应目录文件已存在,创建失败');
} else {
common.mkdirSync(root, () => {
_this.reset(file, message).then(callback());
});
}
}
});
},
mkdirSync: function (root) {
return new Promise((resolve, reject) => {
fs.mkdir(root, 0777, (err) => {
if (err) {
// console.error(root + ' =>对应目录已存在');
reject(err);
} else {
// console.tip(root + '=> 目录已创建完成');
}
resolve();
});
});
var root = file.substring(0, file.indexOf(name));
},
// 判断文件是否存在
hasFile: async (obj) => {
return new Promise((resolve, reject) => {
fs.stat(obj.path, false, (err, stats) => {
common.exists({
path: file,
callback: function (data) {
if (data) {
console.error(file + '对应目录文件已存在,创建失败');
} else {
common.mkdirSync(root, () => {
_this.reset(file, message).then(callback());
});
}
}
});
},
mkdirSync: function (root) {
return new Promise((resolve, reject) => {
fs.mkdir(root, 0777, (err) => {
if (err) {
// console.error(root + ' =>对应目录已存在');
reject(err);
} else {
// console.tip(root + '=> 目录已创建完成');
}
resolve();
});
});
if (!!stats) {
resolve(stats)
} else {
reject();
}
})
})
},
// 读取文件
readFile: (obj) => {
return new Promise((resolve, reject) => {
let dir = obj.path;
if (obj.isAbsolute) {
dir = path.resolve(__dirname, obj.path);
}
},
// 判断文件是否存在
// todo 后续用stat替换
exists: function (obj) {
return new Promise((resolve, reject) => {
fs.exists(obj.path, (exists) => {
if (!exists) {
reject(exists);
}
resolve(exists);
});
});
fs.readFile(dir, obj.encode || 'utf8', (err, file) => {
if (err) {
reject(err);
} else {
resolve(file);
}
// resolve(err, file);
// obj.callback(err, file);
});
})
},
// 读取文件
readFile: function (obj) {
return new Promise((resolve, reject) => {
let dir = obj.path;
if (obj.isAbsolute) {
dir = path.resolve(__dirname, obj.path);
}
fs.readFile(dir, obj.encode || 'utf8', (err, file) => {
if (err) {
reject(err);
} else {
resolve(file);
}
// resolve(err, file);
// obj.callback(err, file);
});
})
},
},
};

@@ -167,7 +170,7 @@

common.prototype.JSON = {
get: function (file) {
const dir = path.resolve(__dirname, file);
const fileStr = fs.readFileSync(dir);
return JSON.parse(fileStr);
}
get: function (file) {
const dir = path.resolve(__dirname, file);
const fileStr = fs.readFileSync(dir);
return JSON.parse(fileStr);
}
};

@@ -177,86 +180,86 @@

common.prototype.tools = {
formatDate: function (date, type, format) {
const arr = ['00', '01', '02', '03', '04', '05', '06', '07', '08', '09'];
const D = date.getDate(),
M = date.getMonth() + 1,
Y = date.getFullYear(),
h = date.getHours(),
m = date.getMinutes(),
s = date.getSeconds();
formatDate: function (date, type, format) {
const arr = ['00', '01', '02', '03', '04', '05', '06', '07', '08', '09'];
const D = date.getDate(),
M = date.getMonth() + 1,
Y = date.getFullYear(),
h = date.getHours(),
m = date.getMinutes(),
s = date.getSeconds();
const _date = `${Y}-${arr[M] || M}-${arr[D] || D}`.split('-').join(format),
_time = `${arr[h] || h}:${arr[m] || m}:${arr[s] || s}`
return {
date: _date,
time: _time,
fullDate: `${_date} ${_time}`
};
},
formatData: function (obj, type) {
const _this = this,
data = decodeURI(obj.toString());
if (type === 'json') {
data = _this.dataToObj(data);
}
return data;
},
dataToObj: function (url) {
var obj = {};
var keyvalue = [];
var key = '',
value = '';
const _date = `${Y}-${arr[M] || M}-${arr[D] || D}`.split('-').join(format),
_time = `${arr[h] || h}:${arr[m] || m}:${arr[s] || s}`
return {
date: _date,
time: _time,
fullDate: `${_date} ${_time}`
};
},
formatData: function (obj, type) {
const _this = this,
data = decodeURI(obj.toString());
if (type === 'json') {
data = _this.dataToObj(data);
}
return data;
},
dataToObj: function (url) {
var obj = {};
var keyvalue = [];
var key = '',
value = '';
var paraString = url.substring(0, url.length).split('&');
for (var i in paraString) {
keyvalue = paraString[i].split('=');
key = keyvalue[0];
value = keyvalue[1];
obj[key] = value;
var paraString = url.substring(0, url.length).split('&');
for (var i in paraString) {
keyvalue = paraString[i].split('=');
key = keyvalue[0];
value = keyvalue[1];
obj[key] = value;
}
return JSON.stringify(obj);
},
getDir: function () {
return new Promise((resolve, reject) => {
process.exec(`pwd`, (err, stdout, stderr) => {
if (!!err) {
reject(err);
} else {
resolve(stdout);
}
return JSON.stringify(obj);
},
getDir: function () {
return new Promise((resolve, reject) => {
process.exec(`pwd`, (err, stdout, stderr) => {
if (!!err) {
reject(err);
} else {
resolve(stdout);
}
})
});
}
})
});
}
};
common.prototype.template = {
templateReg : /\{\{(.*?)\}\}/g,
render: function (template, context) {
reg = this.templateReg;
return template.replace(/\{\{(.*?)\}\}/g, (match, key) => {
const arr = key.split('.'); // 判断是否携带功能参数
let str = '';
const _key = arr[0]
if (arr.length > 1) {
const type = arr[1];
const _val = context[_key];
if (type === 'encode') {
str = encodeURIComponent(_val);
} else if (type === 'decode') {
str = decodeURIComponent(_val);
}
} else {
str = context[_key];
}
return str;
});
},
getTemplateKey:function(template){
reg = this.templateReg;
const str = reg.exec(template)[1];
if(str.indexOf('.')){
return str.split('.')[0]
}else{
return str;
}
templateReg: /\{\{(.*?)\}\}/g,
render: function (template, context) {
reg = this.templateReg;
return template.replace(/\{\{(.*?)\}\}/g, (match, key) => {
const arr = key.split('.'); // 判断是否携带功能参数
let str = '';
const _key = arr[0]
if (arr.length > 1) {
const type = arr[1];
const _val = context[_key];
if (type === 'encode') {
str = encodeURIComponent(_val);
} else if (type === 'decode') {
str = decodeURIComponent(_val);
}
} else {
str = context[_key];
}
return str;
});
},
getTemplateKey: function (template) {
reg = this.templateReg;
const str = reg.exec(template)[1];
if (str.indexOf('.')) {
return str.split('.')[0]
} else {
return str;
}
}
}

@@ -263,0 +266,0 @@

@@ -6,2 +6,3 @@ #!/usr/bin/env node

// TODO 这里同样要改成可配置的
function gitConfig(cmd, opations) {

@@ -8,0 +9,0 @@

+207
-148
#!/usr/bin/env node
const process = require('child_process');
color = require('colors-cli/toxic');
const color = require('colors-cli/toxic');
const iosTools = require('../common/iosTools');
const question = require('../common/question');
const question = require('../common/_IOSQuestion');
const appListManage = require('../common/appListManage');
const utils = require('../common/utils');
const log = utils.msg;
// const path = require('path');
module.exports = function (cmd, options) {
class App {
constructor(props) {
// super(props)
const {
cmd,
options
} = props;
this.state = {
cmd,
options
};;
}
if (!!options.start) {
/**
* 1. 没参数,则直接打开list
* 2. none 则跳过list,直接打开模拟器,什么都不做
* 3. type 则寻找对应id打开
*/
if (options.start === true) {
init() {
const { options, cmd } = this.state;
const { start, install, yanxuan, url, translate, add, info, remove, update, config } = options;
if (!!start) {
this.onStart(start)
} else if (install) {
this.onInstall();
} else if (yanxuan) {
this.onYanXuan()
} else if (url) {
this.onUrl({ cmd,url});
} else if (translate) {
this.onTranslate({ cmd, url: translate })
} else if (add) {
this.onAddApp();
} else if (info) {
this.onInfo(info);
} else if (remove) {
this.onRemove(remove)
} else if (update) {
this.onUpdate(update);
} else if (config) {
this.onConfig()
}else {
console.log('试试 -h?')
}
question.chooseApp((answers) => {
if (answers === false) {
iosTools.openIphone();
} else {
const appInfo = iosTools.getAppInfo(answers.app, 'cname');
iosTools.openIphone(() => {
process.exec(`xcrun simctl launch booted ${appInfo.boundId}`);
});
}
}
})
onStart(param) {
/**
* 1. 没参数,则直接打开list
* 2. none 则跳过list,直接打开模拟器,什么都不做
* 3. type 则寻找对应id打开
*/
if (param === true) {
} else {
if (options.start === 'none') {
// 不选择app,仅打开模拟器
iosTools.openIphone();
} else {
const appInfo = iosTools.getAppInfo(options.start, 'name');
if (!!appInfo.boundId) {
iosTools.openIphone(() => {
process.exec(`xcrun simctl launch booted ${appInfo.boundId}`);
});
} else {
console.log(`未找到${options.start},请确认已经安装对应app或已更新app清单库文件`)
}
}
}
} else if (options.install === true) {
// 安装
question.chooseApp((answers) => {
const appInfo = iosTools.getAppInfo(answers.app, 'cname');
iosTools.installPackage(appInfo);
});
} else if (options.yanxuan === true) {
// 启动客户端
iosTools.openIphone(() => {
process.exec(`xcrun simctl launch booted `);
});
question.chooseApp((answers) => {
} else if (!!options.url) {
let url = options.url;
if (!/^http(s){0,1}:\/\//.test(url)) {
log.warn('检测到url 没有带http|https ,请确认是否为遗漏');
}
let type = 'list';
if (!!cmd) {
type = cmd.toLocaleLowerCase();
}
if (answers === false) {
iosTools.openIphone();
} else {
const appInfo = iosTools.getAppInfo(answers.app, 'cname');
iosTools.openIphone(() => {
process.exec(`xcrun simctl launch booted ${appInfo.boundId}`);
});
}
if (type === 'list') {
question.chooseApp((answers) => {
const appInfo = iosTools.getAppInfo(answers.app, 'cname');
url = iosTools.translateURL(url, appInfo);
iosTools.openUrl(url);
});
} else if (type === 'safari') {
// url不处理
iosTools.openUrl(url);
} else {
const appInfo = iosTools.getAppInfo(type, 'name');
if (!!appInfo.name) {
url = iosTools.translateURL(url, appInfo);
} else {
url = iosTools.translateURL(url, type);
}
iosTools.openUrl(url);
}
})
} else {
if (param === 'none') {
// 不选择app,仅打开模拟器
iosTools.openIphone();
} else {
const appInfo = iosTools.getAppInfo(param, 'name');
if (!!appInfo.boundId) {
iosTools.openIphone(() => {
process.exec(`xcrun simctl launch booted ${appInfo.boundId}`);
});
} else {
console.log(`未找到${param},请确认已经安装对应app或已更新app清单库文件`)
}
}
}
}
} else if (!!options.translate) {
// 翻译
const url = options.translate;
let type = '';
if (!!cmd) {
type = cmd.toLocaleLowerCase();
}
const appInfo = iosTools.getAppInfo(type, 'name');
console.log(iosTools.translateURL(url, appInfo));
} else if (!!options.init) {
// console.log(options.init);
// 初始化配置表单
} else if (!!options.add) {
// 对本地json配置进行添加
addApp();
} else if (!!options.info) {
let type = options.info
if (type === true) {
onInstall(param) {
// 安装
question.chooseApp((answers) => {
const appInfo = iosTools.getAppInfo(answers.app, 'cname');
iosTools.installPackage(appInfo);
});
}
appListManage.getList().then(file => {
console.log(file);
})
} else {
const appInfo = iosTools.getAppInfo(type, 'name');
if (!!appInfo.name) {
console.log(appInfo);
} else {
console.log(`未找到 ${type}`)
}
}
} else if (!!options.remove) {
onYanXuan(param) {
// 启动客户端
iosTools.openIphone(() => {
process.exec(`xcrun simctl launch booted `);
});
}
iosTools.judgeTypeAndChooseList(options.remove).then((info) => {
onUrl(param) {
const { url, cmd } = param;
let _url = url;
if (!/^http(s){0,1}:\/\//.test(url)) {
log.warn('检测到url 没有带http|https ,请确认是否为遗漏');
}
let type = 'list';
if (!!cmd) {
type = cmd.toLocaleLowerCase();
}
appListManage.removeApp(info).then().catch(err => {
console.log(err);
});
}).catch((err) => {
console.log(`删除失败`)
});
if (type === 'list') {
question.chooseApp((answers) => {
const appInfo = iosTools.getAppInfo(answers.app, 'cname');
_url = iosTools.translateURL(url, appInfo);
iosTools.openUrl(_url);
});
} else if (type === 'safari') {
// url不处理
iosTools.openUrl(url);
} else {
const appInfo = iosTools.getAppInfo(type, 'name');
if (!!appInfo.name) {
_url = iosTools.translateURL(url, appInfo);
} else {
_url = iosTools.translateURL(url, type);
}
iosTools.openUrl(_url);
}
}
} else if (!!options.update) {
onTranslate(param) {
// 翻译
const { cmd, url } = param;
iosTools.judgeTypeAndChooseList(options.update).then((info) => {
question.updateApp(info).then((info) => {
appListManage.updateApp(info)
});
}).catch((err) => {
// console.log(`更新失败`)
question.confirm(`目标不存在,是否改为新增`).then((answers) => {
addApp();
})
});
} else if (!!options.config) {
let type = '';
if (!!cmd) {
type = cmd.toLocaleLowerCase();
}
const appInfo = iosTools.getAppInfo(type, 'name');
console.log(iosTools.translateURL(url, appInfo));
}
question.getConfig().then((answers) => {
// console.log(answers);
if (answers.type === 'export') {
appListManage.exportsConfig(answers);
} else if (answers.type === 'import') {
appListManage.importConfig(answers);
} else if (answers.type === 'userDefined') {
appListManage.userDefined(answers);
} else if (answers.type === 'reset') {
appListManage.resetConfig(answers);
} else if (answers.type === 'this') {
appListManage.useThisDirFile(answers);
}
});
} else {
console.log('pan ios -h 可以查看命令');
}
onAddApp() {
question.inputAppInfo().then((info) => {
appListManage.addApp(info).then().catch(err => {
console.log(err);
});
}).catch(err => console.log(err));
}
onInfo(param) {
const type = param;
if (type === true) {
appListManage.getList().then(file => {
console.log(file);
})
} else {
const appInfo = iosTools.getAppInfo(type, 'name');
if (!!appInfo.name) {
console.log(appInfo);
} else {
console.log(`未找到 ${type}`)
}
}
}
onRemove(param) {
iosTools.judgeTypeAndChooseList(param).then((info) => {
appListManage.removeApp(info).then().catch(err => {
console.log(err);
});
}).catch((err) => {
console.log(`删除失败`)
});
}
onUpdate(param) {
const _this = this;
iosTools.judgeTypeAndChooseList(param).then((info) => {
question.updateApp(info).then((info) => {
appListManage.updateApp(info)
});
}).catch((err) => {
// console.log(`更新失败`)
question.confirm(`目标不存在,是否改为新增`).then((answers) => {
_this.onAddApp();
})
});
}
onConfig(){
question.getConfig().then((answers) => {
if (answers.type === 'export') {
appListManage.exportsConfig(answers);
} else if (answers.type === 'import') {
appListManage.importConfig(answers);
} else if (answers.type === 'userDefined') {
appListManage.userDefined(answers);
} else if (answers.type === 'reset') {
appListManage.resetConfig(answers);
} else if (answers.type === 'thisRoot') {
appListManage.useThisDirFile(answers);
}
});
}
}
// 省代码
const addApp = () => {
question.inputAppInfo().then((info) => {
appListManage.addApp(info).then().catch(err => {
console.log(err);
});
}).catch(err => console.log(err));
}
module.exports = (cmd, options) => {
const app = new App({
cmd,
options
});
app.init();
};

@@ -6,5 +6,6 @@

var hostName = os.hostname();
var ifaces = os.networkInterfaces();
var ip = [];
const hostName = os.hostname();
const ifaces = os.networkInterfaces();
const ipv4 = [];
const ipv6=[];
for (var x in ifaces) {

@@ -14,4 +15,7 @@

var object = ifaces[x][y];
if (object["family"] === 'IPv4') {
ip.push(object.address);
ipv4.push(object.address);
} else if (object["family"] === 'IPv6'){
ipv6.push(object.address);
}

@@ -22,4 +26,5 @@ }

var json = {
ip: ip,
host: hostName,
ipv4,
ipv6,
hostName,
system: os.type(),

@@ -30,3 +35,3 @@ release: os.release(),

return console.log( JSON.stringify(json) );
return console.log( JSON.stringify(json,'',4) );

@@ -33,0 +38,0 @@ }

#!/usr/bin/env node
// 此功能作废,考虑到现如今脚手架泛滥,没必要再做个轮子出来
const inquirer = require('inquirer');

@@ -4,0 +5,0 @@ const process = require('child_process');

@@ -15,4 +15,18 @@ // #!/usr/bin/env node

const process = require('child_process');
process.exec(`xcrun instruments -w`);
// const process = require('child_process');
// process.exec(`curl -o "./index.text" "hello world"`, (err, stdout, stderr) => {
// console.log(stdout);
// });
// const utils = require('../common/utils');
// // utils.file.read('/private/etc/hosts').then((file) => {
// // console.log(file);
// // });
// utils.file.reset('/private/etc/hosts', '220.181.72.188 pub.mail.163.com').then(() => {
// utils.file.read('/private/etc/hosts').then((file) => {
// console.log(file);
// });;
// });
// console.log(a);
{
"name": "daji",
"version": "1.3.1",
"version": "1.4.0",
"description": "",

@@ -26,3 +26,5 @@ "main": "index.js",

"cmdify": "^0.0.4",
"through": "^2.3.6"
"through": "^2.3.6",
"getfiles": "1.1.0",
"cfiles": "1.0.3"
},

@@ -33,2 +35,2 @@ "bugs": {

"homepage": "https://github.com/cpu220/Daji"
}
}
const path = require('path');
const fs = require('fs');
const utils = require('./utils');
const inquirer = require('inquirer');
const _config = require('../data/config.json');
const listJSONRoot = _config.panJSON;
const appJson = require(listJSONRoot);
const process = require('child_process');
const iosTools = require('./iosTools');
class question {
constructor() {
this.state = {
}
this.getAppName = this.getAppName.bind(this);
this.getIphoneList = this.getIphoneList.bind(this);
this.chooseApp = this.chooseApp.bind(this);
this.chooseDevice = this.chooseDevice.bind(this);
this.inputAppInfo = this.inputAppInfo.bind(this);
this.confirm = this.confirm.bind(this);
}
// 获取appName 列表
getAppName() {
let result = [];
const listLength = appJson.list.length;
for (let i = 0; i < listLength; i++) {
result.push(appJson.list[i].cname);
}
return result;
}
// 获取当前设备的模拟器list
getIphoneList() {
return new Promise((resolve, reject) => {
console.log('== 正在获取本地设备清单 =='.x34);
console.log('ps: 首次启动时间较长,请耐心等待... \n');
process.exec("xcrun instruments -w 'iphone'", (err, stdout, stderr) => {
const arr = stderr.split('\n')
const iphoneList = [];
for (let i = 1; i < arr.length; i++) {
if (/^iPhone/.test(arr[i])) {
iphoneList.push(arr[i]);
}
}
resolve(iphoneList.reverse());
});
})
}
/**
* 获取本地的applist,并给与选择
*
* @memberof question
*/
chooseApp(callback) {
const list = this.getAppName();
if (list.length === 0) {
console.log('当前未添加任何app信息,如想添加请查阅文档');
callback(false);
} else {
const appList = [{
type: 'list',
name: 'app',
message: 'choose a app',
choices: this.getAppName() || [],
filter: function (val) {
return val;
}
}];
inquirer.prompt(appList).then(function (answers) {
if (!!callback) {
callback(answers);
}
});
}
}
/**
* 获取本地设备清单,并给与选择
*
* @param {any} callback
* @memberof question
*/
chooseDevice(callback) {
this.getIphoneList().then(data => {
const list = [{
type: 'list',
name: 'iphone',
message: '选择设备',
choices: data,
filter: function (val) {
return val;
}
}];
inquirer.prompt(list).then(function (answers) {
if (!!callback) {
callback(answers);
}
});
})
}
inputAppInfo() {
const _this = this;
return new Promise((resolve, reject) => {
const list = _this.formatInfoList({});
inquirer.prompt(list).then(function (answers) {
const result = _this.formatInfoListForResult(answers);
resolve(result);
});
});
}
/**
* 用于条件判断
*
* @param {any} msg
* @memberof question
*/
confirm(msg, callback) {
const list = [{
type: 'confirm',
name: 'flag',
message: msg
}];
return new Promise((resolve, reject) => {
inquirer.prompt(list).then(function (answers) {
resolve(answers);
});
})
}
/**
* 更新app,并获取更新后的数据
*
* @param {any} appInfo
* @returns
* @memberof question
*/
updateApp(appInfo) {
const _this = this;
// console.log(appInfo);
return new Promise((resolve, reject) => {
const list = _this.formatInfoList(appInfo);
inquirer.prompt(list).then(function (answers) {
const result = _this.formatInfoListForResult(answers);
result.name = appInfo.name; // name为主键,不允许修改
resolve(result);
});
})
}
formatInfoList(appInfo) {
const name = [{
type: 'input',
name: 'name',
message: 'app的英文名(用于启动指令)',
validate: (val) => {
if (val.trim() === '') {
return '请填写app的英文名';
}
return true;
}
}]
const list = [{
type: 'input',
name: 'cname',
default: appInfo.cname || null,
message: 'app的中文名(用于list展示)',
validate: (val) => {
if (val.trim() === '') {
return '请填写app的中文名';
}
return true;
}
}, {
type: 'input',
name: 'packageName',
message: 'app文件名(xxx.app)',
default: appInfo.packageName || null,
validate: (val) => {
if (val.trim() === '') {
return '请填写正确的packageName';
}
return true;
}
}, {
type: 'input',
name: 'boundId',
message: '请填写boundId',
default: appInfo.boundId || null,
validate: (val) => {
if (val.trim() === '') {
return '请填写boundId';
}
return true;
}
}, {
type: 'input',
name: 'scheme',
message: '请填写scheme(用于调用对应app打开H5页面,如:xxx://webview?url=)',
default: appInfo.scheme || null,
validate: (val) => {
if (val.trim() === '') {
return '请填写scheme';
}
return true;
}
},
{
type: 'input',
name: 'url',
message: 'app包仓库地址(git地址),用于存放对应app包,如果不需要安装可以不填写直接回车',
default: !!appInfo.repository ? appInfo.repository.url : null,
// validate: (val) => {
// if (!/^git/.test(val)) {
// return '请填写正确的仓库地址,如 git@xxx';
// }
// return true;
// }
}
];
if (!!appInfo.name) {
return list;
} else {
return [].concat(name, list);
}
}
formatInfoListForResult(answers) {
return Object.assign({}, {
"name": answers.name || '',
"cname": answers.cname,
"packageName": answers.packageName,
"boundId": answers.boundId,
"scheme": answers.scheme,
"repository": {
"type": "git",
"url": answers.url
}
});
}
// 输入地址
async getConfig() {
const _this =this;
const file = await utils.file.getFile('./', ['json', 'js']);
const configList = [{
type: 'list',
message: '请选择操作类型',
name: 'type',
choices: [{
name: '导出',
value: 'export'
}, {
name: '导入',
value: 'import'
}, {
name: '自定义配置项目录',
value: 'userDefined'
}, {
name: '重置',
value: 'reset'
}, {
name: '使用当前目录文件',
value: 'this'
}],
}, {
type: 'input',
name: 'url',
message: "请输入地址",
when: (answers) => {
if (answers.type !== 'reset' && answers.type !== 'this') {
return answers.type;
}
},
validate: (val) => {
let _urlObj = path.parse(val);
if (!!_urlObj.ext.trim() === false) {
return '请填写准确的文件地址(xxx/xxx/xxx.xx)';
}
return true;
}
}, {
type: 'list',
name: 'fileName',
message: '输选择文件名',
choices:file||[],
when: (answers) => {
if (answers.type === 'this') {
return answers.type;
}
},
filter: function (val) {
return val;
}
}];
return new Promise((resolve, reject) => {
inquirer.prompt(configList).then((answers) => {
resolve(answers);
}).catch(err => {
reject(err);
});
});
}
}
// const a = new question();
module.exports = new question();
// a.chooseApp()
{
"version": "1.0.0",
"panJSON": "../data/pan.json"
}
{
"version": "1.1.0",
"list": [
]
}