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

Compare commits

...

48 Commits

Author SHA1 Message Date
sunnylqm
724088a810 v1.18.0 2024-02-03 21:28:38 +08:00
sunnylqm
7c20b30c85 feat: support expo 2024-02-03 21:27:47 +08:00
sunnylqm
6a053c6428 v1.17.0 2024-01-30 19:15:15 +08:00
sunnylqm
f202fc590d fix: rndir path 2024-01-30 19:15:00 +08:00
sunnylqm
0f8cf3c399 v1.16.0 2024-01-30 17:50:32 +08:00
sunnylqm
6a0d82c7a5 fix: rndir path 2024-01-30 17:50:09 +08:00
sunnylqm
eed19992d8 v1.15.0 2024-01-30 12:43:48 +08:00
sunnylqm
1b5078831c fix: require path 2024-01-30 12:43:31 +08:00
sunnylqm
bc9aff343a v1.14.0 2024-01-29 19:11:06 +08:00
sunnylqm
7aaa32a5a2 v1.14.0-beta.0 2024-01-29 19:02:01 +08:00
sunnylqm
ab7920fe38 feat: support symlink 2024-01-29 19:01:11 +08:00
sunnylqm
d912ace4a7 v1.13.0 2023-09-19 18:40:12 +08:00
sunnylqm
8af4d314ce fix appid equal 2023-09-19 18:36:26 +08:00
sunnylqm
f2d5269512 feat: support rn0.71 android hermes 2023-07-20 18:27:14 +08:00
sunnylqm
fe24c4ca36 v1.12.0 2023-07-20 18:25:47 +08:00
sunnylqm
cf61c297a6 update endpoint 2023-01-29 10:35:44 +08:00
sunnylqm
f9adc700ed v1.11.0 2023-01-11 23:36:13 +08:00
sunnylqm
dcff16cbb5 support source-map 2023-01-11 23:35:39 +08:00
sunnylqm
2bb8e83010 v1.10.0 2022-07-01 23:08:16 +08:00
sunnylqm
0cfc6e4f0d support rn 69 hermes 2022-07-01 23:02:20 +08:00
sunnylqm
da7bdbfdd2 v1.9.0 2022-06-29 09:42:05 +08:00
sunnylqm
07ee28ba3b add updateVersionInfo 2022-06-29 09:41:44 +08:00
sunnylqm
dae3e4024f v1.8.1 2021-12-24 17:55:15 +08:00
sunnylqm
d673b5736a Fix selectApp id 2021-12-24 17:53:14 +08:00
sunnylqm
732845faad Cleanup headers 2021-10-28 18:01:12 +08:00
sunnylqm
bcfdd67ea8 v1.8.0 2021-10-18 18:24:15 +08:00
sunnylqm
27ea54c1ec Update package output 2021-10-18 18:22:56 +08:00
sunnylqm
ba0fa836d1 v1.7.2 2021-10-18 18:02:43 +08:00
sunnylqm
bde76094fc v1.7.1 2021-10-18 18:00:21 +08:00
sunnylqm
f1d6c3744e v1.7.0 2021-10-18 17:54:07 +08:00
sunnylqm
768484d7b5 Add packageVersion 2021-10-18 17:53:29 +08:00
sunnylqm
d6632ffcc6 v1.7.0-beta.0 2021-10-18 17:28:01 +08:00
sunnylqm
24f5b316a9 v1.6.0 2021-10-10 12:39:29 +08:00
sunnylqm
03a4108a08 汉化 2021-10-10 12:39:00 +08:00
sunnylqm
32d7ed9b00 v1.5.0 2021-09-01 14:55:09 +08:00
sunnylqm
6f3d45c3f2 Add acc option 2021-09-01 14:54:17 +08:00
sunnylqm
25cb724921 v1.4.2 2021-06-23 10:05:55 +08:00
sunnylqm
a7b79a30e8 Print server error 2021-06-23 10:05:29 +08:00
sunnylqm
11799dd0c1 v1.4.1 2021-04-11 23:29:56 +08:00
sunnylqm
2ab0cad7e5 Detect hermes first 2021-04-11 23:29:44 +08:00
sunnylqm
ec8d6a767b v1.4.0 2021-04-11 23:26:59 +08:00
sunnylqm
fa8290fcbf Re-enable gradle check for hermes 2021-04-11 23:26:43 +08:00
sunnylqm
46d308c7c2 v1.4.0-beta1 2021-04-11 18:11:24 +08:00
sunnylqm
9e721e1858 try require diff separately 2021-04-11 18:11:08 +08:00
sunnylqm
c30454976c v1.4.0-beta0 2021-04-08 16:07:10 +08:00
sunnylqm
3d73b95140 Add hdiff 2021-04-07 22:09:48 +08:00
sunnylqm
32cafd92bf v1.3.2 2021-03-05 12:27:53 +08:00
sunnylqm
ea10cd7828 Show current filesize 2021-03-05 12:27:38 +08:00
13 changed files with 3573 additions and 3158 deletions

29
LICENSE
View File

@@ -1,29 +0,0 @@
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,6 +80,33 @@
},
"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
}
}
},
@@ -113,7 +140,9 @@
"default": ".pushy/output/${platform}.${time}.ppk",
"hasValue": true
},
"verbose": {}
"sourcemap": {
"default": false
}
}
},
"release": {
@@ -123,7 +152,7 @@
"description": "Create diff patch",
"options": {
"output": {
"default": "build/output/diff",
"default": ".pushy/output/diff",
"hasValue": true
}
}
@@ -132,7 +161,7 @@
"description": "Create diff patch from a Android package(.apk)",
"options": {
"output": {
"default": "build/output/diff-${time}.apk-patch",
"default": ".pushy/output/diff-${time}.apk-patch",
"hasValue": true
}
}
@@ -141,7 +170,34 @@
"description": "Create diff patch from a iOS package(.ipa)",
"options": {
"output": {
"default": "build/output/diff-${time}.ipa-patch",
"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",
"hasValue": true
}
}

View File

@@ -1,6 +1,6 @@
{
"name": "react-native-update-cli",
"version": "1.3.1",
"version": "1.18.0",
"description": "Command tools for javaScript updater with `pushy` service for react native apps.",
"main": "index.js",
"bin": {
@@ -36,9 +36,10 @@
"cli-arguments": "^0.2.1",
"filesize-parser": "^1.5.0",
"fs-extra": "8",
"gradle-to-js": "^2.0.0",
"gradle-to-js": "^2.0.1",
"node-fetch": "^2.6.1",
"progress": "^2.0.3",
"properties": "^1.2.1",
"read": "^1.0.7",
"request": "^2.88.2",
"tcp-ping": "^0.1.1",

3117
pnpm-lock.yaml generated Normal file

File diff suppressed because it is too large Load Diff

View File

@@ -1,9 +1,5 @@
/**
* Created by tdzl2003 on 2/13/16.
*/
const fetch = require('node-fetch');
const defaultEndpoint = 'http://u.reactnative.cn/api'
const defaultEndpoint = 'https://update.reactnative.cn/api';
let host = process.env.PUSHY_REGISTRY || defaultEndpoint;
const fs = require('fs');
import request from 'request';
@@ -22,7 +18,7 @@ let savedSession = undefined;
const userAgent = `react-native-update-cli/${packageJson.version}`;
exports.loadSession = async function() {
exports.loadSession = async function () {
if (fs.existsSync('.update')) {
try {
exports.replaceSession(JSON.parse(fs.readFileSync('.update', 'utf8')));
@@ -36,15 +32,15 @@ exports.loadSession = async function() {
}
};
exports.getSession = function() {
exports.getSession = function () {
return session;
};
exports.replaceSession = function(newSession) {
exports.replaceSession = function (newSession) {
session = newSession;
};
exports.saveSession = function() {
exports.saveSession = function () {
// Only save on change.
if (session !== savedSession) {
const current = session;
@@ -54,7 +50,7 @@ exports.saveSession = function() {
}
};
exports.closeSession = function() {
exports.closeSession = function () {
if (fs.existsSync('.update')) {
fs.unlinkSync('.update');
savedSession = undefined;
@@ -65,7 +61,14 @@ exports.closeSession = function() {
async function query(url, options) {
const resp = await fetch(url, options);
const json = await resp.json();
const text = await resp.text();
let json;
try {
json = JSON.parse(text);
} catch (e) {
throw new Error(`Server error: ${text}`);
}
if (resp.status !== 200) {
throw Object.assign(new Error(json.message || json.error), {
status: resp.status,
@@ -75,7 +78,7 @@ async function query(url, options) {
}
function queryWithoutBody(method) {
return function(api) {
return function (api) {
return query(host + api, {
method,
headers: {
@@ -87,7 +90,7 @@ function queryWithoutBody(method) {
}
function queryWithBody(method) {
return function(api, body) {
return function (api, body) {
return query(host + api, {
method,
headers: {
@@ -107,29 +110,37 @@ exports.doDelete = queryWithBody('DELETE');
async function uploadFile(fn, key) {
const { url, backupUrl, formData, maxSize } = await exports.post('/upload', {
ext: path.extname(fn)
ext: path.extname(fn),
});
let realUrl = url;
if (backupUrl) {
const pingResult = await tcpPing({
address: url.replace('https://', ''),
attempts: 4,
timeout: 1000,
});
// console.log({pingResult});
if (isNaN(pingResult.avg) || pingResult.avg > 150) {
if (global.USE_ACC_OSS) {
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});
}
const fileSize = fs.statSync(fn).size;
if (maxSize && fileSize > filesizeParser(maxSize)) {
throw new Error(`此文件大小超出上限${maxSize}。您可以考虑升级付费业务以提升此限制。详情请访问:${pricingPageUrl}`)
throw new Error(
`此文件大小${(fileSize / 1048576).toFixed(
1,
)}m, 超出当前额度${maxSize}。您可以考虑升级付费业务以提升此额度。详情请访问: ${pricingPageUrl}`,
);
}
const bar = new ProgressBar(' Uploading [:bar] :percent :etas', {
const bar = new ProgressBar(' 上传中 [:bar] :percent :etas', {
complete: '=',
incomplete: ' ',
total: fileSize,
@@ -141,17 +152,13 @@ async function uploadFile(fn, key) {
}
formData.file = fs.createReadStream(fn);
formData.file.on('data', function(data) {
formData.file.on('data', function (data) {
bar.tick(data.length);
});
request.post(
realUrl,
{
formData,
headers: {
'User-Agent': userAgent,
'X-AccessToken': session ? session.token : '',
},
},
(err, resp, body) => {
if (err) {
@@ -162,13 +169,7 @@ async function uploadFile(fn, key) {
Object.assign(new Error(body), { status: resp.statusCode }),
);
}
resolve(
body
? // qiniu
JSON.parse(body)
: // aliyun oss
{ hash: formData.key },
);
resolve({ hash: formData.key });
},
);
});

View File

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

View File

@@ -1,7 +1,3 @@
/**
* Created by tdzl2003 on 2/22/16.
*/
const path = require('path');
import { getRNVersion, translateOptions } from './utils';
import * as fs from 'fs-extra';
@@ -12,21 +8,16 @@ import { checkPlatform } from './app';
const { spawn, spawnSync } = require('child_process');
const g2js = require('gradle-to-js/lib/parser');
const os = require('os');
const properties = require('properties');
var diff;
var bsdiff, hdiff, diff;
try {
var bsdiff = require('node-bsdiff');
diff = typeof bsdiff != 'function' ? bsdiff.diff : bsdiff;
} catch (e) {
diff = function () {
console.warn(
'This function needs "node-bsdiff". Please run "npm i node-bsdiff" from your project directory first!',
);
throw new Error(
'This function needs module "node-bsdiff". Please install it first.',
);
};
}
bsdiff = require('node-bsdiff').diff;
} catch (e) {}
try {
hdiff = require('node-hdiffpatch').diff;
} catch (e) {}
async function runReactNativeBundleCommand(
bundleName,
@@ -38,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 = [];
@@ -58,9 +49,21 @@ async function runReactNativeBundleCommand(
fs.emptyDirSync(outputFolder);
let cliPath = require.resolve('react-native/local-cli/cli.js', {
paths: [process.cwd()],
});
try {
cliPath = require.resolve('@expo/cli', {
paths: [process.cwd()],
});
} catch (e) {}
const bundleCommand = cliPath.includes('@expo/cli')
? 'export:embed'
: 'bundle';
Array.prototype.push.apply(reactNativeBundleArgs, [
path.join('node_modules', 'react-native', 'local-cli', 'cli.js'),
'bundle',
cliPath,
bundleCommand,
'--assets-dest',
outputFolder,
'--bundle-output',
@@ -104,8 +107,39 @@ async function runReactNativeBundleCommand(
),
);
} else {
if (gradleConfig.enableHermes) {
await compileHermesByteCode(bundleName, outputFolder);
let hermesEnabled = false;
if (platform === 'android') {
const gradlePropeties = await new Promise((resolve) => {
properties.parse(
'./android/gradle.properties',
{ path: true },
function (error, props) {
if (error) {
console.error(error);
resolve(null);
}
resolve(props);
},
);
});
hermesEnabled = gradlePropeties.hermesEnabled;
if (typeof hermesEnabled !== 'boolean')
hermesEnabled = gradleConfig.enableHermes;
} else if (
platform === 'ios' &&
fs.existsSync('ios/Pods/hermes-engine')
) {
hermesEnabled = true;
}
if (hermesEnabled) {
await compileHermesByteCode(
bundleName,
outputFolder,
sourcemapOutput,
);
}
resolve(null);
}
@@ -125,7 +159,6 @@ 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') &&
@@ -135,35 +168,58 @@ async function checkGradleConfig() {
break;
}
}
crunchPngs = gradleConfig.android.buildTypes.release.crunchPngs;
} catch (e) {}
return {
enableHermes,
crunchPngs,
}
};
}
async function compileHermesByteCode(bundleName, outputFolder) {
async function compileHermesByteCode(
bundleName,
outputFolder,
sourcemapOutput,
) {
console.log(`Hermes enabled, now compiling to hermes bytecode:\n`);
const hermesPackage = fs.existsSync('node_modules/hermes-engine')
? 'node_modules/hermes-engine' // 0.2+
: 'node_modules/hermesvm'; // < 0.2
const hermesPath = `${hermesPackage}/${getHermesOSBin()}`;
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' },
// >= rn 0.69
const rnDir = path.dirname(
require.resolve('react-native', {
paths: [process.cwd()],
}),
);
const hermesCommand = path.join(
rnDir,
`/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()}`;
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');
}
console.log(
'Running hermesc: ' + hermesCommand + ' ' + args.join(' ') + '\n',
);
spawnSync(hermesCommand, args, {
stdio: 'ignore',
});
}
async function pack(dir, output) {
@@ -203,7 +259,7 @@ async function pack(dir, output) {
});
zipfile.end();
});
console.log('Bundled saved to: ' + output);
console.log('ppk热更包已生成并保存到: ' + output);
}
function readEntire(entry, zipFile) {
@@ -482,25 +538,55 @@ function enumZipEntries(zipFn, callback) {
});
}
function diffArgsCheck(args, options, diffFn) {
const [origin, next] = args;
if (!origin || !next) {
console.error(`Usage: pushy ${diffFn} <origin> <next>`);
process.exit(1);
}
if (diffFn.startsWith('hdiff')) {
if (!hdiff) {
console.error(
`This function needs "node-hdiffpatch".
Please run "npm i node-hdiffpatch" to install`,
);
process.exit(1);
}
diff = hdiff;
} else {
if (!bsdiff) {
console.error(
`This function needs "node-bsdiff".
Please run "npm i node-bsdiff" to install`,
);
process.exit(1);
}
diff = bsdiff;
}
const { output } = options;
return {
origin,
next,
realOutput: output.replace(/\$\{time\}/g, '' + Date.now()),
};
}
export const commands = {
bundle: async function ({ options }) {
const platform = checkPlatform(
options.platform || (await question('Platform(ios/android):')),
options.platform || (await question('平台(ios/android):')),
);
let {
bundleName,
entryFile,
intermediaDir,
output,
dev,
verbose,
} = translateOptions({
...options,
platform,
});
let { bundleName, entryFile, intermediaDir, output, dev, sourcemap } =
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());
@@ -519,11 +605,12 @@ export const commands = {
entryFile,
intermediaDir,
platform,
sourcemap ? sourcemapOutput : '',
);
await pack(path.resolve(intermediaDir), realOutput);
const v = await question('Would you like to publish it?(Y/N)');
const v = await question('是否现在上传此热更包?(Y/N)');
if (v.toLowerCase() === 'y') {
await this.publish({
args: [realOutput],
@@ -535,30 +622,41 @@ export const commands = {
},
async diff({ args, options }) {
const [origin, next] = args;
const { output } = options;
const { origin, next, realOutput } = diffArgsCheck(args, options, 'diff');
const realOutput = output.replace(/\$\{time\}/g, '' + Date.now());
await diffFromPPK(origin, next, realOutput, 'index.bundlejs');
console.log(`${realOutput} generated.`);
},
if (!origin || !next) {
console.error('pushy diff <origin> <next>');
process.exit(1);
}
async hdiff({ args, options }) {
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] = args;
const { output } = options;
const { origin, next, realOutput } = diffArgsCheck(
args,
options,
'diffFromApk',
);
const realOutput = output.replace(/\$\{time\}/g, '' + Date.now());
await diffFromPackage(
origin,
next,
realOutput,
'assets/index.android.bundle',
);
console.log(`${realOutput} generated.`);
},
if (!origin || !next) {
console.error('pushy diffFromApk <origin> <next>');
process.exit(1);
}
async hdiffFromApk({ args, options }) {
const { origin, next, realOutput } = diffArgsCheck(
args,
options,
'hdiffFromApk',
);
await diffFromPackage(
origin,
@@ -570,15 +668,26 @@ export const commands = {
},
async diffFromIpa({ args, options }) {
const [origin, next] = args;
const { output } = options;
const { origin, next, realOutput } = diffArgsCheck(
args,
options,
'diffFromIpa',
);
const realOutput = output.replace(/\$\{time\}/g, '' + Date.now());
await diffFromPackage(origin, next, realOutput, 'main.jsbundle', (v) => {
const m = /^Payload\/[^/]+\/(.+)$/.exec(v);
return m && m[1];
});
if (!origin || !next) {
console.error('pushy diffFromIpa <origin> <next>');
process.exit(1);
}
console.log(`${realOutput} generated.`);
},
async hdiffFromIpa({ args, options }) {
const { origin, next, realOutput } = diffArgsCheck(
args,
options,
'hdiffFromIpa',
);
await diffFromPackage(origin, next, realOutput, 'main.jsbundle', (v) => {
const m = /^Payload\/[^/]+\/(.+)$/.exec(v);

View File

@@ -1,21 +1,20 @@
#!/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);
}
@@ -33,20 +32,21 @@ 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('Not loggined.\nRun `pushy login` at your project directory to login.');
console.log('尚未登录。\n请在项目目录中运行`pushy login`命令来登录');
return;
}
console.error(err.stack);
process.exit(-1);
});
};
}
run();
run();

View File

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

View File

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

View File

@@ -43,7 +43,11 @@ export function translateOptions(options) {
export function getRNVersion() {
const version = JSON.parse(
fs.readFileSync(path.resolve('node_modules/react-native/package.json')),
fs.readFileSync(
require.resolve('react-native/package.json', {
paths: [process.cwd()],
}),
),
).version;
// We only care about major and minor version.
@@ -106,9 +110,8 @@ export async function getIpaInfo(fn) {
if (updateJsonFile) {
appCredential = JSON.parse(updateJsonFile.toString()).ios;
}
const {
CFBundleShortVersionString: versionName,
} = await appInfoParser.parse();
const { CFBundleShortVersionString: versionName } =
await appInfoParser.parse();
let buildTimeTxtBuffer = await appInfoParser.parser.getEntry(
/payload\/.+?\.app\/pushy_build_time.txt/,
);
@@ -139,11 +142,11 @@ export function saveToLocal(originPath, destName) {
export function printVersionCommand() {
console.log('react-native-update-cli: ' + pkg.version);
try {
const PACKAGE_JSON_PATH = path.resolve(
process.cwd(),
'node_modules',
'react-native-update',
'package.json',
const PACKAGE_JSON_PATH = require.resolve(
'react-native-update/package.json',
{
paths: [process.cwd()],
},
);
console.log('react-native-update: ' + require(PACKAGE_JSON_PATH).version);
} catch (e) {

View File

@@ -1,13 +1,4 @@
/**
* Created by tdzl2003 on 4/2/16.
*/
const {
get,
post,
put,
uploadFile,
} = require('./api');
const { get, post, put, uploadFile } = require('./api');
import { question, saveToLocal } from './utils';
import { checkPlatform, getSelectedApp } from './app';
@@ -17,17 +8,24 @@ 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;
}
@@ -38,10 +36,17 @@ 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;
}
}
}
@@ -50,14 +55,21 @@ 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;
}
@@ -67,47 +79,88 @@ 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('Usage: pushy publish <ppkFile> --platform ios|android');
throw new Error(
'使用方法: pushy publish ppk后缀文件 --platform ios|android',
);
}
const platform = checkPlatform(options.platform || await question('Platform(ios/android):'));
const platform = checkPlatform(
options.platform || (await question('平台(ios/android):')),
);
const { appId } = await getSelectedApp(platform);
const { hash } = await uploadFile(fn);
const { id } = await post(`/app/${appId}/version/create`, {
name: name || await question('Enter version name:') || '(未命名)',
name: name || (await question('输入版本名称: ')) || '(未命名)',
hash,
description: description || await question('Enter description:'),
metaInfo: metaInfo || await question('Enter meta info:'),
description: description || (await question('输入版本描述:')),
metaInfo: metaInfo || (await question('输入自定义的 meta info:')),
});
// TODO local diff
saveToLocal(fn, `${appId}/ppk/${id}.ppk`);
console.log(`Version published: ${id}`);
console.log(`已成功上传新热更包id: ${id}`);
const v = await question('Would you like to bind packages to this version?(Y/N)');
const v = await question('是否现在将此热更应用到原生包上?(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('Platform(ios/android):'));
versions: async function ({ options }) {
const platform = checkPlatform(
options.platform || (await question('平台(ios/android):')),
);
const { appId } = await getSelectedApp(platform);
await listVersions(appId);
},
update: async function({args, options}) {
const platform = checkPlatform(options.platform || await question('Platform(ios/android):'));
update: 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 pkgId = options.packageId || (await choosePackage(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 参数');
}
await put(`/app/${appId}/package/${pkgId}`, {
versionId,
});
console.log('Ok.');
}
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('操作成功');
},
};

2897
yarn.lock

File diff suppressed because it is too large Load Diff