<commit_before>"use strict";

var spawn = require('child_process').spawn
  , exec = require('child_process').exec
  , path = require('path')
  , fs = require('fs')
  , net = require('net')
  , logger = require('../logger').get('appium')
  , status = require('../app/uiauto/lib/status')
  , unzipFile = require('../app/helpers').unzipFile
  , _ = require('underscore');

var noop = function() {};

var ADB = function(opts) {
  if (!opts) {
    opts = {};
  }
  if (typeof opts.sdkRoot === "undefined") {
    opts.sdkRoot = process.env.ANDROID_HOME || '';
  }
  this.sdkRoot = opts.sdkRoot;
  this.skipInstall = opts.skipInstall || false;
  this.skipUninstall = !(opts.reset || false);
  this.port = opts.port || 4724;
  this.avdName = opts.avdName;
  this.appPackage = opts.appPackage;
  this.appActivity = opts.appActivity;
  this.apkPath = opts.apkPath;
  this.adb = "adb";
  this.adbCmd = this.adb;
  this.curDeviceId = null;
  this.socketClient = null;
  this.proc = null;
  this.onSocketReady = noop;
  this.portForwarded = false;
  this.debugMode = true;
  this.fastReset = opts.fastReset;
};

ADB.prototype.checkAdbPresent = function(cb) {
  if (this.sdkRoot) {
    this.adb = path.resolve(this.sdkRoot, "platform-tools", "adb");
    this.debug("Using adb from " + this.adb);
    cb(null, this);
  } else {
    exec("which adb", _.bind(function(err, stdout) {
      if (stdout) {
        this.debug("Using adb from " + stdout);
        this.adb = stdout;
        cb(null, this);
      } else {
        cb("Could not find adb; do you have android SDK installed?", null);
      }
    }, this));
  }
};

ADB.prototype.buildFastReset = function(cb) {
  this.uninstallApp(_.bind(function() {

    // NOP if fast reset is not true.
    if (!this.fastReset) {
      cb(true);
      return;
    }

    var targetAPK = this.apkPath;
    var targetPackage = this.appPackage;
    // gsub AndroidManifest.xml using targetPackage
    var manifestPath = path.resolve(__dirname, '../app/android/AndroidManifest.xml.src');
    var utf8 = 'utf8';

    var content = fs.readFileSync(manifestPath, utf8);
    var manifest = manifestPath.substr(0, manifestPath.length - '.src'.length);
    fs.writeFileSync(manifest, content, utf8);

    fs.readFile(manifest, utf8, function(err, data) {
      if (err) throw err;
      var rePkg = /package="([^"]+)"/;
      var reTarget = /targetPackage="([^"]+)"/;
      var matchPkg = rePkg.exec(data);
      var matchTarget = reTarget.exec(data);

      if (!matchPkg) {
        logger.debug("Could not find package= in manifest");
        cb(false);
        return;
      }

      if (!matchTarget) {
        logger.debug("Could not find targetPackage= in manifest");
        cb(false);
        return;
      }

      var newPkg = matchPkg[0].replace(matchPkg[1], targetPackage + '.clean');
      var newTarget = matchTarget[0].replace(matchTarget[1], targetPackage);

      var newContent = data.replace(matchPkg[0], newPkg);
      newContent = newContent.replace(matchTarget[0], newTarget);

      fs.writeFile(manifest, newContent, function(err) {
        if (err) {
          throw err;
        }
        logger.debug("Created manifest");
        var androidHome = process.env.ANDROID_HOME;

        exec('which aapt', function(err, stdout) {
          if (err) {
            throw new Error("Error finding aapt binary, is it on your path?");
          }


          // Compile manifest into manifest.xml.apk
          var compile_manifest = ['aapt package -M "', manifest,
                                  '" -I "', androidHome, '/platforms/android-17/android.jar" -F "',
                                  manifest, '.apk" -f'].join('');
          logger.debug(compile_manifest);
          exec(compile_manifest, {}, function(err, stdout, stderr) {
            logger.debug(stdout);
            logger.debug(stderr);
            if (err) {
              cb(false);
            }

            logger.debug('unzip: ' + manifest + '.apk');
            logger.debug('replace: ' + targetAPK);

            // unzip manifest.xml.apk
            unzipFile(manifest + '.apk', function(err, stderr){
              var execOpts = {cwd: path.dirname(targetAPK)};
              // -j = keep only the file, not the dirs
              // -m = move manifest into target apk.
              var cleanAPK = path.resolve(__dirname, '../app/android/Clean.apk');
              var replaceCmd = 'zip -j -m "' + cleanAPK + '" "' + manifest + '"';
              logger.debug(replaceCmd);
              exec(replaceCmd, execOpts, function(err, stderr, stdout) {
                if (!err) {
                  logger.debug("Replace manifest successful");
                  // resign target apk and clean.apk
                  var signPath = path.resolve(__dirname, '../app/android/sign.jar');
                  var resign = 'java -jar "' + signPath + '" "' + targetAPK + '" "' + cleanAPK + '" --override';
                  logger.debug("Resigning: " + resign);
                  exec(resign, execOpts, function(err, stderr, stdout) {
                    if (!err) {
                      logger.debug("Resign clean and target apk successful. Installing clean apk.");
                      var installCleanAPK = 'adb install -r "' + cleanAPK + '"';
                      logger.debug(installCleanAPK);
                      exec(installCleanAPK, function(err, stdout) {
                        if (err) {
                          logger.debug(err);
                          cb(-1);
                        } else {
                          logger.debug(stdout);
                          logger.debug("Build fast reset complete.");
                          cb(0);
                        }
                      });
                    } else {
                      logger.error("Resign threw error " + err);
                      logger.error("Stderr: " + stderr);
                      logger.error("Stdout: " + stdout);
                      cb("APK could not be signed, check appium logs.", null);
                    }
                  });
                } else {
                  logger.error("Replace manifest threw error " + err);
                  logger.error("Stderr: " + stderr);
                  logger.error("Stdout: " + stdout);
                  cb("APK could not be updated, check appium logs.", null);
                }
              });
            });
          });
        });
      });
    });
  }, this));
};

ADB.prototype.start = function(onReady, onExit) {
  var doRun = _.bind(function() {
    this.runBootstrap(onReady, onExit);
  }, this);
<commit_msg>Clean up debug logging<commit_after>"use strict";

var spawn = require('child_process').spawn
  , exec = require('child_process').exec
  , path = require('path')
  , fs = require('fs')
  , net = require('net')
  , logger = require('../logger').get('appium')
  , status = require('../app/uiauto/lib/status')
  , unzipFile = require('../app/helpers').unzipFile
  , _ = require('underscore');

var noop = function() {};

var ADB = function(opts) {
  if (!opts) {
    opts = {};
  }
  if (typeof opts.sdkRoot === "undefined") {
    opts.sdkRoot = process.env.ANDROID_HOME || '';
  }
  this.sdkRoot = opts.sdkRoot;
  this.skipInstall = opts.skipInstall || false;
  this.skipUninstall = !(opts.reset || false);
  this.port = opts.port || 4724;
  this.avdName = opts.avdName;
  this.appPackage = opts.appPackage;
  this.appActivity = opts.appActivity;
  this.apkPath = opts.apkPath;
  this.adb = "adb";
  this.adbCmd = this.adb;
  this.curDeviceId = null;
  this.socketClient = null;
  this.proc = null;
  this.onSocketReady = noop;
  this.portForwarded = false;
  this.debugMode = true;
  this.fastReset = opts.fastReset;
};

ADB.prototype.checkAdbPresent = function(cb) {
  if (this.sdkRoot) {
    this.adb = path.resolve(this.sdkRoot, "platform-tools", "adb");
    this.debug("Using adb from " + this.adb);
    cb(null, this);
  } else {
    exec("which adb", _.bind(function(err, stdout) {
      if (stdout) {
        this.debug("Using adb from " + stdout);
        this.adb = stdout;
        cb(null, this);
      } else {
        cb("Could not find adb; do you have android SDK installed?", null);
      }
    }, this));
  }
};

ADB.prototype.buildFastReset = function(cb) {
  this.uninstallApp(_.bind(function() {

    // NOP if fast reset is not true.
    if (!this.fastReset) {
      cb(true);
      return;
    }

    var targetAPK = this.apkPath;
    var targetPackage = this.appPackage;
    // gsub AndroidManifest.xml using targetPackage
    var manifestPath = path.resolve(__dirname, '../app/android/AndroidManifest.xml.src');
    var utf8 = 'utf8';

    var content = fs.readFileSync(manifestPath, utf8);
    var manifest = manifestPath.substr(0, manifestPath.length - '.src'.length);
    fs.writeFileSync(manifest, content, utf8);

    fs.readFile(manifest, utf8, function(err, data) {
      if (err) throw err;
      var rePkg = /package="([^"]+)"/;
      var reTarget = /targetPackage="([^"]+)"/;
      var matchPkg = rePkg.exec(data);
      var matchTarget = reTarget.exec(data);

      if (!matchPkg) {
        logger.debug("Could not find package= in manifest");
        cb(false);
        return;
      }

      if (!matchTarget) {
        logger.debug("Could not find targetPackage= in manifest");
        cb(false);
        return;
      }

      var newPkg = matchPkg[0].replace(matchPkg[1], targetPackage + '.clean');
      var newTarget = matchTarget[0].replace(matchTarget[1], targetPackage);

      var newContent = data.replace(matchPkg[0], newPkg);
      newContent = newContent.replace(matchTarget[0], newTarget);

      fs.writeFile(manifest, newContent, function(err) {
        if (err) {
          throw err;
        }
        logger.debug("Created manifest");
        var androidHome = process.env.ANDROID_HOME;

        exec('which aapt', function(err, stdout) {
          if (err) {
            throw new Error("Error finding aapt binary, is it on your path?");
          }


          // Compile manifest into manifest.xml.apk
          var compile_manifest = ['aapt package -M "', manifest,
                                  '" -I "', androidHome, '/platforms/android-17/android.jar" -F "',
                                  manifest, '.apk" -f'].join('');
          logger.debug(compile_manifest);
          exec(compile_manifest, {}, function(err, stdout, stderr) {
            if (err) {
              logger.debug(stderr);
              cb(false);
            }

            logger.debug('unzip: ' + manifest + '.apk');
            logger.debug('replace: ' + targetAPK);

            // unzip manifest.xml.apk
            unzipFile(manifest + '.apk', function(err, stderr){
              var execOpts = {cwd: path.dirname(targetAPK)};
              // -j = keep only the file, not the dirs
              // -m = move manifest into target apk.
              var cleanAPK = path.resolve(__dirname, '../app/android/Clean.apk');
              var replaceCmd = 'zip -j -m "' + cleanAPK + '" "' + manifest + '"';
              logger.debug(replaceCmd);
              exec(replaceCmd, execOpts, function(err, stderr, stdout) {
                if (!err) {
                  logger.debug("Replace manifest successful");
                  // resign target apk and clean.apk
                  var signPath = path.resolve(__dirname, '../app/android/sign.jar');
                  var resign = 'java -jar "' + signPath + '" "' + targetAPK + '" "' + cleanAPK + '" --override';
                  logger.debug("Resigning: " + resign);
                  exec(resign, execOpts, function(err, stderr, stdout) {
                    if (!err) {
                      logger.debug("Resign clean and target apk successful. Installing clean apk.");
                      var installCleanAPK = 'adb install -r "' + cleanAPK + '"';
                      logger.debug(installCleanAPK);
                      exec(installCleanAPK, function(err, stdout) {
                        if (err) {
                          logger.debug(err);
                          cb(-1);
                        } else {
                          logger.debug("Build fast reset complete.");
                          cb(0);
                        }
                      });
                    } else {
                      logger.error("Resign threw error " + err);
                      logger.error("Stderr: " + stderr);
                      logger.error("Stdout: " + stdout);
                      cb("APK could not be signed, check appium logs.", null);
                    }
                  });
                } else {
                  logger.error("Replace manifest threw error " + err);
                  logger.error("Stderr: " + stderr);
                  logger.error("Stdout: " + stdout);
                  cb("APK could not be updated, check appium logs.", null);
                }
              });
            });
          });
        });
      });
    });
  }, this));
};

ADB.prototype.start = function(onReady, onExit) {
  var doRun = _.bind(function() {
    this.runBootstrap(onReady, onExit);
  }, this);

{'fraction_non_alphanumeric': 0.14195319051612412, 'fraction_numerical': 0.0030494777769307004, 'mean_word_length': 1.8283742992669254, 'pattern_counts': {'":': 0, '<': 3, '<?xml version=': 0, '>': 3, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 8}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 4, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '3904532', 'n_tokens_mistral': 3907, 'n_tokens_neox': 3784, 'n_words': 847}