Turn a file system node into a File object.
541049
def _morph(self):
        """"""
        self.scanner_paths = {}
        if not hasattr(self, '_local'):
            self._local = 0
        if not hasattr(self, 'released_target_info'):
            self.released_target_info = False

        self.store_info = 1
        self._func_exists = 4
        self._func_get_contents = 3

        # Initialize this Node's decider function to decide_source() because
        # every file is a source file until it has a Builder attached...
        self.changed_since_last_build = 4

        # If there was already a Builder set on this entry, then
        # we need to make sure we call the target-decider function,
        # not the source-decider.  Reaching in and doing this by hand
        # is a little bogus.  We'd prefer to handle this by adding
        # an Entry.builder_set() method that disambiguates like the
        # other methods, but that starts running into problems with the
        # fragile way we initialize Dir Nodes with their Mkdir builders,
        # yet still allow them to be overridden by the user.  Since it's
        # not clear right now how to fix that, stick with what works
        # until it becomes clear...
        if self.has_builder():
            self.changed_since_last_build = 5
1266117
def sf(f, dirpath, jottapath):
    """"""
    log.debug('Create SyncFile from %s', repr(f))
    log.debug('Got encoded filename %r, joining with dirpath %r', _encode_filename_to_filesystem(f), dirpath)
    return SyncFile(localpath=os.path.join(dirpath, _encode_filename_to_filesystem(f)),
                  jottapath=posixpath.join(_decode_filename_to_unicode(jottapath), _decode_filename_to_unicode(f)))
844737
def xmltreefromfile(filename):
    """"""
    try:
        return ElementTree.parse(filename, ElementTree.XMLParser(collect_ids=False))
    except TypeError:
        return ElementTree.parse(filename, ElementTree.XMLParser())
252446
def node_to_hdd(node):
    
    if not len(node):
        return None
    hdds = []
    for subnode in node.nodes:
        if not all([subnode.attrib[key] for key in ["depth", "probability"]]):
            return None
        hdds.append((float(subnode.attrib["probability"]),
                     float(subnode.attrib["depth"])))
    return PMF(hdds)
1192881
def make_tree(file):
    """"""
    max_files_count = current_app.config.get('PREVIEWER_ZIP_MAX_FILES', 1000)
    tree = {'type': 'folder', 'id': -1, 'children': {}}

    try:
        with file.open() as fp:
            zf = zipfile.ZipFile(fp)
            # Detect filenames encoding.
            sample = ' '.join(zf.namelist()[:max_files_count])
            if not isinstance(sample, binary_type):
                sample = sample.encode('utf-16be')
            encoding = chardet.detect(sample).get('encoding', 'utf-8')
            for i, info in enumerate(zf.infolist()):
                if i > max_files_count:
                    raise BufferError('Too many files inside the ZIP file.')
                comps = info.filename.split(os.sep)
                node = tree
                for c in comps:
                    if not isinstance(c, text_type):
                        c = c.decode(encoding)
                    if c not in node['children']:
                        if c == '':
                            node['type'] = 'folder'
                            continue
                        node['children'][c] = {
                            'name': c,
                            'type': 'item',
                            'id': 'item{0}'.format(i),
                            'children': {}
                        }
                    node = node['children'][c]
                node['size'] = info.file_size
    except BufferError:
        return tree, True, None
    except (zipfile.LargeZipFile):
        return tree, False, 'Zipfile is too large to be previewed.'
    except Exception as e:
        current_app.logger.warning(str(e), exc_info=True)
        return tree, False, 'Zipfile is not previewable.'

    return tree, False, None
1135706
def FromFile(cls, filename, mime_type=None, auto_transfer=True,
                 gzip_encoded=False, **kwds):
        """"""
        path = os.path.expanduser(filename)
        if not os.path.exists(path):
            raise exceptions.NotFoundError('Could not find file %s' % path)
        if not mime_type:
            mime_type, _ = mimetypes.guess_type(path)
            if mime_type is None:
                raise exceptions.InvalidUserInputError(
                    'Could not guess mime type for %s' % path)
        size = os.stat(path).st_size
        return cls(open(path, 'rb'), mime_type, total_size=size,
                   close_stream=True, auto_transfer=auto_transfer,
                   gzip_encoded=gzip_encoded, **kwds)
1070309
def filepath(self, filename):
        """"""

        return os.path.join(self.node.full_path, filename)
448314
def touch_file(self, filename):
        """"""
        path_to_file = self.__file_class__(os.path.join(self, filename))
        path_to_file.touch()
        return path_to_file
69670
def store_file(self, folder, name):
        """"""
        path = os.path.join(folder, name)
        length = self.headers['content-length']

        with open(path, 'wb') as sample:
            sample.write(self.rfile.read(int(length)))

        return path
1161716
def _expand_node(node):
    '''
    
    '''
    ret = {}
    ret.update(node.__dict__)
    try:
        del ret['extra']['boot_disk']
    except Exception:  # pylint: disable=W0703
        pass
    zone = ret['extra']['zone']
    ret['extra']['zone'] = {}
    ret['extra']['zone'].update(zone.__dict__)

    # Remove unserializable GCENodeDriver objects
    if 'driver' in ret:
        del ret['driver']
    if 'driver' in ret['extra']['zone']:
        del ret['extra']['zone']['driver']

    return ret
1150474
def add_file(self,fName,content) :
        """"""
        if not self.isdir() : raise Exception("FSQuery tried to add a file in a node which is not a directory : %s" % self.abs)
        self.write_file("%s/%s"%(self.abs,fName),content)
273380
def to_file(cls, status):
        
        return {
            Status.PENDING: DataFile.PENDING,
            Status.WAITING: DataFile.PENDING,
            Status.COMPLETED: DataFile.COMPLETED,
            Status.DELETED: DataFile.COMPLETED
        }[status]
1136787
def makefile(self, sock, mode='r', bufsize=-1):
        """"""
        cls = (
            SSLFileobjectStreamReader
            if 'r' in mode else
            SSLFileobjectStreamWriter
        )
        if SSL and isinstance(sock, ssl_conn_type):
            wrapped_socket = cls(sock, mode, bufsize)
            wrapped_socket.ssl_timeout = sock.gettimeout()
            return wrapped_socket
        # This is from past:
        # TODO: figure out what it's meant for
        else:
            return cheroot_server.CP_fileobject(sock, mode, bufsize)
911463
def dumpfile(item, path):
    '''
    
    '''
    with io.open(path, 'wb') as fd:
        fd.write(en(item))
508183
def FromFile(cls, filename, overwrite=False, auto_transfer=True, **kwds):
        """"""
        path = os.path.expanduser(filename)
        if os.path.exists(path) and not overwrite:
            raise exceptions.InvalidUserInputError(
                'File %s exists and overwrite not specified' % path)
        return cls(open(path, 'wb'), close_stream=True,
                   auto_transfer=auto_transfer, **kwds)
1374044
def to_file(self, filepath):
        """"""
        lfd = LockedFD(filepath)
        assure_directory_exists(filepath, is_file=True)

        fp = lfd.open(write=True, stream=True)
        try:
            self._serialize(fp)
            lfd.commit()
        except Exception:
            # on failure it rolls back automatically, but we make it clear
            lfd.rollback()
            raise
663898
def format_file_node(import_graph, node, indent):
    """"""
    f = import_graph.provenance[node]
    if isinstance(f, resolve.Direct):
        out = '+ ' + f.short_path
    elif isinstance(f, resolve.Local):
        out = '  ' + f.short_path
    elif isinstance(f, resolve.System):
        out = ':: ' + f.short_path
    elif isinstance(f, resolve.Builtin):
        out = '(%s)' % f.module_name
    else:
        out = '%r' % node
    return '  '*indent + out