本文整理汇总了Python中rbtools.utils.filesystem.make_tempfile函数的典型用法代码示例。如果您正苦于以下问题:Python make_tempfile函数的具体用法?Python make_tempfile怎么用?Python make_tempfile使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了make_tempfile函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的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
示例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
示例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')
示例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))
示例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
示例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
示例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
示例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)
示例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')
示例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
示例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
示例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)
示例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)
示例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
示例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')