This seems preferable, unfortunately seems to create an archive
 that aws config parsing has a problem w/
zip = `git ls-tree -r --name-only HEAD | zip - -q -@`
185013
def write_to_object(object)
      bundle_name = '.bundle.tmp'
      write_bundle(bundle_name)
      object.write(File.open(bundle_name))
      File.delete(bundle_name)
    end
1373391
def zip_source_model(ssmLT, archive_zip='', log=logging.info):
    
    basedir = os.path.dirname(ssmLT)
    if os.path.basename(ssmLT) != 'ssmLT.xml':
        orig = ssmLT
        ssmLT = os.path.join(basedir, 'ssmLT.xml')
        with open(ssmLT, 'wb') as f:
            f.write(open(orig, 'rb').read())

    archive_zip = archive_zip or os.path.join(basedir, 'ssmLT.zip')
    if os.path.exists(archive_zip):
        sys.exit('%s exists already' % archive_zip)
    oq = mock.Mock(inputs={'source_model_logic_tree': ssmLT})
    checksum = readinput.get_checksum32(oq)
    checkfile = os.path.join(os.path.dirname(ssmLT), 'CHECKSUM.txt')
    with open(checkfile, 'w') as f:
        f.write(str(checksum))
    files = logictree.collect_info(ssmLT).smpaths + [
        os.path.abspath(ssmLT), os.path.abspath(checkfile)]
    general.zipfiles(files, archive_zip, log=log, cleanup=True)
    return archive_zip
1286211
def init_git_pillar(opts):
    '''
    
    '''
    ret = []
    for opts_dict in [x for x in opts.get('ext_pillar', [])]:
        if 'git' in opts_dict:
            try:
                pillar = salt.utils.gitfs.GitPillar(
                    opts,
                    opts_dict['git'],
                    per_remote_overrides=git_pillar.PER_REMOTE_OVERRIDES,
                    per_remote_only=git_pillar.PER_REMOTE_ONLY,
                    global_only=git_pillar.GLOBAL_ONLY)
                ret.append(pillar)
            except salt.exceptions.FileserverConfigError:
                if opts.get('git_pillar_verify_config', True):
                    raise
                else:
                    log.critical('Could not initialize git_pillar')
    return ret
196278
def aws_env_args(subparsers):
    """"""
    env_parser = subparsers.add_parser('aws_environment')
    env_parser.add_argument('vault_path',
                            help='Full path(s) to the AWS secret')
    export_arg(env_parser)
    base_args(env_parser)
1073442
function copyJekyllConfig() {
    return streamToPromise(
        gulp.src(paths.src.jekyll)
            .pipe(rename('_config.yaml'))
            .pipe(gulp.dest(paths.out.docs.base))
    );
}
1254382
function (buildConfig) {
        var projectRoot = buildConfig.projectRoot;
        var packageFile = path.join(projectRoot, 'package.json');

        var url = require(packageFile).repository.url;
        var prefix = 'github.com/';

        return url.substring(url.indexOf(prefix) + prefix.length, url.lastIndexOf('.git'));
    }
834249
def main():
    
    logging.basicConfig(
        format='[%(asctime)s] %(levelname)s -- %(message)s',
        level=logging.DEBUG)

    parser = argparse.ArgumentParser(description='')
    parser.add_argument('git_url', help='Url of the repo to sync')
    parser.add_argument('branch_name', default='master', help='Branch of repo to sync', nargs='?')
    parser.add_argument('repo_dir', default='.', help='Path to clone repo under', nargs='?')
    args = parser.parse_args()

    for line in GitPuller(
        args.git_url,
        args.branch_name,
        args.repo_dir
    ).pull():
        print(line)
94268
function createMiddleware(options) {
  /**
   * Express middleware handling Git API Blob requests
   *
   * Only a small subset will be implemented
   *
   * @param {Request} req Request object
   * @param {Response} res Response object
   * @param {callback} next next middleware in chain
   *
   * @see https://developer.github.com/v3/git/blobs/#get-a-blob
   */
  return (req, res, next) => {
    // GET /repos/:owner/:repo/git/blobs/:file_sha
    const { owner } = req.params;
    const repoName = req.params.repo;
    const sha = req.params.file_sha;
    const host = req.mappedSubDomain ? `localhost:${options.listen[req.protocol].port}` : req.headers.host;

    const repPath = resolveRepositoryPath(options, owner, repoName);

    if (sha.match(/[0-9a-f]/g).length !== 40) {
      // invalid sha format
      res.status(422).json({
        message: 'The sha parameter must be exactly 40 characters and contain only [0-9a-f].',
        documentation_url: 'https://developer.github.com/v3/git/blobs/#get-a-blob',
      });
      return;
    }
    getObject(repPath, sha)
      .then(({ object: content }) => {
        res.json({
          sha,
          size: content.length,
          url: `${req.protocol}://${host}${req.path}`,
          content: `${content.toString('base64')}\n`,
          encoding: 'base64',
        });
      })
      .catch((err) => {
        // TODO: use generic errors
        if (err.code === 'ReadObjectFail') {
          options.logger.debug(`[blobHandler] resource not found: ${err.message}`);
          res.status(404).json({
            message: 'Not Found',
            documentation_url: 'https://developer.github.com/v3/git/blobs/#get-a-blob',
          });
        } else {
          options.logger.debug(`[blobHandler] code: ${err.code} message: ${err.message} stack: ${err.stack}`);
          next(err);
        }
      });
  };
}
13478
def lint():
    """"""
    py_files = subprocess.check_output("git ls-files")
    if PY3:
        py_files = py_files.decode()
    py_files = [x for x in py_files.split() if x.endswith('.py')]
    py_files = ' '.join(py_files)
    sh("%s -m flake8 %s" % (PYTHON, py_files), nolog=True)
273657
async function gitStashSave(options) {
  debug('Stashing files...')
  // Save ref to the current index
  indexTree = await writeTree(options)
  // Add working copy changes to index
  await execGit(['add', '.'], options)
  // Save ref to the working copy index
  workingCopyTree = await writeTree(options)
  // Restore the current index
  await execGit(['read-tree', indexTree], options)
  // Remove all modifications
  await execGit(['checkout-index', '-af'], options)
  // await execGit(['clean', '-dfx'], options)
  debug('Done stashing files!')
  return [workingCopyTree, indexTree]
}
348277
def ls(args):
    
    table = []
    queues = list(resources.sqs.queues.filter(QueueNamePrefix="github"))
    max_age = datetime.now(tzutc()) - timedelta(days=15)
    for topic in resources.sns.topics.all():
        account_id = ARN(topic.arn).account_id
        try:
            bucket = resources.s3.Bucket("deploy-status-{}".format(account_id))
            status_objects = bucket.objects.filter(Prefix=ARN(topic.arn).resource)
            recent_status_objects = {o.key: o for o in status_objects if o.last_modified > max_age}
        except ClientError:
            continue
        if ARN(topic.arn).resource.startswith("github"):
            for queue in queues:
                queue_name = os.path.basename(queue.url)
                if queue_name.startswith(ARN(topic.arn).resource):
                    row = dict(Topic=topic, Queue=queue)
                    status_object = bucket.Object(os.path.join(queue_name, "status"))
                    if status_object.key not in recent_status_objects:
                        continue
                    try:
                        github, owner, repo, events, instance = os.path.dirname(status_object.key).split("-", 4)
                        status = json.loads(status_object.get()["Body"].read().decode("utf-8"))
                        row.update(status, Owner=owner, Repo=repo, Instance=instance,
                                   Updated=status_object.last_modified)
                    except Exception:
                        pass
                    table.append(row)
    args.columns = ["Owner", "Repo", "Instance", "Status", "Ref", "Commit", "Updated", "Topic", "Queue"]
    page_output(tabulate(table, args))
699515
def load_config(path=None):
    """"""
    # NOTE: Initially I wanted to inherit Path to encapsulate Git access
    # there but there's no easy way to subclass pathlib.Path :(
    head_sha = get_sha1_from("HEAD")
    revision = head_sha
    saved_config_path = load_val_from_git_cfg("config_path")
    if not path and saved_config_path is not None:
        path = saved_config_path

    if path is None:
        path = find_config(revision=revision)
    else:
        if ":" not in path:
            path = f"{head_sha}:{path}"

            revision, _col, _path = path.partition(":")
            if not revision:
                revision = head_sha

    config = DEFAULT_CONFIG

    if path is not None:
        config_text = from_git_rev_read(path)
        d = toml.loads(config_text)
        config = config.new_child(d)

    return path, config
250324
def config_warn(type = :subtrees)
      warn "You shall setup 'Falkorlib.config.git[#{type.to_sym}]' to configure #{type} as follows:"
      warn "     FalkorLib.config.git do |c|"
      warn "       c[#{type.to_sym}] = {"
      warn "          '<subdir>' => {"
      warn "             :url    => '<giturl>',"
      warn "             :branch => 'develop'   # if different from master"
      warn "          },"
      warn "        }"
      warn "     end"
      if type == :submodules
        warn "This will configure the Git submodule into FalkorLib.config.git.submodulesdir"
        warn "i.e. '#{FalkorLib.config.git[:submodulesdir]}'" if FalkorLib.config.git[:submodulesdir]
      end
    end
1235098
def get_tree_from_sha(self, ref):
        '''
        
        '''
        try:
            return self.repo.rev_parse(ref).tree
        except (gitdb.exc.ODBError, AttributeError):
            return None
759582
function buildOnce(config) {
  // verify config
  if (!lintConfig(config)) throw new Error('invalid config')

  // set default holder
  if (!config.holder) {
    config.holder = { name: 'app', stub: 'epii' }
  }

  // prepare static dir
  shell.mkdir('-p', config.$path.target.client)
  shell.mkdir('-p', config.$path.target.vendor)

  // process source
  pureRecipe(config, CONTEXT)
  viewRecipe(config, CONTEXT)
  sassRecipe(config, CONTEXT)
  fileRecipe(config, CONTEXT)
}
463714
function cloneMean(options, done){

  // TODO - Possibly remove depdendency of git all together and download and optionally add a remote.
  if (!shell.which('git')) return console.log(chalk.red('Prerequisite not installed: git'));
  var name = options.name;
  var source = (options.git ? 'git@github.com:linnovate/mean.git' : 'https://github.com/linnovate/mean.git');

  // Allow specifying specific repo
  if (options.repo) {
    source = options.repo;
  }

  // If full clone is specified do a normal clone - default is a shallow --depth 1 clone"
  var shallow = (options.full ? '' : ' --depth 1 ');

  // Install the specified branch or the stableTag - No more MASTER!
  //var branch = options.branch ? options.branch : stableTag;
  var branch = options.branch;
  source = branch + ' ' + source + ' "' + name + '"';
  var gitCmd = 'git clone ' + shallow + ' -b' + source;
  console.log(chalk.green('Cloning branch: %s into destination folder:'), options.branch, name);
  console.log(chalk.green(gitCmd));

  // Running clone
  shell.exec(gitCmd , function(status, output) {
    if (status) {
	    console.log(output);
	    return done(status);
    }
    console.log();
    done();

  });
}
305216
def git_list_config(repo_dir):
    """"""
    command = ['git', 'config', '--list']
    raw = execute_git_command(command, repo_dir=repo_dir).splitlines()
    output = {key: val for key, val in
              [cfg.split('=', 1) for cfg in raw]}
    # TODO(sam): maybe turn this into more easily navigable
    # nested dicts?
    # e.g. {'alias': {'branches': ..., 'remotes': ...}}
    return output