Git Filter Repo
Git Filter Repo
/usr/bin/env python3
"""
git-filter-repo filters git repositories, similar to git filter-branch, BFG
repo cleaner, and others. The basic idea is that it works by running
git fast-export <options> | filter | git fast-import <options>
where this program not only launches the whole pipeline but also serves as
the 'filter' in the middle. It does a few additional things on top as well
in order to make it into a well-rounded filtering tool.
If there are particular pieces of the API you are concerned about, and
there is not already a testcase for it in t9391-lib-usage.sh or
t9392-python-callback.sh, please contribute a testcase. That will not
prevent me from changing the API, but it will allow you to look at the
history of a testcase to see whether and how the API changed.
***** END API BACKWARD COMPATIBILITY CAVEAT *****
"""
import argparse
import collections
import fnmatch
import gettext
import io
import os
import platform
import re
import shutil
import subprocess
import sys
import time
import textwrap
# The globals to make visible to callbacks. They will see all our imports for
# free, as well as our public API.
public_globals = ["__builtins__", "argparse", "collections", "fnmatch",
"gettext", "io", "os", "platform", "re", "shutil",
"subprocess", "sys", "time", "textwrap", "tzinfo",
"timedelta", "datetime"] + __all__
deleted_hash = b'0'*40
write_marks = True
date_format_permissive = True
def gettext_poison(msg):
if "GIT_TEST_GETTEXT_POISON" in os.environ: # pragma: no cover
return "# GETTEXT POISON #"
return gettext.gettext(msg)
_ = gettext_poison
def setup_gettext():
TEXTDOMAIN="git-filter-repo"
podir = os.environ.get("GIT_TEXTDOMAINDIR") or "@@LOCALEDIR@@"
if not os.path.isdir(podir): # pragma: no cover
podir = None # Python has its own fallback; use that
def _timedelta_to_seconds(delta):
"""
Converts timedelta to seconds
"""
offset = delta.days*86400 + delta.seconds + (delta.microseconds+0.0)/1000000
return round(offset)
class FixedTimeZone(tzinfo):
"""
Fixed offset in minutes east from UTC.
"""
tz_re = re.compile(br'^([-+]?)(\d\d)(\d\d)$')
def date_to_string(dateobj):
epoch = datetime.fromtimestamp(0, dateobj.tzinfo)
return(b'%d %s' % (int(_timedelta_to_seconds(dateobj - epoch)),
dateobj.tzinfo.tzname(0)))
def decode(bytestr):
'Try to convert bytestr to utf-8 for outputting as an error message.'
return bytestr.decode('utf-8', 'backslashreplace')
def glob_to_regex(glob_bytestr):
'Translate glob_bytestr into a regex on bytestrings'
class PathQuoting:
_unescape = {b'a': b'\a',
b'b': b'\b',
b'f': b'\f',
b'n': b'\n',
b'r': b'\r',
b't': b'\t',
b'v': b'\v',
b'"': b'"',
b'\\':b'\\'}
_unescape_re = re.compile(br'\\([a-z"\\]|[0-9]{3})')
_escape = [bytes([x]) for x in range(127)]+[
b'\\'+bytes(ord(c) for c in oct(x)[2:]) for x in range(127,256)]
_reverse = dict(map(reversed, _unescape.items()))
for x in _reverse:
_escape[ord(x)] = b'\\'+_reverse[x]
_special_chars = [len(x) > 1 for x in _escape]
@staticmethod
def unescape_sequence(orig):
seq = orig.group(1)
return PathQuoting._unescape[seq] if len(seq) == 1 else bytes([int(seq, 8)])
@staticmethod
def dequote(quoted_string):
if quoted_string.startswith(b'"'):
assert quoted_string.endswith(b'"')
return PathQuoting._unescape_re.sub(PathQuoting.unescape_sequence,
quoted_string[1:-1])
return quoted_string
@staticmethod
def enquote(unquoted_string):
# Option 1: Quoting when fast-export would:
# pqsc = PathQuoting._special_chars
# if any(pqsc[x] for x in set(unquoted_string)):
# Option 2, perf hack: do minimal amount of quoting required by fast-import
if unquoted_string.startswith(b'"') or b'\n' in unquoted_string:
pqe = PathQuoting._escape
return b'"' + b''.join(pqe[x] for x in unquoted_string) + b'"'
return unquoted_string
class AncestryGraph(object):
"""
A class that maintains a direct acycle graph of commits for the purpose of
determining if one commit is the ancestor of another.
def __init__(self):
# The next internal identifier we will use; increments with every commit
# added to the AncestryGraph
self.cur_value = 0
# Determine depth for commit, then insert the info into the graph
depth = 1
if parents:
depth += max(self.graph[p][0] for p in graph_parents)
self.graph[self.cur_value] = (depth, graph_parents)
def _ensure_reverse_maps_populated(self):
if not self._hash_to_id:
assert not self._reverse_value
self._hash_to_id = {v: k for k, v in self.git_hash.items()}
self._reverse_value = {v: k for k, v in self.value.items()}
class MailmapInfo(object):
def __init__(self, filename):
self.changes = {}
self._parse_file(filename)
m = name_and_email_re.match(line)
if not m:
raise SystemExit(err)
proper_name, proper_email = m.groups()
if len(line) == m.end():
self.changes[(None, proper_email)] = (proper_name, proper_email)
continue
rest = line[m.end():]
m = name_and_email_re.match(rest)
if m:
commit_name, commit_email = m.groups()
if len(rest) != m.end():
raise SystemExit(err)
else:
commit_name, commit_email = rest, None
self.changes[(commit_name, commit_email)] = (proper_name, proper_email)
class ProgressWriter(object):
def __init__(self):
self._last_progress_update = time.time()
self._last_message = None
def finish(self):
self._last_progress_update = 0
if self._last_message:
self.show(self._last_message)
sys.stdout.write("\n")
class _IDs(object):
"""
A class that maintains the 'name domain' of all the 'marks' (short int
id for a blob/commit git object). There are two reasons this mechanism
is necessary:
(1) the output text of fast-export may refer to an object using a different
mark than the mark that was assigned to that object using IDS.new().
(This class allows you to translate the fast-export marks, "old" to
the marks assigned from IDS.new(), "new").
(2) when we prune a commit, its "old" id becomes invalid. Any commits
which had that commit as a parent needs to use the nearest unpruned
ancestor as its parent instead.
Note that for purpose (1) above, this typically comes about because the user
manually creates Blob or Commit objects (for insertion into the stream).
It could also come about if we attempt to read the data from two different
repositories and trying to combine the data (git fast-export will number ids
from 1...n, and having two 1's, two 2's, two 3's, causes issues; granted, we
this scheme doesn't handle the two streams perfectly either, but if the first
fast export stream is entirely processed and handled before the second stream
is started, this mechanism may be sufficient to handle it).
"""
def __init__(self):
"""
Init
"""
# The id for the next created blob/commit object
self._next_id = 1
# A map of new-ids to every old-id that points to the new-id (1:N map)
self._reverse_translation = {}
def has_renames(self):
"""
Return whether there have been ids remapped to new values
"""
return bool(self._translation)
def new(self):
"""
Should be called whenever a new blob or commit object is created. The
returned value should be used as the id/mark for that object.
"""
rv = self._next_id
self._next_id += 1
return rv
def __str__(self):
"""
Convert IDs to string; used for debugging
"""
rv = "Current count: %d\nTranslation:\n" % self._next_id
for k in sorted(self._translation):
rv += " %d -> %s\n" % (k, self._translation[k])
rv += "Reverse translation:\n"
reverse_keys = list(self._reverse_translation.keys())
if None in reverse_keys: # pragma: no cover
reverse_keys.remove(None)
reverse_keys = sorted(reverse_keys)
reverse_keys.append(None)
for k in reverse_keys:
rv += " " + str(k) + " -> " + str(self._reverse_translation[k]) + "\n"
return rv
class _GitElement(object):
"""
The base class for all git elements that we create.
"""
def __init__(self):
# A string that describes what type of Git element this is
self.type = None
def __bytes__(self):
"""
Convert GitElement to bytestring; used for debugging
"""
old_dumped = self.dumped
writeme = io.BytesIO()
self.dump(writeme)
output_lines = writeme.getvalue().splitlines()
writeme.close()
self.dumped = old_dumped
return b"%s:\n %s" % (type(self).__name__.encode(),
b"\n ".join(output_lines))
class _GitElementWithId(_GitElement):
"""
The base class for Git elements that have IDs (commits and blobs)
"""
def __init__(self):
_GitElement.__init__(self)
class Blob(_GitElementWithId):
"""
This class defines our representation of git blob elements (i.e. our
way of representing file contents).
"""
# Record original id
self.original_id = original_id
file_.write(b'blob\n')
file_.write(b'mark :%d\n' % self.id)
file_.write(b'data %d\n%s' % (len(self.data), self.data))
file_.write(b'\n')
class Reset(_GitElement):
"""
This class defines our representation of git reset elements. A reset
event is the creation (or recreation) of a named branch, optionally
starting from a specific revision).
"""
class FileChange(_GitElement):
"""
This class defines our representation of file change elements. File change
elements are components within a Commit element.
"""
# Denote the type of file-change (b'M' for modify, b'D' for delete, etc)
# We could
# assert(type(type_) == bytes)
# here but I don't just due to worries about performance overhead...
self.type = type_
if type_ == b'DELETEALL':
assert filename is None and id_ is None and mode is None
self.filename = b'' # Just so PathQuoting.enquote doesn't die
else:
assert filename is not None
if type_ == b'M':
assert id_ is not None and mode is not None
elif type_ == b'D':
assert id_ is None and mode is None
elif type_ == b'R': # pragma: no cover (now avoid fast-export renames)
assert mode is None
if id_ is None:
raise SystemExit(_("new name needed for rename of %s") % filename)
self.filename = (self.filename, id_)
self.blob_id = None
def dump(self, file_):
"""
Write this file-change element to a file
"""
skipped_blob = (self.type == b'M' and self.blob_id is None)
if skipped_blob: return
self.dumped = 1
quoted_filename = PathQuoting.enquote(self.filename)
if self.type == b'M' and isinstance(self.blob_id, int):
file_.write(b'M %s :%d %s\n' % (self.mode, self.blob_id, quoted_filename))
elif self.type == b'M':
file_.write(b'M %s %s %s\n' % (self.mode, self.blob_id, quoted_filename))
elif self.type == b'D':
file_.write(b'D %s\n' % quoted_filename)
elif self.type == b'DELETEALL':
file_.write(b'deleteall\n')
else:
raise SystemExit(_("Unhandled filechange type: %s") % self.type) # pragma: no
cover
class Commit(_GitElementWithId):
"""
This class defines our representation of commit elements. Commit elements
contain all the information associated with a commit.
"""
# Record original id
self.original_id = original_id
self.parents = parents
if not self.parents:
file_.write(b'reset %s\n' % self.branch)
file_.write((b'commit %s\n'
b'mark :%d\n'
b'author %s <%s> %s\n'
b'committer %s <%s> %s\n'
) % (
self.branch, self.id,
self.author_name, self.author_email, self.author_date,
self.committer_name, self.committer_email, self.committer_date
))
if self.encoding:
file_.write(b'encoding %s\n' % self.encoding)
file_.write(b'data %d\n%s%s' %
(len(self.message), self.message, extra_newline))
for i, parent in enumerate(self.parents):
file_.write(b'from ' if i==0 else b'merge ')
if isinstance(parent, int):
file_.write(b':%d\n' % parent)
else:
file_.write(b'%s\n' % parent)
for change in self.file_changes:
change.dump(file_)
if not self.parents and not self.file_changes:
# Workaround a bug in pre-git-2.22 versions of fast-import with
# the get-mark directive.
file_.write(b'\n')
file_.write(b'\n')
def first_parent(self):
"""
Return first parent commit
"""
if self.parents:
return self.parents[0]
return None
class Tag(_GitElementWithId):
"""
This class defines our representation of annotated tag elements.
"""
# Record original id
self.original_id = original_id
self.dumped = 1
class Progress(_GitElement):
"""
This class defines our representation of progress elements. The progress
element only contains a progress message, which is printed by fast-import
when it processes the progress output.
"""
class Checkpoint(_GitElement):
"""
This class defines our representation of checkpoint elements. These
elements represent events which force fast-import to close the current
packfile, start a new one, and to save out all current branch refs, tags
and marks.
"""
def __init__(self):
_GitElement.__init__(self)
file_.write(b'checkpoint\n')
file_.write(b'\n')
class LiteralCommand(_GitElement):
"""
This class defines our representation of commands. The literal command
includes only a single line, and is not processed in any special way.
"""
file_.write(self.line)
class Alias(_GitElement):
"""
This class defines our representation of fast-import alias elements. An
alias element is the setting of one mark to the same sha1sum as another,
usually because the newer mark corresponded to a pruned commit.
"""
self.ref = ref
self.to_ref = to_ref
class FastExportParser(object):
"""
A class for parsing and handling the output from fast-export. This
class allows the user to register callbacks when various types of
data are encountered in the fast-export output. The basic idea is that,
FastExportParser takes fast-export output, creates the various objects
as it encounters them, the user gets to use/modify these objects via
callbacks, and finally FastExportParser outputs the modified objects
in fast-import format (presumably so they can be used to create a new
repo).
"""
def __init__(self,
tag_callback = None, commit_callback = None,
blob_callback = None, progress_callback = None,
reset_callback = None, checkpoint_callback = None,
done_callback = None):
# Members below simply store callback functions for the various git
# elements
self._tag_callback = tag_callback
self._blob_callback = blob_callback
self._reset_callback = reset_callback
self._commit_callback = commit_callback
self._progress_callback = progress_callback
self._checkpoint_callback = checkpoint_callback
self._done_callback = done_callback
# Keep track of which refs appear from the export, and which make it to
# the import (pruning of empty commits, renaming of refs, and creating
# new manual objects and inserting them can cause these to differ).
self._exported_refs = set()
self._imported_refs = set()
# A list of the branches we've seen, plus the last known commit they
# pointed to. An entry in latest_*commit will be deleted if we get a
# reset for that branch. These are used because of fast-import's weird
# decision to allow having an implicit parent via naming the branch
# instead of requiring branches to be specified via 'from' directives.
self._latest_commit = {}
self._latest_orig_commit = {}
# A handle to the output file for the output we generate (we call dump
# on many of the git elements we create).
self._output = None
def _advance_currentline(self):
"""
Grab the next line of input
"""
self._currentline = self._input.readline()
def _parse_optional_mark(self):
"""
If the current line contains a mark, parse it and advance to the
next line; return None otherwise
"""
mark = None
matches = self._mark_re.match(self._currentline)
if matches:
mark = int(matches.group(1))
self._advance_currentline()
return mark
def _parse_optional_filechange(self):
"""
If the current line contains a file-change object, then parse it
and advance the current line; otherwise return None. We only care
about file changes of type b'M' and b'D' (these are the only types
of file-changes that fast-export will provide).
"""
filechange = None
changetype = self._currentline[0:1]
if changetype == b'M':
(changetype, mode, idnum, path) = self._currentline.split(None, 3)
if idnum[0:1] == b':':
idnum = idnum[1:]
path = path.rstrip(b'\n')
# We translate the idnum to our id system
if len(idnum) != 40:
idnum = _IDS.translate( int(idnum) )
if idnum is not None:
if path.startswith(b'"'):
path = PathQuoting.dequote(path)
filechange = FileChange(b'M', path, idnum, mode)
else:
filechange = b'skipped'
self._advance_currentline()
elif changetype == b'D':
(changetype, path) = self._currentline.split(None, 1)
path = path.rstrip(b'\n')
if path.startswith(b'"'):
path = PathQuoting.dequote(path)
filechange = FileChange(b'D', path)
self._advance_currentline()
elif changetype == b'R': # pragma: no cover (now avoid fast-export renames)
rest = self._currentline[2:-1]
if rest.startswith(b'"'):
m = self._quoted_string_re.match(rest)
if not m:
raise SystemExit(_("Couldn't parse rename source"))
orig = PathQuoting.dequote(m.group(0))
new = rest[m.end()+1:]
else:
orig, new = rest.split(b' ', 1)
if new.startswith(b'"'):
new = PathQuoting.dequote(new)
filechange = FileChange(b'R', orig, new)
self._advance_currentline()
return filechange
def _parse_original_id(self):
original_id = self._currentline[len(b'original-oid '):].rstrip()
self._advance_currentline()
return original_id
def _parse_encoding(self):
encoding = self._currentline[len(b'encoding '):].rstrip()
self._advance_currentline()
return encoding
self._advance_currentline()
return (name, email, when)
def _parse_data(self):
"""
Reads data from _input. Current-line will be advanced until it is beyond
the data.
"""
fields = self._currentline.split()
assert fields[0] == b'data'
size = int(fields[1])
data = self._input.read(size)
self._advance_currentline()
if self._currentline == b'\n':
self._advance_currentline()
return data
def _parse_blob(self):
"""
Parse input data into a Blob object. Once the Blob has been created, it
will be handed off to the appropriate callbacks. Current-line will be
advanced until it is beyond this blob's data. The Blob will be dumped
to _output once everything else is done (unless it has been skipped by
the callback).
"""
# Parse the Blob
self._advance_currentline()
id_ = self._parse_optional_mark()
original_id = None
if self._currentline.startswith(b'original-oid'):
original_id = self._parse_original_id();
data = self._parse_data()
if self._currentline == b'\n':
self._advance_currentline()
# If fast-export text had a mark for this blob, need to make sure this
# mark translates to the blob's true id.
if id_:
blob.old_id = id_
_IDS.record_rename(id_, blob.id)
def _parse_reset(self):
"""
Parse input data into a Reset object. Once the Reset has been created,
it will be handed off to the appropriate callbacks. Current-line will
be advanced until it is beyond the reset data. The Reset will be dumped
to _output once everything else is done (unless it has been skipped by
the callback).
"""
# Parse the Reset
ref = self._parse_ref_line(b'reset')
self._exported_refs.add(ref)
ignoreme, from_ref = self._parse_optional_parent_ref(b'from')
if self._currentline == b'\n':
self._advance_currentline()
# Update metadata
self._latest_commit[reset.ref] = reset.from_ref
self._latest_orig_commit[reset.ref] = reset.from_ref
def _parse_commit(self):
"""
Parse input data into a Commit object. Once the Commit has been created,
it will be handed off to the appropriate callbacks. Current-line will
be advanced until it is beyond the commit data. The Commit will be dumped
to _output once everything else is done (unless it has been skipped by
the callback OR the callback has removed all file-changes from the commit).
"""
# Parse the Commit. This may look involved, but it's pretty simple; it only
# looks bad because a commit object contains many pieces of data.
branch = self._parse_ref_line(b'commit')
self._exported_refs.add(branch)
id_ = self._parse_optional_mark()
original_id = None
if self._currentline.startswith(b'original-oid'):
original_id = self._parse_original_id();
author_name = None
author_email = None
if self._currentline.startswith(b'author'):
(author_name, author_email, author_date) = self._parse_user(b'author')
commit_msg = self._parse_data()
pinfo = [self._parse_optional_parent_ref(b'from')]
# Due to empty pruning, we can have real 'from' and 'merge' lines that
# due to commit rewriting map to a parent of None. We need to record
# 'from' if its non-None, and we need to parse all 'merge' lines.
while self._currentline.startswith(b'merge '):
pinfo.append(self._parse_optional_parent_ref(b'merge'))
orig_parents, parents = [list(tmp) for tmp in zip(*pinfo)]
# If fast-export text had a mark for this commit, need to make sure this
# mark translates to the commit's true id.
if id_:
commit.old_id = id_
_IDS.record_rename(id_, commit.id)
def _parse_tag(self):
"""
Parse input data into a Tag object. Once the Tag has been created,
it will be handed off to the appropriate callbacks. Current-line will
be advanced until it is beyond the tag data. The Tag will be dumped
to _output once everything else is done (unless it has been skipped by
the callback).
"""
# Parse the Tag
tag = self._parse_ref_line(b'tag')
self._exported_refs.add(b'refs/tags/'+tag)
id_ = self._parse_optional_mark()
ignoreme, from_ref = self._parse_optional_parent_ref(b'from')
original_id = None
if self._currentline.startswith(b'original-oid'):
original_id = self._parse_original_id();
# If fast-export text had a mark for this tag, need to make sure this
# mark translates to the tag's true id.
if id_:
tag.old_id = id_
_IDS.record_rename(id_, tag.id)
# The tag might not point at anything that still exists (self.from_ref
# will be None if the commit it pointed to and all its ancestors were
# pruned due to being empty)
if tag.from_ref:
# Print out this tag's information
if not tag.dumped:
self._imported_refs.add(b'refs/tags/'+tag.ref)
tag.dump(self._output)
else:
tag.skip()
def _parse_progress(self):
"""
Parse input data into a Progress object. Once the Progress has
been created, it will be handed off to the appropriate
callbacks. Current-line will be advanced until it is beyond the
progress data. The Progress will be dumped to _output once
everything else is done (unless it has been skipped by the callback).
"""
# Parse the Progress
message = self._parse_ref_line(b'progress')
if self._currentline == b'\n':
self._advance_currentline()
# Call any user callback to allow them to modify the progress messsage
if self._progress_callback:
self._progress_callback(progress)
def _parse_checkpoint(self):
"""
Parse input data into a Checkpoint object. Once the Checkpoint has
been created, it will be handed off to the appropriate
callbacks. Current-line will be advanced until it is beyond the
checkpoint data. The Checkpoint will be dumped to _output once
everything else is done (unless it has been skipped by the callback).
"""
# Parse the Checkpoint
self._advance_currentline()
if self._currentline == b'\n':
self._advance_currentline()
def _parse_literal_command(self):
"""
Parse literal command. Then just dump the line as is.
"""
# Create the literal command object
command = LiteralCommand(self._currentline)
self._advance_currentline()
def get_exported_and_imported_refs(self):
return self._exported_refs, self._imported_refs
def record_id_rename(old_id, new_id):
"""
Register a new translation
"""
handle_transitivity = True
_IDS.record_rename(old_id, new_id, handle_transitivity)
# Internal globals
_IDS = _IDs()
_SKIPPED_COMMITS = set()
BLOB_HASH_TO_NEW_ID = {}
class SubprocessWrapper(object):
@staticmethod
def decodify(args):
if type(args) == str:
return args
else:
assert type(args) == list
return [decode(x) if type(x)==bytes else x for x in args]
@staticmethod
def call(*args, **kwargs):
if 'cwd' in kwargs:
kwargs['cwd'] = decode(kwargs['cwd'])
return subprocess.call(SubprocessWrapper.decodify(*args), **kwargs)
@staticmethod
def check_output(*args, **kwargs):
if 'cwd' in kwargs:
kwargs['cwd'] = decode(kwargs['cwd'])
return subprocess.check_output(SubprocessWrapper.decodify(*args), **kwargs)
@staticmethod
def check_call(*args, **kwargs): # pragma: no cover # used by filter-lamely
if 'cwd' in kwargs:
kwargs['cwd'] = decode(kwargs['cwd'])
return subprocess.check_call(SubprocessWrapper.decodify(*args), **kwargs)
@staticmethod
def Popen(*args, **kwargs):
if 'cwd' in kwargs:
kwargs['cwd'] = decode(kwargs['cwd'])
return subprocess.Popen(SubprocessWrapper.decodify(*args), **kwargs)
subproc = subprocess
if platform.system() == 'Windows' or 'PRETEND_UNICODE_ARGS' in os.environ:
subproc = SubprocessWrapper
class GitUtils(object):
@staticmethod
def get_commit_count(repo, *args):
"""
Return the number of commits that have been made on repo.
"""
if not args:
args = ['--all']
if len(args) == 1 and isinstance(args[0], list):
args = args[0]
p = subproc.Popen(["git", "rev-list", "--count"] + args,
stdout=subprocess.PIPE, stderr=subprocess.PIPE,
cwd=repo)
if p.wait() != 0:
raise SystemExit(_("%s does not appear to be a valid git repository")
% decode(repo))
return int(p.stdout.read())
@staticmethod
def get_total_objects(repo):
"""
Return the number of objects (both packed and unpacked)
"""
p1 = subproc.Popen(["git", "count-objects", "-v"],
stdout=subprocess.PIPE, cwd=repo)
lines = p1.stdout.read().splitlines()
# Return unpacked objects + packed-objects
return int(lines[0].split()[1]) + int(lines[2].split()[1])
@staticmethod
def is_repository_bare(repo_working_dir):
out = subproc.check_output('git rev-parse --is-bare-repository'.split(),
cwd=repo_working_dir)
return (out.strip() == b'true')
@staticmethod
def determine_git_dir(repo_working_dir):
d = subproc.check_output('git rev-parse --git-dir'.split(),
cwd=repo_working_dir).strip()
if repo_working_dir==b'.' or d.startswith(b'/'):
return d
return os.path.join(repo_working_dir, d)
@staticmethod
def get_refs(repo_working_dir):
try:
output = subproc.check_output('git show-ref'.split(),
cwd=repo_working_dir)
except subprocess.CalledProcessError as e:
# If error code is 1, there just aren't any refs; i.e. new repo.
# If error code is other than 1, some other error (e.g. not a git repo)
if e.returncode != 1:
raise SystemExit('fatal: {}'.format(e))
output = ''
return dict(reversed(x.split()) for x in output.splitlines())
@staticmethod
def get_config_settings(repo_working_dir):
output = ''
try:
output = subproc.check_output('git config --list'.split(),
cwd=repo_working_dir)
except subprocess.CalledProcessError as e: # pragma: no cover
raise SystemExit('fatal: {}'.format(e))
# FIXME: Ignores multi-valued keys, just let them overwrite for now
return dict(line.split(b'=', maxsplit=1)
for line in output.strip().split(b"\n"))
@staticmethod
def get_blob_sizes(quiet = False):
blob_size_progress = ProgressWriter()
num_blobs = 0
processed_blobs_msg = _("Processed %d blob sizes")
@staticmethod
def get_file_changes(repo, parent_hash, commit_hash):
"""
Return a FileChanges list with the differences between parent_hash
and commit_hash
"""
file_changes = []
return file_changes
@staticmethod
def print_my_version():
with open(__file__, 'br') as f:
contents = f.read()
# If people replaced @@LOCALEDIR@@ string to point at their local
# directory, undo it so we can get original source version.
contents = re.sub(br'\A#\!.*',
br'#!/usr/bin/env python3', contents)
contents = re.sub(br'(\("GIT_TEXTDOMAINDIR"\) or ").*"',
br'\1@@LOCALEDIR@@"', contents)
class FilteringOptions(object):
default_replace_text = b'***REMOVED***'
class AppendFilter(argparse.Action):
def __call__(self, parser, namespace, values, option_string=None):
user_path = values
suffix = option_string[len('--path-'):] or 'match'
if suffix.startswith('rename'):
mod_type = 'rename'
match_type = option_string[len('--path-rename-'):] or 'match'
values = values.split(b':')
if len(values) != 2:
raise SystemExit(_("Error: --path-rename expects one colon in its"
" argument: <old_name:new_name>."))
if values[0] and values[1] and not (
values[0].endswith(b'/') == values[1].endswith(b'/')):
raise SystemExit(_("Error: With --path-rename, if OLD_NAME and "
"NEW_NAME are both non-empty and either ends "
"with a slash then both must."))
if any(v.startswith(b'/') for v in values):
raise SystemExit(_("Error: Pathnames cannot begin with a '/'"))
components = values[0].split(b'/') + values[1].split(b'/')
else:
mod_type = 'filter'
match_type = suffix
components = values.split(b'/')
if values.startswith(b'/'):
raise SystemExit(_("Error: Pathnames cannot begin with a '/'"))
for illegal_path in [b'.', b'..']:
if illegal_path in components:
raise SystemExit(_("Error: Invalid path component '%s' found in '%s'")
% (decode(illegal_path), decode(user_path)))
if match_type == 'regex':
values = re.compile(values)
items = getattr(namespace, self.dest, []) or []
items.append((mod_type, match_type, values))
if (match_type, mod_type) == ('glob', 'filter'):
if not values.endswith(b'*'):
extension = b'*' if values.endswith(b'/') else b'/*'
items.append((mod_type, match_type, values+extension))
setattr(namespace, self.dest, items)
class HelperFilter(argparse.Action):
def __call__(self, parser, namespace, values, option_string=None):
af = FilteringOptions.AppendFilter(dest='path_changes',
option_strings=None)
dirname = values if values[-1:] == b'/' else values+b'/'
if option_string == '--subdirectory-filter':
af(parser, namespace, dirname, '--path-match')
af(parser, namespace, dirname+b':', '--path-rename')
elif option_string == '--to-subdirectory-filter':
af(parser, namespace, b':'+dirname, '--path-rename')
else:
raise SystemExit(_("Error: HelperFilter given invalid option_string: %s")
% option_string) # pragma: no cover
class FileWithPathsFilter(argparse.Action):
def __call__(self, parser, namespace, values, option_string=None):
if not namespace.path_changes:
namespace.path_changes = []
namespace.path_changes += FilteringOptions.get_paths_from_file(values)
@staticmethod
def create_arg_parser():
# Include usage in the summary, so we can put the description first
summary = _('''Rewrite (or analyze) repository history
Basic Usage:
git-filter-repo --analyze
git-filter-repo [FILTER/RENAME/CONTROL OPTIONS]
All callback functions are of the same general format. For a command line
argument like
--foo-callback 'BODY'
Note that if BODY resolves to a filename, then the contents of that file
will be used as the BODY in the callback function.
EXAMPLES
(These reports can help you choose how to filter your repo; it can
be useful to re-run this command after filtering to regenerate the
report and verify the changes look correct.)
To extract the history of 'src/', rename all files to have a new leading
directory 'my-module' (e.g. src/foo.java -> my-module/src/foo.java), and
add a 'my-module-' prefix to all tags:
git filter-repo --path src/ --to-subdirectory-filter my-module --tag-rename
'':'my-module-'
formatter_class=argparse.RawDescriptionHelpFormatter)
analyze = parser.add_argument_group(title=_("Analysis"))
analyze.add_argument('--analyze', action='store_true',
help=_("Analyze repository history and create a report that may be "
"useful in determining what to filter in a subsequent run. "
"Will not modify your repo."))
analyze.add_argument('--report-dir',
metavar='DIR_OR_FILE',
type=os.fsencode,
dest='report_dir',
help=_("Directory to write report, defaults to
GIT_DIR/filter_repo/analysis,"
"refuses to run if exists, --force delete existing dir first."))
callback.add_argument('--blob-callback', metavar="FUNCTION_BODY_OR_FILE",
help=_("Python code body for processing blob objects; see "
"CALLBACKS section below."))
callback.add_argument('--commit-callback', metavar="FUNCTION_BODY_OR_FILE",
help=_("Python code body for processing commit objects; see "
"CALLBACKS section below."))
callback.add_argument('--tag-callback', metavar="FUNCTION_BODY_OR_FILE",
help=_("Python code body for processing tag objects. Note that "
"lightweight tags have no tag object and are thus not "
"handled by this callback. See CALLBACKS section below."))
callback.add_argument('--reset-callback', metavar="FUNCTION_BODY_OR_FILE",
help=_("Python code body for processing reset objects; see "
"CALLBACKS section below."))
desc = _(
"Specifying alternate source or target locations implies --partial,\n"
"except that the normal default for --replace-refs is used. However,\n"
"unlike normal uses of --partial, this doesn't risk mixing old and new\n"
"history since the old and new histories are in different repositories.")
location = parser.add_argument_group(title=_("Location to filter from/to"),
description=desc)
location.add_argument('--source', type=os.fsencode,
help=_("Git repository to read from"))
location.add_argument('--target', type=os.fsencode,
help=_("Git repository to overwrite with filtered history"))
misc.add_argument('--dry-run', action='store_true',
help=_("Do not change the repository. Run `git fast-export` and "
"filter its output, and save both the original and the "
"filtered version for comparison. This also disables "
"rewriting commit messages due to not knowing new commit "
"IDs and disables filtering of some empty commits due to "
"inability to query the fast-import backend." ))
misc.add_argument('--debug', action='store_true',
help=_("Print additional information about operations being "
"performed and commands being run. When used together "
"with --dry-run, also show extra information about what "
"would be run."))
# WARNING: --state-branch has some problems:
# * It does not work well with manually inserted objects (user creating
# Blob() or Commit() or Tag() objects and calling
# RepoFilter.insert(obj) on them).
# * It does not work well with multiple source or multiple target repos
# * It doesn't work so well with pruning become-empty commits (though
# --refs doesn't work so well with it either)
# These are probably fixable, given some work (e.g. re-importing the
# graph at the beginning to get the AncestryGraph right, doing our own
# export of marks instead of using fast-export --export-marks, etc.), but
# for now just hide the option.
misc.add_argument('--state-branch',
#help=_("Enable incremental filtering by saving the mapping of old "
# "to new objects to the specified branch upon exit, and"
# "loading that mapping from that branch (if it exists) "
# "upon startup."))
help=argparse.SUPPRESS)
misc.add_argument('--stdin', action='store_true',
help=_("Instead of running `git fast-export` and filtering its "
"output, filter the fast-export stream from stdin. The "
"stdin must be in the expected input format (e.g. it needs "
"to include original-oid directives)."))
misc.add_argument('--quiet', action='store_true',
help=_("Pass --quiet to other git commands called"))
return parser
@staticmethod
def sanity_check_args(args):
if args.analyze and args.path_changes:
raise SystemExit(_("Error: --analyze is incompatible with --path* flags; "
"it's a read-only operation."))
if args.analyze and args.stdin:
raise SystemExit(_("Error: --analyze is incompatible with --stdin."))
# If no path_changes are found, initialize with empty list but mark as
# not inclusive so that all files match
if args.path_changes == None:
args.path_changes = []
args.inclusive = False
else:
# Similarly, if we have no filtering paths, then no path should be
# filtered out. Based on how newname() works, the easiest way to
# achieve that is setting args.inclusive to False.
if not any(x[0] == 'filter' for x in args.path_changes):
args.inclusive = False
# Also check for incompatible --use-base-name and --path-rename flags.
if args.use_base_name:
if any(x[0] == 'rename' for x in args.path_changes):
raise SystemExit(_("Error: --use-base-name and --path-rename are "
"incompatible."))
# Also throw some sanity checks on git version here;
# PERF: remove these checks once new enough git versions are common
p = subproc.Popen('git fast-export -h'.split(),
stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
output = p.stdout.read()
if b'--anonymize-map' not in output: # pragma: no cover
global date_format_permissive
date_format_permissive = False
if not any(x in output for x in [b'--mark-tags',b'--[no-]mark-tags']): #
pragma: no cover
global write_marks
write_marks = False
if args.state_branch:
# We need a version of git-fast-export with --mark-tags
raise SystemExit(_("Error: need git >= 2.24.0"))
if not any(x in output for x in [b'--reencode', b'--[no-]reencode']): #
pragma: no cover
if args.preserve_commit_encoding:
# We need a version of git-fast-export with --reencode
raise SystemExit(_("Error: need git >= 2.23.0"))
else:
# Set args.preserve_commit_encoding to None which we'll check for later
# to avoid passing --reencode=yes to fast-export (that option was the
# default prior to git-2.23)
args.preserve_commit_encoding = None
# If we don't have fast-exoprt --reencode, we may also be missing
# diff-tree --combined-all-paths, which is even more important...
p = subproc.Popen('git diff-tree -h'.split(),
stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
output = p.stdout.read()
if b'--combined-all-paths' not in output:
# We need a version of git-diff-tree with --combined-all-paths
raise SystemExit(_("Error: need git >= 2.22.0"))
# End of sanity checks on git version
if args.max_blob_size:
suffix = args.max_blob_size[-1]
if suffix not in '1234567890':
mult = {'K': 1024, 'M': 1024**2, 'G': 1024**3}
if suffix not in mult:
raise SystemExit(_("Error: could not parse --strip-blobs-bigger-than"
" argument %s")
% args.max_blob_size)
args.max_blob_size = int(args.max_blob_size[0:-1]) * mult[suffix]
else:
args.max_blob_size = int(args.max_blob_size)
@staticmethod
def get_replace_text(filename):
replace_literals = []
replace_regexes = []
with open(filename, 'br') as f:
for line in f:
line = line.rstrip(b'\r\n')
@staticmethod
def get_paths_from_file(filename):
new_path_changes = []
with open(filename, 'br') as f:
for line in f:
line = line.rstrip(b'\r\n')
@staticmethod
def default_options():
return FilteringOptions.parse_args([], error_on_empty = False)
@staticmethod
def parse_args(input_args, error_on_empty = True):
parser = FilteringOptions.create_arg_parser()
if not input_args and error_on_empty:
parser.print_usage()
raise SystemExit(_("No arguments specified."))
args = parser.parse_args(input_args)
if args.help:
parser.print_help()
raise SystemExit()
if args.paths:
raise SystemExit("Error: Option `--paths` unrecognized; did you mean --path
or --paths-from-file?")
if args.version:
GitUtils.print_my_version()
raise SystemExit()
FilteringOptions.sanity_check_args(args)
if args.mailmap:
args.mailmap = MailmapInfo(args.mailmap)
if args.replace_text:
args.replace_text = FilteringOptions.get_replace_text(args.replace_text)
if args.replace_message:
args.replace_message =
FilteringOptions.get_replace_text(args.replace_message)
if args.strip_blobs_with_ids:
with open(args.strip_blobs_with_ids, 'br') as f:
args.strip_blobs_with_ids = set(f.read().split())
else:
args.strip_blobs_with_ids = set()
if (args.partial or args.refs) and not args.replace_refs:
args.replace_refs = 'update-no-add'
args.repack = not (args.partial or args.refs or args.no_gc)
if args.refs or args.source or args.target:
args.partial = True
if not args.refs:
args.refs = ['--all']
return args
class RepoAnalyze(object):
@staticmethod
def equiv_class(stats, filename):
return stats['equivalence'].get(filename, (filename,))
@staticmethod
def setup_equivalence_for_rename(stats, oldname, newname):
# if A is renamed to B and B is renamed to C, then the user thinks of
# A, B, and C as all being different names for the same 'file'. We record
# this as an equivalence class:
# stats['equivalence'][name] = (A,B,C)
# for name being each of A, B, and C.
old_tuple = stats['equivalence'].get(oldname, ())
if newname in old_tuple:
return
elif old_tuple:
new_tuple = tuple(list(old_tuple)+[newname])
else:
new_tuple = (oldname, newname)
for f in new_tuple:
stats['equivalence'][f] = new_tuple
@staticmethod
def setup_or_update_rename_history(stats, commit, oldname, newname):
rename_commits = stats['rename_history'].get(oldname, set())
rename_commits.add(commit)
stats['rename_history'][oldname] = rename_commits
@staticmethod
def handle_renames(stats, commit, change_types, filenames):
for index, change_type in enumerate(change_types):
if change_type == ord(b'R'):
oldname, newname = filenames[index], filenames[-1]
RepoAnalyze.setup_equivalence_for_rename(stats, oldname, newname)
RepoAnalyze.setup_or_update_rename_history(stats, commit,
oldname, newname)
@staticmethod
def handle_file(stats, graph, commit, modes, shas, filenames):
mode, sha, filename = modes[-1], shas[-1], filenames[-1]
# Figure out kind of deletions to undo for this file, and update lists
# of all-names-by-sha and all-filenames
delmode = 'tree_deletions'
if mode != b'040000':
delmode = 'file_deletions'
stats['names'][sha].add(filename)
stats['allnames'].add(filename)
# If we get a modify/add for a path that was renamed, we may need to break
# the equivalence class. However, if the modify/add was on a branch that
# doesn't have the rename in its history, we are still okay.
need_to_break_equivalence = False
if equiv[-1] != filename:
for rename_commit in stats['rename_history'][filename]:
if graph.is_ancestor(rename_commit, commit):
need_to_break_equivalence = True
if need_to_break_equivalence:
for f in equiv:
if f in stats['equivalence']:
del stats['equivalence'][f]
@staticmethod
def analyze_commit(stats, graph, commit, parents, date, file_changes):
graph.add_commit_and_parents(commit, parents)
for change in file_changes:
modes, shas, change_types, filenames = change
if len(parents) == 1 and change_types.startswith(b'R'):
change_types = b'R' # remove the rename score; we don't care
if modes[-1] == b'160000':
continue
elif modes[-1] == b'000000':
# Track when files/directories are deleted
for f in RepoAnalyze.equiv_class(stats, filenames[-1]):
if any(x == b'040000' for x in modes[0:-1]):
stats['tree_deletions'][f] = date
else:
stats['file_deletions'][f] = date
elif change_types.strip(b'AMT') == b'':
RepoAnalyze.handle_file(stats, graph, commit, modes, shas, filenames)
elif modes[-1] == b'040000' and change_types.strip(b'RAM') == b'':
RepoAnalyze.handle_file(stats, graph, commit, modes, shas, filenames)
elif change_types.strip(b'RAMT') == b'':
RepoAnalyze.handle_file(stats, graph, commit, modes, shas, filenames)
RepoAnalyze.handle_renames(stats, commit, change_types, filenames)
else:
raise SystemExit(_("Unhandled change type(s): %(change_type)s "
"(in commit %(commit)s)")
% ({'change_type': change_types, 'commit': commit})
) # pragma: no cover
@staticmethod
def gather_data(args):
unpacked_size, packed_size = GitUtils.get_blob_sizes()
stats = {'names': collections.defaultdict(set),
'allnames' : set(),
'file_deletions': {},
'tree_deletions': {},
'equivalence': {},
'rename_history': collections.defaultdict(set),
'unpacked_size': unpacked_size,
'packed_size': packed_size,
'num_commits': 0}
# Show the final commits processed message and record the number of commits
commit_parse_progress.finish()
stats['num_commits'] = num_commits
return stats
@staticmethod
def write_report(reportdir, stats):
def datestr(datetimestr):
return datetimestr if datetimestr else _('<present>').encode()
def dirnames(path):
while True:
path = os.path.dirname(path)
yield path
if path == b'':
break
dir_deleted_data = {}
for name in dir_size['packed']:
dir_deleted_data[name] = stats['tree_deletions'].get(name, None)
Also, the sum of the packed sizes can add up to more than the
repository size; if the same contents appeared in the repository in
multiple places, git will automatically de-dupe and store only one
copy, while the way sizes are added in this analysis adds the size
for each file path that has those contents. Further, if a file is
ever reverted to a previous version's contents, the previous
version's size will be counted multiple times in this analysis, even
though git will only store it once.
""")[1:]).encode())
f.write(b"\n")
f.write(("=== %s ===\n" % _("Deletions")).encode())
f.write(textwrap.dedent(_("""
Whether a file is deleted is not a binary quality, since it can be
deleted on some branches but still exist in others. Also, it might
exist in an old tag, but have been deleted in versions newer than
that. More thorough tracking could be done, including looking at
merge commits where one side of history deleted and the other modified,
in order to give a more holistic picture of deletions. However, that
algorithm would not only be more complex to implement, it'd also be
quite difficult to present and interpret by users. Since --analyze
is just about getting a high-level rough picture of history, it instead
implements the simplistic rule that is good enough for 98% of cases:
A file is marked as deleted if the last commit in the fast-export
stream that mentions the file lists it as deleted.
This makes it dependent on topological ordering, but generally gives
the "right" answer.
""")[1:]).encode())
f.write(b"\n")
f.write(("=== %s ===\n" % _("Renames")).encode())
f.write(textwrap.dedent(_("""
Renames share the same non-binary nature that deletions do, plus
additional challenges:
* If the renamed file is renamed again, instead of just two names for
a path you can have three or more.
* Rename pairs of the form (oldname, newname) that we consider to be
different names of the "same file" might only be valid over certain
commit ranges. For example, if a new commit reintroduces a file
named oldname, then new versions of oldname aren't the "same file"
anymore. We could try to portray this to the user, but it's easier
for the user to just break the pairing and only report unbroken
rename pairings to the user.
* The ability for users to rename files differently in different
branches means that our chains of renames will not necessarily be
linear but may branch out.
""")[1:]).encode())
f.write(b"\n")
@staticmethod
def run(args):
if args.report_dir:
reportdir = args.report_dir
else:
git_dir = GitUtils.determine_git_dir(b'.')
if os.path.isdir(reportdir):
if args.force:
sys.stdout.write(_("Warning: Removing recursively: \"%s\"") %
decode(reportdir))
shutil.rmtree(reportdir)
else:
sys.stdout.write(_("Error: dir already exists (use --force to
delete): \"%s\"\n") % decode(reportdir))
sys.exit(1)
os.mkdir(reportdir)
class InputFileBackup:
def __init__(self, input_file, output_file):
self.input_file = input_file
self.output_file = output_file
def close(self):
self.input_file.close()
self.output_file.close()
def readline(self):
line = self.input_file.readline()
self.output_file.write(line)
return line
class DualFileWriter:
def __init__(self, file1, file2):
self.file1 = file1
self.file2 = file2
def flush(self):
self.file1.flush()
self.file2.flush()
def close(self):
self.file1.close()
self.file2.close()
class RepoFilter(object):
def __init__(self,
args,
filename_callback = None,
message_callback = None,
name_callback = None,
email_callback = None,
refname_callback = None,
blob_callback = None,
commit_callback = None,
tag_callback = None,
reset_callback = None,
done_callback = None):
self._args = args
# Names of files that were tweaked in any commit; such paths could lead
# to subsequent commits being empty
self._files_tweaked = set()
# A set of original_ids (i.e. original hashes) for which we have not yet
# gotten the new hashses; the value is always the corresponding fast-export
# id (i.e. commit.id)
self._pending_renames = collections.OrderedDict()
# Other vars
self._sanity_checks_handled = False
self._finalize_handled = False
self._orig_refs = None
self._config_settings = {}
self._newnames = {}
self._stash = None
def _handle_arg_callbacks(self):
def make_callback(argname, str):
callback_globals = {g: globals()[g] for g in public_globals}
callback_locals = {}
exec('def callback({}, _do_not_use_this_var = None):\n'.format(argname)+
' '+'\n '.join(str.splitlines()), callback_globals, callback_locals)
return callback_locals['callback']
def handle(type):
callback_field = '_{}_callback'.format(type)
code_string = getattr(self._args, type+'_callback')
if code_string:
if os.path.exists(code_string):
with open(code_string, 'r', encoding='utf-8') as f:
code_string = f.read()
if getattr(self, callback_field):
raise SystemExit(_("Error: Cannot pass a %s_callback to RepoFilter "
"AND pass --%s-callback"
% (type, type)))
if 'return ' not in code_string and \
type not in ('blob', 'commit', 'tag', 'reset'):
raise SystemExit(_("Error: --%s-callback should have a return statement")
% type)
setattr(self, callback_field, make_callback(type, code_string))
handle('filename')
handle('message')
handle('name')
handle('email')
handle('refname')
handle('blob')
handle('commit')
handle('tag')
handle('reset')
def _run_sanity_checks(self):
self._sanity_checks_handled = True
if not self._managed_output:
if not self._args.replace_refs:
# If not _managed_output we don't want to make extra changes to the
# repo, so set default to no-op 'update-no-add'
self._args.replace_refs = 'update-no-add'
return
if self._args.debug:
print("[DEBUG] Passed arguments:\n{}".format(self._args))
if response.lower() != 'y':
os.remove(ran_path)
already_ran = False
@staticmethod
def loose_objects_are_replace_refs(git_dir, refs, num_loose_objects):
replace_objects = set()
for refname, rev in refs.items():
if not refname.startswith(b'refs/replace/'):
continue
replace_objects.add(rev)
validobj_re = re.compile(rb'^[0-9a-f]{40}$')
object_dir=os.path.join(git_dir, b'objects')
for root, dirs, files in os.walk(object_dir):
for filename in files:
objname = os.path.basename(root)+filename
if objname not in replace_objects and validobj_re.match(objname):
return False
return True
@staticmethod
def sanity_check(refs, is_bare, config_settings):
def abort(reason):
dirname = config_settings.get(b'remote.origin.url', b'')
msg = ""
if dirname and os.path.isdir(dirname):
msg = _("Note: when cloning local repositories, you need to pass\n"
" --no-local to git clone to avoid this issue.\n")
raise SystemExit(
_("Aborting: Refusing to destructively overwrite repo history since\n"
"this does not look like a fresh clone.\n"
" (%s)\n%s"
"Please operate on a fresh clone instead. If you want to proceed\n"
"anyway, use --force.") % (reason, msg))
# Avoid letting people running with weird setups and overwriting GIT_DIR
# elsewhere
git_dir = GitUtils.determine_git_dir(b'.')
if is_bare and git_dir != b'.':
abort(_("GIT_DIR must be ."))
elif not is_bare and git_dir != b'.git':
abort(_("GIT_DIR must be .git"))
# Make sure repo is fully packed, just like a fresh clone would be.
# Note that transfer.unpackLimit defaults to 100, meaning that a
# repository with no packs and less than 100 objects should be considered
# fully packed.
output = subproc.check_output('git count-objects -v'.split())
stats = dict(x.split(b': ') for x in output.splitlines())
num_packs = int(stats[b'packs'])
num_loose_objects = int(stats[b'count'])
if num_packs > 1 or \
num_loose_objects >= 100 or \
(num_packs == 1 and num_loose_objects > 0 and
not RepoFilter.loose_objects_are_replace_refs(git_dir, refs,
num_loose_objects)):
abort(_("expected freshly packed repo"))
# Make sure there is precisely one remote, named "origin"...or that this
# is a new bare repo with no packs and no remotes
output = subproc.check_output('git remote'.split()).strip()
if not (output == b"origin" or (num_packs == 0 and not output)):
abort(_("expected one remote, origin"))
# Read through the pending renames until we find it or we've read them all,
# and return whatever we might find
self._flush_renames(old_hash)
return self._commit_renames.get(old_hash, None)
Returns a tuple:
(parents, new_first_parent_if_would_become_non_merge)'''
# Remove duplicate parents (if both sides of history have lots of commits
# which become empty due to pruning, the most recent ancestor on both
# sides may be the same commit), except only remove parents that have
# been rewritten due to previous empty pruning.
seen = set()
seen_add = seen.add
# Deleting duplicate rewritten parents means keeping parents if either
# they have not been seen or they are ones that have not been rewritten.
parents_copy = parents
uniq = [[p, orig_parents[i], is_rewritten[i]] for i, p in enumerate(parents)
if not (p in seen or seen_add(p)) or not is_rewritten[i]]
parents, orig_parents, is_rewritten = [list(x) for x in zip(*uniq)]
if len(parents) < 2:
return parents_copy, parents[0]
# Flatten unnecessary merges. (If one side of history is entirely
# empty commits that were pruned, we may end up attempting to
# merge a commit with its ancestor. Remove parents that are an
# ancestor of another parent.)
num_parents = len(parents)
to_remove = []
for cur in range(num_parents):
if not is_rewritten[cur]:
continue
for other in range(num_parents):
if cur == other:
continue
if not self._graph.is_ancestor(parents[cur], parents[other]):
continue
# parents[cur] is an ancestor of parents[other], so parents[cur]
# seems redundant. However, if it was intentionally redundant
# (e.g. a no-ff merge) in the original, then we want to keep it.
if not always_prune and \
self._orig_graph.is_ancestor(orig_parents[cur],
orig_parents[other]):
continue
# Some folks want their history to have all first parents be merge
# commits (except for any root commits), and always do a merge --no-ff.
# For such folks, don't remove the first parent even if it's an
# ancestor of other commits.
if self._args.no_ff and cur == 0:
continue
# Okay so the cur-th parent is an ancestor of the other-th parent,
# and it wasn't that way in the original repository; mark the
# cur-th parent as removable.
to_remove.append(cur)
break # cur removed, so skip rest of others -- i.e. check cur+=1
for x in reversed(to_remove):
parents.pop(x)
if len(parents) < 2:
return parents_copy, parents[0]
if self._args.prune_empty == 'never':
return False
always_prune = (self._args.prune_empty == 'always')
if len(parents) < 2:
# Special logic for commits that started empty...
if not had_file_changes and not always_prune:
had_parents_pruned = (len(parents) < len(orig_parents) or
(len(orig_parents) == 1 and
orig_parents[0] in _SKIPPED_COMMITS))
# If the commit remains empty and had parents which were pruned,
# then prune this commit; otherwise, retain it
return (not commit.file_changes and had_parents_pruned)
# We can only get here if the commit didn't start empty, so if it's
# empty now, it obviously became empty
if not commit.file_changes:
return True
# If there are no parents of this commit and we didn't match the case
# above, then this commit cannot be pruned. Since we have no parent(s)
# to compare to, abort now to prevent future checks from failing.
if not parents:
return False
# Finally, the hard case: due to either blob rewriting, or due to pruning
# of empty commits wiping out the first parent history back to the merge
# base, the list of file_changes we have may not actually differ from our
# (new) first parent's version of the files, i.e. this would actually be
# an empty commit. Check by comparing the contents of this commit to its
# (remaining) parent.
#
# NOTE on why this works, for the case of original first parent history
# having been pruned away due to being empty:
# The first parent history having been pruned away due to being
# empty implies the original first parent would have a tree (after
# filtering) that matched the merge base's tree. Since
# file_changes has the changes needed to go from what would have
# been the first parent to our new commit, and what would have been
# our first parent has a tree that matches the merge base, then if
# the new first parent has a tree matching the versions of files in
# file_changes, then this new commit is empty and thus prunable.
fi_input, fi_output = self._import_pipes
self._flush_renames() # Avoid fi_output having other stuff present
# Optimization note: we could have two loops over file_changes, the
# first doing all the self._output.write() calls, and the second doing
# the rest. But I'm worried about fast-import blocking on fi_output
# buffers filling up so I instead read from it as I go.
for change in commit.file_changes:
parent = new_1st_parent or commit.parents[0] # exists due to above checks
quoted_filename = PathQuoting.enquote(change.filename)
if isinstance(parent, int):
self._output.write(b"ls :%d %s\n" % (parent, quoted_filename))
else:
self._output.write(b"ls %s %s\n" % (parent, quoted_filename))
self._output.flush()
parent_version = fi_output.readline().split()
if change.type == b'D':
if parent_version != [b'missing', quoted_filename]:
return False
else:
blob_sha = change.blob_id
if isinstance(change.blob_id, int):
self._output.write(b"get-mark :%d\n" % change.blob_id)
self._output.flush()
blob_sha = fi_output.readline().rstrip()
if parent_version != [change.mode, b'blob', blob_sha, quoted_filename]:
return False
return True
if blob.original_id in self._args.strip_blobs_with_ids:
blob.skip()
if ( self._args.replace_text
# not (if blob contains zero byte in the first 8Kb, that is, if blob is
binary data)
and not b"\0" in blob.data[0:8192]
):
for literal, replacement in self._args.replace_text['literals']:
blob.data = blob.data.replace(literal, replacement)
for regex, replacement in self._args.replace_text['regexes']:
blob.data = regex.sub(replacement, blob.data)
if self._blob_callback:
self._blob_callback(blob, self.callback_metadata())
def _filter_files(self, commit):
def filename_matches(path_expression, pathname):
''' Returns whether path_expression matches pathname or a leading
directory thereof, allowing path_expression to not have a trailing
slash even if it is meant to match a leading directory. '''
if path_expression == b'':
return True
n = len(path_expression)
if (pathname.startswith(path_expression) and
(path_expression[n-1:n] == b'/' or
len(pathname) == n or
pathname[n:n+1] == b'/')):
return True
return False
args = self._args
new_file_changes = {} # Assumes no renames or copies, otherwise collisions
for change in commit.file_changes:
# NEEDSWORK: _If_ we ever want to pass `--full-tree` to fast-export and
# parse that output, we'll need to modify this block; `--full-tree`
# issues a deleteall directive which has no filename, and thus this
# block would normally strip it. Of course, FileChange() and
# _parse_optional_filechange() would need updates too.
if change.type == b'DELETEALL':
new_file_changes[b''] = change
continue
if change.filename in self._newnames:
change.filename = self._newnames[change.filename]
else:
original_filename = change.filename
change.filename = newname(args.path_changes, change.filename,
args.use_base_name, args.inclusive)
if self._filename_callback:
change.filename = self._filename_callback(change.filename)
self._newnames[original_filename] = change.filename
if not change.filename:
continue # Filtering criteria excluded this file; move on to next one
if change.filename in new_file_changes:
# Getting here means that path renaming is in effect, and caused one
# path to collide with another. That's usually bad, but can be okay
# under two circumstances:
# 1) Sometimes people have a file named OLDFILE in old revisions of
# history, and they rename to NEWFILE, and would like to rewrite
# history so that all revisions refer to it as NEWFILE. As such,
# we can allow a collision when (at least) one of the two paths
# is a deletion. Note that if OLDFILE and NEWFILE are unrelated
# this also allows the rewrite to continue, which makes sense
# since OLDFILE is no longer in the way.
# 2) If OLDFILE and NEWFILE are exactly equal, then writing them
# both to the same location poses no problem; we only need one
# file. (This could come up if someone copied a file in some
# commit, then later either deleted the file or kept it exactly
# in sync with the original with any changes, and then decides
# they want to rewrite history to only have one of the two files)
colliding_change = new_file_changes[change.filename]
if change.type == b'D':
# We can just throw this one away and keep the other
continue
elif change.type == b'M' and (
change.mode == colliding_change.mode and
change.blob_id == colliding_change.blob_id):
# The two are identical, so we can throw this one away and keep other
continue
elif new_file_changes[change.filename].type != b'D':
raise SystemExit(_("File renaming caused colliding pathnames!\n") +
_(" Commit: {}\n").format(commit.original_id) +
_(" Filename: {}").format(change.filename))
# Strip files that are too large
if self._args.max_blob_size and \
self._unpacked_size.get(change.blob_id, 0) > self._args.max_blob_size:
continue
if self._args.strip_blobs_with_ids and \
change.blob_id in self._args.strip_blobs_with_ids:
continue
# Otherwise, record the change
new_file_changes[change.filename] = change
commit.file_changes = [v for k,v in sorted(new_file_changes.items())]
self._graph.record_external_commits(external_parents)
self._orig_graph.record_external_commits(external_parents)
self._graph.add_commit_and_parents(commit.id, parents) # new githash unknown
self._orig_graph.add_commit_and_parents(commit.old_id, orig_parents,
commit.original_id)
# Find out which files were modified by the callbacks. Such paths could
# lead to subsequent commits being empty (e.g. if removing a line containing
# a password from every version of a file that had the password, and some
# later commit did nothing more than remove that line)
final_file_changes = set(commit.file_changes)
if self._args.replace_text or self._blob_callback:
differences = orig_file_changes.union(final_file_changes)
else:
differences = orig_file_changes.symmetric_difference(final_file_changes)
self._files_tweaked.update(x.filename for x in differences)
# Show progress
self._num_commits += 1
if not self._args.quiet:
self._progress_writer.show(self._parsed_message % self._num_commits)
@staticmethod
def _do_tag_rename(rename_pair, tagname):
old, new = rename_pair.split(b':', 1)
old, new = b'refs/tags/'+old, b'refs/tags/'+new
if tagname.startswith(old):
return tagname.replace(old, new, 1)
return tagname
def _save_marks_files(self):
basenames = [b'source-marks', b'target-marks']
working_dir = self._args.target or b'.'
# Run 'git hash-object $MARKS_FILE' for each marks file, save result
blob_hashes = {}
for marks_basename in basenames:
marks_file = os.path.join(self.results_tmp_dir(), marks_basename)
if not os.path.isfile(marks_file): # pragma: no cover
raise SystemExit(_("Failed to find %s to save to %s")
% (marks_file, self._args.state_branch))
cmd = ['git', '-C', working_dir, 'hash-object', '-w', marks_file]
blob_hashes[marks_basename] = subproc.check_output(cmd).strip()
def importer_only(self):
self._run_sanity_checks()
self._setup_output()
# Handle sanity checks, though currently none needed for export-only cases
self._run_sanity_checks()
def _read_stash(self):
if self._orig_refs and b'refs/stash' in self._orig_refs and \
self._args.refs == ['--all']:
repo_working_dir = self._args.source or b'.'
git_dir = GitUtils.determine_git_dir(repo_working_dir)
stash = os.path.join(git_dir, b'logs', b'refs', b'stash')
if os.path.exists(stash):
with open(stash, 'br') as f:
self._stash = f.read()
out = subproc.check_output('git rev-list -g refs/stash'.split(),
cwd=repo_working_dir)
self._args.refs.extend(decode(out.strip()).split())
def _write_stash(self):
if self._stash:
target_working_dir = self._args.target or b'.'
git_dir = GitUtils.determine_git_dir(target_working_dir)
stash = os.path.join(git_dir, b'logs', b'refs', b'stash')
with open(stash, 'bw') as f:
self._stash = self._full_hash_re.sub(self._translate_full_commit_hash,
self._stash)
f.write(self._stash)
print(_("Rewrote the stash."))
def _setup_output(self):
if not self._args.dry_run:
location = ['-C', self._args.target] if self._args.target else []
fip_cmd = ['git'] + location + ['-c', 'core.ignorecase=false',
'fast-import', '--force', '--quiet']
if date_format_permissive:
fip_cmd.append('--date-format=raw-permissive')
if self._args.state_branch:
target_marks_file = self._load_marks_file(b'target-marks')
fip_cmd.extend([b'--export-marks='+target_marks_file,
b'--import-marks='+target_marks_file])
self._fip = subproc.Popen(fip_cmd, bufsize=-1,
stdin=subprocess.PIPE, stdout=subprocess.PIPE)
self._import_pipes = (self._fip.stdin, self._fip.stdout)
if self._args.dry_run or self._args.debug:
self._fe_filt = os.path.join(self.results_tmp_dir(),
b'fast-export.filtered')
self._output = open(self._fe_filt, 'bw')
else:
self._output = self._fip.stdin
if self._args.debug and not self._args.dry_run:
self._output = DualFileWriter(self._fip.stdin, self._output)
tmp = [decode(x) if isinstance(x, bytes) else x for x in fip_cmd]
print("[DEBUG] Running: {}".format(' '.join(tmp)))
print(" (using the following file as input: {})"
.format(decode(self._fe_filt)))
def _migrate_origin_to_heads(self):
refs_to_migrate = set(x for x in self._orig_refs
if x.startswith(b'refs/remotes/origin/'))
if not refs_to_migrate:
return
if self._args.debug:
print("[DEBUG] Migrating refs/remotes/origin/* -> refs/heads/*")
target_working_dir = self._args.target or b'.'
p = subproc.Popen('git update-ref --no-deref --stdin'.split(),
stdin=subprocess.PIPE, cwd=target_working_dir)
for ref in refs_to_migrate:
if ref == b'refs/remotes/origin/HEAD':
p.stdin.write(b'delete %s %s\n' % (ref, self._orig_refs[ref]))
del self._orig_refs[ref]
continue
newref = ref.replace(b'refs/remotes/origin/', b'refs/heads/')
if newref not in self._orig_refs:
p.stdin.write(b'create %s %s\n' % (newref, self._orig_refs[ref]))
p.stdin.write(b'delete %s %s\n' % (ref, self._orig_refs[ref]))
self._orig_refs[newref] = self._orig_refs[ref]
del self._orig_refs[ref]
p.stdin.close()
if p.wait():
raise SystemExit(_("git update-ref failed; see above")) # pragma: no cover
def _final_commands(self):
self._finalize_handled = True
self._done_callback and self._done_callback()
if not self._args.quiet:
self._progress_writer.finish()
#
# First, handle commit_renames
#
old_commit_renames = dict()
if not already_ran:
commit_renames = {old: new
for old, new in self._commit_renames.items()
}
else:
# Read commit-map into old_commit_renames
with open(os.path.join(metadata_dir, b'commit-map'), 'br') as f:
f.readline() # Skip the header line
for line in f:
(old,new) = line.split()
old_commit_renames[old] = new
# Use A->B mappings in old_commit_renames, and B->C mappings in
# self._commit_renames to yield A->C mappings in commit_renames
commit_renames = {old: self._commit_renames.get(newish, newish)
for old, newish in old_commit_renames.items()}
# If there are any B->C mappings in self._commit_renames for which
# there was no A->B mapping in old_commit_renames, then add the
# B->C mapping to commit_renames too.
seen = set(old_commit_renames.values())
commit_renames.update({old: new
for old, new in self._commit_renames.items()
if old not in seen})
#
# Second, handle ref_maps
#
exported_refs, imported_refs = self.get_exported_and_imported_refs()
old_commit_unrenames = dict()
if not already_ran:
old_ref_map = dict((refname, (old_hash, deleted_hash))
for refname, old_hash in orig_refs.items()
if refname in exported_refs)
else:
# old_commit_renames talk about how commits were renamed in the original
# run. Let's reverse it to find out how to get from the intermediate
# commit name, back to the original. Because everything in orig_refs
# right now refers to the intermediate commits after the first run(s),
# and we need to map them back to what they were before any changes.
old_commit_unrenames = dict((v,k) for (k,v) in old_commit_renames.items())
old_ref_map = {}
# Populate old_ref_map from the 'ref-map' file
with open(os.path.join(metadata_dir, b'ref-map'), 'br') as f:
f.readline() # Skip the header line
for line in f:
(old,intermediate,ref) = line.split()
old_ref_map[ref] = (old, intermediate)
# Append to old_ref_map items from orig_refs that were exported, but
# get the actual original commit name
for refname, old_hash in orig_refs.items():
if refname in old_ref_map:
continue
if refname not in exported_refs:
continue
# Compute older_hash
original_hash = old_commit_unrenames.get(old_hash, old_hash)
old_ref_map[refname] = (original_hash, deleted_hash)
new_refs = {}
new_refs_initialized = False
ref_maps = {}
self._orig_graph._ensure_reverse_maps_populated()
for refname, pair in old_ref_map.items():
old_hash, hash_ref_becomes_if_not_imported_in_this_run = pair
if refname not in imported_refs:
new_hash = hash_ref_becomes_if_not_imported_in_this_run
elif old_hash in commit_renames:
intermediate = old_commit_renames.get(old_hash,old_hash)
if intermediate in self._commit_renames:
new_hash = self._remap_to(intermediate)
else:
new_hash = intermediate
else: # Must be either an annotated tag, or a ref whose tip was pruned
if not new_refs_initialized:
target_working_dir = self._args.target or b'.'
new_refs = GitUtils.get_refs(target_working_dir)
if refname in new_refs:
new_hash = new_refs[refname]
else:
new_hash = deleted_hash
ref_maps[refname] = (old_hash, new_hash)
if self._args.source or self._args.target:
if not new_refs_initialized:
target_working_dir = self._args.target or b'.'
new_refs = GitUtils.get_refs(target_working_dir)
for ref, new_hash in new_refs.items():
if ref not in orig_refs and not ref.startswith(b'refs/replace/'):
old_hash = b'0'*len(new_hash)
ref_maps[ref] = (old_hash, new_hash)
#
# Third, handle first_changes
#
old_first_changes = dict()
if already_ran:
# Read first_changes into old_first_changes
with open(os.path.join(metadata_dir, b'first-changed-commits'), 'br') as f:
for line in f:
changed_commit, undeleted_self_or_ancestor = line.strip().split()
old_first_changes[changed_commit] = undeleted_self_or_ancestor
# We need to find the commits that were modified whose parents were not.
# To be able to find parents, we need the commit names as of the beginning
# of this run, and then when we are done, we need to map them back to the
# name of the commits from before any git-filter-repo runs.
#
# We are excluding here any commits deleted in previous git-filter-repo
# runs
undo_old_commit_renames = dict((v,k) for (k,v) in old_commit_renames.items()
if v != deleted_hash)
# Get a list of all commits that were changed, as of the beginning of
# this latest run.
changed_commits = {new
for (old,new) in old_commit_renames.items()
if old != new and new != deleted_hash} | \
{old
for (old,new) in self._commit_renames.items()
if old != new}
special_changed_commits = {old
for (old,new) in old_commit_renames.items()
if new == deleted_hash}
first_changes = dict()
for (old,new) in self._commit_renames.items():
if old == new:
# old wasn't modified, can't be first change if not even a change
continue
if old_commit_unrenames.get(old,old) != old:
# old was already modified in previous run; while it might represent
# something that is still a first change, we'll handle that as we
# loop over old_first_changes below
continue
if any(parent in changed_commits
for parent in self._orig_graph.get_parent_hashes(old)):
# a parent of old was modified, so old is not a first change
continue
# At this point, old IS a first change. We need to find out what new
# commit it maps to, or if it doesn't map to one, what new commit was
# its most recent ancestor that wasn't pruned.
if new is None:
new = self._remap_to(old)
first_changes[old] = (new if new is not None else deleted_hash)
for (old,undeleted_self_or_ancestor) in old_first_changes.items():
if undeleted_self_or_ancestor == deleted_hash:
# old represents a commit that was pruned and whose entire ancestry
# was pruned. So, old is still a first change
first_changes[old] = undeleted_self_or_ancestor
continue
intermediate = old_commit_renames.get(old, old)
usoa = undeleted_self_or_ancestor
new_ancestor = self._commit_renames.get(usoa, usoa)
if intermediate == deleted_hash:
# old was pruned in previous rewrite
if usoa != new_ancestor:
# old's ancestor got rewritten in this filtering run; we can drop
# this one from first_changes.
continue
# Getting here means old was a first change and old was pruned in a
# previous run, and its ancestors that survived were non rewritten in
# this run, so old remains a first change
first_changes[old] = new_ancestor # or usoa, since new_ancestor == usoa
continue
assert(usoa == intermediate) # old wasn't pruned => usoa == intermediate
f.write(textwrap.dedent(_('''
The following commits used to be merge commits but due to filtering
are now regular commits; they likely have suboptimal commit messages
(e.g. "Merge branch next into master"). Original commit hash on the
left, commit hash after filtering/rewriting on the right:
''')[1:]).encode())
for oldhash, newhash in self._commits_no_longer_merges:
f.write(' {} {}\n'.format(oldhash, newhash).encode())
f.write(b'\n')
if self._commits_referenced_but_removed:
issues_found = True
f.write(textwrap.dedent(_('''
The following commits were filtered out, but referenced in another
commit message. The reference to the now-nonexistent commit hash
(or a substring thereof) was left as-is in any commit messages:
''')[1:]).encode())
for bad_commit_reference in self._commits_referenced_but_removed:
f.write(' {}\n'.format(bad_commit_reference).encode())
f.write(b'\n')
if not issues_found:
f.write(_("No filtering problems encountered.\n").encode())
def finish(self):
''' Alternative to run() when there is no input of our own to parse,
meaning that run only really needs to close the handle to fast-import
and let it finish, thus making a call to "run" feel like a misnomer. '''
assert not self._input
assert self._managed_output
self.run()
def get_exported_and_imported_refs(self):
return self._parser.get_exported_and_imported_refs()
def run(self):
start = time.time()
if not self._input and not self._output:
self._run_sanity_checks()
if not self._args.dry_run and not self._args.partial:
self._migrate_origin_to_heads()
self._setup_input(use_done_feature = True)
self._setup_output()
assert self._sanity_checks_handled
if self._input:
# Create and run the filter
self._repo_working_dir = self._args.source or b'.'
self._parser = FastExportParser(blob_callback = self._tweak_blob,
commit_callback = self._tweak_commit,
tag_callback = self._tweak_tag,
reset_callback = self._tweak_reset,
done_callback = self._final_commands)
self._parser.run(self._input, self._output)
if not self._finalize_handled:
self._final_commands()
# Final cleanup:
# If we need a repack, then nuke the reflogs and repack.
# If we need a reset, do a reset --hard
reset = not GitUtils.is_repository_bare(target_working_dir)
self.cleanup(target_working_dir, self._args.repack, reset,
run_quietly=self._args.quiet,
show_debuginfo=self._args.debug)
def main():
setup_gettext()
args = FilteringOptions.parse_args(sys.argv[1:])
if args.analyze:
RepoAnalyze.run(args)
else:
filter = RepoFilter(args)
filter.run()
if __name__ == '__main__':
main()