2
2
mirror of https://github.com/octoleo/restic.git synced 2024-11-22 21:05:10 +00:00
restic/internal/restic/backend_find.go

56 lines
1.3 KiB
Go
Raw Normal View History

2016-08-31 20:39:36 +00:00
package restic
2017-06-03 15:39:57 +00:00
import (
"context"
"fmt"
2017-06-03 15:39:57 +00:00
)
2016-08-31 20:39:36 +00:00
// A MultipleIDMatchesError is returned by Find() when multiple IDs with a
// given prefix are found.
type MultipleIDMatchesError struct{ prefix string }
func (e *MultipleIDMatchesError) Error() string {
2021-08-25 14:11:28 +00:00
return fmt.Sprintf("multiple IDs with prefix %q found", e.prefix)
}
// A NoIDByPrefixError is returned by Find() when no ID for a given prefix
2016-08-31 20:39:36 +00:00
// could be found.
type NoIDByPrefixError struct{ prefix string }
2016-08-31 20:39:36 +00:00
func (e *NoIDByPrefixError) Error() string {
return fmt.Sprintf("no matching ID found for prefix %q", e.prefix)
}
2016-08-31 20:39:36 +00:00
// Find loads the list of all files of type t and searches for names which
// start with prefix. If none is found, nil and ErrNoIDPrefixFound is returned.
// If more than one is found, nil and ErrMultipleIDMatches is returned.
func Find(ctx context.Context, be Lister, t FileType, prefix string) (ID, error) {
match := ID{}
2016-08-31 20:39:36 +00:00
ctx, cancel := context.WithCancel(ctx)
defer cancel()
err := be.List(ctx, t, func(id ID, size int64) error {
name := id.String()
if len(name) >= len(prefix) && prefix == name[:len(prefix)] {
if match.IsNull() {
match = id
2016-08-31 20:39:36 +00:00
} else {
return &MultipleIDMatchesError{prefix}
2016-08-31 20:39:36 +00:00
}
}
return nil
})
if err != nil {
return ID{}, err
2016-08-31 20:39:36 +00:00
}
if !match.IsNull() {
2016-08-31 20:39:36 +00:00
return match, nil
}
return ID{}, &NoIDByPrefixError{prefix}
2016-08-31 20:39:36 +00:00
}