Prepare the commit message in tmp_file.

    It will build the commit message prefilling the component line, as well
    as the signature using the git author and the modified files.

    The file remains untouched if it is not empty.
180469
def _prepare_commit_msg(tmp_file, author, files_modified=None, template=None):
    
    files_modified = files_modified or []
    template = template or "{component}:\n\nSigned-off-by: {author}\n{extra}"
    if hasattr(template, "decode"):
        template = template.decode()

    with open(tmp_file, "r", "utf-8") as fh:
        contents = fh.readlines()
        msg = filter(lambda x: not (x.startswith("#") or x.isspace()),
                     contents)
        if len(list(msg)):
            return

    component = "unknown"
    components = _get_components(files_modified)

    if len(components) == 1:
        component = components[0]
    elif len(components) > 1:
        component = "/".join(components)
        contents.append(
            "# WARNING: Multiple components detected - consider splitting "
            "commit.\r\n"
        )

    with open(tmp_file, "w", "utf-8") as fh:
        fh.write(template.format(component=component,
                                 author=author,
                                 extra="".join(contents)))
272146
def write_log(self, message):
        
        if self.stream_log and not self.ended:
            # points to the Git stream write
            self.stream_log.write(message)
            return True
664446
def prepare
      raise AlreadyPreparedError.new(@path) if prepared?
      in_work_tree :tmp do
        FileUtils.touch '.silo'
        @git.add '.silo'
        @git.commit_index 'Enabled Silo for this repository'
      end
    end
154552
def git_commit(repo_dir, message=None, amend=False, stage=True):
    """"""
    if stage:
        git_add_all(repo_dir)
    command = ['git', 'commit', '--allow-empty']
    if amend:
        command.append('--amend')
        if not message:
            command.append('--no-edit')
    if message:
        command.extend(['--message', pipes.quote(message)])
    elif not amend:
        # if not amending and no message, allow an empty message
        command.extend(['--message=', '--allow-empty-message'])
    return execute_git_command(command, repo_dir=repo_dir)
1284076
def do_commit(repo, message_template, branch_name, hexsha):
    ""
    repo.git.add(repo.working_tree_dir)

    if not repo.git.diff(staged=True):
        _LOGGER.warning('No modified files in this Autorest run')
        return False

    checkout_and_create_branch(repo, branch_name)
    msg = message_template.format(hexsha=hexsha)
    commit = repo.index.commit(msg)
    _LOGGER.info("Commit done: %s", msg)
    return commit.hexsha
1045276
def commit(*args):
    """"""
    parser = argparse.ArgumentParser(prog="%s %s" % (__package__, commit.__name__), description=commit.__doc__)
    parser.add_argument('FILENAME', help="file(s) to commit", nargs="*", default=['.'])
    args = parser.parse_args(args)

    config = FragmentsConfig()

    for s, curr_path in _iterate_over_files(args.FILENAME, config, statuses='MAD'):
        key = os.path.relpath(curr_path, config.root)
        if key not in config['files']:
            yield "Could not commit '%s' because it is not being followed" % os.path.relpath(curr_path)
            continue

        if s in 'MA':
            repo_path = os.path.join(config.directory, config['files'][key])
            with _smart_open(repo_path, 'w') as repo_file:
                with _smart_open(curr_path, 'r') as curr_file:
                    repo_file.write(curr_file.read())
            os.utime(repo_path, os.stat(curr_path)[7:9])
            yield "'%s' committed" % os.path.relpath(curr_path)
        elif s == 'D':
            yield "Could not commit '%s' because it has been removed, instead revert or forget it" % os.path.relpath(curr_path)
        elif s == ' ':
            yield "Could not commit '%s' because it has not been changed" % os.path.relpath(curr_path)
543301
def commit(filename):
    
    try:
        repo = Repo()
        # gitcmd = repo.git
        # gitcmd.commit(filename)
        index = repo.index
        index.commit("Updated file: {0}".format(filename))
    except Exception as e:
        print("exception while commit: %s" % e.message)
791774
def amend_commit_message(self, cherry_pick_branch):
        

        commit_prefix = ""
        if self.prefix_commit:
            commit_prefix = f"[{get_base_branch(cherry_pick_branch)}] "
        updated_commit_message = f"""{commit_prefix}{self.get_commit_message(self.commit_sha1)}
(cherry picked from commit {self.commit_sha1})


Co-authored-by: {get_author_info_from_short_sha(self.commit_sha1)}"""
        if self.dry_run:
            click.echo(f"  dry-run: git commit --amend -m '{updated_commit_message}'")
        else:
            cmd = ["git", "commit", "--amend", "-m", updated_commit_message]
            try:
                subprocess.check_output(cmd, stderr=subprocess.STDOUT)
            except subprocess.CalledProcessError as cpe:
                click.echo("Failed to amend the commit message \u2639")
                click.echo(cpe.output)
        return updated_commit_message
507680
def set_commit(self, commit, logmsg=None):
        """"""
        # check the type - assume the best if it is a base-string
        invalid_type = False
        if isinstance(commit, Object):
            invalid_type = commit.type != Commit.type
        elif isinstance(commit, SymbolicReference):
            invalid_type = commit.object.type != Commit.type
        else:
            try:
                invalid_type = self.repo.rev_parse(commit).type != Commit.type
            except (BadObject, BadName):
                raise ValueError("Invalid object: %s" % commit)
            # END handle exception
        # END verify type

        if invalid_type:
            raise ValueError("Need commit, got %r" % commit)
        # END handle raise

        # we leave strings to the rev-parse method below
        self.set_object(commit, logmsg)

        return self
801225
public function beforeAction() : void
    {
        $this->repository->setCommitMsg(Git\CommitMessage::createFromFile($this->file, $this->commentChar));
        parent::beforeAction();
    }
26306
def commit_index(self, message):
        
        tree_id = self.write_tree()

        args = ['commit-tree', tree_id, '-p', self.ref_head]

        # todo, this can end in a race-condition with other processes adding commits
        commit = self.command_exec(args, message)[0].decode('utf-8').strip()
        self.command_exec(['update-ref', self.ref_head, commit])

        return commit
84878
def commit_source_archive(file, message)
      from_directory do
        result_dir = File.join(packages_dir, name)
        FileUtils.mkdir_p(result_dir)

        result_path = File.join(result_dir, File.basename(file))
        FileUtils.cp(file, result_path)
        @git.commit_file(result_path, "Source archive added")

        unarchiver = if file =~ /\.zip$/
                       Tetra::Unzip.new
                     else
                       Tetra::Tar.new
                     end

        Dir.glob(File.join("src", "*")).each { |f| FileUtils.rm_rf(f) }
        unarchiver.decompress(file, "src")
        commit_sources(message, true)
      end
    end
189009
def get_commit_command(self, message, author=None):
        """"""
        command = ['git']
        if author:
            command.extend(('-c', 'user.name=%s' % author.name))
            command.extend(('-c', 'user.email=%s' % author.email))
        command.append('commit')
        command.append('--all')
        command.append('--message')
        command.append(message)
        return command
21256
def modified_lines_in_file(file)
      @modified_lines ||= {}
      unless @modified_lines[file]
        @modified_lines[file] =
          Overcommit::GitRepo.extract_modified_lines(file, staged: true)

        # Include lines modified in last commit if amending
        if amendment?
          subcmd = 'show --format=%n'
          @modified_lines[file] +=
            Overcommit::GitRepo.extract_modified_lines(file, subcmd: subcmd)
        end
      end
      @modified_lines[file]
    end
489086
def merge(self, commit_message='', sha=None):
        
        parameters = {'commit_message': commit_message}
        if sha:
            parameters['sha'] = sha
        url = self._build_url('merge', base_url=self._api)
        json = self._json(self._put(url, data=dumps(parameters)), 200)
        self.merge_commit_sha = json['sha']
        return json['merged']
1138361
def commit(self, message=None):
        

        flags = filters.Items()

        if self._status:
            flags.add_flags(self._status)

        if self._code_review is not None:
            flags.add_flags("code-review %s" % self._code_review)

        if self._verified is not None:
            flags.add_flags("verified %s" % self._verified)

        if message:
            flags.add_flags("message '%s'" % message)

        query = ['gerrit', 'review', str(flags), str(self._review)]

        results = self.client.exec_command(' '.join(query))
        stdin, stdout, stderr = results

        # NOTE(flaper87): Log error messages
        error = []
        for line in stderr:
            error.append(line)

        # True if success
        return not error
16603
def set_config_from_commit(self, commit):
        
        for line in commit.message.body:
            pattern = re.compile(r"^gitlint-ignore:\s*(.*)")
            matches = pattern.match(line)
            if matches and len(matches.groups()) == 1:
                self.set_option('general', 'ignore', matches.group(1))