forked from appium/appium
-
Notifications
You must be signed in to change notification settings - Fork 0
/
grunt-helpers.js
673 lines (637 loc) · 21.8 KB
/
grunt-helpers.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
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
"use strict";
var _ = require("underscore")
, server = require('./server.js')
, rimraf = require('rimraf')
, http = require('http')
, path = require('path')
, temp = require('temp')
, mkdirp = require('mkdirp')
, ncp = require('ncp')
, difflib = require('difflib')
, prompt = require('prompt')
, exec = require('child_process').exec
, spawn = require('child_process').spawn
, parser = require('./app/parser')
, namp = require('namp')
, parseXmlString = require('xml2js').parseString
, appiumVer = require('./package.json').version
, fs = require('fs');
module.exports.startAppium = function(appName, verbose, readyCb, doneCb) {
var app;
if (appName) {
app = (fs.existsSync(appName)) ? appName:
path.resolve(__dirname,
"./sample-code/apps/"+appName+"/build/Release-iphonesimulator/"+appName+".app");
} else {
app = null;
}
return server.run({
app: app
, udid: null
, quiet: !verbose
, port: 4723
, nativeInstrumentsLib: false
, fullReset: false
, noReset: false
, launch: app ? true : false
, log: path.resolve(__dirname, "appium.log")
, address: '127.0.0.1'
, androidDeviceReadyTimeout: 5
, keepArtifacts: false }
, readyCb
, doneCb
);
};
module.exports.runTestsWithServer = function(grunt, appName, testType, deviceType, verbose, cb) {
if (typeof verbose === "undefined") {
verbose = false;
}
var exitCode = null;
var appServer = module.exports.startAppium(appName, verbose, function() {
module.exports.runMochaTests(grunt, appName, testType, deviceType, function(code) {
appServer.close();
exitCode = code;
});
}, function() {
console.log("Appium server exited");
cb(exitCode === 0);
});
};
module.exports.runMochaTests = function(grunt, appName, testType, deviceType, cb) {
// load the options if they are specified
var options = grunt.config(['mochaTestConfig', testType, 'options']);
if (typeof options !== 'object') {
options = grunt.config(['mochaTestConfig', 'options']);
}
if (typeof options.timeout === "undefined") {
options.timeout = 60000;
}
if (typeof options.reporter === "undefined") {
options.reporter = "tap";
}
var args = ['-t', options.timeout, '-R', options.reporter, '--colors'];
var mochaFiles = [];
var fileConfig = grunt.config(['mochaTestWithServer']);
var configAppDevice, nameOk, deviceOk, configAppTests;
_.each(fileConfig, function(config, configAppName) {
configAppDevice = config[0];
configAppTests = config[1];
nameOk = !appName || appName === configAppName;
deviceOk = !deviceType || deviceType === configAppDevice;
if (nameOk && deviceOk) {
_.each(configAppTests, function(testFiles, testKey) {
if (testType == "*" || testType == testKey) {
_.each(testFiles, function(file) {
_.each(grunt.file.expand(file), function(file) {
mochaFiles.push(file);
});
});
}
});
}
});
var exitCodes = [];
var runMochaProc = function() {
var file = mochaFiles.shift();
if (typeof file !== "undefined") {
var mochaProc = spawn('mocha', args.concat(file), {cwd: __dirname});
mochaProc.stdout.setEncoding('utf8');
mochaProc.stderr.setEncoding('utf8');
mochaProc.stdout.on('data', function(data) {
grunt.log.write(data);
});
mochaProc.stderr.on('data', function(data) {
grunt.log.write(data);
});
mochaProc.on('exit', function(code) {
exitCodes.push(code);
runMochaProc();
});
} else {
cb(_.max(exitCodes));
}
};
runMochaProc();
};
module.exports.tail = function(grunt, filename, cb) {
var proc = spawn('tail', ['-f', filename]);
proc.stdout.setEncoding('utf8');
proc.stdout.on('data', function(data) {
grunt.log.write(data);
});
proc.on('exit', function(code) {
cb(code);
});
};
module.exports.setDeviceConfigVer = function(grunt, device, cb) {
var configPath = path.resolve(__dirname, '.appiumconfig');
fs.readFile(configPath, function(err, data) {
var writeVer = function(config) {
if (typeof config[device] === "undefined") {
config[device] = {};
}
config[device].version = appiumVer;
grunt.log.write("\n");
grunt.log.write(JSON.stringify(config));
fs.writeFile(configPath, JSON.stringify(config), cb);
};
if (err) {
grunt.log.write("Config file doesn't exist, creating it");
var config = {};
writeVer(config);
} else {
grunt.log.write("Config file exists, updating it");
writeVer(JSON.parse(data.toString('utf8')));
}
});
};
module.exports.authorize = function(grunt, cb) {
// somewhat messily ported from penguinho's authorize.py
var authFile = '/etc/authorization';
exec('DevToolsSecurity --enable', function(err, stdout, stderr) {
if (err) throw err;
fs.readFile(authFile, 'utf8', function(err, data) {
if (err) throw err;
var origData = data;
var re = /<key>system.privilege.taskport<\/key>\s*\n\s*<dict>\n\s*<key>allow-root<\/key>\n\s*(<[^>]+>)/;
var match = re.exec(data);
if (!match) {
grunt.fatal("Could not find the system.privilege.taskport key in /etc/authorization");
} else {
if (!(/<false\/>/.exec(match[0]))) {
grunt.fatal("/etc/authorization has already been modified to support appium");
} else {
var newText = match[0].replace(match[1], '<true/>');
var newContent = data.replace(match[0], newText);
temp.open('authorization.backup.', function (err, info) {
fs.write(info.fd, origData);
fs.close(info.fd, function(err) {
if (err) throw err;
grunt.log.writeln("Backed up to " + info.path);
var diff = difflib.contextDiff(origData.split("\n"), newContent.split("\n"), {fromfile: "before", tofile: "after"});
grunt.log.writeln("Check this diff to make sure the change looks cool:");
grunt.log.writeln(diff.join("\n"));
prompt.start();
var promptProps = {
properties: {
proceed: {
pattern: /^(y|n)/
, description: "Make changes? [y/n] "
}
}
};
prompt.get(promptProps, function(err, result) {
if (result.proceed == "y") {
fs.writeFile(authFile, newContent, function(err) {
if (err) {
if (err.code === "EACCES") {
grunt.fatal("You need to run this as sudo!");
} else {
throw err;
}
}
grunt.log.writeln("Wrote new /etc/authorization");
cb();
});
} else {
grunt.log.writeln("No changes were made");
cb();
}
});
});
});
}
}
});
});
};
module.exports.build = function(appRoot, cb, sdk) {
if (typeof sdk == "undefined") {
sdk = 'iphonesimulator6.0';
}
var cmd = 'xcodebuild -sdk ' + sdk + ' clean';
console.log("Cleaning build...");
var xcode = exec(cmd, {cwd: appRoot}, function(err, stdout, stderr) {
if (err) {
console.log("Failed cleaning app, maybe it doesn't exist?");
return cb(stdout + "\n" + stderr);
}
console.log("Building app...");
var args = ['-sdk', sdk];
xcode = spawn('xcodebuild', args, {
cwd: appRoot
});
var output = '';
var collect = function(data) { output += data; };
xcode.stdout.on('data', collect);
xcode.stderr.on('data', collect);
xcode.on('exit', function(code) {
if (code === 0) {
cb(null);
} else {
console.log("Failed building app, maybe it doesn't exist?");
cb(output);
}
});
});
};
module.exports.buildApp = function(appDir, cb, sdk) {
if(typeof sdk === "undefined") {
sdk = "iphonesimulator6.1";
}
var appRoot = path.resolve(__dirname, 'sample-code/apps/', appDir);
module.exports.build(appRoot, function(err) {
if (err !== null) {
console.log(err);
cb(false);
} else {
cb(true);
}
}, sdk);
};
module.exports.signApp = function(appName, certName, cb) {
var appPath = path.resolve(__dirname, 'sample-code/apps/', appName,
'build/Release-iphonesimulator');
exec("codesign -f -s \"" + certName + "\" -v " + appName + ".app", {cwd: appPath}, function(err, stdout, stderr) {
console.log(stdout);
console.log(stderr);
if (err) {
cb(false);
} else {
cb(true);
}
});
};
module.exports.downloadUICatalog = function(cb) {
var appBasePath = path.resolve(__dirname, 'sample-code/apps');
var appPath = path.resolve(appBasePath, 'UICatalog');
var zipPath = path.resolve(appBasePath, 'UICatalog.zip');
var UICatUrl = "http://developer.apple.com/library/ios/samplecode/UICatalog/UICatalog.zip";
// clear out anything that's there
try {
fs.unlinkSync(zipPath);
} catch(e) {}
rimraf(appPath, function() {
var file = fs.createWriteStream(zipPath);
console.log("Downloading UI catalog into " + zipPath);
http.get(UICatUrl, function(response) {
response.pipe(file);
response.on('end', function() {
console.log("Download complete");
exec("unzip UICatalog.zip", {cwd: appBasePath}, function() {
console.log("Unzipped into " + appPath);
cb();
});
});
});
});
};
var setupAndroidProj = function(grunt, projPath, args, cb) {
if (!process.env.ANDROID_HOME) {
grunt.fatal("Could not find Android SDK, make sure to export ANDROID_HOME");
}
var cmd = path.resolve(process.env.ANDROID_HOME, "tools", "android");
var proc = spawn(cmd, args, {cwd: projPath});
proc.stdout.setEncoding('utf8');
proc.stderr.setEncoding('utf8');
proc.stdout.on('data', function(data) {
grunt.log.write(data);
});
proc.stderr.on('data', function(data) {
grunt.log.write(data);
});
proc.on('exit', function(code) {
cb(code);
});
};
module.exports.setupAndroidBootstrap = function(grunt, cb) {
var projPath = path.resolve(__dirname, "android", "bootstrap");
var args = ["create", "uitest-project", "-n", "AppiumBootstrap", "-t",
"android-17", "-p", "."];
setupAndroidProj(grunt, projPath, args, cb);
};
module.exports.setupAndroidApp = function(grunt, appName, cb) {
var appPath = path.resolve(__dirname, "sample-code/apps/" + appName);
var args = ["update", "project", "--subprojects", "-t", "android-17", "-p", "."];
setupAndroidProj(grunt, appPath, args, cb);
};
var buildAndroidProj = function(grunt, projPath, target, cb) {
var cmd_name = 'ant';
if (!fs.existsSync(projPath + '/build.xml') &&
fs.existsSync(projPath + '/pom.xml')) {
cmd_name = 'mvn';
}
exec('which ' + cmd_name, function(err, stdout) {
if (err) {
grunt.fatal("Error finding " + cmd_name + " binary, is it on your path?");
} else {
if (stdout) {
var cmd = stdout.trim();
grunt.log.write("Using " + cmd_name + " found at " + cmd);
var proc = spawn(cmd, [target], {cwd: projPath});
proc.stdout.setEncoding('utf8');
proc.stderr.setEncoding('utf8');
proc.stdout.on('data', function(data) {
grunt.log.write(data);
});
proc.stderr.on('data', function(data) {
grunt.log.write(data);
});
proc.on('exit', function(code) {
cb(code);
});
} else {
grunt.fatal("Could not find " + cmd_name + " installed; please make sure it's on PATH");
}
}
});
};
module.exports.buildAndroidBootstrap = function(grunt, cb) {
var projPath = path.resolve(__dirname, "android", "bootstrap");
var binSrc = path.resolve(projPath, "bin", "AppiumBootstrap.jar");
var binDestDir = path.resolve(__dirname, "build", "android_bootstrap");
var binDest = path.resolve(binDestDir, "AppiumBootstrap.jar");
buildAndroidProj(grunt, projPath, "build", function(err) {
if (err) {
console.log("Could not build android bootstrap");
return cb(err);
}
mkdirp(binDestDir, function(err) {
if (err) {
console.log("Could not mkdirp " + binDestDir);
return cb(err);
}
rimraf(binDest, function(err) {
if (err) {
console.log("Could not delete old " + binDest);
return cb(err);
}
ncp(binSrc, binDest, function(err) {
if (err) {
console.log("Could not copy " + binSrc + " to " + binDest);
return cb(err);
}
cb();
});
});
});
});
};
module.exports.buildSelendroidServer = function(cb) {
console.log("Building selendroid server");
getSelendroidVersion(function(err, version) {
if (err) return cb(err);
var buildDir = path.resolve(__dirname, "submodules/selendroid/selendroid-server");
var target = buildDir + "/target/selendroid-server-" + version + ".apk";
var destDir = path.resolve(__dirname, "build/selendroid");
var destBin = path.resolve(destDir, "selendroid.apk");
var srcManifest = path.resolve(__dirname, "submodules", "selendroid",
"selendroid-gem", "selendroid-prebuild", "AndroidManifest.xml");
var dstManifeset = path.resolve(destDir, "AndroidManifest.xml");
var cmd = "mvn install";
exec(cmd, {cwd: buildDir}, function(err, stdout, stderr) {
if (err) {
console.error("Unable to build selendroid server. Stdout was: ");
console.error(stdout);
console.error(stderr);
return cb(err);
}
console.log("Making sure target exists");
fs.stat(target, function(err) {
if (err) {
console.error("Selendroid doesn't exist! Not sure what to do.");
return cb(err);
}
console.log("Selendroid server built successfully, copying to build/selendroid");
rimraf(destDir, function(err) {
if (err) {
console.error("Could not remove " + destDir);
return cb(err);
}
mkdirp(destDir, function(err) {
if (err) {
console.error("Could not create " + destDir);
return cb(err);
}
ncp(target, destBin, function(err) {
if (err) {
console.error("Could not copy " + target + " to " + destBin);
return cb(err);
}
console.log("Copying selendroid manifest as well");
ncp(srcManifest, dstManifeset, function(err) {
if (err) {
console.error("Could not copy manifest");
return cb(err);
}
cb(null);
});
});
});
});
});
});
});
};
var getSelendroidVersion = function(cb) {
console.log("Getting Selendroid version");
var pomXml = path.resolve(__dirname, "submodules", "selendroid",
"selendroid-server", "pom.xml");
fs.readFile(pomXml, function(err, xmlData) {
if (err) {
console.error("Could not find selendroid's pom.xml at");
return cb(err);
}
parseXmlString(xmlData.toString('utf8'), function(err, res) {
if (err) {
console.error("Error parsing selendroid's pom.xml");
return cb(err);
}
var version = res.project.parent[0].version[0];
if (typeof version === "string") {
console.log("Selendroid version is " + version);
cb(null, version);
} else {
cb(new Error("Version " + version + " was not valid"));
}
});
});
};
module.exports.buildAndroidApp = function(grunt, appName, cb) {
var appPath = path.resolve(__dirname, "sample-code/apps/" + appName);
buildAndroidProj(grunt, appPath, "debug", cb);
};
module.exports.buildSelendroidAndroidApp = function(grunt, appName, cb) {
var appPath = path.resolve(__dirname, "sample-code/apps/" + appName);
buildAndroidProj(grunt, appPath, "package", cb);
};
module.exports.installAndroidApp = function(grunt, appName, cb) {
var pkgMap = {'ApiDemos': 'com.example.android.apis'};
if (!_.has(pkgMap, appName)) {
var msg = "We don't know about appName " + appName + ", please edit " +
"grunt-helpers.js:installAndroidApp() to add it and its " +
"package identifier";
grunt.fatal(new Error(msg));
}
var appPath = path.resolve(__dirname, "sample-code/apps/" + appName,
"bin/" + appName + "-debug.apk");
exec("adb uninstall " + pkgMap[appName], function(err, stdout) {
if (err) return grunt.fatal(err);
grunt.log.write(stdout);
exec("adb install -r " + appPath, function(err, stdout) {
if (err) return grunt.fatal(err);
grunt.log.write(stdout);
cb();
});
});
};
module.exports.generateServerDocs = function(grunt, cb) {
var p = parser();
var docFile = path.resolve(__dirname, "docs/server-args.md");
var md = "Appium server arguments\n==========\n\n";
md += "Usage: `node server.js [flags]`\n\n";
md += "### Server flags\n";
md += "All flags are optional, but some are required in conjunction with " +
"certain others.\n\n";
md += "|Flag|Default|Description|Example|\n";
md += "|----|-------|-----------|-------|\n";
_.each(p.rawArgs, function(arg) {
var argNames = arg[0];
var exampleArg = typeof arg[0][1] === "undefined" ? arg[0][0] : arg[0][1];
var argOpts = arg[1];
md += "|`" + argNames.join("`, `") + "`";
md += "|" + ((typeof argOpts.defaultValue === "undefined") ? "" : argOpts.defaultValue);
md += "|" + argOpts.help;
md += "|" + ((typeof argOpts.example === "undefined") ? "" : "`" + exampleArg + " " + argOpts.example + "`");
md += "|\n";
});
fs.writeFile(docFile, md, function(err) {
if (err) {
console.log(err.stack);
grunt.fatal(err);
} else {
grunt.log.write("New docs written! Don't forget to commit and push");
cb();
}
});
};
module.exports.generateAppiumIo = function(grunt, cb) {
getAppiumIoFiles(function(err, template, readme) {
if (err) {
return grunt.fatal(err);
}
var readmeLex = namp.lexer(readme)
, headers = getMarkdownHeaders(readmeLex)
, sidebarHtml = generateSidebarHtml(headers)
, warning = "<!-- THIS FILE IS AUTOMATICALLY GENERATED DO NOT EDIT -->\n"
, bodyHtml = generateBodyHtml(readmeLex, headers)
, submod = path.resolve(__dirname, "submodules/appium.io")
, outfile = submod + "/getting-started.html";
var newDoc = template.replace("{{ SIDENAV }}", sidebarHtml)
.replace("{{ README_SECTIONS }}", bodyHtml)
.replace("{{ WARNING }}", warning);
fs.writeFile(outfile, newDoc, function(err) {
if (err) {
grunt.fatal(err);
} else {
grunt.log.write("Pushing changes to appium.io...");
var cmd = 'git commit -am "updating getting-started via grunt" && ' +
'git pull --rebase origin master && ' +
'git push origin master && ' +
'git checkout gh-pages && ' +
'git pull origin gh-pages && ' +
'git merge master && ' +
'git push origin gh-pages && ' +
'git checkout master';
exec(cmd, {cwd: submod}, function(err, stdout, stderr) {
if (err) {
console.log(stdout);
console.log(stderr);
grunt.fatal(err);
} else {
grunt.log.write("success!");
cb();
}
});
}
});
});
};
var getAppiumIoFiles = function(cb) {
var templateFile = path.resolve(__dirname, "submodules/appium.io/getting-started-template.html")
, readmeFile = path.resolve(__dirname, "README.md");
fs.readFile(templateFile, function(err, templateData) {
if (err) {
cb(err);
} else {
fs.readFile(readmeFile, function(err, readmeData) {
if (err) cb(err); else cb(null, templateData.toString(), readmeData.toString());
});
}
});
};
var getMarkdownHeaders = function(mdTree) {
var headers = {};
_.each(mdTree, function(mdObj) {
if (mdObjIsHeader(mdObj)) {
headers[mdObj.text] = sanitizeMdHeader(mdObj.text);
}
});
return headers;
};
var mdObjIsHeader = function(mdObj) {
return mdObj.depth === 2 && mdObj.type === 'heading';
};
var sanitizeMdHeader = function(header) {
var re = new RegExp(/[^a-zA-Z0-9]/g);
return header.replace(re, "-")
.replace(/-$/, "")
.replace(/-+/g, "-")
.toLowerCase();
};
var generateSidebarHtml = function(headers) {
var html = '';
_.each(headers, function(link, header) {
header = namp(header).html;
header = header.replace(/<[^>]+>/ig, "");
html += '<li><a href="#' + link + '"><i class="icon-chevron-right"></i> ' +
header + '</a></li>\n';
});
return html;
};
var generateBodyHtml = function(readmeMd, headers) {
var html = ''
, inBetweens = []
, inBetweenHtml = ''
, inSection = false;
var addInBetweenHtml = function() {
if (inBetweens.length) {
inBetweenHtml = namp.parser(inBetweens)[0];
html += inBetweenHtml;
inBetweens = [];
}
};
for (var i = 1; i < readmeMd.length; i++) {
var mdObj = readmeMd[i];
if (mdObjIsHeader(mdObj)) {
addInBetweenHtml();
var headerHtml = namp.parser([mdObj])[0];
headerHtml = headerHtml.replace(/<.?p>/ig, '');
if (inSection) {
html += '</section>\n';
}
html += '<section id="' + headers[mdObj.text] + '">\n';
html += '<h2>\n<a href="#' + headers[mdObj.text] + '" class="anchor" ' +
'name="requirements">\n<span class="mini-icon mini-icon-link">' +
'</span>\n</a>\n' + headerHtml + '\n</h2>\n\n';
inSection = true;
} else if (inSection) {
inBetweens.push(mdObj);
}
if (i === readmeMd.length - 1) {
addInBetweenHtml();
}
}
html += '</section>';
return html;
};