Return a file hash, the hash type is set in the master config file
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
279476
def generate_hash(filepath):
    """"""
    fr = FileReader(filepath)
    data = fr.read_bin()
    return _calculate_sha256(data)
104162
def hash(self):
        '''
        
        '''
        hashed = super(Compare, self).hash()
        return khash(hashed, self._comp_value, self._comp_type)
461377
def update_hash(src_file):
    
    hash_file = local.path(src_file) + ".hash"
    new_hash = 0
    with open(hash_file, 'w') as h_file:
        new_hash = get_hash_of_dirs(src_file)
        h_file.write(str(new_hash))
    return new_hash
233384
def get_hash_for_filename(filename, hashfile_path):
    """"""
    filehash = ''
    with open(hashfile_path, 'r') as stream:
        for _cnt, line in enumerate(stream):
            if line.rstrip().endswith(filename):
                filehash = re.match(r'^[A-Za-z0-9]*', line).group(0)
                break
    if filehash:
        return filehash
    raise AttributeError("Filename %s not found in hash file" % filename)
1349155
def get(type, hash)
      dir = directory(type, hash)
      return unless dir
      dir.files.get(key_component(type, hash))
    end
1253007
def file_md5(self, file_name):
        """"""
        with open(file_name, "rb") as f:
            file_contents = f.read()
            file_hash = hashlib.md5(file_contents).hexdigest()
        return file_hash
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
1038646
def __hash_and_stat_file(self, path, saltenv='base'):
        '''
        
        '''
        try:
            path = self._check_proto(path)
        except MinionError as err:
            if not os.path.isfile(path):
                log.warning(
                    'specified file %s is not present to generate hash: %s',
                    path, err
                )
                return {}, None
            else:
                ret = {}
                hash_type = self.opts.get('hash_type', 'md5')
                ret['hsum'] = salt.utils.hashutils.get_hash(path, form=hash_type)
                ret['hash_type'] = hash_type
                return ret
        load = {'path': path,
                'saltenv': saltenv,
                'cmd': '_file_hash'}
        return self.channel.send(load)
1331887
def get_file_hash(storage, path):
    
    contents = storage.open(path).read()
    file_hash = hashlib.md5(contents).hexdigest()

    # Check if content should be gzipped and hash gzipped content
    content_type = mimetypes.guess_type(path)[0] or 'application/octet-stream'
    if settings.is_gzipped and content_type in settings.gzip_content_types:
        cache_key = get_cache_key('gzip_hash_%s' % file_hash)
        file_hash = cache.get(cache_key, False)
        if file_hash is False:
            buffer = BytesIO()
            zf = gzip.GzipFile(
                mode='wb', compresslevel=6, fileobj=buffer, mtime=0.0)
            zf.write(force_bytes(contents))
            zf.close()
            file_hash = hashlib.md5(buffer.getvalue()).hexdigest()
            cache.set(cache_key, file_hash)

    return '"%s"' % file_hash
691504
def to_output_hash
      HASH_SCHEMA.schema(
        map { |attr| [attr.key, attr.to_read_type] }.to_h
      )
    end
1052305
def hash(self):
        """"""
        if self._hash is None:
            tohash = [self.path.name]
            # Hash a maximum of ~1MB of the hdf5 file
            tohash.append(hashfile(self.path, blocksize=65536, count=20))
            self._hash = hashobj(tohash)
        return self._hash
483677
def hash_file(path, digest=None):
  
  digest = digest or hashlib.sha1()
  with open(path, 'rb') as fd:
    s = fd.read(8192)
    while s:
      digest.update(s)
      s = fd.read(8192)
  return digest.hexdigest() if PY3 else digest.hexdigest().decode('utf-8')
463044
def set_hash_key(self, file):
        """"""
        filehasher = hashlib.md5()
        while True:
            data = file.read(8192)
            if not data:
                break
            filehasher.update(data)
        file.seek(0)
        self.hash_key = filehasher.hexdigest()
1276974
def read(key_hash)
      path = key_path(key_hash)
      Marshal.load(File.open(path)) if File.exist?(path)
    end
444402
def hash_from_file_content(string)
      hash = {}
      string.split("\n").each do |line|
        uncommented_line = strip_comment(line)
        if include = extract_include(uncommented_line)
          @includes.push normalized_xcconfig_path(include)
        else
          key, value = extract_key_value(uncommented_line)
          next unless key
          value.gsub!(INHERITED_REGEXP) { |m| hash.fetch(key, m) }
          hash[key] = value
        end
      end
      hash
    end
872637
def hash(self, index_func=os.path.getmtime):
        
        # TODO alternative to filehash => mtime as a faster alternative
        shadir = hashlib.sha256()
        for f in self.files():
            try:
                shadir.update(str(index_func(os.path.join(self.path, f))))
            except (IOError, OSError):
                pass
        return shadir.hexdigest()