Create AUTHORS file using git commits.
328102
def generate_authors(git_dir):
    """"""
    authors = []
    emails = []
    git_log_cmd = ['git', 'log', '--format=%aN|%aE']
    tmp_authors = _run_shell_command(git_log_cmd, git_dir).split('\n')
    for author_str in tmp_authors:
        author, email = author_str.split('|')
        author = author.strip()
        email = email.strip()
        if author.lower() not in [x.lower() for x in authors]:
            if email.lower() not in [x.lower() for x in emails]:
                authors.append(author)
                emails.append(email)
    co_authors_raw = _run_shell_command(['git', 'log'], git_dir)
    co_authors = re.findall('Co-authored-by:.+', co_authors_raw,
                            re.MULTILINE)
    co_authors = [signed.split(":", 1)[1].strip().split('<')
                  for signed in co_authors if signed]
    for author_str in co_authors:
        author, email = author_str.split('<')
        author = author.strip()
        email = email[:-1].strip()
        if author.lower() not in [x.lower() for x in authors]:
            if email.lower() not in [x.lower() for x in emails]:
                authors.append(author)
                emails.append(email)
    authors = sorted(set(authors))
    return authors
344377
def do_create(marfile, files, compress, productversion=None, channel=None,
              signing_key=None, signing_algorithm=None):
    """"""
    with open(marfile, 'w+b') as f:
        with MarWriter(f, productversion=productversion, channel=channel,
                       signing_key=signing_key,
                       signing_algorithm=signing_algorithm,
                       ) as m:
            for f in files:
                m.add(f, compress=compress)
177459
public function collectFromGit()
    {
        // Initial git data
        $git = new Collection();

        $gitDirectory = $this->getDirectory().DIRECTORY_SEPARATOR.self::GIT_DIRECTORY;

        if (is_dir($gitDirectory)) {
            // Get refs info from HEAD
            $branch = '';
            $head = Yaml::parse($gitDirectory.DIRECTORY_SEPARATOR.self::GIT_HEAD);

            // @codeCoverageIgnoreStart
            if (is_array($head) && array_key_exists('ref', $head)) {
                $ref = $head['ref'];
                $r = explode('/', $ref);
                $branch = array_pop($r);
            } 
            // @codeCoverageIgnoreEnd

            // Assign branch information
            $git->set('branch', $branch);

            // Get log information
            $logRaw = self::execute('cd '.$this->getDirectory().';git log -1');
            $idRaw = $logRaw[0];
            $authorRaw = $logRaw[1];

            // Build head information
            if (strpos($authorRaw, '<') !== false) {
                 list($author, $email) = explode('<', str_replace('Author:', '', $authorRaw));

                $id = trim(str_replace('commit', '', $idRaw));
                $author_name = $committer_name = trim($author);
                $author_email = $committer_email = trim($email, '>');
                $message = $logRaw[4].(isset($logRaw[5]) ? '...' : '');
            }
           

            // Assign Head information
            $git->set('head', compact('id', 'author_name', 'author_email', 
                            'committer_name', 'committer_email', 'message'));

            // Get remotes information
            $remotes = array();
            $configRaw = self::execute('cd '.$this->getDirectory().';git config --local -l');
            array_walk($configRaw,function($v) use(&$remotes)
            {
                if (0 === strpos($v, 'remote')) {
                    list($key, $prop) = explode('=', $v);
                    $k = explode('.', $key);
                    $attribute = array_pop($k);
                    $name = array_pop($k);
                    $remotes[$name]['name'] = $name;
                    $remotes[$name][$attribute] = $prop;
                }
            });

            // Assign Remotes information
            $git->set('remotes', array_values($remotes));
        }

        return $git;
    }
622034
def publish(self):
        '''
        
        '''

        self.cleanup

        remote = self.remote
        branch = self.branch
        return self.m(
            'pushing changes to %s/%s' % (remote, branch),
            cmdd=dict(
                cmd='git push -u %s %s' % (remote, branch),
                cwd=self.local
            ),
            more=dict(remote=remote, branch=branch)
        )
46979
def get_authors(repo_path, from_commit):
    
    repo = dulwich.repo.Repo(repo_path)
    refs = get_refs(repo)
    start_including = False
    authors = set()

    if from_commit is None:
        start_including = True

    for commit_sha, children in reversed(
        get_children_per_first_parent(repo_path).items()
    ):
        commit = get_repo_object(repo, commit_sha)
        if (
            start_including or commit_sha.startswith(from_commit) or
            fuzzy_matches_refs(from_commit, refs.get(commit_sha, []))
        ):
            authors.add(commit.author.decode())
            for child in children:
                authors.add(child.author.decode())

            start_including = True

    return '\n'.join(sorted(authors))
1026034
def create(cls, user_id, github_id=None, name=None, **kwargs):
        """"""
        with db.session.begin_nested():
            obj = cls(user_id=user_id, github_id=github_id, name=name,
                      **kwargs)
            db.session.add(obj)
        return obj
903448
def create_user(username, rsa_pub_key, rsa_pub_key_name)
      key_name = "#{username}@#{rsa_pub_key_name}"
      key_path = @configuration.user_key_path(key_name)

      if users_public_keys().include?(key_path)
        raise ::Gitolite::Duplicate, "Public key (#{rsa_pub_key_name}) already exists for user (#{username}) on gitolite server"
      end

      add_commit_file(key_path,rsa_pub_key, "Added public key (#{rsa_pub_key_name}) for user (#{username}) ")

      key_path
    end
346864
def get_authors(project_dir=os.curdir):
    
    authors = set()
    pkg_info_file = os.path.join(project_dir, 'PKG-INFO')
    authors_file = os.path.join(project_dir, 'AUTHORS')
    if os.path.exists(pkg_info_file) and os.path.exists(authors_file):
        with open(authors_file) as authors_fd:
            authors = set(authors_fd.read().splitlines())
    else:
        authors = api.get_authors(repo_path=project_dir)

    return authors
421049
def merge_user_commits(cls, commits):
        
        user = None
        for commit in commits:
            if not user:
                user = commit
            else:
                if commit.committer_time > user.committer_time:
                    commit.line_count += user.line_count
                    user = commit
                else:
                    user.line_count += commit.line_count
        return user
587082
def write_doc_from_tmpfile(self,
                               doc_id,
                               tmpfi,
                               parent_sha,
                               auth_info,
                               commit_msg='',
                               doctype_display_name="document"):
        
        gh_user, author = get_user_author(auth_info)
        doc_filepath = self.path_for_doc(doc_id)
        doc_dir = os.path.split(doc_filepath)[0]
        if parent_sha is None:
            self.checkout_master()
            parent_sha = self.get_master_sha()
        branch = self.create_or_checkout_branch(gh_user, doc_id, parent_sha)

        # build complete (probably type-specific) commit message
        default_commit_msg = "Update %s '%s' via OpenTree API" % (doctype_display_name, doc_id)
        if commit_msg:
            commit_msg = "%s\n\n(%s)" % (commit_msg, default_commit_msg)
        else:
            commit_msg = default_commit_msg

        # create a doc directory if this is a new document  EJM- what if it isn't?
        if not os.path.isdir(doc_dir):
            os.makedirs(doc_dir)

        if os.path.exists(doc_filepath):
            prev_file_sha = self.get_blob_sha_for_file(doc_filepath)
        else:
            prev_file_sha = None
        shutil.copy(tmpfi.name, doc_filepath)
        self._add_and_commit(doc_filepath, author, commit_msg)
        new_sha = git(self.gitdir, self.gitwd, "rev-parse", "HEAD")
        _LOG.debug('Committed document "{i}" to branch "{b}" commit SHA: "{s}"'.format(i=doc_id,
                                                                                       b=branch,
                                                                                       s=new_sha.strip()))
        return {'commit_sha': new_sha.strip(),
                'branch': branch,
                'prev_file_sha': prev_file_sha,
                }
1019188
def get_git_info():
    """"""
    start_dir = abspath(curdir)
    try:
        chdir(dirname(abspath(__file__)))
        re_patt_str = (r'commit\s+(?P<commit_hash>\w+).*?Author:\s+'
                       r'(?P<author_name>.*?)\s+<(?P<author_email>.*?)>\s+Date:\s+'
                       r'(?P<date>.*?)\n\s+(?P<commit_msg>.*?)(?:\ndiff.*?)?$')
        show_out = check_output(['git', 'show']).decode('ascii')
        revp_out = check_output(['git', 'rev-parse', '--abbrev-ref', 'HEAD'])
        revp_out = revp_out.decode('ascii').strip()
        m = re.search(re_patt_str, show_out, re.DOTALL)
        assert m is not None, \
            "Regex pattern:\n\n\"%s\"\n\n failed to match string:\n\n\"%s\"" \
            % (re_patt_str, show_out)
        ret_dict = m.groupdict()
        ret_dict['branch_name'] = revp_out
    finally:
        chdir(start_dir)
    return ret_dict
902473
def create_or_update_release(user, pwd, secret, repo_slug, changelog_file, doc_url, data_file, tag):
    
    # 1- AUTHENTICATION
    if user is not None and secret is None:
        # using username and password
        # validate('user', user, instance_of=str)
        assert isinstance(user, str)
        # validate('pwd', pwd, instance_of=str)
        assert isinstance(pwd, str)
        g = Github(user, pwd)
    elif user is None and secret is not None:
        # or using an access token
        # validate('secret', secret, instance_of=str)
        assert isinstance(secret, str)
        g = Github(secret)
    else:
        raise ValueError("You should either provide username/password OR an access token")
    click.echo("Logged in as {user_name}".format(user_name=g.get_user()))

    # 2- CHANGELOG VALIDATION
    regex_pattern = "[\s\S]*[\n][#]+[\s]*(?P<title>[\S ]*%s[\S ]*)[\n]+?(?P<body>[\s\S]*?)[\n]*?(\n#|$)" % re.escape(tag)
    changelog_section = re.compile(regex_pattern)
    if changelog_file is not None:
        # validate('changelog_file', changelog_file, custom=os.path.exists,
        #          help_msg="changelog file should be a valid file path")
        assert os.path.exists(changelog_file), "changelog file should be a valid file path"
        with open(changelog_file) as f:
            contents = f.read()

        match = changelog_section.match(contents).groupdict()
        if match is None or len(match) != 2:
            raise ValueError("Unable to find changelog section matching regexp pattern in changelog file.")
        else:
            title = match['title']
            message = match['body']
    else:
        title = tag
        message = ''

    # append footer if doc url is provided
    message += "\n\nSee [documentation page](%s) for details." % doc_url

    # 3- REPOSITORY EXPLORATION
    # validate('repo_slug', repo_slug, instance_of=str, min_len=1, help_msg="repo_slug should be a non-empty string")
    assert isinstance(repo_slug, str) and len(repo_slug) > 0, "repo_slug should be a non-empty string"
    repo = g.get_repo(repo_slug)

    # -- Is there a tag with that name ?
    try:
        tag_ref = repo.get_git_ref("tags/" + tag)
    except UnknownObjectException:
        raise ValueError("No tag with name %s exists in repository %s" % (tag, repo.name))

    # -- Is there already a release with that tag name ?
    click.echo("Checking if release %s already exists in repository %s" % (tag, repo.name))
    try:
        release = repo.get_release(tag)
        if release is not None:
            raise ValueError("Release %s already exists in repository %s. Please set overwrite to True if you wish to "
                             "update the release (Not yet supported)" % (tag, repo.name))
    except UnknownObjectException:
        # Release does not exist: we can safely create it.
        click.echo("Creating release %s on repo: %s" % (tag, repo.name))
        click.echo("Release title: '%s'" % title)
        click.echo("Release message:\n--\n%s\n--\n" % message)
        repo.create_git_release(tag=tag, name=title,
                                message=message,
                                draft=False, prerelease=False)

        # add the asset file if needed
        if data_file is not None:
            release = None
            while release is None:
                release = repo.get_release(tag)
            release.upload_asset(path=data_file, label=path.split(data_file)[1], content_type="application/gzip")
528428
def new(self, repo):
        
        #TODO: subclass Commit, pass parent as init param
        try:
            # create new commit instance and set metadata
            commit = Commit()
            author = os.environ.get('USER')
            commit.author = commit.committer = author
            commit.commit_time = commit.author_time = int(time())
            tz = parse_timezone('-0200')[0]
            commit.commit_timezone = commit.author_timezone = tz
            commit.encoding = "UTF-8"
            commit.message = ''

            # set previous version as parent to this one
            parent = repo.versions(-1)
            if parent:
                commit.parents = [parent.id]

            # create new tree, add entries from previous version
            tree = Tree()
            curr = repo.versions(-1)
            if curr:
                for item in curr.items():
                    tree.addItem(item)
            commit.tree = tree.id

            # create new version, and add tree
            version = Version(repo=repo, commit=commit, tree=tree)
            return version

        except Exception, e:
            traceback.print_exc()
            return VersionError(e)
369624
def author_from_git(self):
        
        self.author = None
        try:
            encoding = locale.getdefaultlocale()[1]
            # launch git command and get answer
            cmd = Popen(["git", "config", "--get", "user.name"], stdout=PIPE)
            stdoutdata = cmd.communicate().decode(encoding)
            if (stdoutdata[0]):
                import ipdb;ipdb.set_trace()
                author = stdoutdata[0].rstrip(os.linesep)
                self.author = author#.decode('utf8')
        except ImportError:
            pass
        except CalledProcessError:
            pass
        except OSError:
            pass

        return self.author
584662
def _write_master_branch_resource(self, content, fn, commit_msg, is_json=False):
        
        # TODO: we might want this to push, but currently it is only called in contexts in which
        # we are about to push anyway (document creation)
        with self._master_branch_repo_lock:
            ga = self._create_git_action_for_global_resource()
            with ga.lock():
                ga.checkout_master()
                if is_json:
                    write_as_json(content, fn)
                else:
                    write_to_filepath(content, fn)
                ga._add_and_commit(fn, self._infrastructure_commit_author, commit_msg)
1155500
def pre_commit_hook(argv):
    """"""
    options = get_options()
    # Check if the repo has a configuration repo
    options.update(_read_local_kwalitee_configuration())

    files = []
    for filename in _get_files_modified():
        # get the staged version of the file and
        # write the staged version to temp dir with its full path to
        # avoid overwriting files with the same name
        _, stdout, _ = run("git show :{0}".format(filename), raw_output=True)
        files.append((filename, stdout))

    errors = _pre_commit(files, options)

    for error in errors:
        if hasattr(error, "decode"):
            error = error.decode()
        click.echo(error, file=sys.stderr)

    if errors:
        click.echo(
            "Aborting commit due to kwalitee errors (override with "
            "'git commit --no-verify').",
            file=sys.stderr)
        raise click.Abort
    return 0
723215
def create(self, repo_name, scm='git', private=True, **kwargs):
        
        url = self.bitbucket.url('CREATE_REPO')
        return self.bitbucket.dispatch('POST', url, auth=self.bitbucket.auth, name=repo_name, scm=scm, is_private=private, **kwargs)