Python shutil.copymode() Examples

The following are 30 code examples of shutil.copymode(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module shutil , or try the search function .
Example #1
Source File: file_Utils.py    From warriorframework with Apache License 2.0 6 votes vote down vote up
def copymode(src, dst):
    """
    Copy the permission bits from src to dst. The file contents, owner, and
    group are unaffected. src and dst are path names given as strings.
    :Arguments:
        src - mode of the file to be copied
        dst - file on which mode has to be copied
    :Return:
        True/False - based on the success/failure of the operation
    """
    status = False
    try:
        shutil.copymode(src, dst)
        print_info("mode of src {} copied to dst {} successfully".
                   format(src, dst))
        status = True
    except Exception as e:
        print_error("copying file mode from {} to file {} raised exception {}".
                    format(src, dst, str(e)))
    return status 
Example #2
Source File: fsm_cmd.py    From paasta with Apache License 2.0 6 votes vote down vote up
def make_copyfile_symlink_aware():
    """The reasoning behind this monkeypatch is that cookiecutter doesn't
    respect symlinks at all, and at Yelp we use symlinks to reduce duplication
    in the soa configs. Maybe cookie-cutter will accept a symlink-aware PR?
    """
    orig_copyfile = shutil.copyfile
    orig_copymode = shutil.copymode

    def symlink_aware_copyfile(*args, **kwargs):
        kwargs.setdefault("follow_symlinks", False)
        orig_copyfile(*args, **kwargs)

    def symlink_aware_copymode(*args, **kwargs):
        kwargs.setdefault("follow_symlinks", False)
        orig_copymode(*args, **kwargs)

    shutil.copyfile = symlink_aware_copyfile
    shutil.copymode = symlink_aware_copymode
    try:
        yield
    finally:
        shutil.copyfile = orig_copyfile
        shutil.copymode = orig_copymode 
Example #3
Source File: feedstock_io.py    From conda-smithy with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def copy_file(src, dst):
    """
    Tried to copy utf-8 text files line-by-line to avoid
    getting CRLF characters added on Windows.

    If the file fails to be decoded with utf-8, we revert to a regular copy.
    """
    try:
        with io.open(src, "r", encoding="utf-8") as fh_src:
            with io.open(dst, "w", encoding="utf-8", newline="\n") as fh_dst:
                for line in fh_src:
                    fh_dst.write(line)
    except UnicodeDecodeError:
        # Leave any other files alone.
        shutil.copy(src, dst)

    shutil.copymode(src, dst)

    repo = get_repo(dst)
    if repo:
        repo.index.add([dst]) 
Example #4
Source File: requirements.py    From flocker with Apache License 2.0 6 votes vote down vote up
def requirements_from_infile(infile):
    outfile = infile.sibling(infile.basename()[:-len(".in")])
    with NamedTemporaryFile(
        prefix="{}.".format(outfile.basename()),
        suffix=".created-by-update-requirements-entrypoint",
        dir=os.path.dirname(outfile.parent().path),
        delete=False,
    ) as temporary_outfile:
        print "PROCESSING", infile
        check_call(
            ["docker", "run",
             "--rm",
             "--volume", "{}:/requirements.txt".format(infile.path),
             REQUIREMENTS_IMAGE],
            stdout=temporary_outfile
        )
        shutil.copymode(outfile.path, temporary_outfile.name)
        os.rename(temporary_outfile.name, outfile.path) 
Example #5
Source File: absolute_imports.py    From toil with Apache License 2.0 6 votes vote down vote up
def main(root_path):
    for dir_path, dir_names, file_names in os.walk(root_path):
        for file_name in file_names:
            if file_name.endswith('.py') and file_name != 'setup.py':
                file_path = os.path.join(dir_path, file_name)
                with open(file_path) as file:
                    script = file.read()
                new_script = enable_absolute_imports(script, file_name)
                if new_script is not None:
                    temp_handle, temp_file_path = tempfile.mkstemp(prefix=file_name, dir=dir_path)
                    try:
                        with os.fdopen(temp_handle, 'w') as temp_file:
                            temp_file.write(new_script)
                    except:
                        os.unlink(temp_file_path)
                        raise
                    else:
                        shutil.copymode(file_path,temp_file_path)
                        os.rename(temp_file_path, file_path) 
Example #6
Source File: __init__.py    From dcos with Apache License 2.0 6 votes vote down vote up
def stage_new_units(self, new_wants_dir):
        """Prepare new systemd units for activation.

        Unit files targeted by the symlinks in new_wants_dir are copied to a temporary location in the base systemd
        directory, and the symlinks are rewritten to target the intended final destination of the copied unit files.

        """
        for unit_name in self.unit_names(new_wants_dir):
            wants_symlink_path = os.path.join(new_wants_dir, unit_name)
            package_file_path = os.path.realpath(wants_symlink_path)
            systemd_file_path = os.path.join(self.__base_systemd, unit_name)
            tmp_systemd_file_path = systemd_file_path + self.new_unit_suffix

            # Copy the unit file to the systemd directory with a suffix added to the filename.
            # This file will be moved to systemd_file_path when the new package set is swapped in.
            shutil.copyfile(package_file_path, tmp_systemd_file_path)
            shutil.copymode(package_file_path, tmp_systemd_file_path)

            # Rewrite the symlink to point to the copied unit file's destination.
            # This symlink won't point to the correct file until the copied unit file is moved to its target location
            # during activate_new_unit_files().
            os.remove(wants_symlink_path)
            os.symlink(systemd_file_path, wants_symlink_path) 
Example #7
Source File: main.py    From odoo13-x64 with GNU General Public License v3.0 5 votes vote down vote up
def write_file(self, new_text, filename, old_text, encoding):
        orig_filename = filename
        if self._output_dir:
            if filename.startswith(self._input_base_dir):
                filename = os.path.join(self._output_dir,
                                        filename[len(self._input_base_dir):])
            else:
                raise ValueError('filename %s does not start with the '
                                 'input_base_dir %s' % (
                                         filename, self._input_base_dir))
        if self._append_suffix:
            filename += self._append_suffix
        if orig_filename != filename:
            output_dir = os.path.dirname(filename)
            if not os.path.isdir(output_dir) and output_dir:
                os.makedirs(output_dir)
            self.log_message('Writing converted %s to %s.', orig_filename,
                             filename)
        if not self.nobackups:
            # Make backup
            backup = filename + ".bak"
            if os.path.lexists(backup):
                try:
                    os.remove(backup)
                except OSError as err:
                    self.log_message("Can't remove backup %s", backup)
            try:
                os.rename(filename, backup)
            except OSError as err:
                self.log_message("Can't rename %s to %s", filename, backup)
        # Actually write the new file
        write = super(StdoutRefactoringTool, self).write_file
        write(new_text, filename, old_text, encoding)
        if not self.nobackups:
            shutil.copymode(backup, filename)
        if orig_filename != filename:
            # Preserve the file mode in the new output directory.
            shutil.copymode(orig_filename, filename) 
Example #8
Source File: util.py    From guildai with Apache License 2.0 5 votes vote down vote up
def copyfile(src, dest):
    shutil.copyfile(src, dest)
    shutil.copymode(src, dest) 
Example #9
Source File: main.py    From Imogen with MIT License 5 votes vote down vote up
def write_file(self, new_text, filename, old_text, encoding):
        orig_filename = filename
        if self._output_dir:
            if filename.startswith(self._input_base_dir):
                filename = os.path.join(self._output_dir,
                                        filename[len(self._input_base_dir):])
            else:
                raise ValueError('filename %s does not start with the '
                                 'input_base_dir %s' % (
                                         filename, self._input_base_dir))
        if self._append_suffix:
            filename += self._append_suffix
        if orig_filename != filename:
            output_dir = os.path.dirname(filename)
            if not os.path.isdir(output_dir) and output_dir:
                os.makedirs(output_dir)
            self.log_message('Writing converted %s to %s.', orig_filename,
                             filename)
        if not self.nobackups:
            # Make backup
            backup = filename + ".bak"
            if os.path.lexists(backup):
                try:
                    os.remove(backup)
                except OSError as err:
                    self.log_message("Can't remove backup %s", backup)
            try:
                os.rename(filename, backup)
            except OSError as err:
                self.log_message("Can't rename %s to %s", filename, backup)
        # Actually write the new file
        write = super(StdoutRefactoringTool, self).write_file
        write(new_text, filename, old_text, encoding)
        if not self.nobackups:
            shutil.copymode(backup, filename)
        if orig_filename != filename:
            # Preserve the file mode in the new output directory.
            shutil.copymode(orig_filename, filename) 
Example #10
Source File: fileutil.py    From stagger with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def _replace_chunk(filename, offset, length, chunk, in_place, max_mem):
    assert isinstance(filename, str) or in_place
    with opened(filename, "rb+") as file:
        # If the sizes match, we can simply overwrite the original data.
        if length == len(chunk):
            file.seek(offset)
            file.write(chunk)
            return

        oldsize = file.seek(0, 2)
        newsize = oldsize - length + len(chunk)

        # If the orig chunk is exactly at the end of the file, we can
        # simply truncate the file and then append the new chunk.
        if offset + length == oldsize:
            file.seek(offset)
            file.truncate()
            file.write(chunk)
            return

        if in_place:
            _replace_chunk_in_place(file, offset, length, chunk, oldsize, newsize)
        else: # not in_place
            temp = tempfile.NamedTemporaryFile(dir=os.path.dirname(filename),
                                               prefix="stagger-",
                                               suffix=".tmp",
                                               delete=False)
            try:
                file.seek(0)
                _copy_chunk(file, temp, offset)
                temp.write(chunk)
                file.seek(offset + length)
                _copy_chunk(file, temp, oldsize - offset - length)
            finally:
                temp.close()
                file.close()
            shutil.copymode(filename, temp.name)
            shutil.move(temp.name, filename)
            return 
Example #11
Source File: main.py    From ironpython3 with Apache License 2.0 5 votes vote down vote up
def write_file(self, new_text, filename, old_text, encoding):
        orig_filename = filename
        if self._output_dir:
            if filename.startswith(self._input_base_dir):
                filename = os.path.join(self._output_dir,
                                        filename[len(self._input_base_dir):])
            else:
                raise ValueError('filename %s does not start with the '
                                 'input_base_dir %s' % (
                                         filename, self._input_base_dir))
        if self._append_suffix:
            filename += self._append_suffix
        if orig_filename != filename:
            output_dir = os.path.dirname(filename)
            if not os.path.isdir(output_dir):
                os.makedirs(output_dir)
            self.log_message('Writing converted %s to %s.', orig_filename,
                             filename)
        if not self.nobackups:
            # Make backup
            backup = filename + ".bak"
            if os.path.lexists(backup):
                try:
                    os.remove(backup)
                except OSError as err:
                    self.log_message("Can't remove backup %s", backup)
            try:
                os.rename(filename, backup)
            except OSError as err:
                self.log_message("Can't rename %s to %s", filename, backup)
        # Actually write the new file
        write = super(StdoutRefactoringTool, self).write_file
        write(new_text, filename, old_text, encoding)
        if not self.nobackups:
            shutil.copymode(backup, filename)
        if orig_filename != filename:
            # Preserve the file mode in the new output directory.
            shutil.copymode(orig_filename, filename) 
Example #12
Source File: test_shutil.py    From ironpython3 with Apache License 2.0 5 votes vote down vote up
def test_copymode_follow_symlinks(self):
        tmp_dir = self.mkdtemp()
        src = os.path.join(tmp_dir, 'foo')
        dst = os.path.join(tmp_dir, 'bar')
        src_link = os.path.join(tmp_dir, 'baz')
        dst_link = os.path.join(tmp_dir, 'quux')
        write_file(src, 'foo')
        write_file(dst, 'foo')
        os.symlink(src, src_link)
        os.symlink(dst, dst_link)
        os.chmod(src, stat.S_IRWXU|stat.S_IRWXG)
        # file to file
        os.chmod(dst, stat.S_IRWXO)
        self.assertNotEqual(os.stat(src).st_mode, os.stat(dst).st_mode)
        shutil.copymode(src, dst)
        self.assertEqual(os.stat(src).st_mode, os.stat(dst).st_mode)
        # On Windows, os.chmod does not follow symlinks (issue #15411)
        if os.name != 'nt':
            # follow src link
            os.chmod(dst, stat.S_IRWXO)
            shutil.copymode(src_link, dst)
            self.assertEqual(os.stat(src).st_mode, os.stat(dst).st_mode)
            # follow dst link
            os.chmod(dst, stat.S_IRWXO)
            shutil.copymode(src, dst_link)
            self.assertEqual(os.stat(src).st_mode, os.stat(dst).st_mode)
            # follow both links
            os.chmod(dst, stat.S_IRWXO)
            shutil.copymode(src_link, dst_link)
            self.assertEqual(os.stat(src).st_mode, os.stat(dst).st_mode) 
Example #13
Source File: test_shutil.py    From ironpython3 with Apache License 2.0 5 votes vote down vote up
def test_copymode_symlink_to_symlink(self):
        tmp_dir = self.mkdtemp()
        src = os.path.join(tmp_dir, 'foo')
        dst = os.path.join(tmp_dir, 'bar')
        src_link = os.path.join(tmp_dir, 'baz')
        dst_link = os.path.join(tmp_dir, 'quux')
        write_file(src, 'foo')
        write_file(dst, 'foo')
        os.symlink(src, src_link)
        os.symlink(dst, dst_link)
        os.chmod(src, stat.S_IRWXU|stat.S_IRWXG)
        os.chmod(dst, stat.S_IRWXU)
        os.lchmod(src_link, stat.S_IRWXO|stat.S_IRWXG)
        # link to link
        os.lchmod(dst_link, stat.S_IRWXO)
        shutil.copymode(src_link, dst_link, follow_symlinks=False)
        self.assertEqual(os.lstat(src_link).st_mode,
                         os.lstat(dst_link).st_mode)
        self.assertNotEqual(os.stat(src).st_mode, os.stat(dst).st_mode)
        # src link - use chmod
        os.lchmod(dst_link, stat.S_IRWXO)
        shutil.copymode(src_link, dst, follow_symlinks=False)
        self.assertEqual(os.stat(src).st_mode, os.stat(dst).st_mode)
        # dst link - use chmod
        os.lchmod(dst_link, stat.S_IRWXO)
        shutil.copymode(src, dst_link, follow_symlinks=False)
        self.assertEqual(os.stat(src).st_mode, os.stat(dst).st_mode) 
Example #14
Source File: test_shutil.py    From ironpython3 with Apache License 2.0 5 votes vote down vote up
def test_copymode_symlink_to_symlink_wo_lchmod(self):
        tmp_dir = self.mkdtemp()
        src = os.path.join(tmp_dir, 'foo')
        dst = os.path.join(tmp_dir, 'bar')
        src_link = os.path.join(tmp_dir, 'baz')
        dst_link = os.path.join(tmp_dir, 'quux')
        write_file(src, 'foo')
        write_file(dst, 'foo')
        os.symlink(src, src_link)
        os.symlink(dst, dst_link)
        shutil.copymode(src_link, dst_link, follow_symlinks=False)  # silent fail 
Example #15
Source File: test_shutil.py    From ironpython3 with Apache License 2.0 5 votes vote down vote up
def test_copymode(self):
        from_filename = os.path.join(self.test_dir, "test_copymode_from")
        with open(from_filename, "wb"): pass
        os.chmod(from_filename, 0o642)
        from_stat = os.stat(from_filename)

        to_filename = os.path.join(self.test_dir, "test_copymode_to")
        with open(to_filename, "wb"): pass
        shutil.copymode(from_filename, to_filename)
        to_stat = os.stat(to_filename)

        self.assertEqual(from_stat.st_mode, to_stat.st_mode) 
Example #16
Source File: test_shutil.py    From Project-New-Reign---Nemesis-Main with GNU General Public License v3.0 5 votes vote down vote up
def test_copymode_symlink_to_symlink_wo_lchmod(self):
        tmp_dir = self.mkdtemp()
        src = os.path.join(tmp_dir, 'foo')
        dst = os.path.join(tmp_dir, 'bar')
        src_link = os.path.join(tmp_dir, 'baz')
        dst_link = os.path.join(tmp_dir, 'quux')
        write_file(src, 'foo')
        write_file(dst, 'foo')
        os.symlink(src, src_link)
        os.symlink(dst, dst_link)
        shutil.copymode(src_link, dst_link, follow_symlinks=False)  # silent fail 
Example #17
Source File: mylogin_show_password.py    From mysql-utilities with GNU General Public License v2.0 5 votes vote down vote up
def setup(self):
        # Backup and replace .mylogin.cnf file
        self.mylogin_bkp = "{0}.bkp".format(self.mylogin_src)
        shutil.move(self.mylogin_src, self.mylogin_bkp)

        # Replace with test.mylogin.cnf
        mylogin_test_src = os.path.normpath("./std_data/test.mylogin.cnf")
        shutil.copy(mylogin_test_src, self.mylogin_src)

        # Copy permissions
        shutil.copymode(self.mylogin_bkp, self.mylogin_src)

        return True 
Example #18
Source File: patch.py    From towerlib with MIT License 5 votes vote down vote up
def write_hunks(self, srcname, tgtname, hunks):
    src = open(srcname, "rb")
    tgt = open(tgtname, "wb")

    debug("processing target file %s" % tgtname)

    tgt.writelines(self.patch_stream(src, hunks))

    tgt.close()
    src.close()
    # [ ] TODO: add test for permission copy
    shutil.copymode(srcname, tgtname)
    return True 
Example #19
Source File: file_util.py    From guildai with Apache License 2.0 5 votes vote down vote up
def _try_copy_file(self, src, dest):
        try:
            shutil.copyfile(src, dest)
            shutil.copymode(src, dest)
        except IOError as e:
            if e.errno != 2:  # Ignore file not exists
                if not self.handle_copy_error(e, src, dest):
                    raise
        except OSError as e:  # pylint: disable=duplicate-except
            if not self.handle_copy_error(e, src, dest):
                raise 
Example #20
Source File: freezer.py    From tensorlang with Apache License 2.0 5 votes vote down vote up
def _CopyFile(self, source, target, copyDependentFiles,
            includeMode = False):
        normalizedSource = os.path.normcase(os.path.normpath(source))
        normalizedTarget = os.path.normcase(os.path.normpath(target))
        if normalizedTarget in self.filesCopied:
            return
        if normalizedSource == normalizedTarget:
            return
        self._RemoveFile(target)
        targetDir = os.path.dirname(target)
        self._CreateDirectory(targetDir)
        if not self.silent:
            sys.stdout.write("copying %s -> %s\n" % (source, target))
        shutil.copyfile(source, target)
        shutil.copystat(source, target)
        if includeMode:
            shutil.copymode(source, target)
        self.filesCopied[normalizedTarget] = None
        if copyDependentFiles:
            changedDependencies = []
            for depSource in self._GetDependentFiles(source):
                depTarget = os.path.join(self.targetDir, "lib", os.path.basename(depSource))
                self._CopyFile(depSource, depTarget, copyDependentFiles)
                newName = self._UpdateLibraryName(depTarget)
                if newName:
                    changedDependencies.append((depSource, newName))

            if changedDependencies:
                self._UpdateDependendentFiles(target, changedDependencies) 
Example #21
Source File: cdrom.py    From nitro with GNU General Public License v3.0 5 votes vote down vote up
def add_file(self, path):
        source = Path(path)
        destination = os.path.join(self.cdrom_dir, source.name)
        shutil.copyfile(str(source), destination)
        shutil.copymode(str(source), destination) 
Example #22
Source File: main.py    From Carnets with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def write_file(self, new_text, filename, old_text, encoding):
        orig_filename = filename
        if self._output_dir:
            if filename.startswith(self._input_base_dir):
                filename = os.path.join(self._output_dir,
                                        filename[len(self._input_base_dir):])
            else:
                raise ValueError('filename %s does not start with the '
                                 'input_base_dir %s' % (
                                         filename, self._input_base_dir))
        if self._append_suffix:
            filename += self._append_suffix
        if orig_filename != filename:
            output_dir = os.path.dirname(filename)
            if not os.path.isdir(output_dir) and output_dir:
                os.makedirs(output_dir)
            self.log_message('Writing converted %s to %s.', orig_filename,
                             filename)
        if not self.nobackups:
            # Make backup
            backup = filename + ".bak"
            if os.path.lexists(backup):
                try:
                    os.remove(backup)
                except OSError as err:
                    self.log_message("Can't remove backup %s", backup)
            try:
                os.rename(filename, backup)
            except OSError as err:
                self.log_message("Can't rename %s to %s", filename, backup)
        # Actually write the new file
        write = super(StdoutRefactoringTool, self).write_file
        write(new_text, filename, old_text, encoding)
        if not self.nobackups:
            shutil.copymode(backup, filename)
        if orig_filename != filename:
            # Preserve the file mode in the new output directory.
            shutil.copymode(orig_filename, filename) 
Example #23
Source File: main.py    From Project-New-Reign---Nemesis-Main with GNU General Public License v3.0 5 votes vote down vote up
def write_file(self, new_text, filename, old_text, encoding):
        orig_filename = filename
        if self._output_dir:
            if filename.startswith(self._input_base_dir):
                filename = os.path.join(self._output_dir,
                                        filename[len(self._input_base_dir):])
            else:
                raise ValueError('filename %s does not start with the '
                                 'input_base_dir %s' % (
                                         filename, self._input_base_dir))
        if self._append_suffix:
            filename += self._append_suffix
        if orig_filename != filename:
            output_dir = os.path.dirname(filename)
            if not os.path.isdir(output_dir):
                os.makedirs(output_dir)
            self.log_message('Writing converted %s to %s.', orig_filename,
                             filename)
        if not self.nobackups:
            # Make backup
            backup = filename + ".bak"
            if os.path.lexists(backup):
                try:
                    os.remove(backup)
                except OSError as err:
                    self.log_message("Can't remove backup %s", backup)
            try:
                os.rename(filename, backup)
            except OSError as err:
                self.log_message("Can't rename %s to %s", filename, backup)
        # Actually write the new file
        write = super(StdoutRefactoringTool, self).write_file
        write(new_text, filename, old_text, encoding)
        if not self.nobackups:
            shutil.copymode(backup, filename)
        if orig_filename != filename:
            # Preserve the file mode in the new output directory.
            shutil.copymode(orig_filename, filename) 
Example #24
Source File: test_shutil.py    From Project-New-Reign---Nemesis-Main with GNU General Public License v3.0 5 votes vote down vote up
def test_copymode_follow_symlinks(self):
        tmp_dir = self.mkdtemp()
        src = os.path.join(tmp_dir, 'foo')
        dst = os.path.join(tmp_dir, 'bar')
        src_link = os.path.join(tmp_dir, 'baz')
        dst_link = os.path.join(tmp_dir, 'quux')
        write_file(src, 'foo')
        write_file(dst, 'foo')
        os.symlink(src, src_link)
        os.symlink(dst, dst_link)
        os.chmod(src, stat.S_IRWXU|stat.S_IRWXG)
        # file to file
        os.chmod(dst, stat.S_IRWXO)
        self.assertNotEqual(os.stat(src).st_mode, os.stat(dst).st_mode)
        shutil.copymode(src, dst)
        self.assertEqual(os.stat(src).st_mode, os.stat(dst).st_mode)
        # On Windows, os.chmod does not follow symlinks (issue #15411)
        if os.name != 'nt':
            # follow src link
            os.chmod(dst, stat.S_IRWXO)
            shutil.copymode(src_link, dst)
            self.assertEqual(os.stat(src).st_mode, os.stat(dst).st_mode)
            # follow dst link
            os.chmod(dst, stat.S_IRWXO)
            shutil.copymode(src, dst_link)
            self.assertEqual(os.stat(src).st_mode, os.stat(dst).st_mode)
            # follow both links
            os.chmod(dst, stat.S_IRWXO)
            shutil.copymode(src_link, dst_link)
            self.assertEqual(os.stat(src).st_mode, os.stat(dst).st_mode) 
Example #25
Source File: test_shutil.py    From Project-New-Reign---Nemesis-Main with GNU General Public License v3.0 5 votes vote down vote up
def test_copymode_symlink_to_symlink(self):
        tmp_dir = self.mkdtemp()
        src = os.path.join(tmp_dir, 'foo')
        dst = os.path.join(tmp_dir, 'bar')
        src_link = os.path.join(tmp_dir, 'baz')
        dst_link = os.path.join(tmp_dir, 'quux')
        write_file(src, 'foo')
        write_file(dst, 'foo')
        os.symlink(src, src_link)
        os.symlink(dst, dst_link)
        os.chmod(src, stat.S_IRWXU|stat.S_IRWXG)
        os.chmod(dst, stat.S_IRWXU)
        os.lchmod(src_link, stat.S_IRWXO|stat.S_IRWXG)
        # link to link
        os.lchmod(dst_link, stat.S_IRWXO)
        shutil.copymode(src_link, dst_link, follow_symlinks=False)
        self.assertEqual(os.lstat(src_link).st_mode,
                         os.lstat(dst_link).st_mode)
        self.assertNotEqual(os.stat(src).st_mode, os.stat(dst).st_mode)
        # src link - use chmod
        os.lchmod(dst_link, stat.S_IRWXO)
        shutil.copymode(src_link, dst, follow_symlinks=False)
        self.assertEqual(os.stat(src).st_mode, os.stat(dst).st_mode)
        # dst link - use chmod
        os.lchmod(dst_link, stat.S_IRWXO)
        shutil.copymode(src, dst_link, follow_symlinks=False)
        self.assertEqual(os.stat(src).st_mode, os.stat(dst).st_mode) 
Example #26
Source File: test_shutil.py    From Fluid-Designer with GNU General Public License v3.0 5 votes vote down vote up
def test_copymode_symlink_to_symlink_wo_lchmod(self):
        tmp_dir = self.mkdtemp()
        src = os.path.join(tmp_dir, 'foo')
        dst = os.path.join(tmp_dir, 'bar')
        src_link = os.path.join(tmp_dir, 'baz')
        dst_link = os.path.join(tmp_dir, 'quux')
        write_file(src, 'foo')
        write_file(dst, 'foo')
        os.symlink(src, src_link)
        os.symlink(dst, dst_link)
        shutil.copymode(src_link, dst_link, follow_symlinks=False)  # silent fail 
Example #27
Source File: usb_drive_copymode.py    From pi_video_looper with GNU General Public License v2.0 5 votes vote down vote up
def _load_config(self, config):
        self._mount_path = config.get('usb_drive', 'mount_path')
        self._readonly = config.getboolean('usb_drive', 'readonly')
        self._target_path = config.get('directory', 'path')
        self._copy_mode = config.get('copymode', 'mode')
        self._copyloader = config.getboolean('copymode', 'copyloader')
        self._password = config.get('copymode', 'password')

        #needs to be changed to a more generic approach to support other players
        self._extensions = '|'.join(config.get(self._config.get('video_looper', 'video_player'), 'extensions') \
                                 .translate(str.maketrans('','', ' \t\r\n.')) \
                                 .split(',')) 
Example #28
Source File: patch.py    From toonapilib with MIT License 5 votes vote down vote up
def write_hunks(self, srcname, tgtname, hunks):
    src = open(srcname, "rb")
    tgt = open(tgtname, "wb")

    debug("processing target file %s" % tgtname)

    tgt.writelines(self.patch_stream(src, hunks))

    tgt.close()
    src.close()
    # [ ] TODO: add test for permission copy
    shutil.copymode(srcname, tgtname)
    return True 
Example #29
Source File: usb_drive_copymode.py    From pi_video_looper with GNU General Public License v2.0 5 votes vote down vote up
def copy_with_progress(self, src, dst, *, follow_symlinks=True):
        if os.path.isdir(dst):
            dst = os.path.join(dst, os.path.basename(src))

        # clear screen before copying
        self.clear_screen(False)

        self.copyfile(src, dst, follow_symlinks=follow_symlinks)
        # shutil.copymode(src, dst)
        return dst 
Example #30
Source File: main.py    From misp42splunk with GNU Lesser General Public License v3.0 5 votes vote down vote up
def write_file(self, new_text, filename, old_text, encoding):
        orig_filename = filename
        if self._output_dir:
            if filename.startswith(self._input_base_dir):
                filename = os.path.join(self._output_dir,
                                        filename[len(self._input_base_dir):])
            else:
                raise ValueError('filename %s does not start with the '
                                 'input_base_dir %s' % (
                                         filename, self._input_base_dir))
        if self._append_suffix:
            filename += self._append_suffix
        if orig_filename != filename:
            output_dir = os.path.dirname(filename)
            if not os.path.isdir(output_dir) and output_dir:
                os.makedirs(output_dir)
            self.log_message('Writing converted %s to %s.', orig_filename,
                             filename)
        if not self.nobackups:
            # Make backup
            backup = filename + ".bak"
            if os.path.lexists(backup):
                try:
                    os.remove(backup)
                except OSError as err:
                    self.log_message("Can't remove backup %s", backup)
            try:
                os.rename(filename, backup)
            except OSError as err:
                self.log_message("Can't rename %s to %s", filename, backup)
        # Actually write the new file
        write = super(StdoutRefactoringTool, self).write_file
        write(new_text, filename, old_text, encoding)
        if not self.nobackups:
            shutil.copymode(backup, filename)
        if orig_filename != filename:
            # Preserve the file mode in the new output directory.
            shutil.copymode(orig_filename, filename)