From f3f84b154441584750de7a2d89ecde2278430482 Mon Sep 17 00:00:00 2001 From: Alexander Neumann Date: Mon, 2 Nov 2015 18:51:45 +0100 Subject: [PATCH] Add ID handling for index --- repository/index.go | 36 +++++++++++++++++++++++++++++++++++- repository/index_test.go | 6 ++++++ repository/repository.go | 3 ++- 3 files changed, 43 insertions(+), 2 deletions(-) diff --git a/repository/index.go b/repository/index.go index d74131b84..e7df3168e 100644 --- a/repository/index.go +++ b/repository/index.go @@ -19,7 +19,8 @@ type Index struct { m sync.Mutex pack map[backend.ID]indexEntry - final bool // set to true for all indexes read from the backend ("finalized") + final bool // set to true for all indexes read from the backend ("finalized") + id backend.ID // set to the ID of the index when it's finalized supersedes backend.IDs created time.Time } @@ -395,6 +396,39 @@ func (idx *Index) Finalize(w io.Writer) error { return idx.encode(w) } +// ID returns the ID of the index, if available. If the index is not yet +// finalized, an error is returned. +func (idx *Index) ID() (backend.ID, error) { + idx.m.Lock() + defer idx.m.Unlock() + + if !idx.final { + return backend.ID{}, errors.New("index not finalized") + } + + return idx.id, nil +} + +// SetID sets the ID the index has been written to. This requires that +// Finalize() has been called before, otherwise an error is returned. +func (idx *Index) SetID(id backend.ID) error { + idx.m.Lock() + defer idx.m.Unlock() + + if !idx.final { + return errors.New("indexs is not final") + } + + if !idx.id.IsNull() { + return errors.New("ID already set") + } + + debug.Log("Index.SetID", "ID set to %v", id.Str()) + idx.id = id + + return nil +} + // Dump writes the pretty-printed JSON representation of the index to w. func (idx *Index) Dump(w io.Writer) error { debug.Log("Index.Dump", "dumping index") diff --git a/repository/index_test.go b/repository/index_test.go index 85674de77..d403ed8ad 100644 --- a/repository/index_test.go +++ b/repository/index_test.go @@ -117,6 +117,12 @@ func TestIndexSerialize(t *testing.T) { Assert(t, idx.Final(), "index not final after encoding") + id := randomID() + idx.SetID(id) + id2, err := idx.ID() + Assert(t, id2.Equal(id), + "wrong ID returned: want %v, got %v", id, id2) + idx3, err := repository.DecodeIndex(wr3) OK(t, err) Assert(t, idx3 != nil, diff --git a/repository/repository.go b/repository/repository.go index d119d51d5..436212bcc 100644 --- a/repository/repository.go +++ b/repository/repository.go @@ -526,7 +526,8 @@ func SaveIndex(repo *Repository, index *Index) (backend.ID, error) { } sid := blob.ID() - return sid, nil + err = index.SetID(sid) + return sid, err } // saveIndex saves all indexes in the backend.