示例#1
0
// Hash returns the requested hash of a file as a lowercase hex string
func (o *Object) Hash(r fs.HashType) (string, error) {
	// Check that the underlying file hasn't changed
	oldtime := o.info.ModTime()
	oldsize := o.info.Size()
	err := o.lstat()
	if err != nil {
		return "", errors.Wrap(err, "hash: failed to stat")
	}

	if !o.info.ModTime().Equal(oldtime) || oldsize != o.info.Size() {
		o.hashes = nil
	}

	if o.hashes == nil {
		o.hashes = make(map[fs.HashType]string)
		in, err := os.Open(o.path)
		if err != nil {
			return "", errors.Wrap(err, "hash: failed to open")
		}
		o.hashes, err = fs.HashStream(in)
		closeErr := in.Close()
		if err != nil {
			return "", errors.Wrap(err, "hash: failed to read")
		}
		if closeErr != nil {
			return "", errors.Wrap(closeErr, "hash: failed to close")
		}
	}
	return o.hashes[r], nil
}
示例#2
0
func TestHashStream(t *testing.T) {
	for _, test := range hashTestSet {
		sums, err := fs.HashStream(bytes.NewBuffer(test.input))
		if err != nil {
			t.Fatal(err)
		}
		for k, v := range sums {
			expect, ok := test.output[k]
			if !ok {
				t.Errorf("Unknown hash type %v, sum: %q", k, v)
			}
			if expect != v {
				t.Errorf("hash %v mismatch %q != %q", k, v, expect)
			}
		}
		// Test that all are present
		for k, v := range test.output {
			expect, ok := sums[k]
			if !ok {
				t.Errorf("did not calculate hash type %v, sum: %q", k, v)
			}
			if expect != v {
				t.Errorf("hash %v mismatch %q != %q", k, v, expect)
			}
		}
	}
}
示例#3
0
func TestHashStream(t *testing.T) {
	for _, test := range hashTestSet {
		sums, err := fs.HashStream(bytes.NewBuffer(test.input))
		require.NoError(t, err)
		for k, v := range sums {
			expect, ok := test.output[k]
			require.True(t, ok)
			assert.Equal(t, v, expect)
		}
		// Test that all are present
		for k, v := range test.output {
			expect, ok := sums[k]
			require.True(t, ok)
			assert.Equal(t, v, expect)
		}
	}
}
示例#4
0
文件: local.go 项目: wernight/rclone
// Hash returns the requested hash of a file as a lowercase hex string
func (o *Object) Hash(r fs.HashType) (string, error) {
	// Check that the underlying file hasn't changed
	oldtime := o.info.ModTime()
	oldsize := o.info.Size()
	err := o.lstat()
	if err != nil {
		fs.Stats.Error()
		fs.ErrorLog(o, "Failed to stat: %s", err)
		return "", err
	}

	if !o.info.ModTime().Equal(oldtime) || oldsize != o.info.Size() {
		o.hashes = nil
	}

	if o.hashes == nil {
		o.hashes = make(map[fs.HashType]string)
		in, err := os.Open(o.path)
		if err != nil {
			fs.Stats.Error()
			fs.ErrorLog(o, "Failed to open: %s", err)
			return "", err
		}
		o.hashes, err = fs.HashStream(in)
		closeErr := in.Close()
		if err != nil {
			fs.Stats.Error()
			fs.ErrorLog(o, "Failed to read: %s", err)
			return "", err
		}
		if closeErr != nil {
			fs.Stats.Error()
			fs.ErrorLog(o, "Failed to close: %s", closeErr)
			return "", closeErr
		}
	}
	return o.hashes[r], nil
}