2016-08-31 20:39:36 +00:00
|
|
|
package restic
|
|
|
|
|
2017-06-03 15:39:57 +00:00
|
|
|
import (
|
|
|
|
"context"
|
2020-11-10 21:43:18 +00:00
|
|
|
"fmt"
|
2017-06-03 15:39:57 +00:00
|
|
|
)
|
2016-08-31 20:39:36 +00:00
|
|
|
|
2020-11-10 21:43:18 +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)
|
2020-11-10 21:43:18 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
// A NoIDByPrefixError is returned by Find() when no ID for a given prefix
|
2016-08-31 20:39:36 +00:00
|
|
|
// could be found.
|
2020-11-10 21:43:18 +00:00
|
|
|
type NoIDByPrefixError struct{ prefix string }
|
2016-08-31 20:39:36 +00:00
|
|
|
|
2020-11-10 21:43:18 +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.
|
2023-10-01 11:05:56 +00:00
|
|
|
func Find(ctx context.Context, be Lister, t FileType, prefix string) (ID, error) {
|
2022-10-15 14:00:05 +00:00
|
|
|
match := ID{}
|
2016-08-31 20:39:36 +00:00
|
|
|
|
2020-04-10 09:31:32 +00:00
|
|
|
ctx, cancel := context.WithCancel(ctx)
|
2018-01-20 12:43:07 +00:00
|
|
|
defer cancel()
|
|
|
|
|
2023-10-01 11:05:56 +00:00
|
|
|
err := be.List(ctx, t, func(id ID, size int64) error {
|
|
|
|
name := id.String()
|
|
|
|
if len(name) >= len(prefix) && prefix == name[:len(prefix)] {
|
2022-10-15 14:00:05 +00:00
|
|
|
if match.IsNull() {
|
|
|
|
match = id
|
2016-08-31 20:39:36 +00:00
|
|
|
} else {
|
2020-11-10 21:43:18 +00:00
|
|
|
return &MultipleIDMatchesError{prefix}
|
2016-08-31 20:39:36 +00:00
|
|
|
}
|
|
|
|
}
|
2018-01-20 12:43:07 +00:00
|
|
|
|
|
|
|
return nil
|
|
|
|
})
|
|
|
|
|
|
|
|
if err != nil {
|
2022-10-15 14:00:05 +00:00
|
|
|
return ID{}, err
|
2016-08-31 20:39:36 +00:00
|
|
|
}
|
|
|
|
|
2022-10-15 14:00:05 +00:00
|
|
|
if !match.IsNull() {
|
2016-08-31 20:39:36 +00:00
|
|
|
return match, nil
|
|
|
|
}
|
|
|
|
|
2022-10-15 14:00:05 +00:00
|
|
|
return ID{}, &NoIDByPrefixError{prefix}
|
2016-08-31 20:39:36 +00:00
|
|
|
}
|