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