Python os.chmod() Examples

The following are code examples for showing how to use os.chmod(). They are from open source Python projects. You can vote up the examples you like or vote down the ones you don't like.

Example 1
Project: gpu-mux   Author: google   File: gpumux.py    Apache License 2.0 7 votes vote down vote up
def spawn(self):
        assert self.status is None
        bash_cmd = BASH_CMD % dict(cmd=self.cmd, gpu=self.gpu,
                                   status='%d.status' % self.id)
        open(os.path.join(RUNNING_PATH, '%d.gpu' % self.id), 'w').write(
            str(self.gpu) + '\n')
        open(os.path.join(RUNNING_PATH, '%d.cmd' % self.id), 'w').write(
            str(self.cmd) + '\n')
        open(os.path.join(RUNNING_PATH, '%d.sh' % self.id), 'w').write(bash_cmd)
        open(os.path.join(RUNNING_PATH, '%d.screenrc' % self.id), 'w').write(
            SCREEN_RC % self.id)
        os.chmod(os.path.join(RUNNING_PATH, '%d.sh' % self.id), 0o700)
        popen = subprocess.Popen(['screen', '-dm', '-L',
                                  '-S', self.screen_id,
                                  '-c', '%d.screenrc' % self.id,
                                  './%d.sh' % self.id],
                                 cwd=RUNNING_PATH)
        status = popen.wait()
        assert status == 0 
Example 2
Project: fs_image   Author: facebookincubator   File: test_package_image.py    MIT License 6 votes vote down vote up
def test_package_image_as_btrfs_loopback_writable(self):
        with self._package_image(
            self._sibling_path('create_ops.layer'),
            'btrfs',
            writable_subvolume=True,
        ) as out_path, \
                Unshare([Namespace.MOUNT, Namespace.PID]) as unshare, \
                tempfile.TemporaryDirectory() as mount_dir:
            os.chmod(
                out_path,
                stat.S_IMODE(os.stat(out_path).st_mode)
                | (stat.S_IWUSR | stat.S_IWGRP | stat.S_IWOTH),
            )
            subprocess.check_call(nsenter_as_root(
                unshare, 'mount', '-t', 'btrfs', '-o', 'loop,discard,nobarrier',
                out_path, mount_dir,
            ))
            try:
                subprocess.check_call(nsenter_as_root(
                    unshare, 'touch', os.path.join(mount_dir,
                                                   'create_ops',
                                                   'foo'),
                ))
            finally:
                nsenter_as_root(unshare, 'umount', mount_dir) 
Example 3
Project: fs_image   Author: facebookincubator   File: package_image.py    MIT License 6 votes vote down vote up
def package_image(argv):
    args = parse_args(argv)
    assert not os.path.exists(args.output_path)
    Format.make(args.format).package_full(
        find_built_subvol(args.layer_path, subvolumes_dir=args.subvolumes_dir),
        output_path=args.output_path,
        opts=_Opts(
            subvol_opts=SubvolOpts(readonly=not args.writable_subvolume),
        ),
    )
    # Paranoia: images are read-only after being built
    os.chmod(
        args.output_path,
        stat.S_IMODE(os.stat(args.output_path).st_mode)
            & ~(stat.S_IWUSR | stat.S_IWGRP | stat.S_IWOTH),
    ) 
Example 4
Project: leapp-repository   Author: oamg   File: actor.py    Apache License 2.0 6 votes vote down vote up
def process(self):
        leapp_home = "/root/tmp_leapp_py3"
        py3_leapp = os.path.join(leapp_home, "leapp3")
        os.mkdir(leapp_home)
        os.symlink(
            "/usr/lib/python2.7/site-packages/leapp",
            os.path.join(leapp_home, "leapp"))
        with open(py3_leapp, "w") as f:
            f_content = [
                "#!/usr/bin/python3",
                "import sys",
                "sys.path.append('{}')".format(leapp_home),
                "",
                "import leapp.cli",
                "sys.exit(leapp.cli.main())",
            ]
            f.write("{}\n\n".format("\n".join(f_content)))
        os.chmod(py3_leapp, 0o770) 
Example 5
Project: pyblish-win   Author: pyblish   File: test_netrc.py    GNU Lesser General Public License v3.0 6 votes vote down vote up
def test_security(self):
        # This test is incomplete since we are normally not run as root and
        # therefore can't test the file ownership being wrong.
        d = test_support.TESTFN
        os.mkdir(d)
        self.addCleanup(test_support.rmtree, d)
        fn = os.path.join(d, '.netrc')
        with open(fn, 'wt') as f:
            f.write("""\
                machine foo.domain.com login bar password pass
                default login foo password pass
                """)
        with test_support.EnvironmentVarGuard() as environ:
            environ.set('HOME', d)
            os.chmod(fn, 0600)
            nrc = netrc.netrc()
            self.assertEqual(nrc.hosts['foo.domain.com'],
                             ('bar', None, 'pass'))
            os.chmod(fn, 0o622)
            self.assertRaises(netrc.NetrcParseError, netrc.netrc) 
Example 6
Project: pyblish-win   Author: pyblish   File: test_import.py    GNU Lesser General Public License v3.0 6 votes vote down vote up
def test_execute_bit_not_copied(self):
        # Issue 6070: under posix .pyc files got their execute bit set if
        # the .py file had the execute bit set, but they aren't executable.
        oldmask = os.umask(022)
        sys.path.insert(0, os.curdir)
        try:
            fname = TESTFN + os.extsep + "py"
            f = open(fname, 'w').close()
            os.chmod(fname, (stat.S_IRUSR | stat.S_IRGRP | stat.S_IROTH |
                             stat.S_IXUSR | stat.S_IXGRP | stat.S_IXOTH))
            __import__(TESTFN)
            fn = fname + 'c'
            if not os.path.exists(fn):
                fn = fname + 'o'
                if not os.path.exists(fn):
                    self.fail("__import__ did not result in creation of "
                              "either a .pyc or .pyo file")
            s = os.stat(fn)
            self.assertEqual(stat.S_IMODE(s.st_mode),
                             stat.S_IRUSR | stat.S_IRGRP | stat.S_IROTH)
        finally:
            os.umask(oldmask)
            remove_files(TESTFN)
            unload(TESTFN)
            del sys.path[0] 
Example 7
Project: pyblish-win   Author: pyblish   File: test_shutil.py    GNU Lesser General Public License v3.0 6 votes vote down vote up
def test_on_error(self):
        self.errorState = 0
        os.mkdir(TESTFN)
        self.childpath = os.path.join(TESTFN, 'a')
        f = open(self.childpath, 'w')
        f.close()
        old_dir_mode = os.stat(TESTFN).st_mode
        old_child_mode = os.stat(self.childpath).st_mode
        # Make unwritable.
        os.chmod(self.childpath, stat.S_IREAD)
        os.chmod(TESTFN, stat.S_IREAD)

        shutil.rmtree(TESTFN, onerror=self.check_args_to_onerror)
        # Test whether onerror has actually been called.
        self.assertEqual(self.errorState, 2,
                            "Expected call to onerror function did not happen.")

        # Make writable again.
        os.chmod(TESTFN, old_dir_mode)
        os.chmod(self.childpath, old_child_mode)

        # Clean up.
        shutil.rmtree(TESTFN) 
Example 8
Project: pyblish-win   Author: pyblish   File: test_mailbox.py    GNU Lesser General Public License v3.0 6 votes vote down vote up
def test_permissions_after_flush(self):
        # See issue #5346

        # Make the mailbox world writable. It's unlikely that the new
        # mailbox file would have these permissions after flush(),
        # because umask usually prevents it.
        mode = os.stat(self._path).st_mode | 0o666
        os.chmod(self._path, mode)

        self._box.add(self._template % 0)
        i = self._box.add(self._template % 1)
        # Need to remove one message to make flush() create a new file
        self._box.remove(i)
        self._box.flush()

        self.assertEqual(os.stat(self._path).st_mode, mode) 
Example 9
Project: Flask-Python-GAE-Login-Registration   Author: orymeyer   File: cache.py    Apache License 2.0 6 votes vote down vote up
def set(self, key, value, timeout=None):
        if timeout is None:
            timeout = self.default_timeout
        filename = self._get_filename(key)
        self._prune()
        try:
            fd, tmp = tempfile.mkstemp(suffix=self._fs_transaction_suffix,
                                       dir=self._path)
            with os.fdopen(fd, 'wb') as f:
                pickle.dump(int(time() + timeout), f, 1)
                pickle.dump(value, f, pickle.HIGHEST_PROTOCOL)
            rename(tmp, filename)
            os.chmod(filename, self._mode)
        except (IOError, OSError):
            return False
        else:
            return True 
Example 10
Project: Flask-Python-GAE-Login-Registration   Author: orymeyer   File: cache.py    Apache License 2.0 6 votes vote down vote up
def set(self, key, value, timeout=None):
        if timeout is None:
            timeout = self.default_timeout
        filename = self._get_filename(key)
        self._prune()
        try:
            fd, tmp = tempfile.mkstemp(suffix=self._fs_transaction_suffix,
                                       dir=self._path)
            with os.fdopen(fd, 'wb') as f:
                pickle.dump(int(time() + timeout), f, 1)
                pickle.dump(value, f, pickle.HIGHEST_PROTOCOL)
            rename(tmp, filename)
            os.chmod(filename, self._mode)
        except (IOError, OSError):
            return False
        else:
            return True 
Example 11
Project: Ansible-Example-AB2018   Author: umit-ozturk   File: __init__.py    MIT License 6 votes vote down vote up
def postprocess(self, tempname, filename):
        """Perform any platform-specific postprocessing of `tempname`

        This is where Mac header rewrites should be done; other platforms don't
        have anything special they should do.

        Resource providers should call this method ONLY after successfully
        extracting a compressed resource.  They must NOT call it on resources
        that are already in the filesystem.

        `tempname` is the current (temporary) name of the file, and `filename`
        is the name it will be renamed to by the caller after this routine
        returns.
        """

        if os.name == 'posix':
            # Make the resource executable
            mode = ((os.stat(tempname).st_mode) | 0o555) & 0o7777
            os.chmod(tempname, mode) 
Example 12
Project: Ansible-Example-AB2018   Author: umit-ozturk   File: __init__.py    MIT License 6 votes vote down vote up
def postprocess(self, tempname, filename):
        """Perform any platform-specific postprocessing of `tempname`

        This is where Mac header rewrites should be done; other platforms don't
        have anything special they should do.

        Resource providers should call this method ONLY after successfully
        extracting a compressed resource.  They must NOT call it on resources
        that are already in the filesystem.

        `tempname` is the current (temporary) name of the file, and `filename`
        is the name it will be renamed to by the caller after this routine
        returns.
        """

        if os.name == 'posix':
            # Make the resource executable
            mode = ((os.stat(tempname).st_mode) | 0o555) & 0o7777
            os.chmod(tempname, mode) 
Example 13
Project: flasky   Author: RoseOu   File: util.py    MIT License 6 votes vote down vote up
def rmtree_errorhandler(func, path, exc_info):
    """On Windows, the files in .svn are read-only, so when rmtree() tries to
    remove them, an exception is thrown.  We catch that here, remove the
    read-only attribute, and hopefully continue without problems."""
    exctype, value = exc_info[:2]
    if not ((exctype is WindowsError and value.args[0] == 5) or #others
            (exctype is OSError and value.args[0] == 13) or #python2.4
            (exctype is PermissionError and value.args[3] == 5) #python3.3
            ):
        raise
    # file type should currently be read only
    if ((os.stat(path).st_mode & stat.S_IREAD) != stat.S_IREAD):
        raise
    # convert to read/write
    os.chmod(path, stat.S_IWRITE)
    # use the original function to repeat the operation
    func(path) 
Example 14
Project: flasky   Author: RoseOu   File: pkg_resources.py    MIT License 6 votes vote down vote up
def postprocess(self, tempname, filename):
        """Perform any platform-specific postprocessing of `tempname`

        This is where Mac header rewrites should be done; other platforms don't
        have anything special they should do.

        Resource providers should call this method ONLY after successfully
        extracting a compressed resource.  They must NOT call it on resources
        that are already in the filesystem.

        `tempname` is the current (temporary) name of the file, and `filename`
        is the name it will be renamed to by the caller after this routine
        returns.
        """

        if os.name == 'posix':
            # Make the resource executable
            mode = ((os.stat(tempname).st_mode) | 0x16D) & 0xFFF # 0555, 07777
            os.chmod(tempname, mode) 
Example 15
Project: flasky   Author: RoseOu   File: cache.py    MIT License 6 votes vote down vote up
def set(self, key, value, timeout=None):
        if timeout is None:
            timeout = self.default_timeout
        filename = self._get_filename(key)
        self._prune()
        try:
            fd, tmp = tempfile.mkstemp(suffix=self._fs_transaction_suffix,
                                       dir=self._path)
            with os.fdopen(fd, 'wb') as f:
                pickle.dump(int(time() + timeout), f, 1)
                pickle.dump(value, f, pickle.HIGHEST_PROTOCOL)
            rename(tmp, filename)
            os.chmod(filename, self._mode)
        except (IOError, OSError):
            return False
        else:
            return True 
Example 16
Project: flasky   Author: RoseOu   File: pidfile.py    MIT License 6 votes vote down vote up
def create(self, pid):
        oldpid = self.validate()
        if oldpid:
            if oldpid == os.getpid():
                return
            msg = "Already running on PID %s (or pid file '%s' is stale)"
            raise RuntimeError(msg % (oldpid, self.fname))

        self.pid = pid

        # Write pidfile
        fdir = os.path.dirname(self.fname)
        if fdir and not os.path.isdir(fdir):
            raise RuntimeError("%s doesn't exist. Can't create pidfile." % fdir)
        fd, fname = tempfile.mkstemp(dir=fdir)
        os.write(fd, ("%s\n" % self.pid).encode('utf-8'))
        if self.fname:
            os.rename(fname, self.fname)
        else:
            self.fname = fname
        os.close(fd)

        # set permissions to -rw-r--r--
        os.chmod(self.fname, 420) 
Example 17
Project: unicorn-hat-hd   Author: pimoroni   File: paint.py    MIT License 5 votes vote down vote up
def save(filename):
    try:
        os.mkdir('saves/')
    except OSError:
        pass
    try:
        data = unicornhathd.get_pixels()
        data = repr(data)
        data = data.replace('array', 'list')
        print(filename, data)
        file = open('saves/' + filename + '.py', 'w')
        file.write("""#!/usr/bin/env python
import unicornhathd
import signal

unicornhathd.rotation(0)

pixels = {}

for x in range(unicornhathd.WIDTH):
    for y in range(unicornhathd.HEIGHT):
        r, g, b = pixels[x][y]
        unicornhathd.set_pixel(x, y, r, g, b)

unicornhathd.show()

print("\\nShowing: {}\\nPress Ctrl+C to exit!")

signal.pause()
""".format(data, filename))
        file.close()
        os.chmod('saves/' + filename + '.py', 0o777 | stat.S_IEXEC)

        return("ok" + str(unicornhathd.get_pixels()))
    except AttributeError:
        print("Unable to save, please update")
        print("unicornhathdhathd library!")
        return("fail") 
Example 18
Project: factotum   Author: Denubis   File: update.py    GNU General Public License v3.0 5 votes vote down vote up
def updateFactorio():
	

	file_name = "/tmp/latestFactorio.tar.gz"
	print("Downloading %s" % file_name)

	r = requests.get(DOWNLOADURL, stream=True)
	total_length = int(r.headers.get('content-length'))

	if not os.path.isfile(file_name) or total_length != os.path.getsize(file_name):
		with open(file_name, 'wb') as f:
			for chunk in progress.bar(r.iter_content(chunk_size=1024), expected_size=(total_length/1024) + 1): 
				if chunk:
					f.write(chunk)
					f.flush()
			#os.chmod(file_name, stat.S_IWUSR | stat.S_IRUSR)
	else:
		print("File already exists and file sizes match. Skipping download.")	

	if os.access(FACTORIOPATH, os.W_OK):
		if os.path.isfile(file_name):
			tar = tarfile.open(file_name, "r:gz")
			tar.extractall(path="/tmp")
			tar.close()

			copytree("/tmp/factorio", FACTORIOPATH)
			print("Success.")
		else:
			print("Help! Can't find %s, but I should have!" % (file_name))
			sys.exit(1)			
	else:
		print("Can't write to %s" % (FACTORIOPATH))
		sys.exit(1) 
Example 19
Project: fs_image   Author: facebookincubator   File: test_install_file.py    MIT License 5 votes vote down vote up
def test_install_file(self):
        with tempfile.NamedTemporaryFile() as tf:
            os.chmod(tf.name, stat.S_IXUSR)
            exe_item = _install_file_item(
                from_target='t', source={'source': tf.name}, dest='d/c',
            )
        ep = _InstallablePath(Path(tf.name), ProvidesFile(path='d/c'), 'a+rx')
        self.assertEqual((ep,), exe_item.paths)
        self.assertEqual(tf.name.encode(), exe_item.source)
        self._check_item(exe_item, {ep.provides}, {require_directory('d')})

        # Checks `image.source(path=...)`
        with temp_dir() as td:
            os.mkdir(td / 'b')
            open(td / 'b/q', 'w').close()
            data_item = _install_file_item(
                from_target='t',
                source={'source': td, 'path': '/b/q'},
                dest='d',
            )
        dp = _InstallablePath(td / 'b/q', ProvidesFile(path='d'), 'a+r')
        self.assertEqual((dp,), data_item.paths)
        self.assertEqual(td / 'b/q', data_item.source)
        self._check_item(data_item, {dp.provides}, {require_directory('/')})

        # NB: We don't need to get coverage for this check on ALL the items
        # because the presence of the ProvidesDoNotAccess items it the real
        # safeguard -- e.g. that's what prevents TarballItem from writing
        # to /meta/ or other protected paths.
        with self.assertRaisesRegex(AssertionError, 'cannot start with meta/'):
            _install_file_item(
                from_target='t', source={'source': 'a/b/c'}, dest='/meta/foo',
            ) 
Example 20
Project: jumpserver-python-sdk   Author: jumpserver   File: models.py    GNU General Public License v2.0 5 votes vote down vote up
def private_key_file(self):
        if not self.key_dir:
            self.key_dir = '.'

        if not self.private_key:
            return None
        key_name = '.' + md5(self.private_key.encode('utf-8')).hexdigest()
        key_path = os.path.join(self.key_dir, key_name)
        if not os.path.exists(key_path):
            with open(key_path, 'w') as f:
                f.write(self.private_key)
            os.chmod(key_path, 0o400)
        return key_path 
Example 21
Project: pyblish-win   Author: pyblish   File: mkreal.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def mkrealfile(name):
    st = os.stat(name) # Get the mode
    mode = S_IMODE(st[ST_MODE])
    linkto = os.readlink(name) # Make sure again it's a symlink
    f_in = open(name, 'r') # This ensures it's a file
    os.unlink(name)
    f_out = open(name, 'w')
    while 1:
        buf = f_in.read(BUFSIZE)
        if not buf: break
        f_out.write(buf)
    del f_out # Flush data to disk before changing mode
    os.chmod(name, mode) 
Example 22
Project: pyblish-win   Author: pyblish   File: mkreal.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def mkrealdir(name):
    st = os.stat(name) # Get the mode
    mode = S_IMODE(st[ST_MODE])
    linkto = os.readlink(name)
    files = os.listdir(name)
    os.unlink(name)
    os.mkdir(name, mode)
    os.chmod(name, mode)
    linkto = join(os.pardir, linkto)
    #
    for filename in files:
        if filename not in (os.curdir, os.pardir):
            os.symlink(join(linkto, filename), join(name, filename)) 
Example 23
Project: pyblish-win   Author: pyblish   File: test_refactor.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def check_file_refactoring(self, test_file, fixers=_2TO3_FIXERS,
                               options=None, mock_log_debug=None,
                               actually_write=True):
        tmpdir = tempfile.mkdtemp(prefix="2to3-test_refactor")
        self.addCleanup(shutil.rmtree, tmpdir)
        # make a copy of the tested file that we can write to
        shutil.copy(test_file, tmpdir)
        test_file = os.path.join(tmpdir, os.path.basename(test_file))
        os.chmod(test_file, 0o644)

        def read_file():
            with open(test_file, "rb") as fp:
                return fp.read()

        old_contents = read_file()
        rt = self.rt(fixers=fixers, options=options)
        if mock_log_debug:
            rt.log_debug = mock_log_debug

        rt.refactor_file(test_file)
        self.assertEqual(old_contents, read_file())

        if not actually_write:
            return
        rt.refactor_file(test_file, True)
        new_contents = read_file()
        self.assertNotEqual(old_contents, new_contents)
        return new_contents 
Example 24
Project: pyblish-win   Author: pyblish   File: shutil.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def copymode(src, dst):
    """Copy mode bits from src to dst"""
    if hasattr(os, 'chmod'):
        st = os.stat(src)
        mode = stat.S_IMODE(st.st_mode)
        os.chmod(dst, mode) 
Example 25
Project: pyblish-win   Author: pyblish   File: test_spawn.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def test_spawn(self):
        tmpdir = self.mkdtemp()

        # creating something executable
        # through the shell that returns 1
        if os.name == 'posix':
            exe = os.path.join(tmpdir, 'foo.sh')
            self.write_file(exe, '#!/bin/sh\nexit 1')
            os.chmod(exe, 0777)
        else:
            exe = os.path.join(tmpdir, 'foo.bat')
            self.write_file(exe, 'exit 1')

        os.chmod(exe, 0777)
        self.assertRaises(DistutilsExecError, spawn, [exe])

        # now something that works
        if os.name == 'posix':
            exe = os.path.join(tmpdir, 'foo.sh')
            self.write_file(exe, '#!/bin/sh\nexit 0')
            os.chmod(exe, 0777)
        else:
            exe = os.path.join(tmpdir, 'foo.bat')
            self.write_file(exe, 'exit 0')

        os.chmod(exe, 0777)
        spawn([exe])  # should work without any error 
Example 26
Project: pyblish-win   Author: pyblish   File: install_scripts.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def run (self):
        if not self.skip_build:
            self.run_command('build_scripts')
        self.outfiles = self.copy_tree(self.build_dir, self.install_dir)
        if os.name == 'posix':
            # Set the executable bits (owner, group, and world) on
            # all the scripts we just installed.
            for file in self.get_outputs():
                if self.dry_run:
                    log.info("changing mode of %s", file)
                else:
                    mode = ((os.stat(file)[ST_MODE]) | 0555) & 07777
                    log.info("changing mode of %s to %o", file, mode)
                    os.chmod(file, mode) 
Example 27
Project: pyblish-win   Author: pyblish   File: tarfile.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def extractall(self, path=".", members=None):
        """Extract all members from the archive to the current working
           directory and set owner, modification time and permissions on
           directories afterwards. `path' specifies a different directory
           to extract to. `members' is optional and must be a subset of the
           list returned by getmembers().
        """
        directories = []

        if members is None:
            members = self

        for tarinfo in members:
            if tarinfo.isdir():
                # Extract directories with a safe mode.
                directories.append(tarinfo)
                tarinfo = copy.copy(tarinfo)
                tarinfo.mode = 0700
            self.extract(tarinfo, path)

        # Reverse sort directories.
        directories.sort(key=operator.attrgetter('name'))
        directories.reverse()

        # Set correct owner, mtime and filemode on directories.
        for tarinfo in directories:
            dirpath = os.path.join(path, tarinfo.name)
            try:
                self.chown(tarinfo, dirpath)
                self.utime(tarinfo, dirpath)
                self.chmod(tarinfo, dirpath)
            except ExtractError, e:
                if self.errorlevel > 1:
                    raise
                else:
                    self._dbg(1, "tarfile: %s" % e) 
Example 28
Project: pyblish-win   Author: pyblish   File: tarfile.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def chmod(self, tarinfo, targetpath):
        """Set file permissions of targetpath according to tarinfo.
        """
        if hasattr(os, 'chmod'):
            try:
                os.chmod(targetpath, tarinfo.mode)
            except EnvironmentError, e:
                raise ExtractError("could not change mode") 
Example 29
Project: pyblish-win   Author: pyblish   File: regrtest.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def cleanup_test_droppings(testname, verbose):
    import stat
    import gc

    # First kill any dangling references to open files etc.
    gc.collect()

    # Try to clean up junk commonly left behind.  While tests shouldn't leave
    # any files or directories behind, when a test fails that can be tedious
    # for it to arrange.  The consequences can be especially nasty on Windows,
    # since if a test leaves a file open, it cannot be deleted by name (while
    # there's nothing we can do about that here either, we can display the
    # name of the offending test, which is a real help).
    for name in (test_support.TESTFN,
                 "db_home",
                ):
        if not os.path.exists(name):
            continue

        if os.path.isdir(name):
            kind, nuker = "directory", shutil.rmtree
        elif os.path.isfile(name):
            kind, nuker = "file", os.unlink
        else:
            raise SystemError("os.path says %r exists but is neither "
                              "directory nor file" % name)

        if verbose:
            print "%r left behind %s %r" % (testname, kind, name)
        try:
            # if we have chmod, fix possible permissions problems
            # that might prevent cleanup
            if (hasattr(os, 'chmod')):
                os.chmod(name, stat.S_IRWXU | stat.S_IRWXG | stat.S_IRWXO)
            nuker(name)
        except Exception, msg:
            print >> sys.stderr, ("%r left behind %s %r and it couldn't be "
                "removed: %s" % (testname, kind, name, msg)) 
Example 30
Project: pyblish-win   Author: pyblish   File: test_stat.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def test_mode(self):
        with open(TESTFN, 'w'):
            pass
        if os.name == 'posix':
            os.chmod(TESTFN, 0o700)
            st_mode = self.get_mode()
            self.assertS_IS("REG", st_mode)
            self.assertEqual(stat.S_IMODE(st_mode),
                             stat.S_IRWXU)

            os.chmod(TESTFN, 0o070)
            st_mode = self.get_mode()
            self.assertS_IS("REG", st_mode)
            self.assertEqual(stat.S_IMODE(st_mode),
                             stat.S_IRWXG)

            os.chmod(TESTFN, 0o007)
            st_mode = self.get_mode()
            self.assertS_IS("REG", st_mode)
            self.assertEqual(stat.S_IMODE(st_mode),
                             stat.S_IRWXO)

            os.chmod(TESTFN, 0o444)
            st_mode = self.get_mode()
            self.assertS_IS("REG", st_mode)
            self.assertEqual(stat.S_IMODE(st_mode), 0o444)
        else:
            os.chmod(TESTFN, 0o700)
            st_mode = self.get_mode()
            self.assertS_IS("REG", st_mode)
            self.assertEqual(stat.S_IFMT(st_mode),
                             stat.S_IFREG) 
Example 31
Project: pyblish-win   Author: pyblish   File: test_stat.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def test_directory(self):
        os.mkdir(TESTFN)
        os.chmod(TESTFN, 0o700)
        st_mode = self.get_mode()
        self.assertS_IS("DIR", st_mode) 
Example 32
Project: pyblish-win   Author: pyblish   File: test_zipimport.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def testFileUnreadable(self):
        test_support.unlink(TESTMOD)
        fd = os.open(TESTMOD, os.O_CREAT, 000)
        try:
            os.close(fd)
            self.assertZipFailure(TESTMOD)
        finally:
            # If we leave "the read-only bit" set on Windows, nothing can
            # delete TESTMOD, and later tests suffer bogus failures.
            os.chmod(TESTMOD, 0666)
            test_support.unlink(TESTMOD) 
Example 33
Project: pyblish-win   Author: pyblish   File: test__osx_support.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def test__read_output(self):
        if self.env['PATH']:
            self.env['PATH'] = self.env['PATH'] + ':'
        self.env['PATH'] = self.env['PATH'] + os.path.abspath(self.temp_path_dir)
        test.test_support.unlink(self.prog_name)
        self.addCleanup(test.test_support.unlink, self.prog_name)
        with open(self.prog_name, 'w') as f:
            f.write("#!/bin/sh\n/bin/echo ExpectedOutput\n")
        os.chmod(self.prog_name, stat.S_IRWXU)
        self.assertEqual('ExpectedOutput',
                            _osx_support._read_output(self.prog_name)) 
Example 34
Project: pyblish-win   Author: pyblish   File: test__osx_support.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def test__find_appropriate_compiler(self):
        compilers = (
                        ('gcc-test', 'i686-apple-darwin11-llvm-gcc-4.2'),
                        ('clang', 'clang version 3.1'),
                    )
        config_vars = {
        'CC': 'gcc-test -pthreads',
        'CXX': 'cc++-test',
        'CFLAGS': '-fno-strict-aliasing  -g -O3 -arch ppc -arch i386  ',
        'LDFLAGS': '-arch ppc -arch i386   -g',
        'CPPFLAGS': '-I. -isysroot /Developer/SDKs/MacOSX10.4u.sdk',
        'BLDSHARED': 'gcc-test -bundle -arch ppc -arch i386 -g',
        'LDSHARED': 'gcc-test -bundle -arch ppc -arch i386 '
                        '-isysroot /Developer/SDKs/MacOSX10.4u.sdk -g',
        }
        expected_vars = {
        'CC': 'clang -pthreads',
        'CXX': 'clang++',
        'CFLAGS': '-fno-strict-aliasing  -g -O3 -arch ppc -arch i386  ',
        'LDFLAGS': '-arch ppc -arch i386   -g',
        'CPPFLAGS': '-I. -isysroot /Developer/SDKs/MacOSX10.4u.sdk',
        'BLDSHARED': 'clang -bundle -arch ppc -arch i386 -g',
        'LDSHARED': 'clang -bundle -arch ppc -arch i386 '
                        '-isysroot /Developer/SDKs/MacOSX10.4u.sdk -g',
        }
        self.add_expected_saved_initial_values(config_vars, expected_vars)

        suffix = (':' + self.env['PATH']) if self.env['PATH'] else ''
        self.env['PATH'] = os.path.abspath(self.temp_path_dir) + suffix
        for c_name, c_output in compilers:
            test.test_support.unlink(c_name)
            self.addCleanup(test.test_support.unlink, c_name)
            with open(c_name, 'w') as f:
                f.write("#!/bin/sh\n/bin/echo " + c_output)
            os.chmod(c_name, stat.S_IRWXU)
        self.assertEqual(expected_vars,
                            _osx_support._find_appropriate_compiler(
                                    config_vars)) 
Example 35
Project: pyblish-win   Author: pyblish   File: test__osx_support.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def test__remove_unsupported_archs(self):
        config_vars = {
        'CC': 'clang',
        'CFLAGS': '-fno-strict-aliasing  -g -O3 -arch ppc -arch i386  ',
        'LDFLAGS': '-arch ppc -arch i386   -g',
        'CPPFLAGS': '-I. -isysroot /Developer/SDKs/MacOSX10.4u.sdk',
        'BLDSHARED': 'gcc-4.0 -bundle  -arch ppc -arch i386 -g',
        'LDSHARED': 'gcc-4.0 -bundle  -arch ppc -arch i386 '
                        '-isysroot /Developer/SDKs/MacOSX10.4u.sdk -g',
        }
        expected_vars = {
        'CC': 'clang',
        'CFLAGS': '-fno-strict-aliasing  -g -O3  -arch i386  ',
        'LDFLAGS': ' -arch i386   -g',
        'CPPFLAGS': '-I. -isysroot /Developer/SDKs/MacOSX10.4u.sdk',
        'BLDSHARED': 'gcc-4.0 -bundle   -arch i386 -g',
        'LDSHARED': 'gcc-4.0 -bundle   -arch i386 '
                        '-isysroot /Developer/SDKs/MacOSX10.4u.sdk -g',
        }
        self.add_expected_saved_initial_values(config_vars, expected_vars)

        suffix = (':' + self.env['PATH']) if self.env['PATH'] else ''
        self.env['PATH'] = os.path.abspath(self.temp_path_dir) + suffix
        c_name = 'clang'
        test.test_support.unlink(c_name)
        self.addCleanup(test.test_support.unlink, c_name)
        # exit status 255 means no PPC support in this compiler chain
        with open(c_name, 'w') as f:
            f.write("#!/bin/sh\nexit 255")
        os.chmod(c_name, stat.S_IRWXU)
        self.assertEqual(expected_vars,
                            _osx_support._remove_unsupported_archs(
                                    config_vars)) 
Example 36
Project: pyblish-win   Author: pyblish   File: test_httpservers.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def test_get(self):
        #constructs the path relative to the root directory of the HTTPServer
        response = self.request(self.tempdir_name + '/test')
        self.check_status_and_reason(response, 200, data=self.data)
        # check for trailing "/" which should return 404. See Issue17324
        response = self.request(self.tempdir_name + '/test/')
        self.check_status_and_reason(response, 404)
        response = self.request(self.tempdir_name + '/')
        self.check_status_and_reason(response, 200)
        response = self.request(self.tempdir_name)
        self.check_status_and_reason(response, 301)
        response = self.request('/ThisDoesNotExist')
        self.check_status_and_reason(response, 404)
        response = self.request('/' + 'ThisDoesNotExist' + '/')
        self.check_status_and_reason(response, 404)
        with open(os.path.join(self.tempdir_name, 'index.html'), 'w') as fp:
            response = self.request('/' + self.tempdir_name + '/')
            self.check_status_and_reason(response, 200)
            # chmod() doesn't work as expected on Windows, and filesystem
            # permissions are ignored by root on Unix.
            if os.name == 'posix' and os.geteuid() != 0:
                os.chmod(self.tempdir, 0)
                response = self.request(self.tempdir_name + '/')
                self.check_status_and_reason(response, 404)
                os.chmod(self.tempdir, 0755) 
Example 37
Project: pyblish-win   Author: pyblish   File: test_httpservers.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def setUp(self):
        BaseTestCase.setUp(self)
        self.parent_dir = tempfile.mkdtemp()
        self.cgi_dir = os.path.join(self.parent_dir, 'cgi-bin')
        self.cgi_child_dir = os.path.join(self.cgi_dir, 'child-dir')
        os.mkdir(self.cgi_dir)
        os.mkdir(self.cgi_child_dir)

        # The shebang line should be pure ASCII: use symlink if possible.
        # See issue #7668.
        if hasattr(os, 'symlink'):
            self.pythonexe = os.path.join(self.parent_dir, 'python')
            os.symlink(sys.executable, self.pythonexe)
        else:
            self.pythonexe = sys.executable

        self.nocgi_path = os.path.join(self.parent_dir, 'nocgi.py')
        with open(self.nocgi_path, 'w') as fp:
            fp.write(cgi_file1 % self.pythonexe)
        os.chmod(self.nocgi_path, 0777)

        self.file1_path = os.path.join(self.cgi_dir, 'file1.py')
        with open(self.file1_path, 'w') as file1:
            file1.write(cgi_file1 % self.pythonexe)
        os.chmod(self.file1_path, 0777)

        self.file2_path = os.path.join(self.cgi_dir, 'file2.py')
        with open(self.file2_path, 'w') as file2:
            file2.write(cgi_file2 % self.pythonexe)
        os.chmod(self.file2_path, 0777)

        self.file3_path = os.path.join(self.cgi_child_dir, 'file3.py')
        with open(self.file3_path, 'w') as file3:
            file3.write(cgi_file1 % self.pythonexe)
        os.chmod(self.file3_path, 0777)

        self.cwd = os.getcwd()
        os.chdir(self.parent_dir) 
Example 38
Project: pyblish-win   Author: pyblish   File: test_import.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def test_rewrite_pyc_with_read_only_source(self):
        # Issue 6074: a long time ago on posix, and more recently on Windows,
        # a read only source file resulted in a read only pyc file, which
        # led to problems with updating it later
        sys.path.insert(0, os.curdir)
        fname = TESTFN + os.extsep + "py"
        try:
            # Write a Python file, make it read-only and import it
            with open(fname, 'w') as f:
                f.write("x = 'original'\n")
            # Tweak the mtime of the source to ensure pyc gets updated later
            s = os.stat(fname)
            os.utime(fname, (s.st_atime, s.st_mtime-100000000))
            os.chmod(fname, 0400)
            m1 = __import__(TESTFN)
            self.assertEqual(m1.x, 'original')
            # Change the file and then reimport it
            os.chmod(fname, 0600)
            with open(fname, 'w') as f:
                f.write("x = 'rewritten'\n")
            unload(TESTFN)
            m2 = __import__(TESTFN)
            self.assertEqual(m2.x, 'rewritten')
            # Now delete the source file and check the pyc was rewritten
            unlink(fname)
            unload(TESTFN)
            m3 = __import__(TESTFN)
            self.assertEqual(m3.x, 'rewritten')
        finally:
            chmod_files(TESTFN)
            remove_files(TESTFN)
            unload(TESTFN)
            del sys.path[0] 
Example 39
Project: pyblish-win   Author: pyblish   File: test_subprocess.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def test_args_string(self):
        # args is a string
        f, fname = mkstemp()
        os.write(f, "#!/bin/sh\n")
        os.write(f, "exec '%s' -c 'import sys; sys.exit(47)'\n" %
                    sys.executable)
        os.close(f)
        os.chmod(fname, 0o700)
        p = subprocess.Popen(fname)
        p.wait()
        os.remove(fname)
        self.assertEqual(p.returncode, 47) 
Example 40
Project: pyblish-win   Author: pyblish   File: test_subprocess.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def test_call_string(self):
        # call() function with string argument on UNIX
        f, fname = mkstemp()
        os.write(f, "#!/bin/sh\n")
        os.write(f, "exec '%s' -c 'import sys; sys.exit(47)'\n" %
                    sys.executable)
        os.close(f)
        os.chmod(fname, 0700)
        rc = subprocess.call(fname)
        os.remove(fname)
        self.assertEqual(rc, 47) 
Example 41
Project: pyblish-win   Author: pyblish   File: test_os.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def test_chmod(self):
        self.assertRaises(WindowsError, os.chmod, test_support.TESTFN, 0) 
Example 42
Project: pyblish-win   Author: pyblish   File: test_gettext.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def test_security(self):
        raises = self.assertRaises
        # Test for a dangerous expression
        raises(ValueError, gettext.c2py, "os.chmod('/etc/passwd',0777)") 
Example 43
Project: pyblish-win   Author: pyblish   File: test_argparse.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def tearDown(self):
        os.chdir(self.old_dir)
        for root, dirs, files in os.walk(self.temp_dir, topdown=False):
            for name in files:
                os.chmod(os.path.join(self.temp_dir, name), stat.S_IWRITE)
        shutil.rmtree(self.temp_dir, True) 
Example 44
Project: pyblish-win   Author: pyblish   File: test_argparse.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def create_readonly_file(self, filename):
        file_path = os.path.join(self.temp_dir, filename)
        with open(file_path, 'w') as file:
            file.write(filename)
        os.chmod(file_path, stat.S_IREAD) 
Example 45
Project: Flask-Python-GAE-Login-Registration   Author: orymeyer   File: sessions.py    Apache License 2.0 5 votes vote down vote up
def save(self, session):
        fn = self.get_session_filename(session.sid)
        fd, tmp = tempfile.mkstemp(suffix=_fs_transaction_suffix,
                                   dir=self.path)
        f = os.fdopen(fd, 'wb')
        try:
            dump(dict(session), f, HIGHEST_PROTOCOL)
        finally:
            f.close()
        try:
            rename(tmp, fn)
            os.chmod(fn, self.mode)
        except (IOError, OSError):
            pass 
Example 46
Project: Flask-Python-GAE-Login-Registration   Author: orymeyer   File: sessions.py    Apache License 2.0 5 votes vote down vote up
def save(self, session):
        fn = self.get_session_filename(session.sid)
        fd, tmp = tempfile.mkstemp(suffix=_fs_transaction_suffix,
                                   dir=self.path)
        f = os.fdopen(fd, 'wb')
        try:
            dump(dict(session), f, HIGHEST_PROTOCOL)
        finally:
            f.close()
        try:
            rename(tmp, fn)
            os.chmod(fn, self.mode)
        except (IOError, OSError):
            pass 
Example 47
Project: kvmd   Author: pikvm   File: http.py    GNU General Public License v3.0 5 votes vote down vote up
def run(
        self,
        host: str,
        port: int,
        unix_path: str,
        unix_rm: bool,
        unix_mode: int,
        access_log_format: str,
    ) -> None:

        assert port or unix_path
        if unix_path:
            socket_kwargs: Dict = {}
            if unix_rm and os.path.exists(unix_path):
                os.remove(unix_path)
            server_socket = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
            server_socket.bind(unix_path)
            if unix_mode:
                os.chmod(unix_path, unix_mode)
            socket_kwargs = {"sock": server_socket}
        else:
            socket_kwargs = {"host": host, "port": port}

        aiohttp.web.run_app(
            app=self._make_app(),
            access_log_format=access_log_format,
            print=self.__run_app_print,
            **socket_kwargs,
        ) 
Example 48
Project: slidoc   Author: mitotic   File: multiproxy.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def make_unix_server_socket(socket_path):
    try:
        # Delete any previous socket
        os.unlink(socket_path)
    except OSError:
        if os.path.exists(socket_path):
            raise

    sock = netutil.bind_unix_socket(socket_path)
    os.chmod(socket_path, 0700)
    return sock 
Example 49
Project: fortran_input_reader   Author: miroi   File: update.py    MIT License 5 votes vote down vote up
def make_executable(path):
    mode = os.stat(path).st_mode
    mode |= (mode & 0o444) >> 2    # copy R bits to X
    os.chmod(path, mode)

# ------------------------------------------------------------------------------ 
Example 50
Project: Ansible-Example-AB2018   Author: umit-ozturk   File: bccache.py    MIT License 5 votes vote down vote up
def _get_default_cache_dir(self):
        def _unsafe_dir():
            raise RuntimeError('Cannot determine safe temp directory.  You '
                               'need to explicitly provide one.')

        tmpdir = tempfile.gettempdir()

        # On windows the temporary directory is used specific unless
        # explicitly forced otherwise.  We can just use that.
        if os.name == 'nt':
            return tmpdir
        if not hasattr(os, 'getuid'):
            _unsafe_dir()

        dirname = '_jinja2-cache-%d' % os.getuid()
        actual_dir = os.path.join(tmpdir, dirname)

        try:
            os.mkdir(actual_dir, stat.S_IRWXU)
        except OSError as e:
            if e.errno != errno.EEXIST:
                raise
        try:
            os.chmod(actual_dir, stat.S_IRWXU)
            actual_dir_stat = os.lstat(actual_dir)
            if actual_dir_stat.st_uid != os.getuid() \
               or not stat.S_ISDIR(actual_dir_stat.st_mode) \
               or stat.S_IMODE(actual_dir_stat.st_mode) != stat.S_IRWXU:
                _unsafe_dir()
        except OSError as e:
            if e.errno != errno.EEXIST:
                raise

        actual_dir_stat = os.lstat(actual_dir)
        if actual_dir_stat.st_uid != os.getuid() \
           or not stat.S_ISDIR(actual_dir_stat.st_mode) \
           or stat.S_IMODE(actual_dir_stat.st_mode) != stat.S_IRWXU:
            _unsafe_dir()

        return actual_dir 
Example 51
Project: Ansible-Example-AB2018   Author: umit-ozturk   File: util.py    MIT License 5 votes vote down vote up
def set_mode(self, bits, mask, files):
        if os.name == 'posix' or (os.name == 'java' and os._name == 'posix'):
            # Set the executable bits (owner, group, and world) on
            # all the files specified.
            for f in files:
                if self.dry_run:
                    logger.info("changing mode of %s", f)
                else:
                    mode = (os.stat(f).st_mode | bits) & mask
                    logger.info("changing mode of %s to %o", f, mode)
                    os.chmod(f, mode) 
Example 52
Project: Ansible-Example-AB2018   Author: umit-ozturk   File: shutil.py    MIT License 5 votes vote down vote up
def copymode(src, dst):
    """Copy mode bits from src to dst"""
    if hasattr(os, 'chmod'):
        st = os.stat(src)
        mode = stat.S_IMODE(st.st_mode)
        os.chmod(dst, mode) 
Example 53
Project: Ansible-Example-AB2018   Author: umit-ozturk   File: tarfile.py    MIT License 5 votes vote down vote up
def extractall(self, path=".", members=None):
        """Extract all members from the archive to the current working
           directory and set owner, modification time and permissions on
           directories afterwards. `path' specifies a different directory
           to extract to. `members' is optional and must be a subset of the
           list returned by getmembers().
        """
        directories = []

        if members is None:
            members = self

        for tarinfo in members:
            if tarinfo.isdir():
                # Extract directories with a safe mode.
                directories.append(tarinfo)
                tarinfo = copy.copy(tarinfo)
                tarinfo.mode = 0o700
            # Do not set_attrs directories, as we will do that further down
            self.extract(tarinfo, path, set_attrs=not tarinfo.isdir())

        # Reverse sort directories.
        directories.sort(key=lambda a: a.name)
        directories.reverse()

        # Set correct owner, mtime and filemode on directories.
        for tarinfo in directories:
            dirpath = os.path.join(path, tarinfo.name)
            try:
                self.chown(tarinfo, dirpath)
                self.utime(tarinfo, dirpath)
                self.chmod(tarinfo, dirpath)
            except ExtractError as e:
                if self.errorlevel > 1:
                    raise
                else:
                    self._dbg(1, "tarfile: %s" % e) 
Example 54
Project: Ansible-Example-AB2018   Author: umit-ozturk   File: tarfile.py    MIT License 5 votes vote down vote up
def chmod(self, tarinfo, targetpath):
        """Set file permissions of targetpath according to tarinfo.
        """
        if hasattr(os, 'chmod'):
            try:
                os.chmod(targetpath, tarinfo.mode)
            except EnvironmentError as e:
                raise ExtractError("could not change mode") 
Example 55
Project: Ansible-Example-AB2018   Author: umit-ozturk   File: misc.py    MIT License 5 votes vote down vote up
def rmtree_errorhandler(func, path, exc_info):
    """On Windows, the files in .svn are read-only, so when rmtree() tries to
    remove them, an exception is thrown.  We catch that here, remove the
    read-only attribute, and hopefully continue without problems."""
    # if file type currently read only
    if os.stat(path).st_mode & stat.S_IREAD:
        # convert to read/write
        os.chmod(path, stat.S_IWRITE)
        # use the original function to repeat the operation
        func(path)
        return
    else:
        raise 
Example 56
Project: Ansible-Example-AB2018   Author: umit-ozturk   File: misc.py    MIT License 5 votes vote down vote up
def unzip_file(filename, location, flatten=True):
    """
    Unzip the file (with path `filename`) to the destination `location`.  All
    files are written based on system defaults and umask (i.e. permissions are
    not preserved), except that regular file members with any execute
    permissions (user, group, or world) have "chmod +x" applied after being
    written. Note that for windows, any execute changes using os.chmod are
    no-ops per the python docs.
    """
    ensure_dir(location)
    zipfp = open(filename, 'rb')
    try:
        zip = zipfile.ZipFile(zipfp, allowZip64=True)
        leading = has_leading_dir(zip.namelist()) and flatten
        for info in zip.infolist():
            name = info.filename
            data = zip.read(name)
            fn = name
            if leading:
                fn = split_leading_dir(name)[1]
            fn = os.path.join(location, fn)
            dir = os.path.dirname(fn)
            if fn.endswith('/') or fn.endswith('\\'):
                # A directory
                ensure_dir(fn)
            else:
                ensure_dir(dir)
                fp = open(fn, 'wb')
                try:
                    fp.write(data)
                finally:
                    fp.close()
                    mode = info.external_attr >> 16
                    # if mode and regular file and any execute permissions for
                    # user/group/world?
                    if mode and stat.S_ISREG(mode) and mode & 0o111:
                        # make dest file have execute for user/group/world
                        # (chmod +x) no-op on windows per python docs
                        os.chmod(fn, (0o777 - current_umask() | 0o111))
    finally:
        zipfp.close() 
Example 57
Project: Ansible-Example-AB2018   Author: umit-ozturk   File: vmadm.py    MIT License 5 votes vote down vote up
def create_payload(module, uuid):
    # Create the JSON payload (vmdef) and return the filename.

    p = module.params

    # Filter out the few options that are not valid VM properties.
    module_options = ['debug', 'force', 'state']
    vmattrs = filter(lambda prop: prop not in module_options, p)

    vmdef = {}

    for attr in vmattrs:
        if p[attr]:
            vmdef[attr] = p[attr]

    try:
        vmdef_json = json.dumps(vmdef)
    except Exception as e:
        module.fail_json(
            msg='Could not create valid JSON payload', exception=traceback.format_exc())

    # Create the temporary file that contains our payload, and set tight
    # permissions for it may container sensitive information.
    try:
        # XXX: When there's a way to get the current ansible temporary directory
        # drop the mkstemp call and rely on ANSIBLE_KEEP_REMOTE_FILES to retain
        # the payload (thus removing the `save_payload` option).
        fname = tempfile.mkstemp()[1]
        os.chmod(fname, 0o400)
        with open(fname, 'w') as fh:
            fh.write(vmdef_json)
    except Exception as e:
        module.fail_json(msg='Could not save JSON payload: %s' % to_native(e), exception=traceback.format_exc())

    return fname 
Example 58
Project: Ansible-Example-AB2018   Author: umit-ozturk   File: openssl_privatekey.py    MIT License 5 votes vote down vote up
def generate(self, module):
        """Generate a keypair."""

        if not self.check(module, perms_required=False) or self.force:
            self.privatekey = crypto.PKey()

            try:
                self.privatekey.generate_key(self.type, self.size)
            except (TypeError, ValueError) as exc:
                raise PrivateKeyError(exc)

            try:
                privatekey_file = os.open(self.path, os.O_WRONLY | os.O_CREAT | os.O_TRUNC)
                os.close(privatekey_file)
                if isinstance(self.mode, string_types):
                    try:
                        self.mode = int(self.mode, 8)
                    except ValueError as e:
                        try:
                            st = os.lstat(self.path)
                            self.mode = AnsibleModule._symbolic_mode_to_octal(st, self.mode)
                        except ValueError as e:
                            module.fail_json(msg="%s" % to_native(e), exception=traceback.format_exc())
                os.chmod(self.path, self.mode)
                privatekey_file = os.open(self.path, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, self.mode)
                if self.cipher and self.passphrase:
                    os.write(privatekey_file, crypto.dump_privatekey(crypto.FILETYPE_PEM, self.privatekey,
                                                                     self.cipher, to_bytes(self.passphrase)))
                else:
                    os.write(privatekey_file, crypto.dump_privatekey(crypto.FILETYPE_PEM, self.privatekey))
                os.close(privatekey_file)
                self.changed = True
            except IOError as exc:
                self.remove()
                raise PrivateKeyError(exc)

        self.fingerprint = crypto_utils.get_fingerprint(self.path, self.passphrase)
        file_args = module.load_file_common_arguments(module.params)
        if module.set_fs_attributes_if_different(file_args, False):
            self.changed = True 
Example 59
Project: Ansible-Example-AB2018   Author: umit-ozturk   File: git.py    MIT License 5 votes vote down vote up
def write_ssh_wrapper():
    module_dir = get_module_path()
    try:
        # make sure we have full permission to the module_dir, which
        # may not be the case if we're sudo'ing to a non-root user
        if os.access(module_dir, os.W_OK | os.R_OK | os.X_OK):
            fd, wrapper_path = tempfile.mkstemp(prefix=module_dir + '/')
        else:
            raise OSError
    except (IOError, OSError):
        fd, wrapper_path = tempfile.mkstemp()
    fh = os.fdopen(fd, 'w+b')
    template = b("""#!/bin/sh
if [ -z "$GIT_SSH_OPTS" ]; then
    BASEOPTS=""
else
    BASEOPTS=$GIT_SSH_OPTS
fi

# Let ssh fail rather than prompt
BASEOPTS="$BASEOPTS -o BatchMode=yes"

if [ -z "$GIT_KEY" ]; then
    ssh $BASEOPTS "[email protected]"
else
    ssh -i "$GIT_KEY" -o IdentitiesOnly=yes $BASEOPTS "[email protected]"
fi
""")
    fh.write(template)
    fh.close()
    st = os.stat(wrapper_path)
    os.chmod(wrapper_path, st.st_mode | stat.S_IEXEC)
    return wrapper_path 
Example 60
Project: Ansible-Example-AB2018   Author: umit-ozturk   File: cron.py    MIT License 5 votes vote down vote up
def write(self, backup_file=None):
        """
        Write the crontab to the system. Saves all information.
        """
        if backup_file:
            fileh = open(backup_file, 'w')
        elif self.cron_file:
            fileh = open(self.cron_file, 'w')
        else:
            filed, path = tempfile.mkstemp(prefix='crontab')
            os.chmod(path, int('0644', 8))
            fileh = os.fdopen(filed, 'w')

        fileh.write(self.render())
        fileh.close()

        # return if making a backup
        if backup_file:
            return

        # Add the entire crontab back to the user crontab
        if not self.cron_file:
            # quoting shell args for now but really this should be two non-shell calls.  FIXME
            (rc, out, err) = self.module.run_command(self._write_execute(path), use_unsafe_shell=True)
            os.unlink(path)

            if rc != 0:
                self.module.fail_json(msg=err)

        # set SELinux permissions
        if self.module.selinux_enabled() and self.cron_file:
            self.module.set_default_selinux_context(self.cron_file, False) 
Example 61
Project: interact   Author: dongshengmu   File: util.py    MIT License 5 votes vote down vote up
def create_sharable_file(filename, data):
    """Write to a file that can be read by all."""
    with UserPrivilege():
        with open(filename, 'w') as f:
            f.write(data)
        try:
            # chmod to share DevVM local /tmp across users
            os.chmod(filename, (stat.S_IRUSR | stat.S_IRGRP | stat.S_IROTH |
                                stat.S_IWUSR | stat.S_IWGRP | stat.S_IWOTH))
        except OSError as e:  # OSError: [Errno 1] Operation not permitted
            # If the file is originally created by other, it is R/W for all and the
            # file write is ok. But it can complain for chmod.
            print_warn(e) 
Example 62
Project: interact   Author: dongshengmu   File: util.py    MIT License 5 votes vote down vote up
def create_sharable_file(filename, data):
    """Write to a file that can be read by all."""
    with UserPrivilege():
        with open(filename, 'w') as f:
            f.write(data)
        try:
            # chmod to share DevVM local /tmp across users
            os.chmod(filename, (stat.S_IRUSR | stat.S_IRGRP | stat.S_IROTH |
                                stat.S_IWUSR | stat.S_IWGRP | stat.S_IWOTH))
        except OSError as e:  # OSError: [Errno 1] Operation not permitted
            # If the file is originally created by other, it is R/W for all and the
            # file write is ok. But it can complain for chmod.
            print_warn(e) 
Example 63
Project: scriptfs   Author: iffy   File: scriptfs.py    Apache License 2.0 5 votes vote down vote up
def chmod(self, *args, **kwargs):
        os.chmod(self.root, *args, **kwargs) 
Example 64
Project: scriptfs   Author: iffy   File: scriptfs.py    Apache License 2.0 5 votes vote down vote up
def chmod(self, *args, **kwargs):
        raise FuseOSError(errno.EACCES)
        os.chmod(self.root, *args, **kwargs) 
Example 65
Project: flasky   Author: RoseOu   File: util.py    MIT License 5 votes vote down vote up
def set_mode(self, bits, mask, files):
        if os.name == 'posix':
            # Set the executable bits (owner, group, and world) on
            # all the files specified.
            for f in files:
                if self.dry_run:
                    logger.info("changing mode of %s", f)
                else:
                    mode = (os.stat(f).st_mode | bits) & mask
                    logger.info("changing mode of %s to %o", f, mode)
                    os.chmod(f, mode) 
Example 66
Project: flasky   Author: RoseOu   File: shutil.py    MIT License 5 votes vote down vote up
def copymode(src, dst):
    """Copy mode bits from src to dst"""
    if hasattr(os, 'chmod'):
        st = os.stat(src)
        mode = stat.S_IMODE(st.st_mode)
        os.chmod(dst, mode) 
Example 67
Project: flasky   Author: RoseOu   File: shutil.py    MIT License 5 votes vote down vote up
def copystat(src, dst):
    """Copy all stat info (mode bits, atime, mtime, flags) from src to dst"""
    st = os.stat(src)
    mode = stat.S_IMODE(st.st_mode)
    if hasattr(os, 'utime'):
        os.utime(dst, (st.st_atime, st.st_mtime))
    if hasattr(os, 'chmod'):
        os.chmod(dst, mode)
    if hasattr(os, 'chflags') and hasattr(st, 'st_flags'):
        try:
            os.chflags(dst, st.st_flags)
        except OSError as why:
            if (not hasattr(errno, 'EOPNOTSUPP') or
                why.errno != errno.EOPNOTSUPP):
                raise 
Example 68
Project: flasky   Author: RoseOu   File: tarfile.py    MIT License 5 votes vote down vote up
def chmod(self, tarinfo, targetpath):
        """Set file permissions of targetpath according to tarinfo.
        """
        if hasattr(os, 'chmod'):
            try:
                os.chmod(targetpath, tarinfo.mode)
            except EnvironmentError as e:
                raise ExtractError("could not change mode") 
Example 69
Project: flasky   Author: RoseOu   File: sessions.py    MIT License 5 votes vote down vote up
def save(self, session):
        fn = self.get_session_filename(session.sid)
        fd, tmp = tempfile.mkstemp(suffix=_fs_transaction_suffix,
                                   dir=self.path)
        f = os.fdopen(fd, 'wb')
        try:
            dump(dict(session), f, HIGHEST_PROTOCOL)
        finally:
            f.close()
        try:
            rename(tmp, fn)
            os.chmod(fn, self.mode)
        except (IOError, OSError):
            pass 
Example 70
Project: flasky   Author: RoseOu   File: archive_util.py    MIT License 5 votes vote down vote up
def unpack_tarfile(filename, extract_dir, progress_filter=default_filter):
    """Unpack tar/tar.gz/tar.bz2 `filename` to `extract_dir`

    Raises ``UnrecognizedFormat`` if `filename` is not a tarfile (as determined
    by ``tarfile.open()``).  See ``unpack_archive()`` for an explanation
    of the `progress_filter` argument.
    """
    try:
        tarobj = tarfile.open(filename)
    except tarfile.TarError:
        raise UnrecognizedFormat(
            "%s is not a compressed or uncompressed tar file" % (filename,)
        )
    try:
        tarobj.chown = lambda *args: None   # don't do any chowning!
        for member in tarobj:
            name = member.name
            # don't extract absolute paths or ones with .. in them
            if not name.startswith('/') and '..' not in name.split('/'):
                prelim_dst = os.path.join(extract_dir, *name.split('/'))

                # resolve any links and to extract the link targets as normal files
                while member is not None and (member.islnk() or member.issym()):
                    linkpath = member.linkname
                    if member.issym():
                        linkpath = posixpath.join(posixpath.dirname(member.name), linkpath)
                        linkpath = posixpath.normpath(linkpath)
                    member = tarobj._getmember(linkpath)

                if member is not None and (member.isfile() or member.isdir()):
                    final_dst = progress_filter(name, prelim_dst)
                    if final_dst:
                        if final_dst.endswith(os.sep):
                            final_dst = final_dst[:-1]
                        try:
                            tarobj._extract_member(member, final_dst)  # XXX Ugh
                        except tarfile.ExtractError:
                            pass    # chown/chmod/mkfifo/mknode/makedev failed
        return True
    finally:
        tarobj.close() 
Example 71
Project: flasky   Author: RoseOu   File: environment.py    MIT License 5 votes vote down vote up
def _remove_dir(target):

    #on windows this seems to a problem
    for dir_path, dirs, files in os.walk(target):
        os.chmod(dir_path, stat.S_IWRITE)
        for filename in files:
            os.chmod(os.path.join(dir_path, filename), stat.S_IWRITE)
    shutil.rmtree(target) 
Example 72
Project: flasky   Author: RoseOu   File: easy_install.py    MIT License 5 votes vote down vote up
def _chmod(*args): pass 
Example 73
Project: flasky   Author: RoseOu   File: easy_install.py    MIT License 5 votes vote down vote up
def chmod(path, mode):
    log.debug("changing mode of %s to %o", path, mode)
    try:
        _chmod(path, mode)
    except os.error:
        e = sys.exc_info()[1]
        log.debug("chmod failed: %s", e) 
Example 74
Project: fs_image   Author: facebookincubator   File: test_install_file.py    MIT License 4 votes vote down vote up
def test_install_file_command_recursive(self):
        with TempSubvolumes(sys.argv[0]) as temp_subvolumes:
            subvol = temp_subvolumes.create('tar-sv')
            subvol.run_as_root(['mkdir', subvol.path('d')])

            with temp_dir() as td:
                with open(td / 'data.txt', 'w') as df:
                    print('Hello', file=df)
                os.mkdir(td / 'subdir')
                with open(td / 'subdir/exe.sh', 'w') as ef:
                    print('#!/bin/sh\necho "Hello"', file=ef)
                os.chmod(td / 'subdir/exe.sh', 0o100)

                dir_item = _install_file_item(
                    from_target='t', source={'source': td}, dest='/d/a',
                )

                ps = [
                    _InstallablePath(
                        td,
                        ProvidesDirectory(path='d/a'),
                        'u+rwx,og+rx',
                    ),
                    _InstallablePath(
                        td / 'data.txt',
                        ProvidesFile(path='d/a/data.txt'),
                        'a+r',
                    ),
                    _InstallablePath(
                        td / 'subdir',
                        ProvidesDirectory(path='d/a/subdir'),
                        'u+rwx,og+rx',
                    ),
                    _InstallablePath(
                        td / 'subdir/exe.sh',
                        ProvidesFile(path='d/a/subdir/exe.sh'),
                        'a+rx',
                    ),
                ]
                self.assertEqual(sorted(ps), sorted(dir_item.paths))
                self.assertEqual(td, dir_item.source)
                self._check_item(
                    dir_item, {p.provides for p in ps}, {require_directory('d')}
                )

                # This implicitly checks that `a` precedes its contents.
                dir_item.build(subvol, DUMMY_LAYER_OPTS)

            self.assertEqual(
                ['(Dir)', {'d': ['(Dir)', {'a': ['(Dir)', {
                    'data.txt': ['(File m444 d6)'],
                    'subdir': ['(Dir)', {
                        'exe.sh': ['(File m555 d23)'],
                    }],
                }]}]}],
                render_subvol(subvol),
            ) 
Example 75
Project: pyblish-win   Author: pyblish   File: fileinput.py    GNU Lesser General Public License v3.0 4 votes vote down vote up
def readline(self):
        try:
            line = self._buffer[self._bufindex]
        except IndexError:
            pass
        else:
            self._bufindex += 1
            self._lineno += 1
            self._filelineno += 1
            return line
        if not self._file:
            if not self._files:
                return ""
            self._filename = self._files[0]
            self._files = self._files[1:]
            self._filelineno = 0
            self._file = None
            self._isstdin = False
            self._backupfilename = 0
            if self._filename == '-':
                self._filename = '<stdin>'
                self._file = sys.stdin
                self._isstdin = True
            else:
                if self._inplace:
                    self._backupfilename = (
                        self._filename + (self._backup or os.extsep+"bak"))
                    try: os.unlink(self._backupfilename)
                    except os.error: pass
                    # The next few lines may raise IOError
                    os.rename(self._filename, self._backupfilename)
                    self._file = open(self._backupfilename, self._mode)
                    try:
                        perm = os.fstat(self._file.fileno()).st_mode
                    except OSError:
                        self._output = open(self._filename, "w")
                    else:
                        fd = os.open(self._filename,
                                     os.O_CREAT | os.O_WRONLY | os.O_TRUNC,
                                     perm)
                        self._output = os.fdopen(fd, "w")
                        try:
                            if hasattr(os, 'chmod'):
                                os.chmod(self._filename, perm)
                        except OSError:
                            pass
                    self._savestdout = sys.stdout
                    sys.stdout = self._output
                else:
                    # This may raise IOError
                    if self._openhook:
                        self._file = self._openhook(self._filename, self._mode)
                    else:
                        self._file = open(self._filename, self._mode)
        self._buffer = self._file.readlines(self._bufsize)
        self._bufindex = 0
        if not self._buffer:
            self.nextfile()
        # Recursive call
        return self.readline() 
Example 76
Project: pyblish-win   Author: pyblish   File: tarfile.py    GNU Lesser General Public License v3.0 4 votes vote down vote up
def _extract_member(self, tarinfo, targetpath):
        """Extract the TarInfo object tarinfo to a physical
           file called targetpath.
        """
        # Fetch the TarInfo object for the given name
        # and build the destination pathname, replacing
        # forward slashes to platform specific separators.
        targetpath = targetpath.rstrip("/")
        targetpath = targetpath.replace("/", os.sep)

        # Create all upper directories.
        upperdirs = os.path.dirname(targetpath)
        if upperdirs and not os.path.exists(upperdirs):
            # Create directories that are not part of the archive with
            # default permissions.
            os.makedirs(upperdirs)

        if tarinfo.islnk() or tarinfo.issym():
            self._dbg(1, "%s -> %s" % (tarinfo.name, tarinfo.linkname))
        else:
            self._dbg(1, tarinfo.name)

        if tarinfo.isreg():
            self.makefile(tarinfo, targetpath)
        elif tarinfo.isdir():
            self.makedir(tarinfo, targetpath)
        elif tarinfo.isfifo():
            self.makefifo(tarinfo, targetpath)
        elif tarinfo.ischr() or tarinfo.isblk():
            self.makedev(tarinfo, targetpath)
        elif tarinfo.islnk() or tarinfo.issym():
            self.makelink(tarinfo, targetpath)
        elif tarinfo.type not in SUPPORTED_TYPES:
            self.makeunknown(tarinfo, targetpath)
        else:
            self.makefile(tarinfo, targetpath)

        self.chown(tarinfo, targetpath)
        if not tarinfo.issym():
            self.chmod(tarinfo, targetpath)
            self.utime(tarinfo, targetpath)

    #--------------------------------------------------------------------------
    # Below are the different file methods. They are called via
    # _extract_member() when extract() is called. They can be replaced in a
    # subclass to implement other functionality. 
Example 77
Project: Ansible-Example-AB2018   Author: umit-ozturk   File: tarfile.py    MIT License 4 votes vote down vote up
def _extract_member(self, tarinfo, targetpath, set_attrs=True):
        """Extract the TarInfo object tarinfo to a physical
           file called targetpath.
        """
        # Fetch the TarInfo object for the given name
        # and build the destination pathname, replacing
        # forward slashes to platform specific separators.
        targetpath = targetpath.rstrip("/")
        targetpath = targetpath.replace("/", os.sep)

        # Create all upper directories.
        upperdirs = os.path.dirname(targetpath)
        if upperdirs and not os.path.exists(upperdirs):
            # Create directories that are not part of the archive with
            # default permissions.
            os.makedirs(upperdirs)

        if tarinfo.islnk() or tarinfo.issym():
            self._dbg(1, "%s -> %s" % (tarinfo.name, tarinfo.linkname))
        else:
            self._dbg(1, tarinfo.name)

        if tarinfo.isreg():
            self.makefile(tarinfo, targetpath)
        elif tarinfo.isdir():
            self.makedir(tarinfo, targetpath)
        elif tarinfo.isfifo():
            self.makefifo(tarinfo, targetpath)
        elif tarinfo.ischr() or tarinfo.isblk():
            self.makedev(tarinfo, targetpath)
        elif tarinfo.islnk() or tarinfo.issym():
            self.makelink(tarinfo, targetpath)
        elif tarinfo.type not in SUPPORTED_TYPES:
            self.makeunknown(tarinfo, targetpath)
        else:
            self.makefile(tarinfo, targetpath)

        if set_attrs:
            self.chown(tarinfo, targetpath)
            if not tarinfo.issym():
                self.chmod(tarinfo, targetpath)
                self.utime(tarinfo, targetpath)

    #--------------------------------------------------------------------------
    # Below are the different file methods. They are called via
    # _extract_member() when extract() is called. They can be replaced in a
    # subclass to implement other functionality. 
Example 78
Project: Ansible-Example-AB2018   Author: umit-ozturk   File: lxc_container.py    MIT License 4 votes vote down vote up
def create_script(command):
    """Write out a script onto a target.

    This method should be backward compatible with Python 2.4+ when executing
    from within the container.

    :param command: command to run, this can be a script and can use spacing
                    with newlines as separation.
    :type command: ``str``
    """

    (fd, script_file) = tempfile.mkstemp(prefix='lxc-attach-script')
    f = os.fdopen(fd, 'wb')
    try:
        f.write(to_bytes(ATTACH_TEMPLATE % {'container_command': command}, errors='surrogate_or_strict'))
        f.flush()
    finally:
        f.close()

    # Ensure the script is executable.
    os.chmod(script_file, int('0700', 8))

    # Output log file.
    stdout_file = os.fdopen(tempfile.mkstemp(prefix='lxc-attach-script-log')[0], 'ab')

    # Error log file.
    stderr_file = os.fdopen(tempfile.mkstemp(prefix='lxc-attach-script-err')[0], 'ab')

    # Execute the script command.
    try:
        subprocess.Popen(
            [script_file],
            stdout=stdout_file,
            stderr=stderr_file
        ).communicate()
    finally:
        # Close the log files.
        stderr_file.close()
        stdout_file.close()

        # Remove the script file upon completion of execution.
        os.remove(script_file) 
Example 79
Project: flasky   Author: RoseOu   File: util.py    MIT License 4 votes vote down vote up
def unzip_file(filename, location, flatten=True):
    """
    Unzip the file (with path `filename`) to the destination `location`.  All
    files are written based on system defaults and umask (i.e. permissions are
    not preserved), except that regular file members with any execute
    permissions (user, group, or world) have "chmod +x" applied after being
    written. Note that for windows, any execute changes using os.chmod are
    no-ops per the python docs.
    """
    if not os.path.exists(location):
        os.makedirs(location)
    zipfp = open(filename, 'rb')
    try:
        zip = zipfile.ZipFile(zipfp)
        leading = has_leading_dir(zip.namelist()) and flatten
        for info in zip.infolist():
            name = info.filename
            data = zip.read(name)
            fn = name
            if leading:
                fn = split_leading_dir(name)[1]
            fn = os.path.join(location, fn)
            dir = os.path.dirname(fn)
            if not os.path.exists(dir):
                os.makedirs(dir)
            if fn.endswith('/') or fn.endswith('\\'):
                # A directory
                if not os.path.exists(fn):
                    os.makedirs(fn)
            else:
                fp = open(fn, 'wb')
                try:
                    fp.write(data)
                finally:
                    fp.close()
                    mode = info.external_attr >> 16
                    # if mode and regular file and any execute permissions for user/group/world?
                    if mode and stat.S_ISREG(mode) and  mode & 0o111:
                        # make dest file have execute for user/group/world (chmod +x)
                        # no-op on windows per python docs
                        os.chmod(fn, (0o777-current_umask() | 0o111))
    finally:
        zipfp.close() 
Example 80
Project: flasky   Author: RoseOu   File: tarfile.py    MIT License 4 votes vote down vote up
def _extract_member(self, tarinfo, targetpath, set_attrs=True):
        """Extract the TarInfo object tarinfo to a physical
           file called targetpath.
        """
        # Fetch the TarInfo object for the given name
        # and build the destination pathname, replacing
        # forward slashes to platform specific separators.
        targetpath = targetpath.rstrip("/")
        targetpath = targetpath.replace("/", os.sep)

        # Create all upper directories.
        upperdirs = os.path.dirname(targetpath)
        if upperdirs and not os.path.exists(upperdirs):
            # Create directories that are not part of the archive with
            # default permissions.
            os.makedirs(upperdirs)

        if tarinfo.islnk() or tarinfo.issym():
            self._dbg(1, "%s -> %s" % (tarinfo.name, tarinfo.linkname))
        else:
            self._dbg(1, tarinfo.name)

        if tarinfo.isreg():
            self.makefile(tarinfo, targetpath)
        elif tarinfo.isdir():
            self.makedir(tarinfo, targetpath)
        elif tarinfo.isfifo():
            self.makefifo(tarinfo, targetpath)
        elif tarinfo.ischr() or tarinfo.isblk():
            self.makedev(tarinfo, targetpath)
        elif tarinfo.islnk() or tarinfo.issym():
            self.makelink(tarinfo, targetpath)
        elif tarinfo.type not in SUPPORTED_TYPES:
            self.makeunknown(tarinfo, targetpath)
        else:
            self.makefile(tarinfo, targetpath)

        if set_attrs:
            self.chown(tarinfo, targetpath)
            if not tarinfo.issym():
                self.chmod(tarinfo, targetpath)
                self.utime(tarinfo, targetpath)

    #--------------------------------------------------------------------------
    # Below are the different file methods. They are called via
    # _extract_member() when extract() is called. They can be replaced in a
    # subclass to implement other functionality.