Serializes the specified git tree as an archive (zip/tgz).

@param {string} repPath git repository path
@param {object} tree git tree to process
@param {object} archiver Archiver instance
@returns {Promise<stream.Readable>} readable stream of archive
492708
async function archiveGitTree(repPath, tree, archive) {
  // recursively collect all entries (blobs and trees)
  const allEntries = await collectTreeEntries(repPath, tree, [], '');

  const process = async ({ type, oid, path }) => {
    if (type === 'tree' || type === 'commit') {
      // directory or submodule
      archive.append(null, { name: `${path}/` });
    } else {
      // blob
      const stream = await createBlobReadStream(repPath, oid);
      archive.append(stream, { name: path });
    }
  };

  return new Promise((resolve, reject) => {
    async.eachSeries(
      allEntries,
      async.asyncify(process),
      (err) => {
        if (err) {
          reject(err);
        } else {
          resolve(archive);
        }
      },
    );
  });
}
85450
function git(args) {
  return new Promise((resolve, reject) => {
    exec(`git ${args}`, (err, stdout) => {
      if (err) {
        reject(err);
      } else {
        resolve(stdout.trim());
      }
    });
  });
}
1356326
def repackage(path)
      @logger.debug("Repackaging box '#{@name}' to: #{path}")

      Util::SafeChdir.safe_chdir(@directory) do
        # Find all the files in our current directory and tar it up!
        files = Dir.glob(File.join(".", "**", "*")).select { |f| File.file?(f) }

        # Package!
        Util::Subprocess.execute("bsdtar", "-czf", path.to_s, *files)
      end

      @logger.info("Repackaged box '#{@name}' successfully: #{path}")

      true
    end
439421
def extract_archive(archive_path, dest):
  
  # Make the dest folder if it does not exist
  if not os.path.isdir(dest):
    os.makedirs(dest)

  try:
    tmpfolder = None

    if (not tf.gfile.Exists(archive_path)) or tf.gfile.IsDirectory(archive_path):
      raise ValueError('archive path %s is not a file' % archive_path)

    if archive_path.startswith('gs://'):
      # Copy the file to a local temp folder
      tmpfolder = tempfile.mkdtemp()
      cmd_args = ['gsutil', 'cp', archive_path, tmpfolder]
      _shell_process.run_and_monitor(cmd_args, os.getpid())
      archive_path = os.path.join(tmpfolder, os.path.name(archive_path))

    if archive_path.lower().endswith('.tar.gz'):
      flags = '-xzf'
    elif archive_path.lower().endswith('.tar'):
      flags = '-xf'
    else:
      raise ValueError('Only tar.gz or tar.Z files are supported.')

    cmd_args = ['tar', flags, archive_path, '-C', dest]
    _shell_process.run_and_monitor(cmd_args, os.getpid())
  finally:
    if tmpfolder:
      shutil.rmtree(tmpfolder)
424193
function cloneGitRepo(host, ref) {
    var isBranch = false;

    ref = ref || 'master';
    if (!validateSha(ref)) isBranch = true;

    return Q()

    // Create temporary folder to store git repos
    .then(function() {
        if (GIT_TMP) return;
        return fs.tmp.dir()
            .then(function(_tmp) {
                GIT_TMP = _tmp;
            });
    })

    // Return or clone the git repo
    .then(function() {
        // Unique ID for repo/ref combinaison
        var repoId = crc.crc32(host+'#'+ref).toString(16);

        // Absolute path to the folder
        var repoPath = path.resolve(GIT_TMP, repoId);

        return fs.exists(repoPath)
            .then(function(doExists) {
                if (doExists) return;

                // Clone repo
                return exec('git clone '+host+' '+repoPath)
                .then(function() {
                    return exec('git checkout '+ref, { cwd: repoPath });
                });
            })
            .thenResolve(repoPath);
    });
}
1333584
function cleanDir( path, _preserveGit ) {
    const
    preserveGit = typeof _preserveGit !== 'undefined' ? _preserveGit : false,
    fullPath = Path.resolve( path );
    // If the pah does not exist, everything is fine!
    if ( !FS.existsSync( fullPath ) ) return;

    if ( preserveGit ) {

        /*
         * We must delete the content of this folder but preserve `.git`.
         * The `www` dir, for instance, can be used as a `gh-pages` branch.
         */
        const files = FS.readdirSync( path );
        files.forEach( function forEachFile( filename ) {
            if ( filename === '.git' ) return;
            const
            filepath = Path.join( path, filename ),
            stat = FS.statSync( filepath );
            if ( stat.isDirectory() ) {
                if ( filepath !== '.' && filepath !== '..' ) PathUtils.rmdir( filepath );
            } else FS.unlinkSync( filepath );
        } );
    } else {
        // Brutal clean: remove dir and recreate it.
        PathUtils.rmdir( path );
        PathUtils.mkdir( path );
    }
}
638683
function clone() {
		Release.chdir( Release.dir.base );
		Release.dir.dist = Release.dir.base + "/dist";

		console.log( "Using distribution repo: ", distRemote );
		Release.exec( "git clone " + distRemote + " " + Release.dir.dist,
			"Error cloning repo." );

		// Distribution always works on master
		Release.chdir( Release.dir.dist );
		Release.exec( "git checkout master", "Error checking out branch." );
		console.log();
	}
1333649
def git_wrapper(path):
    '''
    
    '''
    path = os.path.abspath(path)
    if path not in _wrapper_cache:
        if hasattr(Repo, 'commits'):
            _wrapper_cache[path] = _GitWrapperLegacy(path)
        else:
            _wrapper_cache[path] = _GitWrapper(path)

    return _wrapper_cache[path]
551791
public void maybeArchive(final String path, final String name)
    {
        if (Strings.isNullOrEmpty(archiveCommand))
            return;

        archivePending.put(name, executor.submit(new WrappedRunnable()
        {
            protected void runMayThrow() throws IOException
            {
                String command = archiveCommand.replace("%name", name);
                command = command.replace("%path", path);
                exec(command);
            }
        }));
    }
41886
def process_pulls(self, testpulls=None, testarchive=None, expected=None):
        
        from datetime import datetime
        pulls = self.find_pulls(None if testpulls is None else testpulls.values())
        for reponame in pulls:
            for pull in pulls[reponame]:
                try:
                    archive = self.archive[pull.repokey]
                    if pull.snumber in archive:
                        #We pass the archive in so that an existing staging directory (if
                        #different from the configured one) can be cleaned up if the previous
                        #attempt failed and left the file system dirty.
                        pull.init(archive[pull.snumber])
                    else:
                        pull.init({})
                        
                    if self.testmode and testarchive is not None:
                        #Hard-coded start times so that the model output is reproducible
                        if pull.number in testarchive[pull.repokey]:
                            start = testarchive[pull.repokey][pull.number]["start"]
                        else:
                            start = datetime(2015, 4, 23, 13, 8)
                    else:
                        start = datetime.now()
                    archive[pull.snumber] = {"success": False, "start": start,
                                             "number": pull.number, "stage": pull.repodir,
                                             "completed": False, "finished": None}
                    #Once a local staging directory has been initialized, we add the sha
                    #signature of the pull request to our archive so we can track the rest
                    #of the testing process. If it fails when trying to merge the head of
                    #the pull request, the exception block should catch it and email the
                    #owner of the repo.
                    #We need to save the state of the archive now in case the testing causes
                    #an unhandled exception.
                    self._save_archive()

                    pull.begin()
                    self.cron.email(pull.repo.name, "start", self._get_fields("start", pull), self.testmode)
                    pull.test(expected[pull.number])
                    pull.finalize()

                    #Update the status of this pull request on the archive, save the archive
                    #file in case the next pull request throws an unhandled exception.
                    archive[pull.snumber]["completed"] = True
                    archive[pull.snumber]["success"] = abs(pull.percent - 1) < 1e-12

                    #This if block looks like a mess; it is necessary so that we can easily
                    #unit test this processing code by passing in the model outputs etc. that should
                    #have been returned from running live.
                    if (self.testmode and testarchive is not None and
                        pull.number in testarchive[pull.repokey] and
                        testarchive[pull.repokey][pull.number]["finished"] is not None):
                        archive[pull.snumber]["finished"] = testarchive[pull.repokey][pull.number]["finished"]
                    elif self.testmode:
                        archive[pull.snumber]["finished"] = datetime(2015, 4, 23, 13, 9)
                    else:
                        #This single line could replace the whole if block if we didn't have
                        #unit tests integrated with the main code.
                        archive[pull.snumber]["finished"] = datetime.now()
                    self._save_archive()

                    #We email after saving the archive in case the email server causes exceptions.
                    if archive[pull.snumber]["success"]:
                        key = "success"
                    else:
                        key = "failure"
                    self.cron.email(pull.repo.name, key, self._get_fields(key, pull), self.testmode)
                except:
                    import sys, traceback
                    e = sys.exc_info()
                    errmsg = '\n'.join(traceback.format_exception(e[0], e[1], e[2]))
                    err(errmsg)
                    self.cron.email(pull.repo.name, "error", self._get_fields("error", pull, errmsg),
                                    self.testmode)
542257
def git_try_describe(repo_path):
    
    try:
        p = subprocess.Popen(['git', 'describe', '--always', '--dirty'],
                             cwd=repo_path, stdout=subprocess.PIPE,
                             stderr=subprocess.PIPE)
        output, _ = p.communicate()
    except:
        return None
    else:
        if p.returncode == 0:
            return output.strip()

    return None
913223
def _del_repo_from_file(repo, filepath):
    '''
    
    '''
    with salt.utils.files.fopen(filepath) as fhandle:
        output = []
        regex = re.compile(REPO_REGEXP)
        for line in fhandle:
            line = salt.utils.stringutils.to_unicode(line)
            if regex.search(line):
                if line.startswith('#'):
                    line = line[1:]
                cols = salt.utils.args.shlex_split(line.strip())
                if repo != cols[1]:
                    output.append(salt.utils.stringutils.to_str(line))
    with salt.utils.files.fopen(filepath, 'w') as fhandle:
        fhandle.writelines(output)
726126
def install(self, xmlpath):
        
        #Before we can install it, we need to make sure that none of the existing
        #installed paths point to the same repo.
        from os import path
        fullpath = path.abspath(path.expanduser(xmlpath))
        if path.isfile(fullpath):
            repo = RepositorySettings(self, fullpath)
            if repo.name.lower() not in self.repositories:
                self.installed.append(fullpath)
                self._save_installed()
                self.archive[repo.name.lower()] = {}
                self._save_archive()
                
                self.repositories[repo.name.lower()] = repo
        else:
            warn("The file {} does not exist; install aborted.".format(fullpath))
1199744
async function viaTreesApi(identifier, dir, token) {
	const files = [];
	const {repo, ref} = parseIdentifier(identifier);
	const contents = await api(`${repo}/git/trees/${ref}?recursive=1`, token);
	for (const item of contents.tree) {
		if (item.type === 'blob' && item.path.startsWith(dir)) {
			files.push(item.path);
		}
	}
	files.truncated = contents.truncated;
	return files;
}
1093132
def archive(directory, id, destination_path)
      Dir.chdir(@directory) do
        FileUtils.mkdir_p(File.dirname(destination_path))
        run("git archive --format=tar #{id} -- #{directory} | xz -9e > #{destination_path}")
      end
      destination_path
    end
1108069
function (options) {
  var git_repo_path = ((options && options['gcwd']) || process.cwd()) + '/.git';

  return fs.statAsync(git_repo_path)
    .call('isDirectory')
    .then(function (exist) {
      return exist && git_repo_path
    })
}
238627
public void doImport() throws RepositoryException, IOException
   {
      try
      {
         uuid = versionableNode.getUUID();
         path = versionableNode.getVersionHistory().getParent().getPath();
         if (LOG.isDebugEnabled())
         {
            LOG.debug("Started: Import version history for node with path=" + path + " and UUID=" + uuid);
         }

         NodeData versionable = (NodeData)versionableNode.getData();
         // ----- VERSIONABLE properties -----
         // jcr:versionHistory
         TransientPropertyData vh =
            TransientPropertyData.createPropertyData(versionable, Constants.JCR_VERSIONHISTORY, PropertyType.REFERENCE,
               false, new TransientValueData(new Identifier(versionHistory)));

         // jcr:baseVersion
         TransientPropertyData bv =
            TransientPropertyData.createPropertyData(versionable, Constants.JCR_BASEVERSION, PropertyType.REFERENCE,
               false, new TransientValueData(new Identifier(baseVersionUuid)));

         // jcr:predecessors
         List<ValueData> values = new ArrayList<ValueData>();
         for (int i = 0; i < predecessors.length; i++)
         {
            values.add(new TransientValueData(new Identifier(predecessors[i])));
         }
         TransientPropertyData pd =
            TransientPropertyData.createPropertyData(versionable, Constants.JCR_PREDECESSORS, PropertyType.REFERENCE,
               true, values);

         PlainChangesLog changesLog = new PlainChangesLogImpl();
         RemoveVisitor rv = new RemoveVisitor();
         rv.visit((NodeData)((NodeImpl)versionableNode.getVersionHistory()).getData());
         changesLog.addAll(rv.getRemovedStates());
         changesLog.add(ItemState.createAddedState(vh));
         changesLog.add(ItemState.createAddedState(bv));
         changesLog.add(ItemState.createAddedState(pd));
         // remove version properties to avoid referential integrety check
         PlainChangesLog changesLogDelete = new PlainChangesLogImpl();

         changesLogDelete.add(ItemState.createDeletedState(((PropertyImpl)versionableNode
            .getProperty("jcr:versionHistory")).getData()));
         changesLogDelete.add(ItemState.createDeletedState(((PropertyImpl)versionableNode
            .getProperty("jcr:baseVersion")).getData()));
         changesLogDelete.add(ItemState.createDeletedState(((PropertyImpl)versionableNode
            .getProperty("jcr:predecessors")).getData()));
         dataKeeper.save(changesLogDelete);
         // remove version history
         dataKeeper.save(changesLog);
         userSession.save();

         // import new version history
         Map<String, Object> context = new HashMap<String, Object>();
         //context.put("versionablenode", versionableNode);
         context.put(ContentImporter.RESPECT_PROPERTY_DEFINITIONS_CONSTRAINTS, true);
         userSession.getWorkspace().importXML(path, versionHistoryStream, 0, context);
         userSession.save();

         if (LOG.isDebugEnabled())
         {
            LOG.debug("Completed: Import version history for node with path=" + path + " and UUID=" + uuid);
         }

         // fetch list of imported child nodes versions
         List<String> versionUuids = (List<String>)context.get(ContentImporter.LIST_OF_IMPORTED_VERSION_HISTORIES);
         if (versionUuids != null && !versionUuids.isEmpty())
         {
            updateVersionedChildNodes(versionUuids);
         }
      }
      catch (RepositoryException exception)
      {
         LOG.error("Failed: Import version history for node with path=" + path + " and UUID=" + uuid, exception);
         throw new RepositoryException(exception);
      }
      catch (IOException exception)
      {
         LOG.error("Failed: Import version history for node with path=" + path + " and UUID=" + uuid, exception);
         IOException newException = new IOException();
         newException.initCause(exception);
         throw newException;
      }
   }