Refactor cleanup deletion files method

This commit is contained in:
Stefan Martinov 2017-11-01 13:11:45 +01:00
parent 91032a037d
commit 663e50fdf6
3 changed files with 41 additions and 12 deletions

View File

@ -1,13 +1,13 @@
package repo
import (
"fmt"
"io/ioutil"
"os"
"path"
"sort"
"strings"
"time"
"github.com/pkg/errors"
)
const historyRepoJSONPrefix = "contentserver-repo-"
@ -55,21 +55,37 @@ func (h *history) getHistory() (files []string, err error) {
}
func (h *history) cleanup() error {
files, err := h.getHistory()
files, err := h.getFilesForCleanup(maxHistoryVersions)
if err != nil {
return err
}
if len(files) > maxHistoryVersions {
for i := maxHistoryVersions; i < len(files); i++ {
err := os.Remove(files[i])
if err != nil {
return fmt.Errorf("could not remove file %q got %q", files[i], err)
}
for _, f := range files {
err := os.Remove(f)
if err != nil {
return errors.Wrapf(err, "could not remove file %q", f)
}
}
return nil
}
func (h *history) getFilesForCleanup(historyVersions int) (files []string, err error) {
contentFiles, err := h.getHistory()
if err != nil {
return nil, errors.Wrap(err, "could not generate file cleanup list")
}
if len(contentFiles) > historyVersions {
for i := historyVersions; i < len(contentFiles); i++ {
// ignore current repository file to fall back on
if contentFiles[i] == h.getCurrentFilename() {
continue
}
files = append(files, contentFiles[i])
}
}
return files, nil
}
func (h *history) getCurrentFilename() string {
return path.Join(h.varDir, historyRepoJSONPrefix+"current"+historyRepoJSONSuffix)
}

View File

@ -54,8 +54,21 @@ func TestHistoryOrder(t *testing.T) {
files, err := h.getHistory()
assert.NoError(t, err)
assert.Len(t, files, 3)
assert.Equal(t, "testdata/order/contentserver-repo-2017-10-23.json", files[0])
assert.Equal(t, "testdata/order/contentserver-repo-2017-10-22.json", files[1])
assert.Equal(t, "testdata/order/contentserver-repo-2017-10-21.json", files[2])
assert.Len(t, files, 4)
assert.Equal(t, "testdata/order/contentserver-repo-current.json", files[0])
assert.Equal(t, "testdata/order/contentserver-repo-2017-10-23.json", files[1])
assert.Equal(t, "testdata/order/contentserver-repo-2017-10-22.json", files[2])
assert.Equal(t, "testdata/order/contentserver-repo-2017-10-21.json", files[3])
}
func TestGetFilesForCleanup(t *testing.T) {
h := testHistory()
h.varDir = "testdata/order"
files, err := h.getFilesForCleanup(2)
assert.NoError(t,err)
assert.Len(t, files, 2)
assert.Equal(t, "testdata/order/contentserver-repo-2017-10-22.json", files[0])
assert.Equal(t, "testdata/order/contentserver-repo-2017-10-21.json", files[1])
}

View File