本文整理汇总了Python中rbtools.utils.filesystem.make_tempfile函数的典型用法代码示例。如果您正苦于以下问题:Python make_tempfile函数的具体用法?Python make_tempfile怎么用?Python make_tempfile使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了make_tempfile函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Python代码示例。
示例1: diff_directories
def diff_directories(self, old_dir, new_dir):
"""Return uniffied diff between two directories content.
Function save two version's content of directory to temp
files and treate them as casual diff between two files.
"""
old_content = self._directory_content(old_dir)
new_content = self._directory_content(new_dir)
old_tmp = make_tempfile(content=old_content)
new_tmp = make_tempfile(content=new_content)
diff_cmd = ["diff", "-uN", old_tmp, new_tmp]
dl = execute(diff_cmd,
extra_ignore_errors=(1, 2),
translate_newlines=False,
split_lines=True)
# Replacing temporary filenames to
# real directory names and add ids
if dl:
dl[0] = dl[0].replace(old_tmp, old_dir)
dl[1] = dl[1].replace(new_tmp, new_dir)
old_oid = execute(["cleartool", "describe", "-fmt", "%On",
old_dir])
new_oid = execute(["cleartool", "describe", "-fmt", "%On",
new_dir])
dl.insert(2, "==== %s %s ====\n" % (old_oid, new_oid))
return dl
开发者ID:PlasticSCM,项目名称:rbtools,代码行数:30,代码来源:clearcase.py
示例2: _extract_delete_files
def _extract_delete_files(self, depot_file, revision, cl_is_shelved):
"""Extract the 'old' and 'new' files for a delete operation.
Returns a tuple of (old filename, new filename). This can raise a
ValueError if extraction fails.
"""
# Get the old version out of perforce
old_filename = make_tempfile()
self._write_file('%s#%s' % (depot_file, revision), old_filename)
# Make an empty tempfile for the new file
new_filename = make_tempfile()
return old_filename, new_filename
开发者ID:mhahn,项目名称:rbtools,代码行数:14,代码来源:perforce.py
示例3: test_diff_with_pending_changelist
def test_diff_with_pending_changelist(self):
"""Testing PerforceClient.diff with a pending changelist"""
client = self._build_client()
client.p4.repo_files = [
{
'depotFile': '//mydepot/test/README',
'rev': '2',
'action': 'edit',
'change': '12345',
'text': 'This is a test.\n',
},
{
'depotFile': '//mydepot/test/README',
'rev': '3',
'action': 'edit',
'change': '',
'text': 'This is a mess.\n',
},
{
'depotFile': '//mydepot/test/COPYING',
'rev': '1',
'action': 'add',
'change': '12345',
'text': 'Copyright 2013 Joe User.\n',
},
{
'depotFile': '//mydepot/test/Makefile',
'rev': '3',
'action': 'delete',
'change': '12345',
'text': 'all: all\n',
},
]
readme_file = make_tempfile()
copying_file = make_tempfile()
makefile_file = make_tempfile()
client.p4.print_file('//mydepot/test/README#3', readme_file)
client.p4.print_file('//mydepot/test/COPYING#1', copying_file)
client.p4.where_files = {
'//mydepot/test/README': readme_file,
'//mydepot/test/COPYING': copying_file,
'//mydepot/test/Makefile': makefile_file,
}
revisions = client.parse_revision_spec(['12345'])
diff = client.diff(revisions)
self._compare_diff(diff, '07aa18ff67f9aa615fcda7ecddcb354e')
开发者ID:clach04,项目名称:rbtools,代码行数:49,代码来源:test_p4.py
示例4: test_make_tempfile
def test_make_tempfile(self):
"""Testing 'make_tempfile' method."""
fname = filesystem.make_tempfile()
self.assertTrue(os.path.isfile(fname))
self.assertEqual(os.stat(fname).st_uid, os.geteuid())
self.assertTrue(os.access(fname, os.R_OK | os.W_OK))
开发者ID:acres-com-au,项目名称:rbtools,代码行数:7,代码来源:tests.py
示例5: _extract_add_files
def _extract_add_files(self, depot_file, revision, cl_is_shelved):
"""Extract the 'old' and 'new' files for an add operation.
Returns a tuple of (old filename, new filename). This can raise a
ValueError if the extraction fails.
"""
# Make an empty tempfile for the old file
old_filename = make_tempfile()
if cl_is_shelved:
new_filename = make_tempfile()
self._write_file('%[email protected]=%s' % (depot_file, revision), new_filename)
else:
# Just reference the file within the client view
new_filename = self._depot_to_local(depot_file)
return old_filename, new_filename
开发者ID:mhahn,项目名称:rbtools,代码行数:17,代码来源:perforce.py
示例6: _diff_directories
def _diff_directories(self, old_dir, new_dir):
"""Return a unified diff between two directories' content.
This function saves two version's content of directory to temp
files and treats them as casual diff between two files.
Args:
old_dir (unicode):
The path to a directory within a vob.
new_dir (unicode):
The path to a directory within a vob.
Returns:
list:
The diff between the two directory trees, split into lines.
"""
old_content = self._directory_content(old_dir)
new_content = self._directory_content(new_dir)
old_tmp = make_tempfile(content=old_content)
new_tmp = make_tempfile(content=new_content)
diff_cmd = ['diff', '-uN', old_tmp, new_tmp]
dl = execute(diff_cmd,
extra_ignore_errors=(1, 2),
results_unicode=False,
split_lines=True)
# Replace temporary filenames with real directory names and add ids
if dl:
dl[0] = dl[0].replace(old_tmp.encode('utf-8'),
old_dir.encode('utf-8'))
dl[1] = dl[1].replace(new_tmp.encode('utf-8'),
new_dir.encode('utf-8'))
old_oid = execute(['cleartool', 'describe', '-fmt', '%On',
old_dir],
results_unicode=False)
new_oid = execute(['cleartool', 'describe', '-fmt', '%On',
new_dir],
results_unicode=False)
dl.insert(2, b'==== %s %s ====\n' % (old_oid, new_oid))
return dl
开发者ID:reviewboard,项目名称:rbtools,代码行数:44,代码来源:clearcase.py
示例7: _extract_edit_files
def _extract_edit_files(self, depot_file, tip, base_revision,
cl_is_shelved):
"""Extract the 'old' and 'new' files for an edit operation.
Returns a tuple of (old filename, new filename). This can raise a
ValueError if the extraction fails.
"""
# Get the old version out of perforce
old_filename = make_tempfile()
self._write_file('%s#%s' % (depot_file, base_revision), old_filename)
if cl_is_shelved:
new_filename = make_tempfile()
self._write_file('%[email protected]=%s' % (depot_file, tip), new_filename)
else:
# Just reference the file within the client view
new_filename = self._depot_to_local(depot_file)
return old_filename, new_filename
开发者ID:mhahn,项目名称:rbtools,代码行数:19,代码来源:perforce.py
示例8: main
def main(self, request_id):
"""Run the command."""
repository_info, tool = self.initialize_scm_tool(
client_name=self.options.repository_type)
server_url = self.get_server_url(repository_info, tool)
api_client, api_root = self.get_api(server_url)
self.setup_tool(tool, api_root=api_root)
# Check if repository info on reviewboard server match local ones.
repository_info = repository_info.find_server_repository_info(api_root)
# Get the patch, the used patch ID and base dir for the diff
diff_body, diff_revision, base_dir = self.get_patch(
request_id,
api_root,
self.options.diff_revision)
if self.options.patch_stdout:
print diff_body
else:
try:
if tool.has_pending_changes():
message = 'Working directory is not clean.'
if not self.options.commit:
print 'Warning: %s' % message
else:
raise CommandError(message)
except NotImplementedError:
pass
tmp_patch_file = make_tempfile(diff_body)
success = self.apply_patch(repository_info, tool, request_id,
diff_revision, tmp_patch_file, base_dir)
if success and (self.options.commit or
self.options.commit_no_edit):
try:
review_request = api_root.get_review_request(
review_request_id=request_id,
force_text_type='plain')
except APIError, e:
raise CommandError('Error getting review request %s: %s'
% (request_id, e))
message = self._extract_commit_message(review_request)
author = review_request.get_submitter()
try:
tool.create_commit(message, author,
not self.options.commit_no_edit)
print('Changes committed to current branch.')
except NotImplementedError:
raise CommandError('--commit is not supported with %s'
% tool.name)
开发者ID:RiverMeadow,项目名称:rbtools,代码行数:55,代码来源:patch.py
示例9: edit_text
def edit_text(content):
"""Allows a user to edit a block of text and returns the saved result.
The environment's default text editor is used if available, otherwise
vim is used.
"""
tempfile = make_tempfile(content.encode('utf8'))
editor = os.environ.get('EDITOR', 'vim')
subprocess.call([editor, tempfile])
f = open(tempfile)
result = f.read()
f.close()
return result.decode('utf8')
开发者ID:gdyuldin,项目名称:rbtools,代码行数:14,代码来源:console.py
示例10: _patch
def _patch(self, content, patch):
"""Patch content with a patch. Returnes patched content.
The content and the patch should be a list of lines with no
endl."""
content_file = make_tempfile(content=os.linesep.join(content))
patch_file = make_tempfile(content=os.linesep.join(patch))
reject_file = make_tempfile()
output_file = make_tempfile()
patch_cmd = ["patch", "-r", reject_file, "-o", output_file,
"-i", patch_file, content_file]
output = execute(patch_cmd, extra_ignore_errors=(1,),
translate_newlines=False)
if "FAILED at" in output:
logging.debug("patching content FAILED:")
logging.debug(output)
patched = open(output_file).read()
eof_endl = patched.endswith('\n')
patched = patched.splitlines()
if eof_endl:
patched.append('')
try:
os.unlink(content_file)
os.unlink(patch_file)
os.unlink(reject_file)
os.unlink(output_file)
except:
pass
return patched
开发者ID:bcelary,项目名称:rbtools,代码行数:37,代码来源:clearcase.py
示例11: _content_diff
def _content_diff(self, old_content, new_content, old_file,
new_file, unified=True):
"""Returns unified diff as a list of lines with no end lines,
uses temp files. The input content should be a list of lines
without end lines."""
old_tmp = make_tempfile(content=os.linesep.join(old_content))
new_tmp = make_tempfile(content=os.linesep.join(new_content))
diff_cmd = ['diff']
if unified:
diff_cmd.append('-uN')
diff_cmd.extend((old_tmp, new_tmp))
dl = execute(diff_cmd, extra_ignore_errors=(1, 2),
translate_newlines=False, split_lines=False)
eof_endl = dl.endswith('\n')
dl = dl.splitlines()
if eof_endl:
dl.append('')
try:
os.unlink(old_tmp)
os.unlink(new_tmp)
except:
pass
if unified and dl and len(dl) > 1:
# Because the modification time is for temporary files here
# replacing it with headers without modification time.
if dl[0].startswith('---') and dl[1].startswith('+++'):
dl[0] = '--- %s\t' % old_file
dl[1] = '+++ %s\t' % new_file
return dl
开发者ID:bcelary,项目名称:rbtools,代码行数:36,代码来源:clearcase.py
示例12: main
def main(self, request_id):
"""Run the command."""
repository_info, tool = self.initialize_scm_tool()
server_url = self.get_server_url(self.repository_info, self.tool)
api_client, api_root = self.get_api(server_url)
# Get the patch, the used patch ID and base dir for the diff
diff_body, diff_revision, base_dir = self.get_patch(
request_id,
self.options.diff_revision)
tmp_patch_file = make_tempfile(diff_body)
self.apply_patch(tool, request_id, diff_revision, tmp_patch_file,
base_dir)
开发者ID:ronangill,项目名称:rbtools,代码行数:15,代码来源:patch.py
示例13: _exclude_files_not_in_tree
def _exclude_files_not_in_tree(self, patch_file, base_path):
"""Process a diff and remove entries not in the current directory.
The file at the location patch_file will be overwritten by the new
patch.
This function returns a tuple of two booleans. The first boolean
indicates if any files have been excluded. The second boolean indicates
if the resulting diff patch file is empty.
"""
excluded_files = False
empty_patch = True
# If our base path does not have a trailing slash (which it won't
# unless we are at a checkout root), we append a slash so that we can
# determine if files are under the base_path. We do this so that files
# like /trunkish (which begins with /trunk) do not mistakenly get
# placed in /trunk if that is the base_path.
if not base_path.endswith('/'):
base_path += '/'
filtered_patch_name = make_tempfile()
with open(filtered_patch_name, 'w') as filtered_patch:
with open(patch_file, 'r') as original_patch:
include_file = True
for line in original_patch.readlines():
m = self.INDEX_FILE_RE.match(line)
if m:
filename = m.group(1).decode('utf-8')
include_file = filename.startswith(base_path)
if not include_file:
excluded_files = True
else:
empty_patch = False
if include_file:
filtered_patch.write(line)
os.rename(filtered_patch_name, patch_file)
return (excluded_files, empty_patch)
开发者ID:halvorlu,项目名称:rbtools,代码行数:46,代码来源:svn.py
示例14: _extract_move_files
def _extract_move_files(self, old_depot_file, tip, base_revision,
cl_is_shelved):
"""Extract the 'old' and 'new' files for a move operation.
Returns a tuple of (old filename, new filename, new depot path). This
can raise a ValueError if extraction fails.
"""
# XXX: fstat *ought* to work, but perforce doesn't supply the movedFile
# field in fstat (or apparently anywhere else) when a change is
# shelved. For now, _diff_pending will avoid calling this method at all
# for shelved changes, and instead treat them as deletes and adds.
assert not cl_is_shelved
# if cl_is_shelved:
# fstat_path = '%[email protected]=%s' % (depot_file, tip)
# else:
fstat_path = old_depot_file
stat_info = self.p4.fstat(fstat_path,
['clientFile', 'movedFile'])
if 'clientFile' not in stat_info or 'movedFile' not in stat_info:
raise ValueError('Unable to get moved file information')
old_filename = make_tempfile()
self._write_file('%s#%s' % (old_depot_file, base_revision),
old_filename)
# if cl_is_shelved:
# fstat_path = '%[email protected]=%s' % (stat_info['movedFile'], tip)
# else:
fstat_path = stat_info['movedFile']
stat_info = self.p4.fstat(fstat_path,
['clientFile', 'depotFile'])
if 'clientFile' not in stat_info or 'depotFile' not in stat_info:
raise ValueError('Unable to get moved file information')
# Grab the new depot path (to include in the diff index)
new_depot_file = stat_info['depotFile']
# Reference the new file directly in the client view
new_filename = stat_info['clientFile']
return old_filename, new_filename, new_depot_file
开发者ID:mhahn,项目名称:rbtools,代码行数:44,代码来源:perforce.py
示例15: edit_text
def edit_text(content):
"""Allows a user to edit a block of text and returns the saved result.
The environment's default text editor is used if available, otherwise
vi is used.
"""
tempfile = make_tempfile(content.encode('utf8'))
editor = os.environ.get('VISUAL') or os.environ.get('EDITOR') or 'vi'
try:
subprocess.call([editor, tempfile])
except OSError:
print 'No editor found. Set EDITOR environment variable or install vi.'
raise
f = open(tempfile)
result = f.read()
f.close()
return result.decode('utf8')
开发者ID:RiverMeadow,项目名称:rbtools,代码行数:19,代码来源:console.py
示例16: main
def main(self, pull_request_id):
repository_info, tool = self.initialize_scm_tool()
configs = [load_config()]
if self.options.owner is None:
self.options.owner = get_config_value(configs, "GITHUB_OWNER", None)
if self.options.repo is None:
self.options.repo = get_config_value(configs, "GITHUB_REPO", None)
if self.options.owner is None or self.options.repo is None:
raise CommandError("No GITHUB_REPO or GITHUB_OWNER has been configured.")
diff = self.get_patch(pull_request_id)
if self.options.patch_stdout:
print diff
else:
try:
if tool.has_pending_changes():
message = "Working directory is not clean."
if not self.options.commit:
print "Warning: %s" % message
else:
raise CommandError(message)
except NotImplementedError:
pass
tmp_patch_file = make_tempfile(diff)
self.apply_patch(repository_info, tool, pull_request_id, tmp_patch_file)
if self.options.commit:
message = self.generate_commit_message(pull_request_id)
author = self.get_author_from_patch(tmp_patch_file)
try:
tool.create_commit(message, author)
print ("Changes committed to current branch.")
except NotImplementedError:
raise CommandError("--commit is not supported with %s" % tool.name)
开发者ID:jfarrell,项目名称:rbt-github,代码行数:42,代码来源:command.py
示例17: _diff_files
def _diff_files(self, old_file, new_file):
"""Return a unified diff for file.
Args:
old_file (unicode):
The name and version of the old file.
new_file (unicode):
The name and version of the new file.
Returns:
bytes:
The diff between the two files.
"""
# In snapshot view, diff can't access history clearcase file version
# so copy cc files to tempdir by 'cleartool get -to dest-pname pname',
# and compare diff with the new temp ones.
if self.viewtype == 'snapshot':
# Create temporary file first.
tmp_old_file = make_tempfile()
tmp_new_file = make_tempfile()
# Delete so cleartool can write to them.
try:
os.remove(tmp_old_file)
except OSError:
pass
try:
os.remove(tmp_new_file)
except OSError:
pass
execute(['cleartool', 'get', '-to', tmp_old_file, old_file])
execute(['cleartool', 'get', '-to', tmp_new_file, new_file])
diff_cmd = ['diff', '-uN', tmp_old_file, tmp_new_file]
else:
diff_cmd = ['diff', '-uN', old_file, new_file]
dl = execute(diff_cmd,
extra_ignore_errors=(1, 2),
results_unicode=False)
# Replace temporary file name in diff with the one in snapshot view.
if self.viewtype == 'snapshot':
dl = dl.replace(tmp_old_file.encode('utf-8'),
old_file.encode('utf-8'))
dl = dl.replace(tmp_new_file.encode('utf-8'),
new_file.encode('utf-8'))
# If the input file has ^M characters at end of line, lets ignore them.
dl = dl.replace(b'\r\r\n', b'\r\n')
dl = dl.splitlines(True)
# Special handling for the output of the diff tool on binary files:
# diff outputs "Files a and b differ"
# and the code below expects the output to start with
# "Binary files "
if (len(dl) == 1 and
dl[0].startswith(b'Files %s and %s differ'
% (old_file.encode('utf-8'),
new_file.encode('utf-8')))):
dl = [b'Binary files %s and %s differ\n'
% (old_file.encode('utf-8'),
new_file.encode('utf-8'))]
# We need oids of files to translate them to paths on reviewboard
# repository.
old_oid = execute(['cleartool', 'describe', '-fmt', '%On', old_file],
results_unicode=False)
new_oid = execute(['cleartool', 'describe', '-fmt', '%On', new_file],
results_unicode=False)
if dl == [] or dl[0].startswith(b'Binary files '):
if dl == []:
dl = [b'File %s in your changeset is unmodified\n' %
new_file.encode('utf-8')]
dl.insert(0, b'==== %s %s ====\n' % (old_oid, new_oid))
dl.append(b'\n')
else:
dl.insert(2, b'==== %s %s ====\n' % (old_oid, new_oid))
return dl
开发者ID:reviewboard,项目名称:rbtools,代码行数:84,代码来源:clearcase.py
示例18: _path_diff
def _path_diff(self, args):
"""
Process a path-style diff. See _changenum_diff for the alternate
version that handles specific change numbers.
Multiple paths may be specified in `args`. The path styles supported
are:
//path/to/file
Upload file as a "new" file.
//path/to/dir/...
Upload all files as "new" files.
//path/to/file[@#]rev
Upload file from that rev as a "new" file.
//path/to/file[@#]rev,[@#]rev
Upload a diff between revs.
//path/to/dir/...[@#]rev,[@#]rev
Upload a diff of all files between revs in that directory.
"""
r_revision_range = re.compile(r'^(?P<path>//[^@#]+)' +
r'(?P<revision1>[#@][^,]+)?' +
r'(?P<revision2>,[#@][^,]+)?$')
empty_filename = make_tempfile()
tmp_diff_from_filename = make_tempfile()
tmp_diff_to_filename = make_tempfile()
diff_lines = []
for path in args:
m = r_revision_range.match(path)
if not m:
die('Path %r does not match a valid Perforce path.' % (path,))
revision1 = m.group('revision1')
revision2 = m.group('revision2')
first_rev_path = m.group('path')
if revision1:
first_rev_path += revision1
records = self._run_p4(['files', first_rev_path])
# Make a map for convenience.
files = {}
# Records are:
# 'rev': '1'
# 'func': '...'
# 'time': '1214418871'
# 'action': 'edit'
# 'type': 'ktext'
# 'depotFile': '...'
# 'change': '123456'
for record in records:
if record['action'] not in ('delete', 'move/delete'):
if revision2:
files[record['depotFile']] = [record, None]
else:
files[record['depotFile']] = [None, record]
if revision2:
# [1:] to skip the comma.
second_rev_path = m.group('path') + revision2[1:]
records = self._run_p4(['files', second_rev_path])
for record in records:
if record['action'] not in ('delete', 'move/delete'):
try:
m = files[record['depotFile']]
m[1] = record
except KeyError:
files[record['depotFile']] = [None, record]
old_file = new_file = empty_filename
changetype_short = None
for depot_path, (first_record, second_record) in files.items():
old_file = new_file = empty_filename
if first_record is None:
self._write_file(depot_path + '#' + second_record['rev'],
tmp_diff_to_filename)
new_file = tmp_diff_to_filename
changetype_short = 'A'
base_revision = 0
elif second_record is None:
self._write_file(depot_path + '#' + first_record['rev'],
tmp_diff_from_filename)
old_file = tmp_diff_from_filename
changetype_short = 'D'
base_revision = int(first_record['rev'])
elif first_record['rev'] == second_record['rev']:
# We when we know the revisions are the same, we don't need
# to do any diffing. This speeds up large revision-range
# diffs quite a bit.
continue
else:
self._write_file(depot_path + '#' + first_record['rev'],
#.........这里部分代码省略.........
开发者ID:NurKaynar,项目名称:hacklab,代码行数:101,代码来源:perforce.py
示例19: _diff_files
def _diff_files(self, old_file, new_file):
"""Return unified diff for file.
Most effective and reliable way is use gnu diff.
"""
# In snapshot view, diff can't access history clearcase file version
# so copy cc files to tempdir by 'cleartool get -to dest-pname pname',
# and compare diff with the new temp ones.
if self.viewtype == 'snapshot':
# Create temporary file first.
tmp_old_file = make_tempfile()
tmp_new_file = make_tempfile()
# Delete so cleartool can write to them.
try:
os.remove(tmp_old_file)
except OSError:
pass
try:
os.remove(tmp_new_file)
except OSError:
pass
execute(["cleartool", "get", "-to", tmp_old_file, old_file])
execute(["cleartool", "get", "-to", tmp_new_file, new_file])
diff_cmd = ["diff", "-uN", tmp_old_file, tmp_new_file]
else:
diff_cmd = ["diff", "-uN", old_file, new_file]
dl = execute(diff_cmd, extra_ignore_errors=(1, 2),
translate_newlines=False)
# Replace temporary file name in diff with the one in snapshot view.
if self.viewtype == "snapshot":
dl = dl.replace(tmp_old_file, old_file)
dl = dl.replace(tmp_new_file, new_file)
# If the input file has ^M characters at end of line, lets ignore them.
dl = dl.replace('\r\r\n', '\r\n')
dl = dl.splitlines(True)
# Special handling for the output of the diff tool on binary files:
# diff outputs "Files a and b differ"
# and the code below expects the output to start with
# "Binary files "
if (len(dl) == 1 and
dl[0].startswith('Files %s and %s differ' % (old_file, new_file))):
dl = ['Binary files %s and %s differ\n' % (old_file, new_file)]
# We need oids of files to translate them to paths on reviewboard
# repository.
old_oid = execute(["cleartool", "describe", "-fmt", "%On", old_file])
new_oid = execute(["cleartool", "describe", "-fmt", "%On", new_file])
if dl == [] or dl[0].startswith("Binary files "):
if dl == []:
dl = ["File %s in your changeset is unmodified\n" % new_file]
dl.insert(0, "==== %s %s ====\n" % (old_oid, new_oid))
dl.append('\n')
else:
dl.insert(2, "==== %s %s ====\n" % (old_oid, new_oid))
return dl
开发者ID:MistShi,项目名称:rbtools,代码行数:66,代码来源:clearcase.py
示例20: process_diffs
def process_diffs(self, my_diff_entries):
# Diff generation based on perforce client
diff_lines = []
empty_filename = make_tempfile()
tmp_diff_from_filename = make_tempfile()
tmp_diff_to_filename = make_tempfile()
for f in my_diff_entries:
f = f.strip()
if not f:
continue
m = re.search(
r"(?P<type>[ACMD]) (?P<file>.*) "
r"(?P<revspec>rev:revid:[-\d]+) "
r"(?P<parentrevspec>rev:revid:[-\d]+) "
r"src:(?P<srcpath>.*) "
r"dst:(?P<dstpath>.*)$",
f,
)
if not m:
die("Could not parse 'cm log' response: %s" % f)
changetype = m.group("type")
filename = m.group("file")
if changetype == "M":
# Handle moved files as a delete followed by an add.
# Clunky, but at least it works
oldfilename = m.group("srcpath")
oldspec = m.group("revspec")
newfilename = m.group("dstpath")
newspec = m.group("revspec")
self.write_file(oldfilename, oldspec, tmp_diff_from_filename)
dl = self.diff_files(
tmp_diff_from_filename, empty_filename, oldfilename, "rev:revid:-1", oldspec, changetype
)
diff_lines += dl
self.write_file(newfilename, newspec, tmp_diff_to_filename)
dl = self.diff_files(
empty_filename, tmp_diff_to_filename, newfilename, newspec, "rev:revid:-1", changetype
)
diff_lines += dl
else:
newrevspec = m.group("revspec")
parentrevspec = m.group("parentrevspec")
logging.debug("Type %s File %s Old %s New %s" % (changetype, filename, parentrevspec, newrevspec))
old_file = new_file = empty_filename
if changetype in ["A"] or (changetype in ["C"] and parentrevspec == "rev:revid:-1"):
# There's only one content to show
self.write_file(filename, newrevspec, tmp_diff_to_filename)
new_file = tmp_diff_to_filename
elif changetype in ["C"]:
self.write_file(filename, parentrevspec, tmp_diff_from_filename)
old_file = tmp_diff_from_filename
self.write_file(filename, newrevspec, tmp_diff_to_filename)
new_file = tmp_diff_to_filename
elif changetype in ["D"]:
self.write_file(filename, parentrevspec, tmp_diff_from_filename)
old_file = tmp_diff_from_filename
else:
die("Don't know how to handle change type '%s' for %s" % (changetype, filename))
dl = self.diff_files(old_file, new_file, filename, newrevspec, parentrevspec, changetype)
diff_lines += dl
os.unlink(empty_filename)
os.unlink(tmp_diff_from_filename)
os.unlink(tmp_diff_to_filename)
return "".join(diff_lines)
开发者ID:jrabbe,项目名称:rbtools,代码行数:79,代码来源:plastic.py
注:本文中的rbtools.utils.filesystem.make_tempfile函数示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论