write a cache object to filename as a plain text pfn file
167384
def topfnfile(self, fileobj):
		
		for entry in self:
			print >>fileobj, entry.path
		fileobj.close()
348101
def file_hash(load, fnd):
    '''
    
    '''
    if 'env' in load:
        # "env" is not supported; Use "saltenv".
        load.pop('env')

    if not all(x in load for x in ('path', 'saltenv')):
        return ''
    saltenv = load['saltenv']
    if saltenv == 'base':
        saltenv = 'trunk'
    ret = {}
    relpath = fnd['rel']
    path = fnd['path']

    # If the file doesn't exist, we can't get a hash
    if not path or not os.path.isfile(path):
        return ret

    # Set the hash_type as it is determined by config
    ret['hash_type'] = __opts__['hash_type']

    # Check if the hash is cached
    # Cache file's contents should be "hash:mtime"
    cache_path = os.path.join(__opts__['cachedir'],
                              'svnfs',
                              'hash',
                              saltenv,
                              '{0}.hash.{1}'.format(relpath,
                                                    __opts__['hash_type']))
    # If we have a cache, serve that if the mtime hasn't changed
    if os.path.exists(cache_path):
        with salt.utils.files.fopen(cache_path, 'rb') as fp_:
            hsum, mtime = fp_.read().split(':')
            if os.path.getmtime(path) == mtime:
                # check if mtime changed
                ret['hsum'] = hsum
                return ret

    # if we don't have a cache entry-- lets make one
    ret['hsum'] = salt.utils.hashutils.get_hash(path, __opts__['hash_type'])
    cache_dir = os.path.dirname(cache_path)
    # make cache directory if it doesn't exist
    if not os.path.exists(cache_dir):
        os.makedirs(cache_dir)
    # save the cache object "hash:mtime"
    with salt.utils.files.fopen(cache_path, 'w') as fp_:
        fp_.write('{0}:{1}'.format(ret['hsum'], os.path.getmtime(path)))

    return ret
826837
def write
      @cache["version"] = VERSION
      File.open(CACHE_FILE, "w") do |fh|
        fh.puts(JSON.dump(@cache))
      end
    end
69668
private void writeToDiskCache(
      final CacheKey key,
      final EncodedImage encodedImage) {
    FLog.v(TAG, "About to write to disk-cache for key %s", key.getUriString());
    try {
      mFileCache.insert(
          key, new WriterCallback() {
            @Override
            public void write(OutputStream os) throws IOException {
              mPooledByteStreams.copy(encodedImage.getInputStream(), os);
            }
          }
      );
      FLog.v(TAG, "Successful disk-cache write for key %s", key.getUriString());
    } catch (IOException ioe) {
      // Log failure
      // TODO: 3697790
      FLog.w(TAG, ioe, "Failed to write to disk-cache for key %s", key.getUriString());
    }
  }
883911
def tryload_cache(dpath, fname, cfgstr, verbose=None):
    
    try:
        return load_cache(dpath, fname, cfgstr, verbose=verbose)
    except IOError:
        return None
139780
def write(self):
        
        io.debug("Storing cache '{0}'".format(self.path))
        with open(self.path, "w") as file:
            json.dump(self._data, file, sort_keys=True, indent=2,
                      separators=(',', ': '))
703668
def file_hash(load, fnd):
    '''
    
    '''
    if not all(x in load for x in ('path', 'saltenv')):
        return '', None
    ret = {'hash_type': __opts__['hash_type']}
    relpath = fnd['rel']
    path = fnd['path']
    hash_cachedir = os.path.join(__opts__['cachedir'], 'azurefs', 'hashes')
    hashdest = salt.utils.path.join(hash_cachedir,
                                    load['saltenv'],
                                    '{0}.hash.{1}'.format(relpath,
                                                          __opts__['hash_type']))
    if not os.path.isfile(hashdest):
        if not os.path.exists(os.path.dirname(hashdest)):
            os.makedirs(os.path.dirname(hashdest))
        ret['hsum'] = salt.utils.hashutils.get_hash(path, __opts__['hash_type'])
        with salt.utils.files.fopen(hashdest, 'w+') as fp_:
            fp_.write(salt.utils.stringutils.to_str(ret['hsum']))
        return ret
    else:
        with salt.utils.files.fopen(hashdest, 'rb') as fp_:
            ret['hsum'] = salt.utils.stringutils.to_unicode(fp_.read())
        return ret
180324
def file_hash(load, fnd):
    '''
    
    '''
    path = fnd['path']
    ret = {}

    if 'env' in load:
        # "env" is not supported; Use "saltenv".
        load.pop('env')

    if load['saltenv'] not in envs():
        return {}

    # if the file doesn't exist, we can't get a hash
    if not path or not os.path.isfile(path):
        return ret

    # set the hash_type as it is determined by config-- so mechanism won't change that
    ret['hash_type'] = __opts__['hash_type']

    # check if the hash is cached
    # cache file's contents should be "hash:mtime"
    cache_path = os.path.join(
        __opts__['cachedir'],
        'minionfs',
        'hash',
        load['saltenv'],
        '{0}.hash.{1}'.format(fnd['rel'], __opts__['hash_type'])
    )
    # if we have a cache, serve that if the mtime hasn't changed
    if os.path.exists(cache_path):
        try:
            with salt.utils.files.fopen(cache_path, 'rb') as fp_:
                try:
                    hsum, mtime = salt.utils.stringutils.to_unicode(fp_.read()).split(':')
                except ValueError:
                    log.debug(
                        'Fileserver attempted to read incomplete cache file. '
                        'Retrying.'
                    )
                    file_hash(load, fnd)
                    return ret
                if os.path.getmtime(path) == mtime:
                    # check if mtime changed
                    ret['hsum'] = hsum
                    return ret
        # Can't use Python select() because we need Windows support
        except os.error:
            log.debug(
                'Fileserver encountered lock when reading cache file. '
                'Retrying.'
            )
            file_hash(load, fnd)
            return ret

    # if we don't have a cache entry-- lets make one
    ret['hsum'] = salt.utils.hashutils.get_hash(path, __opts__['hash_type'])
    cache_dir = os.path.dirname(cache_path)
    # make cache directory if it doesn't exist
    if not os.path.exists(cache_dir):
        os.makedirs(cache_dir)
    # save the cache object "hash:mtime"
    cache_object = '{0}:{1}'.format(ret['hsum'], os.path.getmtime(path))
    with salt.utils.files.flopen(cache_path, 'w') as fp_:
        fp_.write(cache_object)
    return ret
785235
function cacheTemplate(fn, options) {
  if (options.cache && options.filename) {
    cache[options.filename] = fn;
  }
}
1306550
def cache_file(self, path, saltenv='base', cachedir=None, source_hash=None):
        '''
        
        '''
        return self.get_url(
            path, '', True, saltenv, cachedir=cachedir, source_hash=source_hash)
572642
def update_cache(filename, opts=default_opts, module_globals=None):
    """"""

    if not filename: return None

    orig_filename = filename
    filename = pyc2py(filename)
    if filename in file_cache: del file_cache[filename]
    path = os.path.abspath(filename)
    stat = None
    if get_option('use_linecache_lines', opts):
        fname_list = [filename]
        mapped_path = file2file_remap.get(path)
        if mapped_path:
            fname_list.append(mapped_path)
            for filename in fname_list:
                try:
                    stat = os.stat(filename)
                    plain_lines = linecache.getlines(filename)
                    trailing_nl = has_trailing_nl(plain_lines[-1])
                    lines = {
                        'plain'   : plain_lines,
                        }
                    file_cache[filename] = LineCacheInfo(stat, None, lines,
                                                         path, None)
                except:
                    pass
                pass
            if orig_filename != filename:
                file2file_remap[orig_filename] = filename
                file2file_remap[os.path.abspath(orig_filename)] = filename
                pass
            file2file_remap[path] = filename
            return filename
        pass
    pass

    if os.path.exists(path):
        stat = os.stat(path)
    elif module_globals and '__loader__' in module_globals:
        name = module_globals.get('__name__')
        loader = module_globals['__loader__']
        get_source = getattr(loader, 'get_source', None)
        if name and get_source:
            try:
                data = get_source(name)
            except (ImportError, IOError):
                pass
            else:
                if data is None:
                    # No luck, the PEP302 loader cannot find the source
                    # for this module.
                    return None
                # FIXME: DRY with code below
                lines = {'plain' : data.splitlines()}
                raw_string        = ''.join(lines['plain'])
                trailing_nl       = has_trailing_nl(raw_string)
                if 'style' in opts:
                    key = opts['style']
                    highlight_opts = {'style': key}
                else:
                    key = 'terminal'
                    highlight_opts = {}

                lines[key] = highlight_array(raw_string.split('\n'),
                                    trailing_nl, **highlight_opts)
                file_cache[filename] = \
                  LineCacheInfo(None, None, lines, filename, None)
                file2file_remap[path] = filename
                return True
            pass
        pass
    if not os.path.isabs(filename):
        # Try looking through the module search path, which is only useful
        # when handling a relative filename.
        stat = None
        for dirname in sys.path:
            path = os.path.join(dirname, filename)
            if os.path.exists(path):
                stat = os.stat(path)
                break
            pass
        if not stat: return False
        pass

    try:
        mode = 'r' if PYTHON3 else 'rU'
        with open(path, mode) as fp:
                lines = {'plain' : fp.readlines()}
                eols = fp.newlines
    except:
        return None

    # FIXME: DRY with code above
    raw_string        = ''.join(lines['plain'])
    trailing_nl       = has_trailing_nl(raw_string)
    if 'style' in opts:
        key = opts['style'] or 'default'
        highlight_opts = {'style': key}
    else:
        key = 'terminal'
        highlight_opts = {}

    lines[key] = highlight_array(raw_string.split('\n'),
                                 trailing_nl, **highlight_opts)
    if orig_filename != filename:
        file2file_remap[orig_filename] = filename
        file2file_remap[os.path.abspath(orig_filename)] = filename
        pass
    pass

    file_cache[filename] = LineCacheInfo(stat, None, lines, path, None, eols)
    file2file_remap[path] = filename
    return True
174346
function (data, fragmentKey, cachePath, callback) {
    debug('  write content in file system');
    var basePath =  path.dirname(fragmentKey);
    if (basePath){
      mkdirp.sync(cachePath + '/' + basePath);
    }
    fs.writeFile(cachePath + '/' + fragmentKey, data, function (err) {
      if (err) {
        callback(err);
      } else {
        callback(null, data);
      }
    });
  }
97115
def cache_items(values):
    """"""
    import os
    config_path = os.path.expanduser('~/.config/blockade')
    file_path = os.path.join(config_path, 'cache.txt')
    if not os.path.isfile(file_path):
        file(file_path, 'w').close()
    written = [x.strip() for x in open(file_path, 'r').readlines()]
    handle = open(file_path, 'a')
    for item in values:
        # Because of the option to submit in clear or hashed, we need to make
        # sure we're not re-hashing before adding.
        if is_hashed(item):
            hashed = item
        else:
            hashed = hash_values(item)

        if hashed in written:
            continue
        handle.write(hashed + "\n")
    handle.close()
    return True
686048
def file_hash(load, fnd):
    '''
    
    '''
    if 'env' in load:
        # "env" is not supported; Use "saltenv".
        load.pop('env')

    if not all(x in load for x in ('path', 'saltenv')):
        return ''
    ret = {'hash_type': __opts__['hash_type']}
    relpath = fnd['rel']
    path = fnd['path']
    hashdest = os.path.join(__opts__['cachedir'],
                            'hgfs/hash',
                            load['saltenv'],
                            '{0}.hash.{1}'.format(relpath,
                                                  __opts__['hash_type']))
    if not os.path.isfile(hashdest):
        ret['hsum'] = salt.utils.hashutils.get_hash(path, __opts__['hash_type'])
        with salt.utils.files.fopen(hashdest, 'w+') as fp_:
            fp_.write(ret['hsum'])
        return ret
    else:
        with salt.utils.files.fopen(hashdest, 'rb') as fp_:
            ret['hsum'] = salt.utils.stringutils.to_unicode(fp_.read())
        return ret
1068360
def writeFrame(self, data):
    """"""

    cachename = CACHE_FILE_NAME + str(self.sessionId) + CACHE_FILE_EXT

    try:
      file = open(cachename, "wb")
    except:
      print "file open error"

    try:
      file.write(data)
    except:
      print "file write error"

    file.close()

    return cachename
325476
def _write_cache(self, lines, append=False):
        """"""
        mode = 'at' if append else 'wt'
        with open(self.filepath, mode, encoding='utf8') as fh:
            fh.writelines(line + '\n' for line in lines)
216335
def filename_to_url(filename: str, cache_dir: str = None) -> Tuple[str, str]:
    
    if cache_dir is None:
        cache_dir = CACHE_DIRECTORY

    cache_path = os.path.join(cache_dir, filename)
    if not os.path.exists(cache_path):
        raise FileNotFoundError("file {} not found".format(cache_path))

    meta_path = cache_path + '.json'
    if not os.path.exists(meta_path):
        raise FileNotFoundError("file {} not found".format(meta_path))

    with open(meta_path) as meta_file:
        metadata = json.load(meta_file)
    url = metadata['url']
    etag = metadata['etag']

    return url, etag