2018-08-27 15:09:24 +02:00
|
|
|
package pruning
|
|
|
|
|
|
|
|
import (
|
|
|
|
"sort"
|
2020-08-29 17:44:17 +02:00
|
|
|
"strings"
|
2019-03-22 19:41:12 +01:00
|
|
|
|
|
|
|
"github.com/pkg/errors"
|
2018-08-27 15:09:24 +02:00
|
|
|
)
|
|
|
|
|
|
|
|
type KeepLastN struct {
|
|
|
|
n int
|
|
|
|
}
|
|
|
|
|
|
|
|
func NewKeepLastN(n int) (*KeepLastN, error) {
|
|
|
|
if n <= 0 {
|
|
|
|
return nil, errors.Errorf("must specify positive number as 'keep last count', got %d", n)
|
|
|
|
}
|
|
|
|
return &KeepLastN{n}, nil
|
|
|
|
}
|
|
|
|
|
2018-08-30 11:44:43 +02:00
|
|
|
func (k KeepLastN) KeepRule(snaps []Snapshot) (destroyList []Snapshot) {
|
2018-08-27 15:09:24 +02:00
|
|
|
|
|
|
|
if k.n > len(snaps) {
|
2018-08-30 11:44:43 +02:00
|
|
|
return []Snapshot{}
|
2018-08-27 15:09:24 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
res := shallowCopySnapList(snaps)
|
|
|
|
|
|
|
|
sort.Slice(res, func(i, j int) bool {
|
2020-08-29 17:44:17 +02:00
|
|
|
// by date (youngest first)
|
|
|
|
id, jd := res[i].Date(), res[j].Date()
|
|
|
|
if !id.Equal(jd) {
|
|
|
|
return id.After(jd)
|
|
|
|
}
|
|
|
|
// then lexicographically descending (e.g. b, a)
|
|
|
|
return strings.Compare(res[i].Name(), res[j].Name()) == 1
|
2018-08-27 15:09:24 +02:00
|
|
|
})
|
|
|
|
|
2018-08-30 11:44:43 +02:00
|
|
|
return res[k.n:]
|
2018-08-27 15:09:24 +02:00
|
|
|
}
|