1
0
mirror of https://gitcode.com/github-mirrors/react-native-update-cli.git synced 2025-09-17 18:06:10 +08:00
Code Issues Packages Projects Releases Wiki Activity GitHub Gitee

Compare commits

..

1 Commits

Author SHA1 Message Date
sunnylqm
f51223a662 v1.4.0-beta0 2021-04-08 15:46:20 +08:00
12 changed files with 3119 additions and 3395 deletions

29
LICENSE Normal file
View File

@@ -0,0 +1,29 @@
BSD 3-Clause License
Copyright (c) 2020, reactnativecn
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
3. Neither the name of the copyright holder nor the names of its
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

View File

@@ -80,33 +80,6 @@
},
"packageId": {
"hasValue": true
},
"packageVersion": {
"hasValue": true
}
}
},
"updateVersionInfo": {
"options": {
"platform": {
"hasValue": true
},
"versionId": {
"hasValue": true
},
"name": {
"default": false,
"hasValue": true
},
"description": {
"default": false,
"hasValue": true
},
"metaInfo": {
"default": false,
"hasValue": true
}
}
},
@@ -140,9 +113,7 @@
"default": ".pushy/output/${platform}.${time}.ppk",
"hasValue": true
},
"sourcemap": {
"default": false
}
"verbose": {}
}
},
"release": {
@@ -152,7 +123,7 @@
"description": "Create diff patch",
"options": {
"output": {
"default": ".pushy/output/diff",
"default": "build/output/diff",
"hasValue": true
}
}
@@ -161,7 +132,7 @@
"description": "Create diff patch from a Android package(.apk)",
"options": {
"output": {
"default": ".pushy/output/diff-${time}.apk-patch",
"default": "build/output/diff-${time}.apk-patch",
"hasValue": true
}
}
@@ -170,34 +141,7 @@
"description": "Create diff patch from a iOS package(.ipa)",
"options": {
"output": {
"default": ".pushy/output/diff-${time}.ipa-patch",
"hasValue": true
}
}
},
"hdiff": {
"description": "Create hdiff patch",
"options": {
"output": {
"default": ".pushy/output/hdiff",
"hasValue": true
}
}
},
"hdiffFromApk": {
"description": "Create hdiff patch from a Android package(.apk)",
"options": {
"output": {
"default": ".pushy/output/hdiff-${time}.apk-patch",
"hasValue": true
}
}
},
"hdiffFromIpa": {
"description": "Create hdiff patch from a iOS package(.ipa)",
"options": {
"output": {
"default": ".pushy/output/hdiff-${time}.ipa-patch",
"default": "build/output/diff-${time}.ipa-patch",
"hasValue": true
}
}

View File

@@ -1,6 +1,6 @@
{
"name": "react-native-update-cli",
"version": "1.11.0",
"version": "1.4.0-beta0",
"description": "Command tools for javaScript updater with `pushy` service for react native apps.",
"main": "index.js",
"bin": {
@@ -36,7 +36,7 @@
"cli-arguments": "^0.2.1",
"filesize-parser": "^1.5.0",
"fs-extra": "8",
"gradle-to-js": "^2.0.1",
"gradle-to-js": "^2.0.0",
"node-fetch": "^2.6.1",
"progress": "^2.0.3",
"read": "^1.0.7",

3088
pnpm-lock.yaml generated

File diff suppressed because it is too large Load Diff

View File

@@ -1,3 +1,7 @@
/**
* Created by tdzl2003 on 2/13/16.
*/
const fetch = require('node-fetch');
const defaultEndpoint = 'http://u.reactnative.cn/api';
let host = process.env.PUSHY_REGISTRY || defaultEndpoint;
@@ -61,14 +65,7 @@ exports.closeSession = function () {
async function query(url, options) {
const resp = await fetch(url, options);
const text = await resp.text();
let json;
try {
json = JSON.parse(text);
} catch (e) {
throw new Error(`Server error: ${text}`);
}
const json = await resp.json();
if (resp.status !== 200) {
throw Object.assign(new Error(json.message || json.error), {
status: resp.status,
@@ -115,18 +112,14 @@ async function uploadFile(fn, key) {
let realUrl = url;
if (backupUrl) {
if (global.USE_ACC_OSS) {
const pingResult = await tcpPing({
address: url.replace('https://', ''),
attempts: 4,
timeout: 1000,
});
// console.log({pingResult});
if (isNaN(pingResult.avg) || pingResult.avg > 150) {
realUrl = backupUrl;
} else {
const pingResult = await tcpPing({
address: url.replace('https://', ''),
attempts: 4,
timeout: 1000,
});
// console.log({pingResult});
if (isNaN(pingResult.avg) || pingResult.avg > 150) {
realUrl = backupUrl;
}
}
// console.log({realUrl});
}
@@ -136,11 +129,11 @@ async function uploadFile(fn, key) {
throw new Error(
`此文件大小${(fileSize / 1048576).toFixed(
1,
)}m, 超出当前额度${maxSize}。您可以考虑升级付费业务以提升此额度。详情请访问: ${pricingPageUrl}`,
)}m, 超出当前额度${maxSize}。您可以考虑升级付费业务以提升此额度。详情请访问${pricingPageUrl}`,
);
}
const bar = new ProgressBar(' 上传中 [:bar] :percent :etas', {
const bar = new ProgressBar(' Uploading [:bar] :percent :etas', {
complete: '=',
incomplete: ' ',
total: fileSize,
@@ -159,6 +152,10 @@ async function uploadFile(fn, key) {
realUrl,
{
formData,
headers: {
'User-Agent': userAgent,
'X-AccessToken': session ? session.token : '',
},
},
(err, resp, body) => {
if (err) {
@@ -169,7 +166,13 @@ async function uploadFile(fn, key) {
Object.assign(new Error(body), { status: resp.statusCode }),
);
}
resolve({ hash: formData.key });
resolve(
body
? // qiniu
JSON.parse(body)
: // aliyun oss
{ hash: formData.key },
);
},
);
});

View File

@@ -1,3 +1,7 @@
/**
* Created by tdzl2003 on 2/13/16.
*/
import { question } from './utils';
import fs from 'fs';
const Table = require('tty-table');
@@ -11,7 +15,7 @@ const validPlatforms = {
export function checkPlatform(platform) {
if (!validPlatforms[platform]) {
throw new Error(`无法识别的平台 '${platform}'`);
throw new Error(`Invalid platform '${platform}'`);
}
return platform;
}
@@ -38,9 +42,9 @@ export async function listApp(platform) {
const list = platform ? data.filter((v) => v.platform === platform) : data;
const header = [
{ value: '应用 id' },
{ value: '应用名称' },
{ value: '平台' },
{ value: 'App Id' },
{ value: 'App Name' },
{ value: 'Platform' },
];
const rows = [];
for (const app of list) {
@@ -50,9 +54,9 @@ export async function listApp(platform) {
console.log(Table(header, rows).render());
if (platform) {
console.log(`\ ${list.length} ${platform} 个应用`);
console.log(`\nTotal ${list.length} ${platform} apps`);
} else {
console.log(`\ ${list.length} 个应用`);
console.log(`\nTotal ${list.length} apps`);
}
return list;
}
@@ -61,7 +65,7 @@ export async function chooseApp(platform) {
const list = await listApp(platform);
while (true) {
const id = await question('输入应用 id:');
const id = await question('Enter appId:');
const app = list.find((v) => v.id === (id | 0));
if (app) {
return app;
@@ -71,13 +75,13 @@ export async function chooseApp(platform) {
export const commands = {
createApp: async function ({ options }) {
const name = options.name || (await question('应用名称:'));
const name = options.name || (await question('App Name:'));
const { downloadUrl } = options;
const platform = checkPlatform(
options.platform || (await question('平台(ios/android):')),
options.platform || (await question('Platform(ios/android):')),
);
const { id } = await post('/app/create', { name, platform });
console.log(`已成功创建应用id: ${id}`);
console.log(`Created app ${id}`);
await this.selectApp({
args: [id],
options: { platform, downloadUrl },
@@ -87,10 +91,10 @@ export const commands = {
const { platform } = options;
const id = args[0] || chooseApp(platform);
if (!id) {
console.log('已取消');
console.log('Canceled');
}
await doDelete(`/app/${id}`);
console.log('操作成功');
console.log('Ok.');
},
apps: async function ({ options }) {
const { platform } = options;
@@ -98,9 +102,9 @@ export const commands = {
},
selectApp: async function ({ args, options }) {
const platform = checkPlatform(
options.platform || (await question('平台(ios/android):')),
options.platform || (await question('Platform(ios/android):')),
);
const id = args[0] ? parseInt(args[0]) : (await chooseApp(platform)).id;
const id = args[0] || (await chooseApp(platform)).id;
let updateInfo = {};
if (fs.existsSync('update.json')) {

View File

@@ -1,3 +1,7 @@
/**
* Created by tdzl2003 on 2/22/16.
*/
const path = require('path');
import { getRNVersion, translateOptions } from './utils';
import * as fs from 'fs-extra';
@@ -12,9 +16,6 @@ const os = require('os');
var bsdiff, hdiff, diff;
try {
bsdiff = require('node-bsdiff').diff;
} catch (e) {}
try {
hdiff = require('node-hdiffpatch').diff;
} catch (e) {}
@@ -28,12 +29,12 @@ async function runReactNativeBundleCommand(
config,
) {
let gradleConfig = {};
if (platform === 'android') {
gradleConfig = await checkGradleConfig();
// if (gradleConfig.crunchPngs !== false) {
// throw new Error('请先禁用android的crunchPngs优化具体请参考 https://pushy.reactnative.cn/docs/getting-started.html#%E7%A6%81%E7%94%A8android%E7%9A%84crunch%E4%BC%98%E5%8C%96')
// }
}
// if (platform === 'android') {
// gradleConfig = await checkGradleConfig();
// if (gradleConfig.crunchPngs !== false) {
// throw new Error('请先禁用android的crunchPngs优化具体请参考 https://pushy.reactnative.cn/docs/getting-started.html#%E7%A6%81%E7%94%A8android%E7%9A%84crunch%E4%BC%98%E5%8C%96')
// }
// }
let reactNativeBundleArgs = [];
@@ -94,15 +95,8 @@ async function runReactNativeBundleCommand(
),
);
} else {
if (
(platform === 'android' && gradleConfig.enableHermes) ||
(platform === 'ios' && fs.existsSync('ios/Pods/hermes-engine'))
) {
await compileHermesByteCode(
bundleName,
outputFolder,
sourcemapOutput,
);
if (gradleConfig.enableHermes) {
await compileHermesByteCode(bundleName, outputFolder);
}
resolve(null);
}
@@ -122,6 +116,7 @@ async function checkGradleConfig() {
try {
const gradleConfig = await g2js.parseFile('android/app/build.gradle');
const projectConfig = gradleConfig['project.ext.react'];
crunchPngs = gradleConfig.android.buildTypes.release.crunchPngs;
for (const packagerConfig of projectConfig) {
if (
packagerConfig.includes('enableHermes') &&
@@ -131,7 +126,6 @@ async function checkGradleConfig() {
break;
}
}
crunchPngs = gradleConfig.android.buildTypes.release.crunchPngs;
} catch (e) {}
return {
enableHermes,
@@ -139,38 +133,28 @@ async function checkGradleConfig() {
};
}
async function compileHermesByteCode(
bundleName,
outputFolder,
sourcemapOutput,
) {
async function compileHermesByteCode(bundleName, outputFolder) {
console.log(`Hermes enabled, now compiling to hermes bytecode:\n`);
// >= rn 0.69
let hermesCommand = `node_modules/react-native/sdks/hermesc/${getHermesOSBin()}/hermesc`;
// < rn 0.69
if (!fs.existsSync(hermesCommand)) {
const hermesPackage = fs.existsSync('node_modules/hermes-engine')
? 'node_modules/hermes-engine' // 0.2+
: 'node_modules/hermesvm'; // < 0.2
const hermesPath = `${hermesPackage}/${getHermesOSBin()}`;
const hermesPackage = fs.existsSync('node_modules/hermes-engine')
? 'node_modules/hermes-engine' // 0.2+
: 'node_modules/hermesvm'; // < 0.2
const hermesPath = `${hermesPackage}/${getHermesOSBin()}`;
hermesCommand = fs.existsSync(`${hermesPath}/hermesc`)
? `${hermesPath}/hermesc` // 0.5+
: `${hermesPath}/hermes`; // < 0.5
}
const args = [
'-emit-binary',
'-out',
path.join(outputFolder, bundleName),
path.join(outputFolder, bundleName),
'-O',
];
if (sourcemapOutput) {
args.push('-output-source-map');
}
spawnSync(path.join.apply(null, hermesCommand.split('/')), args, {
stdio: 'ignore',
});
const hermesCommand = fs.existsSync(`${hermesPath}/hermesc`)
? `${hermesPath}/hermesc` // 0.5+
: `${hermesPath}/hermes`; // < 0.5
spawnSync(
path.join.apply(null, hermesCommand.split('/')),
[
'-emit-binary',
'-out',
path.join(outputFolder, bundleName),
path.join(outputFolder, bundleName),
'-O',
],
{ stdio: 'ignore' },
);
}
async function pack(dir, output) {
@@ -210,7 +194,7 @@ async function pack(dir, output) {
});
zipfile.end();
});
console.log('ppk热更包已生成并保存到: ' + output);
console.log('Bundled saved to: ' + output);
}
function readEntire(entry, zipFile) {
@@ -489,7 +473,7 @@ function enumZipEntries(zipFn, callback) {
});
}
function diffArgsCheck(args, options, diffFn) {
function diffArgsCheck({ args, options, diffFn }) {
const [origin, next] = args;
if (!origin || !next) {
@@ -528,16 +512,22 @@ function diffArgsCheck(args, options, diffFn) {
export const commands = {
bundle: async function ({ options }) {
const platform = checkPlatform(
options.platform || (await question('平台(ios/android):')),
options.platform || (await question('Platform(ios/android):')),
);
let { bundleName, entryFile, intermediaDir, output, dev, sourcemap } =
translateOptions({
...options,
platform,
});
let {
bundleName,
entryFile,
intermediaDir,
output,
dev,
verbose,
} = translateOptions({
...options,
platform,
});
const sourcemapOutput = path.join(intermediaDir, bundleName + '.map');
// const sourcemapOutput = path.join(intermediaDir, bundleName + ".map");
const realOutput = output.replace(/\$\{time\}/g, '' + Date.now());
@@ -556,12 +546,11 @@ export const commands = {
entryFile,
intermediaDir,
platform,
sourcemap ? sourcemapOutput : '',
);
await pack(path.resolve(intermediaDir), realOutput);
const v = await question('是否现在上传此热更包?(Y/N)');
const v = await question('Would you like to publish it?(Y/N)');
if (v.toLowerCase() === 'y') {
await this.publish({
args: [realOutput],
@@ -573,25 +562,29 @@ export const commands = {
},
async diff({ args, options }) {
const { origin, next, realOutput } = diffArgsCheck(args, options, 'diff');
const { origin, next, realOutput } = diffArgsCheck({ args, options, diff });
await diffFromPPK(origin, next, realOutput, 'index.bundlejs');
console.log(`${realOutput} generated.`);
},
async hdiff({ args, options }) {
const { origin, next, realOutput } = diffArgsCheck(args, options, 'hdiff');
const { origin, next, realOutput } = diffArgsCheck({
args,
options,
hdiff,
});
await diffFromPPK(origin, next, realOutput, 'index.bundlejs');
console.log(`${realOutput} generated.`);
},
async diffFromApk({ args, options }) {
const { origin, next, realOutput } = diffArgsCheck(
const { origin, next, realOutput } = diffArgsCheck({
args,
options,
'diffFromApk',
);
diffFromApk,
});
await diffFromPackage(
origin,
@@ -603,11 +596,11 @@ export const commands = {
},
async hdiffFromApk({ args, options }) {
const { origin, next, realOutput } = diffArgsCheck(
const { origin, next, realOutput } = diffArgsCheck({
args,
options,
'hdiffFromApk',
);
hdiffFromApk,
});
await diffFromPackage(
origin,
@@ -619,11 +612,11 @@ export const commands = {
},
async diffFromIpa({ args, options }) {
const { origin, next, realOutput } = diffArgsCheck(
const { origin, next, realOutput } = diffArgsCheck({
args,
options,
'diffFromIpa',
);
diffFromIpa,
});
await diffFromPackage(origin, next, realOutput, 'main.jsbundle', (v) => {
const m = /^Payload\/[^/]+\/(.+)$/.exec(v);
@@ -634,11 +627,11 @@ export const commands = {
},
async hdiffFromIpa({ args, options }) {
const { origin, next, realOutput } = diffArgsCheck(
const { origin, next, realOutput } = diffArgsCheck({
args,
options,
'hdiffFromIpa',
);
hdiffFromIpa,
});
await diffFromPackage(origin, next, realOutput, 'main.jsbundle', (v) => {
const m = /^Payload\/[^/]+\/(.+)$/.exec(v);

View File

@@ -1,20 +1,21 @@
#!/usr/bin/env node
/**
* Created by tdzl2003 on 2/13/16.
*/
const { loadSession } = require('./api');
const {loadSession} = require('./api');
const updateNotifier = require('update-notifier');
import { printVersionCommand } from './utils/index.js';
const pkg = require('../package.json');
updateNotifier({ pkg }).notify({ isGlobal: true });
updateNotifier({pkg}).notify({isGlobal: true});
function printUsage({ args }) {
function printUsage({args}) {
// const commandName = args[0];
// TODO: print usage of commandName, or print global usage.
console.log('Usage is under development now.');
console.log(
'Visit `https://github.com/reactnativecn/react-native-pushy` for early document.',
);
console.log('Usage is under development now.')
console.log('Visit `https://github.com/reactnativecn/react-native-pushy` for early document.');
process.exit(1);
}
@@ -32,21 +33,20 @@ function run() {
printVersionCommand();
process.exit();
}
const argv = require('cli-arguments').parse(require('../cli.json'));
global.NO_INTERACTIVE = argv.options['no-interactive'];
global.USE_ACC_OSS = argv.options['acc'];
loadSession()
.then(() => commands[argv.command](argv))
.catch((err) => {
.then(()=>commands[argv.command](argv))
.catch(err=>{
if (err.status === 401) {
console.log('尚未登录。\n请在项目目录中运行`pushy login`命令来登录');
console.log('Not loggined.\nRun `pushy login` at your project directory to login.');
return;
}
console.error(err.stack);
process.exit(-1);
});
}
};
run();
run();

View File

@@ -13,29 +13,24 @@ const Table = require('tty-table');
export async function listPackage(appId) {
const { data } = await get(`/app/${appId}/package/list?limit=1000`);
const header = [{ value: '原生包 Id' }, { value: '原生版本' }];
const header = [{ value: 'Package Id' }, { value: 'Version' }];
const rows = [];
for (const pkg of data) {
const { version } = pkg;
let versionInfo = '';
if (version) {
versionInfo = `, 已绑定:${version.name} (${version.id})`;
versionInfo = ` - ${version.id} ${version.hash.slice(0, 8)} ${
version.name
}`;
} else {
// versionInfo = ' (newest)';
versionInfo = ' (newest)';
}
let output = pkg.name;
if (pkg.status === 'paused') {
output += '(已暂停)';
}
if (pkg.status === 'expired') {
output += '(已过期)';
}
output += versionInfo;
rows.push([pkg.id, output]);
rows.push([pkg.id, `${pkg.name}(${pkg.status})${versionInfo}`]);
}
console.log(Table(header, rows).render());
console.log(`\n ${data.length} 个包`);
console.log(`\nTotal ${data.length} package(s).`);
return data;
}
@@ -43,7 +38,7 @@ export async function choosePackage(appId) {
const list = await listPackage(appId);
while (true) {
const id = await question('输入原生包 id:');
const id = await question('Enter Package Id:');
const app = list.find((v) => v.id === (id | 0));
if (app) {
return app;
@@ -55,7 +50,7 @@ export const commands = {
uploadIpa: async function ({ args }) {
const fn = args[0];
if (!fn || !fn.endsWith('.ipa')) {
throw new Error('使用方法: pushy uploadIpa ipa后缀文件');
throw new Error('Usage: pushy uploadIpa <ipaFile>');
}
const {
versionName,
@@ -67,13 +62,13 @@ export const commands = {
if (appIdInPkg && appIdInPkg !== appId) {
throw new Error(
`appId不匹配当前ipa: ${appIdInPkg}, 当前update.json: ${appId}`,
`appId不匹配当前ipa${appIdInPkg}, 当前update.json${appId}`,
);
}
if (appKeyInPkg && appKeyInPkg !== appKey) {
throw new Error(
`appKey不匹配当前ipa: ${appKeyInPkg}, 当前update.json: ${appKey}`,
`appKey不匹配当前ipa${appKeyInPkg}, 当前update.json${appKey}`,
);
}
@@ -85,12 +80,12 @@ export const commands = {
buildTime,
});
saveToLocal(fn, `${appId}/package/${id}.ipa`);
console.log(`已成功上传ipa原生包id: ${id}`);
console.log(`Ipa uploaded: ${id}`);
},
uploadApk: async function ({ args }) {
const fn = args[0];
if (!fn || !fn.endsWith('.apk')) {
throw new Error('使用方法: pushy uploadApk apk后缀文件');
throw new Error('Usage: pushy uploadApk <apkFile>');
}
const {
versionName,
@@ -102,13 +97,13 @@ export const commands = {
if (appIdInPkg && appIdInPkg !== appId) {
throw new Error(
`appId不匹配当前apk: ${appIdInPkg}, 当前update.json: ${appId}`,
`appId不匹配当前apk${appIdInPkg}, 当前update.json${appId}`,
);
}
if (appKeyInPkg && appKeyInPkg !== appKey) {
throw new Error(
`appKey不匹配当前apk: ${appKeyInPkg}, 当前update.json: ${appKey}`,
`appKey不匹配当前apk${appKeyInPkg}, 当前update.json${appKey}`,
);
}
@@ -120,25 +115,25 @@ export const commands = {
buildTime,
});
saveToLocal(fn, `${appId}/package/${id}.apk`);
console.log(`已成功上传apk原生包id: ${id}`);
console.log(`Apk uploaded: ${id}`);
},
parseIpa: async function ({ args }) {
const fn = args[0];
if (!fn || !fn.endsWith('.ipa')) {
throw new Error('使用方法: pushy parseIpa ipa后缀文件');
throw new Error('Usage: pushy parseIpa <ipaFile>');
}
console.log(await getIpaInfo(fn));
},
parseApk: async function ({ args }) {
const fn = args[0];
if (!fn || !fn.endsWith('.apk')) {
throw new Error('使用方法: pushy parseApk apk后缀文件');
throw new Error('Usage: pushy parseApk <apkFile>');
}
console.log(await getApkInfo(fn));
},
packages: async function ({ options }) {
const platform = checkPlatform(
options.platform || (await question('平台(ios/android):')),
options.platform || (await question('Platform(ios/android):')),
);
const { appId } = await getSelectedApp(platform);
await listPackage(appId);

View File

@@ -26,11 +26,11 @@ exports.commands = {
});
replaceSession({token});
await saveSession();
console.log(`欢迎使用 pushy 热更新服务, ${info.name}.`);
console.log(`Welcome, ${info.name}.`);
},
logout: async function (){
await closeSession();
console.log('已退出登录');
console.log('Logged out.');
},
me: async function (){
const me = await get('/user/me');

View File

@@ -1,4 +1,13 @@
const { get, post, put, uploadFile } = require('./api');
/**
* Created by tdzl2003 on 4/2/16.
*/
const {
get,
post,
put,
uploadFile,
} = require('./api');
import { question, saveToLocal } from './utils';
import { checkPlatform, getSelectedApp } from './app';
@@ -8,24 +17,17 @@ async function showVersion(appId, offset) {
const { data, count } = await get(`/app/${appId}/version/list`);
console.log(`Offset ${offset}`);
for (const version of data) {
let packageInfo = version.packages
.slice(0, 3)
.map((v) => v.name)
.join(', ');
let packageInfo = version.packages.slice(0, 3).map(v=>v.name).join(', ');
const count = version.packages.length;
if (count > 3) {
packageInfo += `...and ${count - 3} more`;
packageInfo += `...and ${count-3} more`;
}
if (count === 0) {
packageInfo = `(no package)`;
} else {
packageInfo = `[${packageInfo}]`;
}
console.log(
`${version.id}) ${version.hash.slice(0, 8)} ${
version.name
} ${packageInfo}`,
);
console.log(`${version.id}) ${version.hash.slice(0, 8)} ${version.name} ${packageInfo}`);
}
return data;
}
@@ -36,17 +38,10 @@ async function listVersions(appId) {
await showVersion(appId, offset);
const cmd = await question('page Up/page Down/Begin/Quit(U/D/B/Q)');
switch (cmd.toLowerCase()) {
case 'u':
offset = Math.max(0, offset - 10);
break;
case 'd':
offset += 10;
break;
case 'b':
offset = 0;
break;
case 'q':
return;
case 'u': offset = Math.max(0, offset - 10); break;
case 'd': offset += 10; break;
case 'b': offset = 0; break;
case 'q': return;
}
}
}
@@ -55,21 +50,14 @@ async function chooseVersion(appId) {
let offset = 0;
while (true) {
const data = await showVersion(appId, offset);
const cmd = await question(
'Enter versionId or page Up/page Down/Begin(U/D/B)',
);
const cmd = await question('Enter versionId or page Up/page Down/Begin(U/D/B)');
switch (cmd.toLowerCase()) {
case 'U':
offset = Math.max(0, offset - 10);
break;
case 'D':
offset += 10;
break;
case 'B':
offset = 0;
break;
default: {
const v = data.find((v) => v.id === (cmd | 0));
case 'U': offset = Math.max(0, offset - 10); break;
case 'D': offset += 10; break;
case 'B': offset = 0; break;
default:
{
const v = data.find(v=>v.id === (cmd | 0));
if (v) {
return v;
}
@@ -79,88 +67,47 @@ async function chooseVersion(appId) {
}
export const commands = {
publish: async function ({ args, options }) {
publish: async function({args, options}) {
const fn = args[0];
const { name, description, metaInfo } = options;
const {name, description, metaInfo } = options;
if (!fn || !fn.endsWith('.ppk')) {
throw new Error(
'使用方法: pushy publish ppk后缀文件 --platform ios|android',
);
throw new Error('Usage: pushy publish <ppkFile> --platform ios|android');
}
const platform = checkPlatform(
options.platform || (await question('平台(ios/android):')),
);
const platform = checkPlatform(options.platform || await question('Platform(ios/android):'));
const { appId } = await getSelectedApp(platform);
const { hash } = await uploadFile(fn);
const { id } = await post(`/app/${appId}/version/create`, {
name: name || (await question('输入版本名称: ')) || '(未命名)',
name: name || await question('Enter version name:') || '(未命名)',
hash,
description: description || (await question('输入版本描述:')),
metaInfo: metaInfo || (await question('输入自定义的 meta info:')),
description: description || await question('Enter description:'),
metaInfo: metaInfo || await question('Enter meta info:'),
});
// TODO local diff
saveToLocal(fn, `${appId}/ppk/${id}.ppk`);
console.log(`已成功上传新热更包id: ${id}`);
console.log(`Version published: ${id}`);
const v = await question('是否现在将此热更应用到原生包上?(Y/N)');
const v = await question('Would you like to bind packages to this version?(Y/N)');
if (v.toLowerCase() === 'y') {
await this.update({ args: [], options: { versionId: id, platform } });
await this.update({args:[], options:{versionId: id, platform}});
}
},
versions: async function ({ options }) {
const platform = checkPlatform(
options.platform || (await question('平台(ios/android):')),
);
versions: async function({options}) {
const platform = checkPlatform(options.platform || await question('Platform(ios/android):'));
const { appId } = await getSelectedApp(platform);
await listVersions(appId);
},
update: async function ({ args, options }) {
const platform = checkPlatform(
options.platform || (await question('平台(ios/android):')),
);
update: async function({args, options}) {
const platform = checkPlatform(options.platform || await question('Platform(ios/android):'));
const { appId } = await getSelectedApp(platform);
const versionId = options.versionId || (await chooseVersion(appId)).id;
let pkgId;
let pkgVersion = options.packageVersion;
if (pkgVersion) {
pkgVersion = pkgVersion.trim();
const { data } = await get(`/app/${appId}/package/list?limit=1000`);
const pkg = data.find((d) => d.name === pkgVersion);
if (pkg) {
pkgId = pkg.id;
} else {
throw new Error(`未查询到匹配原生版本:${pkgVersion}`);
}
}
if (!pkgId) {
pkgId = options.packageId || (await choosePackage(appId)).id;
}
if (!pkgId) {
throw new Error('请提供 packageId 或 packageVersion 参数');
}
const pkgId = options.packageId || (await choosePackage(appId)).id;
await put(`/app/${appId}/package/${pkgId}`, {
versionId,
});
console.log('操作成功');
},
updateVersionInfo: async function ({ args, options }) {
const platform = checkPlatform(
options.platform || (await question('平台(ios/android):')),
);
const { appId } = await getSelectedApp(platform);
const versionId = options.versionId || (await chooseVersion(appId)).id;
const updateParams = {};
options.name && (updateParams.name = options.name);
options.description && (updateParams.description = options.description);
options.metaInfo && (updateParams.metaInfo = options.metaInfo);
await put(`/app/${appId}/version/${versionId}`, updateParams);
console.log('操作成功');
},
console.log('Ok.');
}
};

2897
yarn.lock Normal file

File diff suppressed because it is too large Load Diff