def copydir(args, sourcedir, names):
targetdir, replacements, uid, gid = args
# Don't recurse into CVS directories:
for name in names[:]:
if os.path.normcase(name) in CVS_DIRS:
names.remove(name)
elif os.path.isfile(os.path.join(sourcedir, name)):
# Copy the file:
sn, ext = os.path.splitext(name)
if os.path.normcase(ext) == ".in":
dst = os.path.join(targetdir, sourcedir, sn)
if os.path.exists(dst):
continue
copyin(os.path.join(sourcedir, name), dst, replacements, uid,
gid)
if uid is not None:
os.chown(dst, uid, gid)
else:
src = os.path.join(sourcedir, name)
dst = os.path.join(targetdir, src)
if os.path.exists(dst):
continue
shutil.copyfile(src, dst)
shutil.copymode(src, dst)
if uid is not None:
os.chown(dst, uid, gid)
else:
# Directory:
dn = os.path.join(targetdir, sourcedir, name)
if not os.path.exists(dn):
os.mkdir(dn)
shutil.copymode(os.path.join(sourcedir, name), dn)
if uid is not None:
os.chown(dn, uid, gid)
python类copymode()的实例源码
def copyin(src, dst, replacements, uid, gid):
ifp = open(src)
text = ifp.read()
ifp.close()
for k in replacements:
text = text.replace("<<%s>>" % k, replacements[k])
ofp = open(dst, "w")
ofp.write(text)
ofp.close()
shutil.copymode(src, dst)
if uid is not None:
os.chown(dst, uid, gid)
def _copy_file(path_old, path_new, name):
# HACK: use .template suffix to prevent .py file byte compiling
if path_new.endswith(".template"):
path_new = path_new[:-9]
fp_old = open(path_old, 'r')
fp_new = open(path_new, 'w')
# following django template sysntax
fp_new.write(fp_old.read()\
.replace('{{ project_name }}', name)\
.replace('{{ project_name|upper }}', name.upper())\
.replace('{{ project_name|camel }}', _camelize(name))\
.replace('{{ project_name|camel_cmd }}', _camelize(name, fill_char="_"))
)
fp_old.close()
fp_new.close()
# copy permissions
try:
shutil.copymode(path_old, path_new)
except OSError:
sys.stderr.write("Notice: Couldn't set permission bits on %s. You're probably using an uncommon filesystem setup. No problem.\n" % path_new)
# based on django.core.management.base.copy_helper()
def _copyFile(self, context, src, dest):
src = normLongPath(src)
dest = normLongPath(dest)
with open(src, 'rb') as inp:
with openForWrite(dest, 'wb') as out:
shutil.copyfileobj(inp, out)
shutil.copymode(src, dest)
assert os.path.exists(dest)
def _copyFile(self, context, src, dest):
dest = normLongPath(dest)
src = normLongPath(src)
with open(src, 'rb') as s:
with openForWrite(dest, 'wb') as d:
for m in self.mappers:
x = m.getHeader(context)
if x:
self.__unusedMappers.discard(m)
d.write(x)
for l in s:
for m in self.mappers:
prev = l
l = m.mapLine(context, l)
if prev != l:
self.__unusedMappers.discard(m)
if None == l:
break
if None != l:
d.write(l)
for m in self.mappers:
x = m.getFooter(context)
if x:
self.__unusedMappers.discard(m)
d.write(x)
shutil.copymode(src, dest)
assert os.path.exists(dest)
def retimestamp_and_index_file(inpath, outpath=None, retimestamp=None):
# no retimestamping needed
if retimestamp is None:
return index_file(inpath, outpath)
# retimestamp the input in place and index
elif retimestamp == 'inplace':
from flvlib.scripts.retimestamp_flv import retimestamp_file_inplace
log.debug("Retimestamping file `%s' in place", inpath)
# retimestamp the file inplace
if not retimestamp_file_inplace(inpath):
log.error("Failed to retimestamp `%s' in place", inpath)
return False
return index_file(inpath, outpath)
# retimestamp the input into a temporary file
elif retimestamp == 'atomic':
from flvlib.scripts.retimestamp_flv import retimestamp_file_atomically
log.debug("Retimestamping file `%s' atomically", inpath)
try:
fd, temppath = tempfile.mkstemp()
os.close(fd)
# preserve the permission bits
shutil.copymode(inpath, temppath)
except EnvironmentError, (errno, strerror):
log.error("Failed to create temporary file: %s", strerror)
return False
if not retimestamp_file_atomically(inpath, temppath):
log.error("Failed to retimestamp `%s' atomically", inpath)
# remove the temporary files
force_remove(temppath)
return False
# index the temporary file
if not index_file(temppath, outpath):
force_remove(temppath)
return False
if not outpath:
# If we were not writing directly to the output file
# we need to overwrite the original
try:
shutil.move(temppath, inpath)
except EnvironmentError, (errno, strerror):
log.error("Failed to overwrite the original file with the "
"retimestamped and indexed version: %s", strerror)
return False
else:
# if we were writing directly to the output file we need to remove
# the retimestamped temporary file
force_remove(temppath)
return True
def copy_helper(style, app_or_project, name, directory, other_name=''):
"""
Copies either a Django application layout template or a Django project
layout template into the specified directory.
"""
# style -- A color style object (see django.core.management.color).
# app_or_project -- The string 'app' or 'project'.
# name -- The name of the application or project.
# directory -- The directory to which the layout template should be copied.
# other_name -- When copying an application layout, this should be the name
# of the project.
import re
import shutil
other = {'project': 'app', 'app': 'project'}[app_or_project]
if not re.search(r'^[_a-zA-Z]\w*$', name): # If it's not a valid directory name.
# Provide a smart error message, depending on the error.
if not re.search(r'^[_a-zA-Z]', name):
message = 'make sure the name begins with a letter or underscore'
else:
message = 'use only numbers, letters and underscores'
raise CommandError("%r is not a valid %s name. Please %s." % (name, app_or_project, message))
top_dir = os.path.join(directory, name)
try:
os.mkdir(top_dir)
except OSError, e:
raise CommandError(e)
# Determine where the app or project templates are. Use
# django.__path__[0] because we don't know into which directory
# django has been installed.
template_dir = os.path.join(django.__path__[0], 'conf', '%s_template' % app_or_project)
for d, subdirs, files in os.walk(template_dir):
relative_dir = d[len(template_dir)+1:].replace('%s_name' % app_or_project, name)
if relative_dir:
os.mkdir(os.path.join(top_dir, relative_dir))
for subdir in subdirs[:]:
if subdir.startswith('.'):
subdirs.remove(subdir)
for f in files:
if not f.endswith('.py'):
# Ignore .pyc, .pyo, .py.class etc, as they cause various
# breakages.
continue
path_old = os.path.join(d, f)
path_new = os.path.join(top_dir, relative_dir, f.replace('%s_name' % app_or_project, name))
fp_old = open(path_old, 'r')
fp_new = open(path_new, 'w')
fp_new.write(fp_old.read().replace('{{ %s_name }}' % app_or_project, name).replace('{{ %s_name }}' % other, other_name))
fp_old.close()
fp_new.close()
try:
shutil.copymode(path_old, path_new)
_make_writeable(path_new)
except OSError:
sys.stderr.write(style.NOTICE("Notice: Couldn't set permission bits on %s. You're probably using an uncommon filesystem setup. No problem.\n" % path_new))
def install_scripts(self, context, path):
"""
Install scripts into the created environment from a directory.
:param context: The information for the environment creation request
being processed.
:param path: Absolute pathname of a directory containing script.
Scripts in the 'common' subdirectory of this directory,
and those in the directory named for the platform
being run on, are installed in the created environment.
Placeholder variables are replaced with environment-
specific values.
"""
binpath = context.bin_path
plen = len(path)
for root, dirs, files in os.walk(path):
if root == path: # at top-level, remove irrelevant dirs
for d in dirs[:]:
if d not in ('common', os.name):
dirs.remove(d)
continue # ignore files in top level
for f in files:
srcfile = os.path.join(root, f)
suffix = root[plen:].split(os.sep)[2:]
if not suffix:
dstdir = binpath
else:
dstdir = os.path.join(binpath, *suffix)
if not os.path.exists(dstdir):
os.makedirs(dstdir)
dstfile = os.path.join(dstdir, f)
with open(srcfile, 'rb') as f:
data = f.read()
if srcfile.endswith('.exe'):
mode = 'wb'
else:
mode = 'w'
try:
data = data.decode('utf-8')
data = self.replace_variables(data, context)
except UnicodeDecodeError as e:
data = None
logger.warning('unable to copy script %r, '
'may be binary: %s', srcfile, e)
if data is not None:
with open(dstfile, mode) as f:
f.write(data)
shutil.copymode(srcfile, dstfile)