Downloads via npm or via git clone (tries both) Returns a Promise
559307
function downloadPlatform(projectRoot, platform, version, opts) {
    var target = version ? (platform + '@' + version) : platform;
    return Q().then(function() {
        if (opts.fetch) {
            //append cordova to platform
            if(platform in platforms) {
                target = 'judpack-'+target;
            }

            //gitURLs don't supply a platform, it equals null
            if(!platform) {
                target = version;
            }

            events.emit('log', 'Using cordova-fetch for '+ target);
            return fetch(target, projectRoot, opts);
        }

        if (cordova_util.isUrl(version)) {
            events.emit('log', 'git cloning: ' + version);
            var parts = version.split('#');
            var git_url = parts[0];
            var branchToCheckout = parts[1];
            return lazy_load.git_clone(git_url, branchToCheckout).fail(function(err) {
                // If it looks like a url, but cannot be cloned, try handling it differently.
                // it's because it's a tarball of the form:
                //     - wp8@https://git-wip-us.apache.org/repos/asf?p=cordova-wp8.git;a=snapshot;h=3.7.0;sf=tgz
                //     - https://api.github.com/repos/msopenTech/cordova-browser/tarball/my-branch
                events.emit('verbose', err.message);
                events.emit('verbose', 'Cloning failed. Let\'s try handling it as a tarball');
                return lazy_load.based_on_config(projectRoot, target, opts);
            });
        }
        return lazy_load.based_on_config(projectRoot, target, opts);
    }).fail(function (error) {
        var message = 'Failed to fetch platform ' + target +
            '\nProbably this is either a connection problem, or platform spec is incorrect.' +
            '\nCheck your connection and platform name/version/URL.' +
            '\n' + error;
        return Q.reject(new CordovaError(message));
    }).then(function(libDir) {
        return getPlatformDetailsFromDir(libDir, platform);
    });
}
951966
function gitRemote() {
      return function() {
        var deferred = Q.defer();
        Q.fcall(command('git remote', 'Git remote'))
          .then(function( data ) {
            if ( !data || !data.trim() ) {
              deferred.reject(new Error('Error in step [Git remote]. No remotes founds.'));
            }
            var remotes = data.trim().split('\n');
            if ( remotes.length == 1 ) {
              grunt.option('remote', remotes[0]);
              deferred.resolve(grunt.option('remote'));
            }
            else {
              remotes.forEach(function( item, index, list ) {
                list[index] = format('[%s]-%s', index + 1, item);
              });
              var resp = 0;
              grunt.log.writeln(format('%s ', '\n\nThere are more than 1 remote associate with this repo, please choose the one to push into.\n\n' + remotes.join('\n')));
              while ( isNaN(resp) || resp === 0 || resp > remotes.length ) {
                resp = readlinesync.question('\nYour choice?');
                if ( resp === '' ) {
                  grunt.option('remote', undefined);
                  throw new Error('Error in step [Git remote]. No response from user.');
                }
                resp = parseInt(resp);
              }
              grunt.option('remote', data.trim().split('\n')[resp-1]);//using original output
              deferred.resolve(grunt.option('remote'));
            }

          })
          .catch(function( err ) {
            grunt.option('remote', undefined);
            deferred.reject(err);
          });
        return deferred.promise;
      };
    }
606180
function Repo(name, username) {
  this.name = name;
  this.username = username;
  this.isLoaded = Deferred();
  this.isCloned = Deferred();
  this.isClonning = false;
  this.branch = null;
}
372519
function npmInstall(settings) {
  const message = logger.promise('Running npm install (can take several minutes)');

  const installArgs = {};

  if (settings) {
    if (settings.path) {
      installArgs.cwd = settings.path;
    }

    if (settings.stdio) {
      installArgs.stdio = settings.stdio;
    }
  }

  const npmProcess = spawn('npm', ['install'], installArgs);

  return new Promise((resolve, reject) => {
    npmProcess.on('exit', (code) => {
      if (code !== 0) {
        message.fail();
        reject('npm install failed.');
        return;
      }

      message.succeed();
      resolve();
    });
  });
}
375718
def git_clone(uri, pull=True, reflect=False, cache_dir=None, chdir=True):
    '''
    
    '''
    cache_dir = cache_dir or CACHE_DIR
    # make the uri safe for filesystems
    repo_path = os.path.expanduser(os.path.join(cache_dir, safestr(uri)))
    if not os.path.exists(repo_path):
        from_cache = False
        logger.info(
            'Locally caching git repo [%s] to [%s]' % (uri, repo_path))
        cmd = 'git clone %s %s' % (uri, repo_path)
        sys_call(cmd)
    else:
        from_cache = True
        logger.info(
            'GIT repo loaded from local cache [%s])' % (repo_path))
    if pull and not from_cache:
        os.chdir(repo_path)
        cmd = 'git pull'
        sys_call(cmd, cwd=repo_path)
    if chdir:
        os.chdir(repo_path)
    if reflect:
        if not HAS_DULWICH:
            raise RuntimeError("`pip install dulwich` required!")
        return Repo(repo_path)
    else:
        return repo_path
964468
function executeGit( args, options ) {
	options = options || {};
	return new Promise( function( resolve, reject ) {
		var stdo = '';
		var proc = doSpawn( 'git', args, { cwd: options.cwd ? options.cwd : process.cwd(), stdio: [ 'ignore', 'pipe', 'ignore' ] } );

		function unpipe() {
		}

		if ( options.captureStdout ) {
			proc.stdout.on( 'data', function onStdout( data ) {
                       		stdo += data.toString();
                	} );
		}
		proc.on( 'error', function( err ) {
			unpipe();
			if ( options.ignoreError ) {
				resolve( { out: stdo, code: 0 } );
			} else {
				printError( err, args );
				reject( err );
			}
		} );
		proc.on( 'exit', function( code ) {
			unpipe();
		} );
		proc.on( 'close', function( code ) {
			unpipe();
			if ( code !== 0 && !options.ignoreError ) {
				if ( !options.quiet ) {
					printError( '', args );
				}
				reject( new Error( "Error running git" ) );
			} else {
				resolve( { out: stdo, code: code } );
			}
		} );
	} );
}
565866
function clone(repo, targetPath, opts, cb) {
  opts = opts || {};
  var git = opts.git || 'git';
  var args = ['clone'];

  if (opts.shallow) {
    args.push('--depth');
    args.push('1');
  }

  args.push('--');
  args.push(repo);
  args.push(targetPath);

  var process = spawn(git, args);
  process.on('close', function(status) {
    if (status === 0) {
      if (opts.checkout) {
        _checkout();
      } else {
        cb && cb();
      }
    } else {
      cb && cb(new Error("'git clone' failed with status " + status));
    }
  });

  function _checkout() {
    var args = ['checkout', opts.checkout];
    var process = spawn(git, args, { cwd: targetPath });
    process.on('close', function(status) {
      if (status === 0) {
        cb && cb();
      } else {
        cb && cb(new Error("'git checkout' failed with status " + status));
      }
    });
  }
}
173603
function runSimpleUpgrade (version) {
  return new Promise((resolve) => {
    let npmCommand = (version) ? `npm install -g npm@${version}` : 'npm install -g npm'
    let stdout = []
    let stderr = []
    let child

    try {
      child = spawn('powershell.exe', [ '-NoProfile', '-NoLogo', npmCommand ])
    } catch (error) {
      // This is dirty, but the best way for us to try/catch right now
      resolve({ error })
    }

    child.stdout.on('data', (data) => stdout.push(data.toString()))
    child.stderr.on('data', (data) => stderr.push(data.toString()))

    child.on('exit', () => resolve({ stderr, stdout }))

    child.stdin.end()
  })
}
969015
function checkPackageJsonInGit () {
  return exec('git', ['status', '--porcelain', 'package.json'])
    .then(function ([stdout, stderr]) {
      debug('git status --porcelain package.json', 'stdout', stdout, 'stderr', stderr)
      if (stdout.indexOf('package.json') >= 0) {
        throw new Error('package.json has changes!\n' +
          'I would like to add scripts to your package.json, but ' +
          'there are changes that have not been commited yet.\n' +
          'I don\'t want to damage anything, so I\'m not doing anyhting right now. ' +
          'Please commit your package.json')
      }
    })
}
39256
function performRelease() {
  return gulp.src([config.pkg, config.dist])
      .pipe(git.add({args: '-f'}))
      .pipe(git.commit('release: release version'));
}
946190
function githubRepo (options) {
  try {
    const url = options.data.root.package.repository.url
    const match = url.match(/.*?(:\/\/|@)github\.com[/:](.*?)(#.*?)?$/)
    if (match) {
      return match[2].replace(/\.git$/, '')
    } else {
      return null
    }
  } catch (e) {
    // No repositor-url exists
    return null
  }
}
71315
def fetch(self):
        
        if self._release is not None:
            return self

        self._release = self.expected_release
        if not self.fpath:
            self._commit = self._expected_commit
            return self

         # Only git right now but easily extended to SVN, Mercurial, etc.
        for cmd in ['git', 'git.cmd', 'git.exe']:
            try:
                self.git_fetch(cmd)
                break
            except EnvironmentError:
                pass
        return self
1263384
function(version) {
  var result;
  /** local */
  var ensure = function(key) {
    return function(r) {
      if (r && !r[key]) { throw new Error('result missing ' + key); }
      return r;
    };
  };
  return plugins.first(function(plugin) {
    return Promise.resolve()
    .then(function() { return plugin.match(version); })
    .then(ensure('command'))
    .then(ensure('version'))
    .then(function(r) { return (result = r); });
  })
  .then(function(plugin) {
    return result && _.extend({ plugin: plugin }, result);
  });
}
1202208
function copy(from, to) {
		var mode = fs.statSync(from).mode;
		var src = fs.readFileSync(from, 'utf8');

		var re = /%([0-9A-Z\_]+)%/g;

		function replacer(_, match) {
			// We support the %PERIOD% variable to allow .gitignore to be created. The reason:
			// npm "kindly" ignores .gitignore files, so we have to use this workaround.
			// More info: https://github.com/isaacs/npm/issues/2958

			if (match === 'PERIOD') {
				return '.';
			}

			return templateRules.replace(match);
		}

		try {
			to = to.replace(re, replacer);
			src = src.replace(re, replacer);
		} catch (error) {
			pretty.warning(error + ' in: ' + from);

			// skip this file
			return;
		}

		var fd = fs.openSync(to, 'w', mode);
		fs.writeSync(fd, src);
		fs.closeSync(fd);
	}
36486
function downloadRepo(config, tmpFolder, callback) {

  console.log('Downloading repo...'.magenta);

  // Keep track if the request fails to prevent the continuation of the install
  var requestFailed = false;

  var repoUrl = 'http://server.webhook.com/';

  if(config.server) {
    if(config.server.indexOf('http://') !== 0) {
      config.server = config.server += 'http://';
    }

    if(config.server.indexOf(config.server.length - 1) !== '/') {
      config.server += '/';
    }

    repoUrl = config.server;
  }

  var repoRequest = request(repoUrl + 'download/?site=' + config.siteName + '&token=' + config.siteToken);

  repoRequest
    .on('response', function (response) {
      // If we fail, set it as failing and remove zip file
      if (response.statusCode !== 200) {
        requestFailed = true;
        fs.unlinkSync('repo.zip');
        callback(true);
      }
    })
    .pipe(fs.createWriteStream('repo.zip'))
    .on('close', function () {
      if (requestFailed) return;

      console.log('Extracting Files...'.magenta);
      // Unzip into temporary file
      var zip = new Zip('repo.zip');
      zip.extractAllTo(tmpFolder);
      fs.unlinkSync('repo.zip');
      callback(null, tmpFolder + '/' + fs.readdirSync(tmpFolder)[0]);
    });
}
273982
function cloneFromGit(hostInfo, root, ssh) {
  const branch = hostInfo.committish ? `-b ${hostInfo.committish}` : '';
  let url;

  if (ssh) {
    url = hostInfo.ssh({noCommittish: true});
  } else {
    url = hostInfo.https({noCommittish: true, noGitPlus: true});
  }

  console.log(`Cloning theme from a git repo: ${chalk.green(url)}`);

  return utils
    .spawn(`git clone ${branch} ${url} "${root}" --single-branch`, {
      stdio: 'pipe',
    })
    .then(() => {
      return fs.remove(path.join(root, '.git'));
    })
    .catch((error) => {
      console.log();
      console.log(chalk.red('There was an error while cloning the git repo:'));
      console.log('');
      console.log(chalk.red(error));

      process.exit(1);
    });
}
1221378
function checkGitRepoExistence() {
        return new Promise(function(resolve, reject) {
            var checkRepoCommand = childProcess.exec('git branch');

            checkRepoCommand.stderr.on('data', function(err) {
                reject(err);
            });

            checkRepoCommand.on('close', function(code) {
                if (code === 0) { //0 means ok, 128 means error
                    resolve();
                }
            });
        });
    }