Given a source line in `git diff` output, return the path
        to the source file.
341168
def _parse_source_line(self, line):
        
        if '--git' in line:
            regex = self.SRC_FILE_RE
        elif '--cc' in line:
            regex = self.MERGE_CONFLICT_RE
        else:
            msg = "Do not recognize format of source in line '{}'".format(line)
            raise GitDiffError(msg)

        # Parse for the source file path
        groups = regex.findall(line)

        if len(groups) == 1:
            return groups[0]

        else:
            msg = "Could not parse source path in line '{}'".format(line)
            raise GitDiffError(msg)
1368225
def from_git_rev_read(path):
    """"""
    if ":" not in path:
        raise ValueError("Path identifier must start with a revision hash.")

    cmd = "git", "show", "-t", path
    try:
        return subprocess.check_output(cmd).rstrip().decode("utf-8")
    except subprocess.CalledProcessError:
        raise ValueError
980986
def extract_repo(path, destination, reference)
      fail 'Git not installed' unless Utils.command? 'git'
      Dir.chdir path do
        system "git archive #{reference} | tar -x -C #{destination}"
      end
    end
541459
def diff(path_from, path_to, ignore_empty = False):
  
  fh_from = open(path_from, 'rb')
  fh_to = open(path_to, 'rb')
  diffs = file_diff(fh_from, fh_to, ignore_empty)
  fh_to.close()
  fh_from.close()
  return diffs
1049241
def get_git_changeset():
    """"""
    git_log = Popen(
        'git log --pretty=format:%ct --quiet -1 HEAD',
        stdout=PIPE, stderr=PIPE, shell=True, universal_newlines=True)
    timestamp = git_log.communicate()[0]
    try:
        timestamp = datetime.utcfromtimestamp(int(timestamp))
    except ValueError:
        return None
    return timestamp.strftime('%Y%m%d%H%M%S')
901916
def subtree_diff(path = Dir.pwd)
      raise ArgumentError, "Git 'subtree' command is not available" unless FalkorLib::Git.command? "subtree"
      if FalkorLib.config.git[:subtrees].empty?
        FalkorLib::Git.config_warn(:subtrees)
        return 1
      end
      exit_status = 0
      git_root_dir = rootdir(path)
      Dir.chdir(git_root_dir) do
        FalkorLib.config.git[:subtrees].each do |dir, conf|
          next if conf[:url].nil?
          #url    = conf[:url]
          remote = dir.gsub(/\//, '-')
          branch = (conf[:branch].nil?) ? 'master' : conf[:branch]
          remotes = FalkorLib::Git.remotes
          raise IOError, "The git remote '#{remote}' is not configured" unless remotes.include?( remote )
          raise IOError, "The git subtree directory '#{dir}' does not exists" unless File.directory?( File.join(git_root_dir, dir) )
          info "Git diff on subtree '#{dir}' with remote '#{remote}/#{branch}'"
          exit_status = execute "git diff #{remote}/#{branch} #{FalkorLib::Git.branch?( git_root_dir )}:#{dir}"
        end
      end
      exit_status
    end
1360339
def _get_diff(self):
        """"""
        diff = []
        self._create_sot_file()
        diff_out = self._send_command(
            "show diff rollback-patch file {} file {}".format(
                "sot_file", self.candidate_cfg
            ),
            raw_text=True,
        )
        try:
            diff_out = (
                diff_out.split("Generating Rollback Patch")[1]
                .replace("Rollback Patch is Empty", "")
                .strip()
            )
            for line in diff_out.splitlines():
                if line:
                    if line[0].strip() != "!" and line[0].strip() != ".":
                        diff.append(line.rstrip(" "))
        except (AttributeError, KeyError):
            raise ReplaceConfigException(
                "Could not calculate diff. It's possible the given file doesn't exist."
            )
        return "\n".join(diff)
364539
def find_config(revision):
    """"""
    if not is_git_repo():
        return None

    cfg_path = f"{revision}:.cherry_picker.toml"
    cmd = "git", "cat-file", "-t", cfg_path

    try:
        output = subprocess.check_output(cmd, stderr=subprocess.STDOUT)
        path_type = output.strip().decode("utf-8")
        return cfg_path if path_type == "blob" else None
    except subprocess.CalledProcessError:
        return None
630482
def diff( path, options={} )
      raise Svn::Error, "cannot diff directory #{path}@#{to_s}" if dir? path

      other = options[:with] if options[:with].is_a? Root
      other = repo.revision(options[:with]) if options[:with].is_a? Numeric
      other ||= repo.revision(to_i - 1)

      return other.diff( path, :with => self ) if other < self

      content = ""
      begin
        content = file_content_stream( path ).to_counted_string
      rescue Svn::Error => err
        raise if options[:raise_errors]
      end

      other_content = ""
      begin
        other_content= other.file_content_stream( path ).to_counted_string
      rescue Svn::Error => err
        raise if options[:raise_errors]
      end

      Diff.string_diff( content, other_content ).unified(
          :original_header => "#{path}@#{to_s}",
          :modified_header => "#{path}@#{other}"
        )
    end
965835
def get_versions():
    """"""
    # I am in _version.py, which lives at ROOT/VERSIONFILE_SOURCE. If we have
    # __file__, we can work backwards from there to the root. Some
    # py2exe/bbfreeze/non-CPython implementations don't do __file__, in which
    # case we can only use expanded keywords.

    cfg = get_config()
    verbose = cfg.verbose

    try:
        return git_versions_from_keywords(get_keywords(), cfg.tag_prefix,
                                          verbose)
    except NotThisMethod:
        pass

    try:
        root = os.path.realpath(__file__)
        # versionfile_source is the relative path from the top of the source
        # tree (where the .git directory might live) to this file. Invert
        # this to find the root from __file__.
        for i in cfg.versionfile_source.split('/'):
            root = os.path.dirname(root)
    except NameError:
        return {"version": "0+unknown", "full-revisionid": None,
                "dirty": None,
                "error": "unable to find root of source tree"}

    try:
        pieces = git_pieces_from_vcs(cfg.tag_prefix, root, verbose)
        return render(pieces, cfg.style)
    except NotThisMethod:
        pass

    try:
        if cfg.parentdir_prefix:
            return versions_from_parentdir(cfg.parentdir_prefix, root, verbose)
    except NotThisMethod:
        pass

    _version_path = os.path.join(os.path.dirname(__file__), '_version')
    if os.path.exists(_version_path):
        with open(_version_path) as f:
            l = f.readline().strip()
            return {
                'version': l,
                'error': None,
                'dirty': None,
                'full-revisionid': l
            }

    return {"version": "0+unknown", "full-revisionid": None,
            "dirty": None,
            "error": "unable to compute version"}
1113541
def source(self, getline=linecache.getline):
        
        try:
            return getline(self.filename, self.lineno)
        except Exception as exc:
            return "??? NO SOURCE: {!r}".format(exc)
994540
def get_sha(path=None, log=None, short=False, timeout=None):
    
    # git_command = "git rev-parse HEAD {}".format(repo_name).split()
    # git_command = "git rev-parse HEAD".split()
    git_command = ["git", "rev-parse"]
    if short:
        git_command.append("--short")
    git_command.append("HEAD")

    kwargs = {}
    if path is not None:
        kwargs['cwd'] = path
    if timeout is not None:
        kwargs['timeout'] = timeout

    if log is not None:
        log.debug("{} {}".format(git_command, str(kwargs)))

    sha = subprocess.check_output(git_command, **kwargs)
    try:
        sha = sha.decode('ascii').strip()
    except:
        if log is not None:
            log.debug("decode of '{}' failed".format(sha))

    return sha
1104633
def get_diff_text(old, new, filename):
    """"""
    newline = '\n'
    diff = difflib.unified_diff(
        old, new,
        'original/' + filename,
        'fixed/' + filename,
        lineterm=newline)

    text = ''
    for line in diff:
        text += line

        # Work around missing newline (http://bugs.python.org/issue2142).
        if text and not line.endswith(newline):
            text += newline + r'\ No newline at end of file' + newline

    return text
1224317
def get_src_path(self, obj, append_base=True):
        
        path = getsourcefile(obj)
        if self.src_root not in path:
            # this can happen with e.g.
            # inlinefunc-wrapped functions
            if hasattr(obj, "__module__"):
                path = "%s.%s" % (obj.__module__, obj.__name__)
            else:
                path = obj.__name__
            path = path.replace(".", "/")
        pre, post = path.rsplit(self.src_root + "/", 1)

        lineno = self.get_line_no(obj)
        lineno = "" if lineno is None else "#L{}".format(lineno)

        path = self.src_root + "/" + post + lineno
        if append_base:
            path = os.path.join(self.github_link, path)
        return path
602881
function getFilePath(sourcePath, filename, subDir) {
    if (subDir === void 0) { subDir = ''; }
    var filePath = filename
        .replace(path.resolve(sourcePath), '')
        .replace(path.basename(filename), '');
    if (subDir) {
        filePath = filePath.replace(subDir + path.sep, '');
    }
    if (/^[\/\\]/.test(filePath)) {
        filePath = filePath.substr(1);
    }
    return filePath.replace(/\\/g, '/');
}
239157
def get_modified_files():
    """"""
    c = subprocess.Popen(
        ["git", "diff-index", "--cached", "--name-only", "HEAD"], stdout=subprocess.PIPE
    )
    return c.communicate()[0].splitlines()
620853
def from_path(cls, path):
        """"""
        f = GitFile(path, 'rb')
        try:
            ret = cls.from_file(f)
            ret.path = path
            return ret
        finally:
            f.close()