-
Notifications
You must be signed in to change notification settings - Fork 75
/
index.js
631 lines (553 loc) · 14.8 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
const beautify = require("js-beautify").html;
const child = require("child_process");
const detectIndent = require("detect-indent");
const dottie = require("dottie");
const flattenDeep = require("lodash.flattendeep");
const fs = require("fs");
const list = require("./util").list;
const log = require("./util").log;
const path = require("path");
const plist = require("plist");
const pSettle = require("p-settle");
const resolveFrom = require("resolve-from");
const semver = require("semver");
const stripIndents = require("common-tags/lib/stripIndents");
const unique = require("lodash.uniq");
const Xcode = require("pbxproj-dom/xcode").Xcode;
/**
* Custom type definition for Promises
* @typedef Promise
* @property {*} result See the implementing function for the resolve type and description
* @property {Error} result Rejection error object
*/
const env = {
target: process.env.RNV && list(process.env.RNV)
};
/**
* Returns default values for some options, namely android/ios file/folder paths
* @private
* @return {Object} Defaults
*/
function getDefaults() {
return {
android: "android/app/build.gradle",
ios: "ios"
};
}
/**
* Returns Info.plist filenames
* @private
* @param {Xcode} xcode Opened Xcode project file
* @return {Array} Plist filenames
*/
function getPlistFilenames(xcode) {
return unique(
flattenDeep(
xcode.document.projects.map(project => {
return project.targets.filter(Boolean).map(target => {
return target.buildConfigurationsList.buildConfigurations.map(
config => {
return config.ast.value.get("buildSettings").get("INFOPLIST_FILE")
.text;
}
);
});
})
)
);
}
/**
* Returns numerical version code for a given version name
* @private
* @return {Number} e.g. returns 1002003 for given version 1.2.3
*/
function generateVersionCode(versionName) {
const major = semver.major(versionName);
const minor = semver.minor(versionName);
const patch = semver.patch(versionName);
return 10 ** 6 * major + 10 ** 3 * minor + patch;
}
/**
* Returns the new version code based on program options
* @private
* @return {Number} the new version code
*/
function getNewVersionCode(programOpts, versionCode, versionName, resetBuild) {
if (resetBuild) {
return 1;
}
if (programOpts.setBuild) {
return programOpts.setBuild;
}
if (programOpts.generateBuild) {
return generateVersionCode(versionName);
}
return versionCode ? versionCode + 1 : 1;
}
/**
* CFBundleShortVersionString must be a string composed of three period-separated integers.
* @private
* @param {String} versionName The full version string
* @return {String} e.g. returns '1.2.3' for given '1.2.3-beta.1'. Returns `versionName` if no match is found.
*/
function getCFBundleShortVersionString(versionName) {
const match =
versionName && typeof versionName === "string"
? versionName.match(/\d*\.\d*.\d*/g)
: [];
return match && match[0] ? match[0] : versionName;
}
/**
* Determines whether the project is an Expo app or a plain React Native app
* @private
* @return {Boolean} true if the project is an Expo app
*/
function isExpoProject(projPath) {
try {
let module = resolveFrom(projPath, "expo");
let appInfo = require(`${projPath}/app.json`);
return !!(module && appInfo.expo);
} catch (err) {
return false;
}
}
/**
* Versions your app
* @param {Object} program commander/CLI-style options, camelCased
* @param {string} projectPath Path to your React Native project
* @return {Promise<string|Error>} A promise which resolves with the last commit hash
*/
function version(program, projectPath) {
const prog = Object.assign({}, getDefaults(), program || {});
const projPath = path.resolve(
process.cwd(),
projectPath || prog.args[0] || ""
);
const programOpts = Object.assign({}, prog, {
android: path.join(projPath, prog.android),
ios: path.join(projPath, prog.ios)
});
const targets = [].concat(programOpts.target, env.target).filter(Boolean);
var appPkg;
try {
resolveFrom(projPath, "react-native");
appPkg = require(path.join(projPath, "package.json"));
} catch (err) {
if (err.message === "Cannot find module 'react-native'") {
log({
style: "red",
text: `Is this the right folder? ${err.message} in ${projPath}`
});
} else {
log({
style: "red",
text: err.message
});
log({
style: "red",
text:
"Is this the right folder? Looks like there isn't a package.json here"
});
}
log({
style: "yellow",
text: "Pass the project path as an argument, see --help for usage"
});
if (program.outputHelp) {
program.outputHelp();
}
process.exit(1);
}
var appJSON;
const appJSONPath = path.join(projPath, "app.json");
const isExpoApp = isExpoProject(projPath);
isExpoApp && log({ text: "Expo detected" }, programOpts.quiet);
try {
appJSON = require(appJSONPath);
if (isExpoApp && !programOpts.incrementBuild) {
appJSON = Object.assign({}, appJSON, {
expo: Object.assign({}, appJSON.expo, {
version: appPkg.version
})
});
}
} catch (err) {}
var android;
var ios;
if (!targets.length || targets.indexOf("android") > -1) {
android = new Promise(function(resolve, reject) {
log({ text: "Versioning Android..." }, programOpts.quiet);
var gradleFile;
try {
gradleFile = fs.readFileSync(programOpts.android, "utf8");
} catch (err) {
isExpoApp ||
reject([
{
style: "red",
text: "No gradle file found at " + programOpts.android
},
{
style: "yellow",
text: 'Use the "--android" option to specify the path manually'
}
]);
}
if (!programOpts.incrementBuild && !isExpoApp) {
gradleFile = gradleFile.replace(
/versionName (["'])(.*)["']/,
"versionName $1" + appPkg.version + "$1"
);
}
if (!programOpts.neverIncrementBuild) {
if (isExpoApp) {
const versionCode = dottie.get(appJSON, "expo.android.versionCode");
appJSON = Object.assign({}, appJSON, {
expo: Object.assign({}, appJSON.expo, {
android: Object.assign({}, appJSON.expo.android, {
versionCode: getNewVersionCode(
programOpts,
versionCode,
appPkg.version
)
})
})
});
} else {
gradleFile = gradleFile.replace(/versionCode (\d+)/, function(
match,
cg1
) {
const newVersionCodeNumber = getNewVersionCode(
programOpts,
parseInt(cg1, 10),
appPkg.version
);
return "versionCode " + newVersionCodeNumber;
});
}
}
if (isExpoApp) {
fs.writeFileSync(appJSONPath, JSON.stringify(appJSON, null, 2));
} else {
fs.writeFileSync(programOpts.android, gradleFile);
}
log({ text: "Android updated" }, programOpts.quiet);
resolve();
});
}
if (!targets.length || targets.indexOf("ios") > -1) {
ios = new Promise(function(resolve, reject) {
log({ text: "Versioning iOS..." }, programOpts.quiet);
if (isExpoApp) {
if (!programOpts.neverIncrementBuild) {
const buildNumber = dottie.get(appJSON, "expo.ios.buildNumber");
appJSON = Object.assign({}, appJSON, {
expo: Object.assign({}, appJSON.expo, {
ios: Object.assign({}, appJSON.expo.ios, {
buildNumber: getNewVersionCode(
programOpts,
parseInt(buildNumber, 10),
appPkg.version,
programOpts.resetBuild
).toString()
})
})
});
}
fs.writeFileSync(appJSONPath, JSON.stringify(appJSON, null, 2));
} else if (program.legacy) {
try {
child.execSync("xcode-select --print-path", {
stdio: ["ignore", "ignore", "pipe"]
});
} catch (err) {
reject([
{
style: "red",
text: err
},
{
style: "yellow",
text: "Looks like Xcode Command Line Tools aren't installed"
},
{
text: "\n Install:\n\n $ xcode-select --install\n"
}
]);
return;
}
const agvtoolOpts = {
cwd: programOpts.ios
};
try {
child.execSync("agvtool what-version", agvtoolOpts);
} catch (err) {
const stdout = err.stdout.toString().trim();
reject(
stdout.indexOf("directory") > -1
? [
{
style: "red",
text: "No project folder found at " + programOpts.ios
},
{
style: "yellow",
text: 'Use the "--ios" option to specify the path manually'
}
]
: [
{
style: "red",
text: stdout
}
]
);
return;
}
if (!programOpts.incrementBuild) {
child.spawnSync(
"agvtool",
["new-marketing-version", appPkg.version],
agvtoolOpts
);
}
if (!programOpts.neverIncrementBuild) {
if (programOpts.resetBuild) {
child.execSync("agvtool new-version -all 1", agvtoolOpts);
} else {
child.execSync("agvtool next-version -all", agvtoolOpts);
}
if (programOpts.generateBuild) {
child.execSync(
`agvtool new-version -all ${generateVersionCode(appPkg.version)}`,
agvtoolOpts
);
}
if (programOpts.setBuild) {
child.execSync(
`agvtool new-version -all ${program.setBuild}`,
agvtoolOpts
);
}
}
} else {
// Find any folder ending in .xcodeproj
const xcodeProjects = fs
.readdirSync(programOpts.ios)
.filter(file => /\.xcodeproj$/i.test(file));
if (xcodeProjects.length < 1) {
throw new Error(`Xcode project not found in "${programOpts.ios}"`);
}
const projectFolder = path.join(programOpts.ios, xcodeProjects[0]);
const xcode = Xcode.open(path.join(projectFolder, "project.pbxproj"));
const plistFilenames = getPlistFilenames(xcode);
xcode.document.projects.forEach(project => {
!programOpts.neverIncrementBuild &&
project.targets.filter(Boolean).forEach(target => {
target.buildConfigurationsList.buildConfigurations.forEach(
config => {
if (target.name === appPkg.name) {
const CURRENT_PROJECT_VERSION = getNewVersionCode(
programOpts,
parseInt(
config.ast.value
.get("buildSettings")
.get("CURRENT_PROJECT_VERSION").text,
10
),
appPkg.version,
programOpts.resetBuild
);
config.patch({
buildSettings: {
CURRENT_PROJECT_VERSION
}
});
}
}
);
});
const plistFiles = plistFilenames.map(filename => {
return fs.readFileSync(
path.join(programOpts.ios, filename),
"utf8"
);
});
const parsedPlistFiles = plistFiles.map(file => {
return plist.parse(file);
});
parsedPlistFiles.forEach((json, index) => {
fs.writeFileSync(
path.join(programOpts.ios, plistFilenames[index]),
plist.build(
Object.assign(
{},
json,
!programOpts.incrementBuild
? {
CFBundleShortVersionString: getCFBundleShortVersionString(
appPkg.version
)
}
: {},
!programOpts.neverIncrementBuild
? {
CFBundleVersion: getNewVersionCode(
programOpts,
parseInt(json.CFBundleVersion, 10),
appPkg.version,
programOpts.resetBuild
).toString()
}
: {}
)
)
);
});
plistFilenames.forEach((filename, index) => {
const indent = detectIndent(plistFiles[index]);
fs.writeFileSync(
path.join(programOpts.ios, filename),
stripIndents`
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">` +
"\n" +
beautify(
fs
.readFileSync(path.join(programOpts.ios, filename), "utf8")
.match(/<dict>[\s\S]*<\/dict>/)[0],
Object.assign(
{ end_with_newline: true },
indent.type === "tab"
? { indent_with_tabs: true }
: { indent_size: indent.amount }
)
) +
stripIndents`
</plist>` +
"\n"
);
});
});
xcode.save();
}
log({ text: "iOS updated" }, programOpts.quiet);
resolve();
});
}
return pSettle([android, ios].filter(Boolean))
.then(function(result) {
const errs = result
.filter(function(item) {
return item.isRejected;
})
.map(function(item) {
return item.reason;
});
if (errs.length) {
errs
.reduce(function(a, b) {
return a.concat(b);
}, [])
.forEach(function(err) {
if (program.outputHelp) {
log(
Object.assign({ style: "red", text: err.toString() }, err),
programOpts.quiet
);
}
});
if (program.outputHelp) {
program.outputHelp();
}
throw errs
.map(function(errGrp, index) {
return errGrp
.map(function(err) {
return err.text;
})
.join(", ");
})
.join("; ");
}
const gitCmdOpts = {
cwd: projPath
};
if (
programOpts.amend ||
(process.env.npm_lifecycle_event &&
process.env.npm_lifecycle_event.indexOf("version") > -1 &&
!programOpts.neverAmend)
) {
const latestTag =
(programOpts.amend ||
process.env.npm_config_git_tag_version ||
process.env.npm_config_version_git_tag) &&
!programOpts.skipTag &&
semver.valid(
semver.coerce(
child
.execSync("git log -1 --pretty=%s", gitCmdOpts)
.toString()
.trim()
)
) &&
child
.execSync("git describe --exact-match HEAD", gitCmdOpts)
.toString()
.trim();
log({ text: "Amending..." }, programOpts.quiet);
switch (process.env.npm_lifecycle_event) {
case "version":
child.spawnSync(
"git",
["add"].concat(
isExpoApp ? appJSONPath : [programOpts.android, programOpts.ios]
),
gitCmdOpts
);
break;
case "postversion":
default:
child.execSync("git commit -a --amend --no-edit", gitCmdOpts);
if (latestTag) {
log({ text: "Adjusting Git tag..." }, programOpts.quiet);
child.execSync(
`git tag -af ${latestTag} -m ${latestTag}`,
gitCmdOpts
);
}
}
}
log(
{
style: "green",
text: "Done"
},
programOpts.quiet
);
if (programOpts.neverAmend) {
return true;
}
return child.execSync("git log -1 --pretty=%H", gitCmdOpts).toString();
})
.catch(function(err) {
if (process.env.RNV_ENV === "ava") {
console.error(err);
}
log({
style: "red",
text: "Done, with errors."
});
process.exit(1);
});
}
module.exports = {
getCFBundleShortVersionString: getCFBundleShortVersionString,
getDefaults: getDefaults,
getPlistFilenames: getPlistFilenames,
isExpoProject: isExpoProject,
version: version
};