DXR is a code search and navigation tool aimed at making sense of large projects. It supports full-text and regex searches as well as structural queries.

Git (975a35c0f5)

VCS Links

Line Code
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
'use strict';

/**
 * This file contains all Node.js version of utils functions.
 * Since we're stil in the progress to migrate to Node.js, the
 * missing functions in this file should be in the 'utils-xpc.js'
 *
 * About documents:
 * Users can find comments in the 'utils-xpc.js',
 * which contains the complete functions used in 'utils.js'
 */

var utils = require('./utils');
var path = require('path');
var childProcess = require('child_process');
var fs = require('fs-extra');
var JSZip = require('jszip');
var os = require('os');
var vm = require('vm');
var http = require('http');
var https = require('https');
var url = require('url');
var dive = require('diveSync');
var nodeUUID = require('node-uuid');
var jsdom = require('jsdom');
var esprima = require('esprima');
var procRunning = require('is-running');
var mime = require('mime');
var crypto = require('crypto');
var request = require('request');

// Our gecko will transfer .opus file to audio/ogg datauri type.
mime.define({'audio/ogg': ['opus']});

module.exports = {

  scriptParser: esprima.parse,

  log: function() {
    var args = Array.prototype.slice.call(arguments);
    if (!args.length) {
      console.log('\n');
      return;
    }
    console.log('[' + args[0] + '] ' + args.slice(1).join(' '));
  },

  stdout: function(output) {
    console.log(output);
  },

  normalizePath: function(string) {
    return path.normalize(string);
  },

  joinPath: function() {
    return path.join.apply(path, arguments);
  },

  getOsType: function() {
    var type = os.type();
    return type === 'Windows_NT' ? 'WINNT' : type;
  },

  relativePath: function(from, to) {
    return path.relative(from, to);
  },

  getFile: function() {
    var self = module.exports;
    var args = Array.prototype.slice.call(arguments);
    var src = path.join.apply(path, args);
    src = path.resolve(src);
    var fileStat;
    try {
      fileStat = fs.statSync(src);
    } catch (e) {
      // In order to have compability with xpcshell interface,
      // we just simply let fileStat undefined and don't need
      // to do anything here.
    }
    return {
      exists: function() {
        return self.fileExists(src);
      },
      remove: function() {
        fs.removeSync(src);
      },
      isDirectory: function() {
        return !!fileStat && fileStat.isDirectory();
      },
      isFile: function() {
        return !!fileStat && fileStat.isFile();
      },
      isHidden: function() {
        return /^\./.test(path.basename(src));
      },
      path: src,
      leafName: path.basename(src)
    };
  },

  getFileContent: function(file, type) {
    if (typeof file === 'string') {
      file = this.getFile(file);
    }
    if (file.exists() && file.isFile()) {
      return fs.readFileSync(file.path, { encoding: type || 'utf8' });
    }
  },

  Commander: function(cmd) {
    this.initPath = function() {};
    this.run = function(args, callback, options) {
      var cmds = args.join(' ');

      // In *nix and OSX version commands are run via sh -c YOUR_COMMAND,
      // but in Windows commands are run via cmd /C YOUR_COMMAND,
      // so, we just let execSync module to handle the difference.
      if (cmd === 'sh') {
        cmds = cmds.replace(/^-c/, '');
      } else {
        cmds = cmd + ' ' + cmds;
      }
      // XXX: Most cmds should run synchronously, we should use either promise
      //      pattern inside each script or find a sync module which doesn't
      //      require recompile again since TPBL doesn't support that.
      return new Promise(function(resolve, reject) {
        var proc = childProcess.exec(cmds, { maxBuffer: (4096 * 1024) },
          function(err, stdout, stderr) {
            if (err) {
              options && options.stderr && options.stderr(stderr);
              reject();
            } else {
              options && options.stdout && options.stdout(stdout);
              callback && callback(stdout);
              resolve();
            }
        });
        proc.stdout.on('data', (data) => {
          process.stdout.write(data);
        });
        proc.stderr.on('data', (data) => {
          process.stderr.write(data);
        });
      });
    };

    this.runWithSubprocess = function(args, options) {
      this.run(args, null, options);
    };
  },

  killAppByPid: function(appName) {
    childProcess.exec('adb shell b2g-ps', function(err, stdout) {
      if (!err && stdout) {
        var psMap = utils.psParser(stdout);
        if (psMap[appName] && psMap[appName].PID) {
          childProcess.exec('adb shell kill ' + psMap[appName].PID);
        }
      }
    });
  },

  spawnProcess: function(module, appOptions) {
    this.exitCode = null;

    var args = [
      '--harmony',
      '-e', 'require("' + module + '").execute(' +
        JSON.stringify(appOptions).replace(/\\/g, '\\\\') + ');'
    ];

    return new Promise((resolve, reject) => {
      var proc = childProcess.spawn('node', args, { cwd: __dirname });
      proc.stdout.on('data', (data) => {
        process.stdout.write(data);
      });
      proc.stderr.on('data', (data) => {
        process.stderr.write(data);
      });
      proc.on('exit', (code) => {
        this.exitCode = code;
        resolve(code);
      });
    });
  },

  processIsRunning: function(proc) {
    return procRunning(proc.pid);
  },

  getProcessExitCode: function() {
    return this.exitCode;
  },

  resolve: function(relativePath, gaiaDir) {
    var absPath;
    if (relativePath[0] === '/') {
      absPath = relativePath;
    } else {
      absPath = path.join(gaiaDir, relativePath);
    }
    return this.getFile(absPath);
  },

  getFileAsDataURI: function(file) {
    var data = this.getFileContent(file, 'base64');
    return 'data:' + mime.lookup(file.path) + ';base64,' + data;
  },

  getZip: function() {
    var zip = new JSZip();
    var zipPath;
    var self = this;

    return {
      load: function(zipFile) {
        zipPath = zipFile;
        if (self.fileExists(zipFile)) {
          try {
            zip.load(fs.readFileSync(zipFile));
          } catch (err) {
            console.error(err);
          }
        }
      },

      file: function(name, file, options) {
        try {
          if (!file) {
            let output = zip.file(name);
            return output && output.asText();
          } else {
            return zip.file(name, fs.readFileSync(file.path), options);
          }
        } catch (err) {
          console.error(err);
        }
      },

      entries: function() {
        return Object.keys(zip.files);
      },

      extract: function(entry, dest) {
        try {
          var zipFile = zip.file(entry);
          if (zipFile && !zipFile.dir) {
            fs.outputFileSync(dest, zipFile.asNodeBuffer());
          }
        } catch (err) {
          console.error(err);
        }
      },

      close: function() {
        try {
          fs.outputFileSync(zipPath, zip.generate({ type: 'nodebuffer' }));
        } catch (err) {
          console.error(err);
        }
      }
    };
  },

  getJSON: function(file) {
    var content = this.getFileContent(file);
    try {
      return JSON.parse(content);
    } catch (error) {
      console.error('Invalid JSON file : ' + file.path);
      if (content) {
        console.error('Content of JSON file:\n' + content);
      }
      throw error;
    }
  },

  getDocument: function(content) {
    return jsdom.jsdom(content);
  },

  getXML: function(file) {
    return jsdom.jsdom(this.getFileContent(file));
  },

  getEnv: function(name) {
    return process.env[name];
  },

  setEnv: function(name, value) {
    process.env[name] = value;
  },

  getEnvPath: function() {
    return process.env.PATH.split(path.delimiter);
  },

  getTempFolder: function(dirName) {
    var tmpPath = path.join(os.tmpdir(), dirName);
    fs.mkdirpSync(tmpPath);
    return this.getFile(tmpPath);
  },

  ensureFolderExists: function(file) {
    fs.mkdirpSync(file.path);
  },

  normalizeString: function(appname) {
    return appname.replace(' ', '-').toLowerCase().replace(/\W/g, '');
  },

  ls: function(dir, recursive, includeDir) {
    var files = [];
    if (!dir || !dir.exists()) {
      return [];
    }
    dive(dir.path, { recursive: recursive, directories: includeDir },
      function(err, filePath) {
        if (err) {
          // Skip error
          return;
        }
        files.push(this.getFile(filePath));
      }.bind(this));
    return files;
  },

  download: function(fileUrl, dest, doneCallback, errorCallback) {
    dest = dest || this.joinPath(this.getTempFolder('gaia').path,
                                 (new Date()).getTime() + '.tmp');

    var file = fs.createWriteStream(dest);
    file.on('finish', function() {
      doneCallback && doneCallback(fileUrl, dest);
    });

    request
      .get(fileUrl, function(error, response) {
        if (error && response.statusCode !== 200) {
          errorCallback && errorCallback(fileUrl, dest);
        }
      })
      .pipe(file);
  },

  downloadJSON: function(fileUrl, callback) {
    var protocol = url.parse(fileUrl).protocol;
    var request = (protocol === 'http:') ? http : https;
    request.get(fileUrl, function(res) {
      var body = '';
      res.on('data', function(chunk) {
        body += chunk;
      });
      res.on('end', function() {
        if (callback) {
          callback(JSON.parse(body));
        }
      });
    }).on('error', function(e) {
      throw new Error('Download JSON with error: ' + e);
    });
  },

  readJSONFromPath: function(path) {
    return require(path);
  },

  concatenatedScripts: function(scriptsPaths, targetPath) {
    var concatedScript = scriptsPaths.map(function(path) {
      return this.getFileContent(this.getFile(path));
    }, this).join('\n');

    var targetFile = this.getFile(targetPath);

    this.writeContent(targetFile, concatedScript);
  },

  getDistributionFileContent: function(name, defaultContent, distDir) {
    if (distDir) {
      let distributionFile = this.getFile(distDir, name + '.json');
      if (distributionFile.exists()) {
        return this.getFileContent(distributionFile);
      }
    }
    return JSON.stringify(defaultContent, null, '  ');
  },

  getUUIDMapping: function(config) {
    var UUIDMapping = this.UUIDMapping;
    if (UUIDMapping) {
      return UUIDMapping;
    }
    this.UUIDMapping = UUIDMapping = {};
    // Try to retrieve it from $GAIA_DISTRIBUTION_DIR/uuid.json if exists.
    try {
      var uuidFile = this.getFile(config.GAIA_DISTRIBUTION_DIR, 'uuid.json');
      if (uuidFile.exists()) {
        console.log('uuid.json in GAIA_DISTRIBUTION_DIR found.');
        UUIDMapping = JSON.parse(this.getFileContent(uuidFile));
      }
    } catch (e) {
      // ignore exception if GAIA_DISTRIBUTION_DIR does not exist.
    }
    return UUIDMapping;
  },

  getWebapp: function(app, config) {
    let appDir = this.getFile(app);
    if (!appDir.exists()) {
      throw new Error(' -*- build/utils.js: file not found (' + app + ')\n');
    }

    let manifestFile = this.joinPath(appDir.path, 'manifest.webapp');
    let updateFile = this.joinPath(appDir.path, 'update.webapp');

    // Ignore directories without manifest
    if (!this.fileExists(manifestFile) && !this.fileExists(updateFile)) {
      return;
    }

    let manifest = this.fileExists(manifestFile) ? manifestFile : updateFile;
    let manifestJSON = this.getJSON(this.getFile(manifest));

    // Use the folder name as the the domain name
    let appDomain = appDir.leafName;
    if (manifestJSON.origin) {
      appDomain = this.getNewURI(manifestJSON.origin).host;
    }

    let self = this;
    let webapp = {
      appDirPath: appDir.path,
      manifest: manifestJSON,
      manifestFilePath: manifest,
      url: config.GAIA_SCHEME + appDomain,
      domain: appDomain,
      sourceDirectoryFilePath: appDir.path,
      sourceDirectoryName: appDir.leafName,
      sourceAppDirectoryName: self.getFile(appDir.path, '..').leafName
    };

    // External webapps have a `metadata.json` file
    let metaData = this.getFile(webapp.sourceDirectoryFilePath,
      'metadata.json');
    if (metaData.exists()) {
      let zip = this.getZip();
      zip.load(this.joinPath(webapp.sourceDirectoryFilePath,
                             'application.zip'));
      webapp.pckManifest = JSON.parse(zip.file('manifest.webapp'));
      webapp.metaData = this.getJSON(metaData);
      webapp.appStatus = utils.getAppStatus(
        webapp.metaData.type ||
        (webapp.pckManifest && webapp.pckManifest.type) ||
        'web'
      );
    } else {
      webapp.appStatus = utils.getAppStatus(webapp.manifest.type);
    }

    // Some webapps control their own build
    webapp.buildDirectoryFilePath = this.joinPath(config.STAGE_DIR,
      webapp.sourceDirectoryName);
    webapp.buildManifestFilePath = this.joinPath(webapp.buildDirectoryFilePath,
      'manifest.webapp');

    // Generate the webapp folder name in the profile. Only if it's privileged
    // and it has an origin in its manifest file it'll be able to specify a
    // custom folder name. Otherwise, generate an UUID to use as folder name.
    var webappTargetDirName;
    if (this.isExternalApp(webapp)) {
      var type = webapp.appStatus;
      var isPackaged = false;
      if (webapp.pckManifest) {
        isPackaged = true;
        if (webapp.metaData.origin) {
          throw new Error('External webapp `' + webapp.sourceDirectoryName +
            '` can not have origin in metadata because is packaged');
        }
      }
      if (type === 2 && isPackaged && webapp.pckManifest.origin) {
        webappTargetDirName = this.getNewURI(webapp.pckManifest.origin).host;
      } else {
        // uuid is used for webapp directory name, save it for further usage
        let mapping = this.getUUIDMapping(config);
        var uuid = mapping[webapp.sourceDirectoryName] ||
          '{' + nodeUUID.v4() + '}';
        mapping[webapp.sourceDirectoryName] = webappTargetDirName = uuid;
      }
    } else {
      webappTargetDirName = webapp.domain;
    }
    webapp.profileDirectoryFilePath = this.joinPath(config.COREWEBAPPS_DIR,
                                                    'apps',
                                                    webappTargetDirName);

    return webapp;
  },

  getNewURI: function(uri) {
  console.log('node: getNewURI(', uri, ')\n');
    return {
      host: /[a-z]+:\/\/[@]?([^\/:]+)/.exec(uri)[1],
      prePath: /[a-z]+:\/\/[^\/]+/.exec(uri)[0],
      resolve: function(to) {
        return url.resolve(uri, to);
      }
    };
  },

  isExternalApp: function(webapp) {
    if (webapp.metaData && webapp.metaData.external === undefined) {
      throw new Error('"external" property in metadata.json is required ' +
        'since Firefox OS 2.1, please add it into metadata.json and update ' +
        'preload.py if you use this script to perload your apps. If you ' +
        'created metadata.json for non-external apps, please set "external" ' +
        'to false. metadata.json is in ' + webapp.sourceDirectoryFilePath);
    }
    if (!webapp.metaData || webapp.metaData.external === false) {
      return false;
    } else {
      return true;
    }
  },

  processEvents: function(exitResultFunc) {
    // FIXME: A fake blocking function for porting utils-xpc
    // This workaround will be removed once node.js migration is done
    var exitResult = exitResultFunc();
    if (exitResult.error) {
      throw exitResult.error;
    }
  },

  writeContent :function(file, content) {
    fs.writeFileSync(file.path, content);
  },

  getLocaleBasedir: function(src) {
    return os.type() === 'Windows_NT' ? src.replace('/', '\\', 'g') : src;
  },

  deleteFile: function(filePath) {
    fs.removeSync(filePath);
  },

  fileExists: function(path) {
    try {
      fs.accessSync(path);
      return true;
    } catch(err) {
      return false;
    }
  },

  listFiles: function(path, type, recursive, exclude) {
    var file = (typeof path === 'string' ? this.getFile(path) : path);
    if (!file.isDirectory()) {
      throw new Error('The path is not a directory.');
    }
    var files = this.ls(file, recursive === true, exclude);
    var detectFunc = (type === 0 ? 'isFile' : 'isDirectory');
    // To return simple JavaScript type, We need to put the file path to the
    // array instead of nsIFile.
    var results = [];
    files.forEach(function(file) {
      if (file[detectFunc]()) {
        results.push(file.path);
      }
    });

    return results;
  },

  mkdirs: function(path) {
    fs.mkdirpSync(path);
  },

  dirname: function(filePath) {
    return path.dirname(filePath);
  },

  basename: function(filePath) {
    return path.basename(filePath);
  },

  existsInAppDirs: function(appDirs, appName) {
    var apps = appDirs.split(' ');
    var exists = apps.some(function (appPath) {
      let appFile = this.getFile(appPath);
      return (appName === appFile.leafName);
    }, this);
    return exists;
  },

  copyFileTo: function(filePath, toParent, name) {
    var file = ((typeof filePath === 'string') ?
      this.getFile(filePath) : filePath);
    fs.copySync(file.path, path.join(toParent, name));
  },

  copyDirTo: function(filePath, toParent, name) {
    var file = ((typeof filePath === 'string') ?
      this.getFile(filePath) : filePath);
    fs.copySync(file.path, path.join(toParent, name));
  },

  copyToStage: function(options) {
    var appDir = this.getFile(options.APP_DIR);
    this.copyDirTo(appDir, options.STAGE_DIR, appDir.leafName);
  },

  scriptLoader: {

    scripts: {},

    load: function(filePath, exportObj, withoutCache) {
      if (!withoutCache && this.scripts[filePath]) {
        return;
      }

      var doc = jsdom.jsdom();
      var win = doc.defaultView;

      global.addEventListener = win.addEventListener;
      global.dispatchEvent = win.dispatchEvent;

      for (let key in exportObj) {
        global[key] = exportObj[key];
      }

      try {
        var script = fs.readFileSync(filePath, { encoding: 'utf8' });
        vm.runInThisContext(script, filePath);
        this.scripts[filePath] = true;
      } catch(error) {
        delete this.scripts[filePath];
        throw error;
      }
    }
  },

  createSandbox: function() {
    return {};
  },

  runScriptInSandbox: function(filePath, sandbox) {
    var script = fs.readFileSync(filePath, { encoding: 'utf8' });
    return vm.runInNewContext(script, sandbox);
  },

  getHash: function(data, encoding, algorithm) {
    encoding = encoding || 'utf8';
    algorithm = algorithm || 'sha1';
    return crypto.createHash(algorithm).update(data, encoding).digest('hex');
  },

  exit: function(code) {
    process.exit(code);
  }

};