gilt - A GIT layering tool.
964833
def main(ctx, config, debug):  # pragma: no cover
    
    ctx.obj = {}
    ctx.obj['args'] = {}
    ctx.obj['args']['debug'] = debug
    ctx.obj['args']['config'] = config
1035423
function gitVersionInfo(baseVer = '0.1.0') {
  const current = new Semver(baseVer);
  const identifier = current.prerelease[0] || 'beta';
  const prompt = [];
  const types = {
    major: 'major',
    minor: 'minor',
    patch: 'patch',
    premajor: 'pre-release major',
    preminor: 'pre-release minor',
    prepatch: 'pre-relase patch',
    prerelease: 'pre-release'
  };

  Object.keys(types).forEach(releaseType => {
    const newVer = Semver.inc(current.version, releaseType, releaseType.startsWith('pre') ? identifier : '');

    prompt.push({
      value: newVer,
      name: `${types[releaseType]} (${newVer})`
    });
  });

  return {
    current: current.version,
    prompt
  };
}
563356
def changeset
      @changeset ||= git_diff.map do |diff_file|
        file_diff = FileDiff.new(diff_file)
        file_diff unless FormattingChecker.pure_formatting?(file_diff)
      end.compact
    end
578807
def release(obj, commit='HEAD', components=False):
    """"""
    options = obj.options
    repository = obj.repository

    try:
        sha = 'oid'
        commits = _pygit2_commits(commit, repository)
    except ImportError:
        try:
            sha = 'hexsha'
            commits = _git_commits(commit, repository)
        except ImportError:
            click.echo('To use this feature, please install pygit2. '
                       'GitPython will also work but is not recommended '
                       '(python <= 2.7 only).', file=sys.stderr)
            return 2

    messages = OrderedDict([(getattr(c, sha), c.message) for c in commits])

    for commit_sha1 in amended_commits(messages):
        if commit_sha1 in messages:
            del messages[commit_sha1]

    full_messages = list(
        enrich_git_log_dict(messages, options.get('commit_msg_labels'))
    )
    indent = '  ' if components else ''
    wrapper = textwrap.TextWrapper(
        width=70,
        initial_indent=indent + '- ',
        subsequent_indent=indent + '  ',
    )

    for label, section in options.get('commit_msg_labels'):
        if section is None:
            continue
        bullets = []
        for commit in full_messages:
            bullets += [
                {'text': bullet, 'component': commit['component']}
                for lbl, bullet in commit['paragraphs']
                if lbl == label and bullet is not None
            ]
        if len(bullets) > 0:
            click.echo(section)
            click.echo('~' * len(section))
            click.echo()
            if components:
                def key(cmt):
                    return cmt['component']

                for component, bullets in itertools.groupby(
                        sorted(bullets, key=key), key):
                    bullets = list(bullets)
                    if len(bullets) > 0:
                        click.echo('+ {}'.format(component))
                        click.echo()
                    for bullet in bullets:
                        click.echo(wrapper.fill(bullet['text']))
                    click.echo()
            else:
                for bullet in bullets:
                    click.echo(wrapper.fill(bullet['text']))
            click.echo()

    return 0
469927
function gitTags(wd) {
  const basename = path.basename(wd);
  const keys = ['tag_name', 'datetime_created'];
  const separator = '_,,,_';
  const cmd = `git for-each-ref --format='%(refname:short)${separator}%(taggerdate)' refs/tags`;

  console.log(`Collecting git tags of repo ${chalk.cyan(basename)}`);
  const gitProcess = exec(cmd, {
    cwd: wd
  });
  const rl = readline.createInterface({
    input: gitProcess.stdout
  });

  const tagStats = [];
  return new Promise((resolve, reject) => {
    gitProcess.on('error', (err) => {
      reject(err);
    });

    rl.on('line', (line) => {
      const entry = line.split(separator);
      tagStats.push({
        tag_name: entry[0],
        datetime_created: new Date(entry[1]).toISOString()
      });
    }).on('close', () => {
      if (tagStats.length === 0) {
        reject(new Error(chalk.red(`No tags added to this repo`)));
      }
      resolve(tagStats);
    });

  });
}
1081776
def diff_objects(self, latest_commit_sha):
        
        base = ['git', '--bare', '--git-dir', self.git_path]

        object_shas = []
        summary = {'commits': [], 'trees': [], 'files': []}

        def read_parents_and_tree_from(commit):
            if commit in self.synced_object_shas or commit in object_shas:
                # this commit has already been synced or read
                return None, None

            self.synced_object_shas[commit] = True
            summary['commits'].append(commit)
            object_shas.append(commit)

            object_content = subprocess.check_output(base + ['cat-file', '-p', commit]).decode('utf-8').strip()
            parents = []
            tree = ''
            for line in object_content.splitlines():
                if line.startswith('tree '):
                    tree = line[len('tree '):]
                if line.startswith('parent '):
                    parents.append(line[len('parent '):])

            return parents, tree

        def collect_files_from_tree(tree):
            if tree in self.synced_object_shas or tree in object_shas:
                # we have exactly this tree already synced or read, meaning all its objects as well
                return

            self.synced_object_shas[tree] = True
            summary['trees'].append(tree)
            object_shas.append(tree)

            object_content = subprocess.check_output(base + ['ls-tree', '-r', '-t', tree]).decode('utf-8').strip()

            for line in object_content.splitlines():
                exploded = line.split(' ')

                if len(exploded) < 3:
                    sys.stderr.write("Error: Wrong line format of ls-tree for %s: %s\n" % (tree, line,))
                    sys.exit(1)

                object_to_add = str(exploded[2][:40])
                path = str(exploded[2][41:])

                if object_to_add in self.synced_object_shas or object_to_add in object_shas:
                    # have it already in the list or already synced
                    continue

                object_shas.append(object_to_add)
                self.synced_object_shas[object_to_add] = True
                summary['files'].append([object_to_add, path])

        commits_to_check = [latest_commit_sha]

        while len(commits_to_check):
            sha = commits_to_check.pop(0)
            parents, tree = read_parents_and_tree_from(sha)

            if parents:
                for parent in parents:
                    if parent not in commits_to_check:
                        commits_to_check.append(parent)

            if tree:
                collect_files_from_tree(tree)

        is_debug2() and self.logger.debug("shas_to_check %d: %s " % (len(object_shas), str(object_shas),))

        if not object_shas:
            return [], summary

        try:
            is_debug2() and self.logger.debug("Do git-cat-file-check.sh")

            ssh_stream = create_ssh_stream(read_home_config(), exit_on_failure=False)
            channel = ssh_stream.get_transport().open_session()
            channel.exec_command('git-cat-file-check.sh "%s"' % (self.model_name + '.git',))
            channel.sendall('\n'.join(object_shas))
            channel.shutdown_write()

            def readall(c):
                content = b''
                while True:
                    try:
                        chunk = c.recv(1024)
                        if chunk == b'':
                            break
                        content += chunk
                    except (KeyboardInterrupt, SystemExit):
                        return

                return content

            missing_objects = readall(channel).decode('utf-8').splitlines()
            channel.close()
            ssh_stream.close()

            # make sure we have in summary only SHAs we actually will sync
            for stype in six.iterkeys(summary):
                ids = summary[stype][:]
                for sha in ids:
                    if stype == 'files':
                        if sha[0] not in missing_objects:
                            summary[stype].remove(sha)
                    else:
                        if sha not in missing_objects:
                            summary[stype].remove(sha)

            return missing_objects, summary
        except (KeyboardInterrupt, SystemExit):
            raise
        except Exception as e:
            self.logger.error("Failed to generate diff_objects: %s" % (str(e),))
            for sha in object_shas:
                if sha in self.synced_object_shas:
                    del self.synced_object_shas[sha]
            return None, None
409518
def gofmt(ui, repo, *pats, **opts):
	
	if codereview_disabled:
		raise hg_util.Abort(codereview_disabled)

	files = ChangedExistingFiles(ui, repo, pats, opts)
	files = gofmt_required(files)
	if not files:
		ui.status("no modified go files\n")
		return
	cwd = os.getcwd()
	files = [RelativePath(repo.root + '/' + f, cwd) for f in files]
	try:
		cmd = ["gofmt", "-l"]
		if not opts["list"]:
			cmd += ["-w"]
		if subprocess.call(cmd + files) != 0:
			raise hg_util.Abort("gofmt did not exit cleanly")
	except hg_error.Abort, e:
		raise
	except:
		raise hg_util.Abort("gofmt: " + ExceptionDetail())
	return
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();

  });
}
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]
}
1052308
def git_ls_tree(repo_dir, treeish='HEAD'):
    """"""
    command = ['git', 'ls-tree', '-r', '--full-tree', treeish]
    raw = execute_git_command(command, repo_dir=repo_dir).splitlines()
    output = [l.strip() for l in raw if l.strip()]
    # <mode> <type> <object> <file>
    # make a list of lists with clean elements of equal length
    breakout = [k.split(None, 3) for k in output]
    headers = ['mode', 'type', 'object', 'file']
    return [dict(zip(headers, vals)) for vals in breakout]
1070428
def makefile(dir = Dir.pwd, options = {})
      path = normalized_path(dir)
      path = FalkorLib::Git.rootdir(path) if FalkorLib::Git.init?(path)
      info "=> Setup a root repository makefile in '#{dir}'"
      # Preparing submodule
      submodules = {}
      submodules['Makefiles'] = {
        :url    => 'https://github.com/Falkor/Makefiles.git',
        :branch => 'devel'
      }
      FalkorLib::Git.submodule_init(path, submodules)
      makefile = File.join(path, "Makefile")
      if File.exist?( makefile )
        puts "  ... not overwriting the root Makefile which already exists"
      else
        src_makefile = File.join(path, FalkorLib.config.git[:submodulesdir],
                                 'Makefiles', 'repo', 'Makefile')
        FileUtils.cp src_makefile, makefile
        gitflow_branches = FalkorLib::Config::GitFlow::DEFAULTS[:branches]
        if FalkorLib::GitFlow.init?(path)
          [ :master, :develop ].each do |b|
            gitflow_branches[b.to_sym] = FalkorLib::GitFlow.branches(b.to_sym)
          end
        end
        unless options.nil?
          [ :master, :develop ].each do |b|
            gitflow_branches[b.to_sym] = options[b.to_sym] if options[b.to_sym]
          end
        end
        info "adapting Makefile to the gitflow branches"
        Dir.chdir( path ) do
          run %(
   sed -i '' \
        -e \"s/^GITFLOW_BR_MASTER=production/GITFLOW_BR_MASTER=#{gitflow_branches[:master]}/\" \
        -e \"s/^GITFLOW_BR_DEVELOP=devel/GITFLOW_BR_DEVELOP=#{gitflow_branches[:develop]}/\" \
        Makefile
                        )
        end
        FalkorLib::Git.add(makefile, 'Initialize root Makefile for the repo')
      end
    end
347488
def diff_files
        hsh = {}
        @base.git.diff_files.split("\n").each do |line|
          (info, file) = line.split("\t")
          (mode_src, mode_dest, sha_src, sha_dest, type) = info.split
          hsh[file] = {:path => file, :mode_file => mode_src.to_s[1, 7], :mode_index => mode_dest,
                        :sha_file => sha_src, :sha_index => sha_dest, :type => type}
        end
        hsh
      end
333129
def ext_pillar(minion_id, pillar, *repos):  # pylint: disable=unused-argument
    '''
    
    '''
    opts = copy.deepcopy(__opts__)
    opts['pillar_roots'] = {}
    opts['__git_pillar'] = True
    git_pillar = salt.utils.gitfs.GitPillar(
        opts,
        repos,
        per_remote_overrides=PER_REMOTE_OVERRIDES,
        per_remote_only=PER_REMOTE_ONLY,
        global_only=GLOBAL_ONLY)
    if __opts__.get('__role') == 'minion':
        # If masterless, fetch the remotes. We'll need to remove this once
        # we make the minion daemon able to run standalone.
        git_pillar.fetch_remotes()
    git_pillar.checkout()
    ret = {}
    merge_strategy = __opts__.get(
        'pillar_source_merging_strategy',
        'smart'
    )
    merge_lists = __opts__.get(
        'pillar_merge_lists',
        False
    )
    for pillar_dir, env in six.iteritems(git_pillar.pillar_dirs):
        # Map env if env == '__env__' before checking the env value
        if env == '__env__':
            env = opts.get('pillarenv') \
                or opts.get('saltenv') \
                or opts.get('git_pillar_base')
            log.debug('__env__ maps to %s', env)

        # If pillarenv is set, only grab pillars with that match pillarenv
        if opts['pillarenv'] and env != opts['pillarenv']:
            log.debug(
                'env \'%s\' for pillar dir \'%s\' does not match '
                'pillarenv \'%s\', skipping',
                env, pillar_dir, opts['pillarenv']
            )
            continue
        if pillar_dir in git_pillar.pillar_linked_dirs:
            log.debug(
                'git_pillar is skipping processing on %s as it is a '
                'mounted repo', pillar_dir
            )
            continue
        else:
            log.debug(
                'git_pillar is processing pillar SLS from %s for pillar '
                'env \'%s\'', pillar_dir, env
            )

        pillar_roots = [pillar_dir]

        if __opts__['git_pillar_includes']:
            # Add the rest of the pillar_dirs in this environment to the
            # list, excluding the current pillar_dir being processed. This
            # is because it was already specified above as the first in the
            # list, so that its top file is sourced from the correct
            # location and not from another git_pillar remote.
            pillar_roots.extend(
                [d for (d, e) in six.iteritems(git_pillar.pillar_dirs)
                 if env == e and d != pillar_dir]
            )

        opts['pillar_roots'] = {env: pillar_roots}

        local_pillar = Pillar(opts, __grains__, minion_id, env)
        ret = salt.utils.dictupdate.merge(
            ret,
            local_pillar.compile_pillar(ext=False),
            strategy=merge_strategy,
            merge_lists=merge_lists
        )
    return ret
1164481
function () {
				grunt.config('release.localBranch', 'release_' + new Date().getTime());
				var command = [
					'git fetch --tags ' + grunt.config('release.remoteRepository'),
					'git fetch ' + grunt.config('release.remoteRepository'),
					'git checkout -b ' + grunt.config('release.localBranch') + ' ' +
						grunt.config('release.remoteRepository') + '/' + grunt.config('release.remoteBaseBranch')
				].join(' && ');
				grunt.log.write('Checking out new local branch based on ' + grunt.config('release.remoteBaseBranch') + ': ' + command);
				return command;
			}
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)
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);
        }
      });
  };
}
117393
def main():
    """"""

    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument(
        'githubtoken',
        help="Github OAuth token, see https://developer.github.com/v3/oauth/")
    parser.add_argument('destination', help="location of the downloaded repos")
    parser.add_argument(
        '-n', '--nbrepo', help="number of repositories per language",
        type=int, default=1000)
    parser.add_argument(
        '-d', '--debug', default=False, action='store_true',
        help="show debug messages")

    args = parser.parse_args()
    config_logging(args.debug)

    destination = Path(args.destination)
    nb_repos = args.nbrepo
    token = args.githubtoken

    languages = config_dict('languages.json')
    destination.mkdir(exist_ok=True)

    for pos, language in enumerate(sorted(languages), 1):
        LOGGER.info("Step %.2f%%, %s", 100 * pos / len(languages), language)
        LOGGER.info("Fetch %d repos infos for language %s", nb_repos, language)
        repos = _retrieve_repo_details(language, nb_repos, token)
        LOGGER.info("%d repos details kept. Downloading", len(repos))
        _download_repos(language, repos, destination)
        LOGGER.info("Language %s repos downloaded", language)

    LOGGER.debug("Exit OK")