Example #1
0
    def test_statvfs(self) -> None:
        hello_path = os.path.join(self.mount, "hello")
        fs_info = os.statvfs(hello_path)
        self.assertGreaterEqual(fs_info.f_namemax, 255)
        self.assertGreaterEqual(fs_info.f_frsize, 4096)
        self.assertGreaterEqual(fs_info.f_bsize, 4096)

        self.assertGreaterEqual(os.pathconf(hello_path, "PC_NAME_MAX"), 255)
        self.assertGreaterEqual(os.pathconf(hello_path, "PC_PATH_MAX"), 4096)
        self.assertGreaterEqual(os.pathconf(hello_path, "PC_REC_XFER_ALIGN"), 4096)
        self.assertGreaterEqual(os.pathconf(hello_path, "PC_ALLOC_SIZE_MIN"), 4096)
        self.assertGreaterEqual(os.pathconf(hello_path, "PC_REC_MIN_XFER_SIZE"), 4096)
 def __init__(self, sub_folder, file_name):
     valid_chars = "-_.%s%s" % (string.ascii_letters, string.digits)
     date = datetime.datetime.now()
     log_folder = os.path.join( Config().get_param("logs_folder"), sub_folder,
             "%d" % date.year, "%02d" % date.month, "%02d" % date.day)
     if os.path.exists(log_folder) == False:
         os.makedirs(log_folder)
     self.file_name = os.path.join( log_folder, "%d.%02d.%02d_%02d-%02d-%02d---%s.log" % (date.year, date.month,
             date.day, date.hour, date.minute, date.second,
             ''.join(c if c in valid_chars else '.' for c in file_name) ))
     # cut file name if it's too long
     if self.file_name.__len__() >= os.pathconf(log_folder, 'PC_NAME_MAX'):
         self.file_name = "%s.log" \
                 % self.file_name[:os.pathconf(log_folder, 'PC_NAME_MAX')-10]
     self.append_to_log(file_name.replace(".", " ").replace("-", "  --  "))
Example #3
0
def pathconf(space, path, w_name):
    num = confname_w(space, w_name, os.pathconf_names)
    try:
        res = os.pathconf(path, num)
    except OSError as e:
        raise wrap_oserror(space, e)
    return space.wrap(res)
Example #4
0
    def get(path, attr):
        """Get an extended attribute on a specified file.

        path - path name of file to check
        attr - name of attribute to get

        None is returned if the named attribute does not exist.  OSError
        is raised if path does not exist or is not readable."""
        
        if not os.access(path, os.F_OK):
            raise OSError(errno.ENOENT, 'No such file or directory', path)

        if os.pathconf(path, _PC_XATTR_EXISTS)<=0:
            return

        fd=libc.attropen(path, attr, os.O_RDONLY, 0)
        if fd<0:
            return

        v=''
        while True:
            buf=os.read(fd, 1024)
            if len(buf)<1:
                break
            v+=buf

        libc.close(fd)

        return v
	def _max_path(self):
		val = self._max_path_value
		if val is None:
			fileno = getattr(self.fp, 'fileno', None)
			fileno = os.curdir if fileno is None else fileno()
			self._max_path_value = val = os.pathconf(fileno, 'PC_PATH_MAX')
		return val
Example #6
0
def _get_pathconf(file_system_path, param_suffix, default):
    """Return a pathconf parameter value for a filesystem.
    """
    param_str = [s for s in os.pathconf_names if s.endswith(param_suffix)]
    if len(param_str) == 1:
        try:
            return os.pathconf(file_system_path, param_str[0])
        except OSError:
            pass
    return default
Example #7
0
def max_path():
    """Return the maximum length for a path.

    :return: the maximum length
    :rtype: int
    """
    if sys.platform == 'win32':  # unix: no cover
        from ctypes.wintypes import MAX_PATH
        return MAX_PATH
    else:
        return os.pathconf('/', 'PC_PATH_MAX')
Example #8
0
 def _storage_max_filename_length(self, storage):
     """
     Query filesystem for maximum filename length (e.g. AUFS has 242).
     """
     dir_to_test = storage.location
     while not os.path.exists(dir_to_test):
         dir_to_test = os.path.dirname(dir_to_test)
     try:
         return os.pathconf(dir_to_test, 'PC_NAME_MAX')
     except Exception:
         return 255  # Should be safe on most backends
Example #9
0
 def _record_path(self, subject, id):
     max_len = os.pathconf(
         subject,
         "PC_NAME_MAX") if os.name == "posix" else 255  # maximum NTFS and FAT32 filename length
     b64id = self._b64id(id)
     # split into chunks of proper length
     b64id = [b64id[i:i + max_len - 1]
              for i in range(0, len(b64id), max_len - 1)]
     # prepend dirs with @ (does not occur in b64) to avoid conflict with b64-named files in the same dir
     b64id = ["@" + s for s in b64id[:-1]] + [b64id[-1]]
     path = os.path.join(subject, *b64id)
     return path
def max_path():
    """Return the maximum length for a path.

    :return: the maximum length
    :rtype: int
    """
    if sys.platform == "win32":
        from ctypes.wintypes import MAX_PATH

        return MAX_PATH
    else:
        return os.pathconf("/", "PC_PATH_MAX")
Example #11
0
    def supported(path=None):
        """Detect whether extended attribute support is available.

        path - path to file to check for extended attribute support.
        Availablity can vary from one file system to another.

        If path is None then return True if the system in general supports
        extended attributes."""
        
        if not path:
            return True

        return os.pathconf(path, _PC_XATTR_ENABLED)
Example #12
0
 def __init__(self, head_dir):
     """Inits DumpGenerator."""
     self.digit = 0
     self.offset = 1
     self.outdir = ''
     self.pattern = [re.compile(r'^\[PATCH[^]]*\]'), re.compile(r'[^-a-z.A-Z_0-9]'),
                     re.compile(r'\.\.\.'), re.compile(r'\.*$|^-|-$'), re.compile(r'--*')]
     self.pc_name_max = os.pathconf('/tmp', 'PC_NAME_MAX')
     self.revision_range = []
     self.latest_commit_id = b''
     self.latest_tag = ''
     if not os.path.exists(head_dir) or not os.path.exists(os.path.join(DEST_DIR, '.gitdump')) \
             or not os.path.exists(os.path.join(DEST_DIR, '.gitdump', 'DUMP_HEAD')):
         _init_meta_dir(head_dir)
Example #13
0
        def _get_result_dir_name(parameter_setting, hide_parameters, method=None):
            """ internal function to create result dir name in different ways"""
            if not method:
                parameter_str = "}{".join(
                    ("%s#%s" % (key, value))
                    for key, value in parameter_setting.iteritems()
                    if key not in hide_parameters
                )
            elif method == "hash":
                parameter_str = "}{".join(
                    ("%s#%s" % (key, hash(str(value).replace(" ", ""))))
                    for key, value in parameter_setting.iteritems()
                    if key not in hide_parameters
                )

            parameter_str = parameter_str.replace("'", "")
            parameter_str = parameter_str.replace(" ", "")
            parameter_str = parameter_str.replace("[", "")
            parameter_str = parameter_str.replace("]", "")
            parameter_str = parameter_str.replace(os.sep, "")
            result_name = "{%s}" % input_name

            if parameter_str != "":
                result_name += "{%s}" % (parameter_str)

            # Determine the path where this result will be stored
            # and create the directory if necessary
            result_dir = base_dir
            result_dir += os.sep + result_name
            # filename is to long
            # (longer than allowed including optional offsets for pyspace
            #  result csv naming conventions)
            # create a md5 hash of the result name and use that one
            import platform

            CURRENTOS = platform.system()
            if CURRENTOS == "Windows":
                # the maximum length for a filename on Windows is 255
                if len(result_dir) > 255 - 32:
                    result_name = "{" + hashlib.md5(result_name).hexdigest() + "}"
                    result_dir = base_dir
                    result_dir += os.sep + result_name
                return result_dir
            else:
                if len(result_dir) > os.pathconf(os.curdir, "PC_NAME_MAX") - 32:
                    result_name = "{" + hashlib.md5(result_name).hexdigest() + "}"
                    result_dir = base_dir
                    result_dir += os.sep + result_name
                return result_dir
Example #14
0
    def test_name_max(self):

        name_max = os.pathconf(self.tempdir, os.pathconf_names['PC_NAME_MAX'])

        file1 = os.path.join(
            self.tempdir,
            ''.join(random.choice(string.ascii_letters) for _ in range(name_max)))
        ftrans = FileTransaction()
        ftrans.open(file1, "w")
        ftrans.commit()
        self.assertTrue(os.path.exists(file1))

        file2 = file1 + random.choice(string.ascii_letters)
        ftrans = FileTransaction()
        self.assertRaises(IOError, ftrans.open, file2, "w")
Example #15
0
def NSIterateSearchPaths(directory):
    CoreFoundation = ctypes.cdll.LoadLibrary("/System/Library/Frameworks/CoreFoundation.framework/Versions/A/CoreFoundation")
    NSStartSearchPathEnumeration = CoreFoundation.NSStartSearchPathEnumeration
    NSGetNextSearchPathEnumeration = CoreFoundation.NSGetNextSearchPathEnumeration
    PATH_MAX = os.pathconf('/', os.pathconf_names['PC_PATH_MAX'])
    PATH_ENCODING = 'utf8'
    path_buffer = ctypes.create_string_buffer(PATH_MAX)
    paths = []
    state = NSStartSearchPathEnumeration(directory, 1)
    while True:
        state = NSGetNextSearchPathEnumeration(state, path_buffer)
        if state == 0:
            break
        path = os.path.expanduser(path_buffer.value.decode(PATH_ENCODING))
        return path
Example #16
0
    def listx(path):
        """Return a list of extended attributes set on the named file.

        path - path name of file to check
        
        OSError is raised if path does not exist or is not readable."""
        if not os.access(path, os.F_OK):
            raise OSError(errno.ENOENT, 'No such file or directory', path)

        if os.pathconf(path, _PC_XATTR_EXISTS)<=0:
            return []

        fd=libc.attropen(path, '.', os.O_RDONLY, 0)
        if fd<0:
            return []

        odir=os.getcwd()
        os.fchdir(fd)
        attrs=os.listdir('.')
        os.chdir(odir)
        libc.close(fd)

        return attrs
Example #17
0
                                    quote)
from pkg_resources import iter_entry_points
from publicsuffix import PublicSuffixList

from .composed import composable
from .iterable import map_if_iter
from .value import encode_json

logger = logging.getLogger(__name__)



DEFAULT_METHOD = 'get'

if hasattr(os, 'pathconf'):
    PC_NAME_MAX = os.pathconf(os.path.dirname(__file__), 'PC_NAME_MAX')
else:
    PC_NAME_MAX = 255  # pragma: no cover


@contextmanager
def eexist_is_ok():
    try:
        yield
    except OSError as exc:
        if exc.errno != errno.EEXIST:
            raise


class Method(object):
    """ Method objects 'get' responses from a url.
Example #18
0
 def present(path):
     """Return True if extended attributes exist on the named file."""
     
     return os.pathconf(path, _PC_XATTR_EXISTS)>0
Example #19
0
 def pathconf(self, name):
     return os.pathconf(self, name)
Example #20
0
import signal

import sys

from cStringIO import StringIO

from wal_e import subprocess
from wal_e.subprocess import PIPE

# This is not used in this module, but is imported by dependent
# modules, so do this to quiet pyflakes.
assert PIPE

# Determine the maximum number of bytes that can be written atomically
# to a pipe
PIPE_BUF_BYTES = os.pathconf('.', os.pathconf_names['PC_PIPE_BUF'])


class NonBlockPipeFileWrap(object):
    def __init__(self, fp):
        # Make the file nonblocking (but don't lose its previous flags)
        flags = fcntl.fcntl(fp, fcntl.F_GETFL)
        fcntl.fcntl(fp, fcntl.F_SETFL, flags | os.O_NONBLOCK)

        self._fp = fp

    def read(self, size=None):
        # Some adaptation from gevent's examples/processes.py
        accum = StringIO()

        while size is None or accum.tell() < size:
Example #21
0
 def name_max(self):
     if 'PC_NAME_MAX' in os.pathconf_names:
         pc_name_max = os.pathconf_names['PC_NAME_MAX']
         return os.pathconf(self._archive_root, pc_name_max)
     else:
         return 255
Example #22
0
 def test_os_pathconf(self):
     os = self.posix
     assert os.pathconf("/tmp", "PC_NAME_MAX") >= 31
     # Linux: the following gets 'No such file or directory'
     raises(OSError, os.pathconf, "", "PC_PIPE_BUF")
     raises(ValueError, os.pathconf, "/tmp", "##")
Example #23
0
    def __init__(
            self,
            root_path,  # type: Text
            create=False,  # type: bool
            create_mode=0o777,  # type: SupportsInt
            expand_vars=True,  # type: bool
    ):
        # type: (...) -> None
        """Create an OSFS instance."""
        super(OSFS, self).__init__()
        if isinstance(root_path, bytes):
            root_path = fsdecode(root_path)
        self.root_path = root_path
        _drive, _root_path = os.path.splitdrive(fsdecode(fspath(root_path)))
        _root_path = _drive + (_root_path or "/") if _drive else _root_path
        _root_path = os.path.expanduser(
            os.path.expandvars(_root_path) if expand_vars else _root_path)
        _root_path = os.path.normpath(os.path.abspath(_root_path))
        self._root_path = _root_path

        if create:
            try:
                if not os.path.isdir(_root_path):
                    os.makedirs(_root_path, mode=int(create_mode))
            except OSError as error:
                raise errors.CreateFailed(
                    "unable to create {} ({})".format(root_path, error), error)
        else:
            if not os.path.isdir(_root_path):
                message = "root path '{}' does not exist".format(_root_path)
                raise errors.CreateFailed(message)

        _meta = self._meta = {
            "network": False,
            "read_only": False,
            "supports_rename": True,
            "thread_safe": True,
            "unicode_paths": os.path.supports_unicode_filenames,
            "virtual": False,
        }

        try:
            # https://stackoverflow.com/questions/7870041/check-if-file-system-is-case-insensitive-in-python
            # I don't know of a better way of detecting case insensitivity of a
            # filesystem
            with tempfile.NamedTemporaryFile(prefix="TmP") as _tmp_file:
                _meta["case_insensitive"] = os.path.exists(
                    _tmp_file.name.lower())
        except Exception:
            if platform.system() != "Darwin":
                _meta["case_insensitive"] = os.path.normcase("Aa") == "aa"

        if _WINDOWS_PLATFORM:  # pragma: no cover
            _meta["invalid_path_chars"] = (
                "".join(six.unichr(n) for n in range(31)) + '\\:*?"<>|')
        else:
            _meta["invalid_path_chars"] = "\0"

            if "PC_PATH_MAX" in os.pathconf_names:
                try:
                    _meta["max_sys_path_length"] = os.pathconf(
                        fsencode(_root_path), os.pathconf_names["PC_PATH_MAX"])
                except OSError:  # pragma: no cover
                    # The above fails with nfs mounts on OSX. Go figure.
                    pass
Example #24
0
process.maxEvents = cms.untracked.PSet(
  input = cms.untracked.int32({{ max_events }}),
)
process.source = cms.Source(
  "PoolSource",
  fileNames          = cms.untracked.vstring(inputFiles),
  duplicateCheckMode = cms.untracked.string('noDuplicateCheck')
)

process.genxsec = cms.EDAnalyzer("GenXSecAnalyzer")

process.p = cms.Path(process.genxsec)
process.schedule = cms.Schedule(process.p)
"""

MAX_NAME_LEN = os.pathconf('/', 'PC_NAME_MAX')

parent_id = os.getpid()


def handle_worker():
    def sig_int(signal_num, frame):
        parent = psutil.Process(parent_id)
        for child in parent.children():
            if child.pid != os.getpid():
                child.kill()
        parent.kill()
        psutil.Process(os.getpid()).kill()

    signal.signal(signal.SIGINT, sig_int)
Example #25
0
    def __init__(
            self,
            root_path,  # type: Text
            create=False,  # type: bool
            create_mode=0o777,  # type: SupportsInt
            expand_vars=True,  # type: bool
    ):
        # type: (...) -> None
        """Create an OSFS instance.

        Arguments:
            root_path (str or ~os.PathLike): An OS path or path-like object
                to the location on your HD you wish to manage.
            create (bool): Set to `True` to create the root directory if it
                does not already exist, otherwise the directory should exist
                prior to creating the ``OSFS`` instance (defaults to `False`).
            create_mode (int): The permissions that will be used to create
                the directory if ``create`` is `True` and the path doesn't
                exist, defaults to ``0o777``.
            expand_vars(bool): If `True` (the default) environment variables
                of the form ``~``, ``$name`` or ``${name}`` will be expanded.

        Raises:
            `fs.errors.CreateFailed`: If ``root_path`` does not
                exist, or could not be created.

        """
        super(OSFS, self).__init__()
        if isinstance(root_path, bytes):
            root_path = fsdecode(root_path)
        self.root_path = root_path
        _drive, _root_path = os.path.splitdrive(fsdecode(fspath(root_path)))
        _root_path = _drive + (_root_path or "/") if _drive else _root_path
        _root_path = os.path.expanduser(
            os.path.expandvars(_root_path) if expand_vars else _root_path)
        _root_path = os.path.normpath(os.path.abspath(_root_path))
        self._root_path = _root_path

        if create:
            try:
                if not os.path.isdir(_root_path):
                    os.makedirs(_root_path, mode=int(create_mode))
            except OSError as error:
                raise errors.CreateFailed(
                    "unable to create {} ({})".format(root_path, error), error)
        else:
            if not os.path.isdir(_root_path):
                message = "root path '{}' does not exist".format(_root_path)
                raise errors.CreateFailed(message)

        _meta = self._meta = {
            "network": False,
            "read_only": False,
            "supports_rename": True,
            "thread_safe": True,
            "unicode_paths": os.path.supports_unicode_filenames,
            "virtual": False,
        }

        try:
            # https://stackoverflow.com/questions/7870041/check-if-file-system-is-case-insensitive-in-python
            # I don't know of a better way of detecting case insensitivity of a
            # filesystem
            with tempfile.NamedTemporaryFile(prefix="TmP") as _tmp_file:
                _meta["case_insensitive"] = os.path.exists(
                    _tmp_file.name.lower())
        except Exception:
            if platform.system() != "Darwin":
                _meta["case_insensitive"] = os.path.normcase("Aa") == "aa"

        if _WINDOWS_PLATFORM:  # pragma: no cover
            _meta["invalid_path_chars"] = (
                "".join(six.unichr(n) for n in range(31)) + '\\:*?"<>|')
        else:
            _meta["invalid_path_chars"] = "\0"

            if "PC_PATH_MAX" in os.pathconf_names:
                try:
                    _meta["max_sys_path_length"] = os.pathconf(
                        fsencode(_root_path), os.pathconf_names["PC_PATH_MAX"])
                except OSError:  # pragma: no cover
                    # The above fails with nfs mounts on OSX. Go figure.
                    pass
Example #26
0
 def f(i):
     return os.pathconf("/tmp", i)
Example #27
0
import os

from page_loader import app

max_len = os.pathconf('/', 'PC_NAME_MAX')

NAMES = [('http://test.io/courses', app.get_name, 'test-io-courses'),
         ('http://test.io/courses', app.get_directory_name,
          'test-io-courses_files'),
         ('http://test.io/courses', app.get_page_name, 'test-io-courses.html')]

PAGE_ELEMENTS_NAMES = [
    ('http://test.io/courses', 'assets/pic.png', 'test-io-assets-pic.png'),
    ('http://test.io', 'assets/pic.png', 'test-io-assets-pic.png'),
    ('http://test.io', 'assets/pic', 'test-io-assets-pic')
]

IS_LOCAL_TEST_ITEMS = [("https://cdn2.test.io/assets/menu.css", 'test.io',
                        False),
                       ("https://test.io/assets/menu.css", 'test.io', True),
                       ("assets/menu.css", 'test.io', True)]

PAGE_ELEMENTS = [
    ('https://eg-b.github.io/python-project-lvl3/assets/application.css',
     'eg-b-github-io-python-project-lvl3-assets-application.css'),
    ('https://eg-b.github.io/python-project-lvl3/courses/hexlet',
     'eg-b-github-io-python-project-lvl3-courses-hexlet'),
    ('https://eg-b.github.io/python-project-lvl3/assets/professions'
     '/python.svg',
     'eg-b-github-io-python-project-lvl3-assets-professions-python.svg'),
    ('https://eg-b.github.io/python-project-lvl3/packs/js/runtime.js',
Example #28
0
os.lstat("path")  # $ getAPathArgument="path"
os.lstat(path="path")  # $ getAPathArgument="path"

os.mkdir("path")  # $ getAPathArgument="path"
os.mkdir(path="path")  # $ getAPathArgument="path"

os.makedirs("name")  # $ getAPathArgument="name"
os.makedirs(name="name")  # $ getAPathArgument="name"

os.mkfifo("path")  # $ getAPathArgument="path"
os.mkfifo(path="path")  # $ getAPathArgument="path"

os.mknod("path")  # $ getAPathArgument="path"
os.mknod(path="path")  # $ getAPathArgument="path"

os.pathconf("path", "name")  # $ getAPathArgument="path"
os.pathconf(path="path", name="name")  # $ getAPathArgument="path"

os.readlink("path")  # $ getAPathArgument="path"
os.readlink(path="path")  # $ getAPathArgument="path"

os.remove("path")  # $ getAPathArgument="path"
os.remove(path="path")  # $ getAPathArgument="path"

os.removedirs("name")  # $ getAPathArgument="name"
os.removedirs(name="name")  # $ getAPathArgument="name"

os.rename("src", "dst")  # $ getAPathArgument="src" getAPathArgument="dst"
os.rename(src="src",
          dst="dst")  # $ getAPathArgument="src" getAPathArgument="dst"
Example #29
0
 def pathconf(self, name):
     """ .. seealso:: :func:`os.pathconf` """
     return os.pathconf(self, name)
Example #30
0
import tornado.ioloop
import tornado.web
from tornado.concurrent import Future
from tornado.httpclient import AsyncHTTPClient
from tornado.options import options

import frontik.loggers
import frontik.producers.json_producer
import frontik.producers.xml_producer
from frontik.compat import iteritems
from frontik.handler import ErrorHandler
from frontik.loggers.request import RequestLogger

app_logger = logging.getLogger('frontik.app')

MAX_MODULE_NAME_LENGTH = os.pathconf('/', 'PC_PATH_MAX') - 1


def get_frontik_and_apps_versions(application):
    from frontik.version import version
    import simplejson
    import sys
    import tornado

    versions = etree.Element('versions')
    etree.SubElement(versions, 'frontik').text = version
    etree.SubElement(versions, 'tornado').text = tornado.version
    etree.SubElement(versions, 'lxml.etree.LXML').text = '.'.join(
        str(x) for x in etree.LXML_VERSION)
    etree.SubElement(versions, 'lxml.etree.LIBXML').text = '.'.join(
        str(x) for x in etree.LIBXML_VERSION)
Example #31
0
def test_truncate_name():
    long_filename = os.path.join(DIR_PATH, 'a' * 256 + '.jpg')
    name_max = os.pathconf('/', 'PC_NAME_MAX')
    test_filename = truncate_name(long_filename)
    assert len(test_filename) == name_max + len(DIR_PATH)
Example #32
0
from usb.core import USBError
from usb._debug import methodtrace
import logging

__author__ = 'Wander Lairson Costa'

__all__ = ['get_backend']

_logger = logging.getLogger('usb.backend.libusb01')

# usb.h

_PC_PATH_MAX = 4

if sys.platform != 'win32':
    _PATH_MAX = os.pathconf('.', _PC_PATH_MAX)
else:
    _PATH_MAX = 511


# libusb-win32 makes all structures packed, while
# default libusb only does for some structures
# _PackPolicy defines the structure packing according
# to the platform.
class _PackPolicy(object):
    pass


if sys.platform == 'win32':
    _PackPolicy._pack_ = 1
Example #33
0
    def setacl_nfs4(self, job, data):
        job.set_progress(0, 'Preparing to set acl.')
        options = data['options']
        dacl = data.get('dacl', [])

        if osc.IS_LINUX or not os.pathconf(data['path'], 64):
            raise CallError(
                f"NFSv4 ACLS are not supported on path {data['path']}",
                errno.EOPNOTSUPP)

        self._common_perm_path_validate(data['path'])

        if dacl and options['stripacl']:
            raise CallError(
                'Setting ACL and stripping ACL are not permitted simultaneously.',
                errno.EINVAL)

        uid = -1 if data.get('uid', None) is None else data['uid']
        gid = -1 if data.get('gid', None) is None else data['gid']
        if options['stripacl']:
            a = acl.ACL(file=data['path'])
            a.strip()
            a.apply(data['path'])
        else:
            inheritable_is_present = False
            cleaned_acl = []
            lockace_is_present = False
            for entry in dacl:
                ace = {
                    'tag': (acl.ACLWho(entry['tag'])).name,
                    'id':
                    entry['id'],
                    'type':
                    entry['type'],
                    'perms':
                    self.__convert_to_adv_permset(entry['perms']['BASIC'])
                    if 'BASIC' in entry['perms'] else entry['perms'],
                    'flags':
                    self.__convert_to_adv_flagset(entry['flags']['BASIC'])
                    if 'BASIC' in entry['flags'] else entry['flags'],
                }
                if ace['flags'].get('INHERIT_ONLY') and not ace['flags'].get(
                        'DIRECTORY_INHERIT', False) and not ace['flags'].get(
                            'FILE_INHERIT', False):
                    raise CallError(
                        'Invalid flag combination. DIRECTORY_INHERIT or FILE_INHERIT must be set if INHERIT_ONLY is set.',
                        errno.EINVAL)
                if ace['tag'] == 'EVERYONE' and self.__convert_to_basic_permset(
                        ace['perms']) == 'NOPERMS':
                    lockace_is_present = True
                elif ace['flags'].get('DIRECTORY_INHERIT') or ace['flags'].get(
                        'FILE_INHERIT'):
                    inheritable_is_present = True

                cleaned_acl.append(ace)

            if not inheritable_is_present:
                raise CallError(
                    'At least one inheritable ACL entry is required',
                    errno.EINVAL)

            if options['canonicalize']:
                cleaned_acl = self.canonicalize_acl_order(cleaned_acl)

            if not lockace_is_present:
                locking_ace = {
                    'tag': 'EVERYONE',
                    'id': None,
                    'type': 'ALLOW',
                    'perms': self.__convert_to_adv_permset('NOPERMS'),
                    'flags': self.__convert_to_adv_flagset('INHERIT')
                }
                cleaned_acl.append(locking_ace)

            a = acl.ACL()
            a.__setstate__(cleaned_acl)
            a.apply(data['path'])

        if not options['recursive']:
            os.chown(data['path'], uid, gid)
            job.set_progress(100, 'Finished setting NFS4 ACL.')
            return

        job.set_progress(10, f'Recursively setting ACL on {data["path"]}.')
        self._winacl(data['path'], 'clone', uid, gid, options)
        job.set_progress(100, 'Finished setting NFS4 ACL.')
Example #34
0
#!/usr/bin/python

import os, sys

print "%s" % os.pathconf_names

no = os.pathconf('example240_os_pathconf.py', 'PC_NAME_MAX')
print "Maximum length of a filename :%d" % no

no = os.pathconf('example240_os_pathconf.py', 'PC_FILESIZEBITS')
print "file size in bits: %d" % no
Example #35
0
def get_filename_max_length(directory: str) -> int:
    max_len = 255
    if hasattr(os, 'pathconf') and 'PC_NAME_MAX' in os.pathconf_names:
        max_len = os.pathconf(directory, 'PC_NAME_MAX')
    return max_len
Example #36
0
import os, sys
import traceback
import re
import socket_error

Resolver.configure('tornado.platform.caresresolver.CaresResolver')
resolver = Resolver()

libc = ctypes.cdll.LoadLibrary('libc.so.6')
splice_syscall = libc.splice

SPLICE_F_NONBLOCK = 0x02
SPLICE_F_MOVE = 0x01

try:
    chunk_size = os.pathconf('.', os.pathconf_names['PC_PIPE_BUF'])
except:
    print 'pathconf failed'
    import resource
    chunk_size = resource.getpagesize()

header = 'GET /'
opt_header = 'OPTIO'


def make_response(status,
                  body,
                  content_type='text/plain',
                  extra_headers=None,
                  length=True):
    res = 'HTTP/1.1 %s\r\n' % status
Example #37
0
# Some platform dependent stuff
import sys, os

class Struct(Structure):
    pass

if sys.platform=='win32':
    _libname = 'libusb0.dll'
    LIBUSB_PATH_MAX = 512
    Struct._pack_ = 1
    LIBUSB_HAS_GET_DRIVER_NP = 0
    LIBUSB_HAS_DETACH_KERNEL_DRIVER_NP = 0
elif sys.platform=='linux2':
    _libname = ctypes.util.find_library('usb-0.1')
    LIBUSB_PATH_MAX = os.pathconf('/',4)+1 
    LIBUSB_HAS_GET_DRIVER_NP = 1
    LIBUSB_HAS_DETACH_KERNEL_DRIVER_NP = 1
else: raise 'libusb0.py: Operating system not supported.'    


#================================================================
# Type definitions
#================================================================

#------- USB Device classes ---------
USB_CLASS_PER_INTERFACE = 0     # Device class specified per interface
USB_CLASS_AUDIO         = 1
USB_CLASS_COMM          = 2
USB_CLASS_HID           = 3
USB_CLASS_PRINTER       = 7
Example #38
0
from usb.core import USBError
from usb._debug import methodtrace
import logging

__author__ = 'Wander Lairson Costa'

__all__ = ['get_backend']

_logger = logging.getLogger('usb.backend.libusb01')

# usb.h

_PC_PATH_MAX = 4

if sys.platform != 'win32':
    _PATH_MAX = os.pathconf('.', _PC_PATH_MAX)
else:
    _PATH_MAX = 511

# libusb-win32 makes all structures packed, while
# default libusb only does for some structures
# _PackPolicy defines the structure packing according
# to the platform.
class _PackPolicy(object):
    pass

if sys.platform == 'win32':
    _PackPolicy._pack_ = 1

# Data structures
Example #39
0
import __init__ as flow
import optparse
import sys
import os
import json
import signal

try:
    from commands import getoutput
    _ncpu = int(getoutput("grep -c -e '^processor' /proc/cpuinfo"))
except Exception, e:
    _ncpu = 4

try:
    _maxdepth = int(os.pathconf('/', 'PC_PATH_MAX')) / 2
except Exception, e:
    _maxdepth = 128

signal.signal(signal.SIGINT, lambda signal, frame: sys.exit(-1))
signal.signal(signal.SIGTERM, lambda signal, frame: sys.exit(-1))

# setup static functions


def main(commandargs=sys.argv):
    parser = optparse.OptionParser(prog="flow",
                                   formatter=optparse.IndentedHelpFormatter(
                                       width=os.getenv('COLUMNS', 132)),
                                   version=flow.__version__)
    parser.add_option("-q",
Example #40
0
import unittest
import errno
import os
from commontest import abs_test_dir, old_test_dir, Myrm, \
    rdiff_backup, compare_recursive
from rdiff_backup import rpath, Globals, regress, Time

if os.name == "nt":
    NAME_MAX_LEN = 255
else:
    NAME_MAX_LEN = os.pathconf(abs_test_dir, 'PC_NAME_MAX')


class LongNameTest(unittest.TestCase):
    """Test the longname module"""
    root_rp = rpath.RPath(Globals.local_connection, abs_test_dir)
    out_rp = root_rp.append_path('output')

    def test_length_limit(self):
        """Confirm that length limit is NAME_MAX_LEN

        Some of these tests depend on the length being at most
        NAME_MAX_LEN, so check to make sure it's accurate.

        """
        Myrm(self.out_rp.path)
        self.out_rp.mkdir()

        really_long = self.out_rp.append('a' * NAME_MAX_LEN)
        really_long.touch()
Example #41
0
File: lock.py Project: HuaiQiu/ktbs
LOG = getLogger(__name__)
PID = getpid()

if sys.platform.lower().find('darwin') != -1:
    def get_semaphore_name(resource_uri):
        """Return a safe semaphore name for a resource.

        :param basestring resource_uri: the URI of the resource.
        :return: safe semaphore name.
        :rtype: str
        """

        sem_name = md5(resource_uri).hexdigest()[:29]
        return sem_name
else:
    NAME_MAX_SEM = pathconf("/", 'PC_NAME_MAX') - 4 # according to man 7 sem_overview
    def get_semaphore_name(resource_uri):
        """Return a safe semaphore name for a resource.

        posix_ipc doesn't accept '/' inside the semaphore name but the name must
        begin with '/'.

        :param basestring resource_uri: the URI of the resource.
        :return: safe semaphore name.
        :rtype: str
        """

        sem_name = str('/' + resource_uri.replace('/', '-'))
        if len(sem_name) > NAME_MAX_SEM:
            sem_name = '/' + md5(resource_uri).hexdigest()
        return sem_name
 def pathconf(self, name):
     return os.pathconf(self, name)
Example #43
0
                                    unquote)
from pkg_resources import iter_entry_points
from publicsuffix import PublicSuffixList

from .py2compat import urlquote
from .composed import composable
from .iterable import map_if_iter
from .value import encode_json

logger = logging.getLogger(__name__)


DEFAULT_METHOD = 'get'

if hasattr(os, 'pathconf'):
    PC_NAME_MAX = os.pathconf(os.path.dirname(__file__), 'PC_NAME_MAX')
else:
    PC_NAME_MAX = 255  # pragma: no cover


@contextmanager
def eexist_is_ok():
    try:
        yield
    except OSError as exc:
        if exc.errno != errno.EEXIST:
            raise


class Method(object):
    """ Method objects 'get' responses from a url.
Example #44
0
 def name_max(self):
     if 'PC_NAME_MAX' in os.pathconf_names:
         pc_name_max = os.pathconf_names['PC_NAME_MAX']
         return os.pathconf(self._archive_root, pc_name_max)
     else:
         return 255
Example #45
0
  elif _arg in ( '-v', '--verbose' ):
    VERBOSE += 1
  elif _arg in ( '-t', '--timeout' ):
    try:
      TIMEOUT = int( _args.next() )
      assert TIMEOUT > 0
    except:
      sys.exit( 'Error: %s requires a positive numerical argument' % _arg )
  elif _arg in ( '-6', '--ipv6' ):
    FAMILY = socket.AF_UNSPEC
  elif _arg == '--flat':
    FLAT = True
  elif _arg == '--static':
    STATIC = True
  elif _arg == '--offline':
    ONLINE = False
    STATIC = True
  elif _arg == '--limit':
    try:
      LIMIT = float( _args.next() ) * 1024
    except:
      sys.exit( 'Error: %s requires a numerical argument' % _arg )
  elif _arg == '--daemon':
    LOG = _args.next()
  elif _arg == '--debug':
    DEBUG = True
  else:
    sys.exit( 'Error: invalid option %r' % _arg )

MAXFILELEN = os.pathconf( ROOT, 'PC_NAME_MAX' ) - len(SUFFIX)
Example #46
0
#返回path指定的文件夹包含的文件或文件夹的名字的列表 
# ./当前路径(相对路径)

os.walk(top[, topdown=True[, onerror=None[, followlinks=False]]])
# 输出在文件夹中的文件名通过在树中游走,向上或者向下。默认遍历所有目录树,返回一个可迭代的生成器,使用for循环可以进行处理
import os
o = os.walk('d:\new\')
print(f for f in o)

os.stat(path)
# 获取path指定的路径的信息,功能等同于C API中的stat()系统调用。

os.statvfs(path)
# 获取指定路径的文件系统统计信息

os.pathconf(path,name)
# 返回相关文件的系统配置信息

os.utime(path, times)
# 返回指定的path文件的访问和修改的时间

"""
文件权限
"""
os.access(path,mode)
# 检验权限模式

os.chmod(path,mode)
# 更改权限

os.chown(path,uid,gid)
Example #47
0
__author__ = 'Wander Lairson Costa'

__all__ = ['get_backend']

_logger = logging.getLogger('usb.backend.libusb0')

# usb.h

if sys.platform.find('bsd') != -1 or sys.platform.find('mac') != -1 or \
        sys.platform.find('darwin') != -1 or sys.platform.find('sunos5') != -1:
    _PATH_MAX = 1024
elif sys.platform == 'win32' or sys.platform == 'cygwin':
    _PATH_MAX = 511
else:
    _PATH_MAX = os.pathconf('.', 'PC_PATH_MAX')


# libusb-win32 makes all structures packed, while
# default libusb only does for some structures
# _PackPolicy defines the structure packing according
# to the platform.
class _PackPolicy(object):
    pass


if sys.platform == 'win32' or sys.platform == 'cygwin':
    _PackPolicy._pack_ = 1

# Data structures
Example #48
0
 def pathconf(self, name):
     """Wraps os.pathconf"""
     return os.pathconf(self, name)
Example #49
0
File: path.py Project: Byron/bcore
 def pathconf(self, name):
     """see os.pathconf"""
     return os.pathconf(self._expandvars(self), name)
Example #50
0
 def test_os_pathconf(self):
     os = self.posix
     assert os.pathconf("/tmp", "PC_NAME_MAX") >= 31
     # Linux: the following gets 'No such file or directory'
     raises(OSError, os.pathconf, "", "PC_PIPE_BUF")
     raises(ValueError, os.pathconf, "/tmp", "##")
Example #51
0
File: util.py Project: aragilar/asv
from __future__ import (absolute_import, division, print_function,
                        unicode_literals)

import json
import math
import os
import select
import subprocess
import time

try:
    from select import PIPE_BUF
except ImportError:
    # PIPE_BUF is not available on Python 2.6
    PIPE_BUF = os.pathconf('.', os.pathconf_names['PC_PIPE_BUF'])

import six
from six.moves import xrange

from .console import log
from .extern import minify_json


def human_file_size(size):
    """
    Returns a human-friendly string representing a file size
    that is 2-4 characters long.

    For example, depending on the number of bytes given, can be one
    of::
Example #52
0
def pathconf(space, path, w_name):
    num = confname_w(space, w_name, os.pathconf_names)
    try:
        res = os.pathconf(path, num)
    except OSError, e:
        raise wrap_oserror(space, e)
Example #53
0
__author__ = 'Wander Lairson Costa'

__all__ = ['get_backend']

_logger = logging.getLogger('usb.backend.libusb0')

# usb.h

if sys.platform.find('bsd') != -1 or sys.platform.find('mac') != -1 or \
        sys.platform.find('darwin') != -1 or sys.platform.find('sunos5') != -1:
    _PATH_MAX = 1024
elif sys.platform == 'win32' or sys.platform == 'cygwin':
    _PATH_MAX = 511
else:
    _PATH_MAX = os.pathconf('.', 'PC_PATH_MAX')

# libusb-win32 makes all structures packed, while
# default libusb only does for some structures
# _PackPolicy defines the structure packing according
# to the platform.
class _PackPolicy(object):
    pass

if sys.platform == 'win32' or sys.platform == 'cygwin':
    _PackPolicy._pack_ = 1

# Data structures

class _usb_descriptor_header(Structure):
    _pack_ = 1
Example #54
0
LOG = getLogger(__name__)
PID = getpid()

if sys.platform.lower().find('darwin') != -1:
    def get_semaphore_name(resource_uri):
        """Return a safe semaphore name for a resource.

        :param basestring resource_uri: the URI of the resource.
        :return: safe semaphore name.
        :rtype: str
        """

        sem_name = md5(resource_uri).hexdigest()[:29]
        return sem_name
else:
    NAME_MAX_SEM = pathconf("/", 'PC_NAME_MAX') - 4 # according to man 7 sem_overview
    def get_semaphore_name(resource_uri):
        """Return a safe semaphore name for a resource.

        posix_ipc doesn't accept '/' inside the semaphore name but the name must
        begin with '/'.

        :param basestring resource_uri: the URI of the resource.
        :return: safe semaphore name.
        :rtype: str
        """

        sem_name = str('/' + resource_uri.replace('/', '-'))
        if len(sem_name) > NAME_MAX_SEM:
            sem_name = '/' + md5(resource_uri).hexdigest()
        return sem_name
Example #55
0
File: path.py Project: RichDijk/eXe
 def pathconf(self, name):
     """Wraps os.pathconf"""
     return os.pathconf(self, name)
Example #56
0
File: util.py Project: minrk/asv
from __future__ import (absolute_import, division, print_function,
                        unicode_literals)

import json
import math
import os
import select
import subprocess
import sys
import time

try:
    from select import PIPE_BUF
except ImportError:
    # PIPE_BUF is not available on Python 2.6
    PIPE_BUF = os.pathconf('.', os.pathconf_names['PC_PIPE_BUF'])

import six
from six.moves import xrange

from .console import log
from .extern import minify_json


def human_file_size(size):
    """
    Returns a human-friendly string representing a file size
    that is 2-4 characters long.

    For example, depending on the number of bytes given, can be one
    of::
Example #57
0
 def pathconf(self, name):
     """ .. seealso:: :func:`os.pathconf` """
     return os.pathconf(self, name)
Example #58
0
Public License for more details.

You should have received a copy of the GNU General Public License along
with this program. If not, see https://www.gnu.org/licenses/
"""

from __future__ import annotations

import os
from functools import cached_property

from core import file, typing as T
from core.utils import base64

_PrefixSuffixT = T.Tuple[T.Optional[T.Path], str]
_default_max_name_length: int = os.pathconf(".", "PC_NAME_MAX")


class VaultFileKey(os.PathLike):
    """ HGI vault file key properties """
    # NOTE This is implemented in a separate class to keep that part of
    # the logic outside VaultFile and to decouple it from the filesystem
    _delimiter: T.ClassVar[str] = "-"

    _prefix: T.Optional[T.Path]  # inode prefix path, without the LSB
    _suffix: str  # LSB and encoded basename suffix name

    def __init__(self,
                 path: T.Path,
                 inode: T.Optional[int] = None,
                 max_file_name_length: int = _default_max_name_length) -> None: