示例#1
0
def get_attributes(path):
    '''
    Return a dictionary object with the Windows
    file attributes for a file.

    CLI Example:

    .. code-block:: bash

        salt '*' file.get_attributes c:\\temp\\a.txt
    '''
    err = ''
    if not os.path.exists(path):
        err += 'File not found\n'
    if err:
        return err

    # set up dictionary for attribute values
    attributes = {}

    # Get cumulative int value of attributes
    intAttributes = win32file.GetFileAttributes(path)

    # Assign individual attributes
    attributes['archive'] = (intAttributes & 32) == 32
    attributes['reparsePoint'] = (intAttributes & 1024) == 1024
    attributes['compressed'] = (intAttributes & 2048) == 2048
    attributes['directory'] = (intAttributes & 16) == 16
    attributes['encrypted'] = (intAttributes & 16384) == 16384
    attributes['hidden'] = (intAttributes & 2) == 2
    attributes['normal'] = (intAttributes & 128) == 128
    attributes['notIndexed'] = (intAttributes & 8192) == 8192
    attributes['offline'] = (intAttributes & 4096) == 4096
    attributes['readonly'] = (intAttributes & 1) == 1
    attributes['system'] = (intAttributes & 4) == 4
    attributes['temporary'] = (intAttributes & 256) == 256

    # check if it's a Mounted Volume
    attributes['mountedVolume'] = False
    if attributes['reparsePoint'] is True and attributes['directory'] is True:
        fileIterator = win32file.FindFilesIterator(path)
        findDataTuple = next(fileIterator)
        if findDataTuple[6] == 0xA0000003:
            attributes['mountedVolume'] = True
    # check if it's a soft (symbolic) link

    # Note:  os.path.islink() does not work in
    #   Python 2.7 for the Windows NTFS file system.
    #   The following code does, however, work (tested in Windows 8)

    attributes['symbolicLink'] = False
    if attributes['reparsePoint'] is True:
        fileIterator = win32file.FindFilesIterator(path)
        findDataTuple = next(fileIterator)
        if findDataTuple[6] == 0xA000000C:
            attributes['symbolicLink'] = True

    return attributes
示例#2
0
    def _deleteFolderWin32(self, full_path):
        """A function like shutil.rmtree using win32api.

    The win32file apis must be used for this task on win32 platform
    because the win32 shell libs cannot handle file paths > 256 chars long.

    Args:
      full_path: Absolute path of the folder to recursively delete.
    """
        unicode_path = '\\\\?\\%s' % full_path
        folder_iterator = win32file.FindFilesIterator(unicode_path + '\\*')

        FILE_ATTRIBUTE = 0
        FILE_NAME = 8
        FILE_ATTRIBUTE_DIRECTORY_VISTA = 8208
        for file_info in folder_iterator:
            if file_info[FILE_NAME] == '.' or file_info[FILE_NAME] == '..':
                continue
            if (file_info[FILE_ATTRIBUTE] == win32file.FILE_ATTRIBUTE_DIRECTORY
                    or file_info[FILE_ATTRIBUTE]
                    == FILE_ATTRIBUTE_DIRECTORY_VISTA):
                self._deleteFolderWin32('%s\\%s' %
                                        (full_path, file_info[FILE_NAME]))
                continue
            else:
                win32file.DeleteFileW('%s\\%s' %
                                      (unicode_path, file_info[FILE_NAME]))
        del folder_iterator
        win32file.RemoveDirectory(unicode_path)
示例#3
0
def canonicalize_tail_win32(path: str) -> str:
    """Efficient canonicalize tail for windows."""

    p = pathlib.Path(path)
    par = p.parent

    try:
        # Equivalent to FindFirstFileW, the moral equivalent of stat().
        # The file name in the returned struct will have "true" case.
        itr = win32file.FindFilesIterator(path)
        info = next(itr)
        canon_name: str = info[8]
        p = par / canon_name
    except StopIteration:
        # Couldn't find the path component.
        pass
    except Exception as e:
        # something else went wrong, somehow, log exception and swallow
        # likely this is a permission denied
        log.error("Unexpected exception in FindFirstFile: %s", e)

    ret = str(p)

    lname = get_long_path_name(ret)

    ret = lname or ret

    return ret
 def testIter(self):
     dir = os.path.join(os.getcwd(), "*")
     files = win32file.FindFilesW(dir)
     set1 = set()
     set1.update(files)
     set2 = set()
     for file in win32file.FindFilesIterator(dir):
         set2.add(file)
     assert len(set2) > 5, "This directory has less than 5 files!?"
     self.failUnlessEqual(set1, set2)
示例#5
0
def IteratePaths(path, append_eol=False):
    """FindFirstFile 系を使って、パス名をイテレートする。append_eol=True にすると、最後に "eol" という1行をリストに入れるので、検索の終了判定などに使える。"""
    for elem in win32file.FindFilesIterator(path + "\\*"):
        if elem[8] == "." or elem[8] == "..": continue
        if elem[0] & win32file.FILE_ATTRIBUTE_DIRECTORY:
            yield from IteratePaths(os.path.join(path, elem[8]))
        #end ディレクトリ
        yield os.path.join(path, elem[8])
    #EOL挿入
    if append_eol: yield "eol"
示例#6
0
 def testEmptyDir(self):
     test_path = os.path.join(win32api.GetTempPath(), "win32file_test_directory")
     try:
         # Note: previously used shutil.rmtree, but when looking for
         # reference count leaks, that function showed leaks!  os.rmdir
         # doesn't have that problem.
         os.rmdir(test_path)
     except os.error:
         pass
     os.mkdir(test_path)
     try:
         num = 0
         for i in win32file.FindFilesIterator(os.path.join(test_path, "*")):
             num += 1
         # Expecting "." and ".." only
         self.failUnlessEqual(2, num)
     finally:
         os.rmdir(test_path)
示例#7
0
def IteratePaths(path, append_eol=False):
    """FindFirstFile 系を使って、パス名をイテレートする。append_eol=True にすると、最後に "eol" という1行をリストに入れるので、検索の終了判定などに使える。"""
    try:
        for elem in win32file.FindFilesIterator(os.path.join(path, "*")):
            if elem[8] == "." or elem[8] == "..":
                continue
            if elem[0] & win32file.FILE_ATTRIBUTE_DIRECTORY:
                yield from IteratePaths(os.path.join(path, elem[8]))
            # end ディレクトリ
            yield os.path.join(path, elem[8])
        # end iterate
    except pywintypes.error as e:
        log.error(
            "Access denied while searching paths at %s (%s)." %
            (path, e))
    # end except
    # EOL挿入
    if append_eol:
        yield "eol"
 def testEmptySpec(self):
     spec = os.path.join(os.getcwd(), "*.foo_bar")
     num = 0
     for i in win32file.FindFilesIterator(spec):
         num += 1
     self.failUnlessEqual(0, num)
示例#9
0
文件: path.py 项目: thuvu33/test-1
 def _fileSystemBaseName(path, stem, leaf):
   findData = win32file.FindFilesIterator(path).next()
   return str(findData[8])
示例#10
0
 def testEmptySpec(self):
     spec = os.path.join(os.getcwd(), "*.foo_bar")
     num = 0
     for i in win32file.FindFilesIterator(spec):
         num += 1
     assert 0 == num
示例#11
0
 def testBadDir(self):
     dir = os.path.join(os.getcwd(), "a dir that doesnt exist", "*")
     with pytest.raises(win32file.error):
         win32file.FindFilesIterator(dir)