diff --git a/datastore/bolt/token.go b/datastore/bolt/token.go index a060b53ea..3bf797a1c 100644 --- a/datastore/bolt/token.go +++ b/datastore/bolt/token.go @@ -1,8 +1,6 @@ package bolt import ( - "bytes" - "github.com/boltdb/bolt" "github.com/drone/drone/common" ) @@ -24,19 +22,10 @@ func (db *DB) GetToken(user, label string) (*common.Token, error) { func (db *DB) InsertToken(token *common.Token) error { key := []byte(token.Login + "/" + token.Label) return db.Update(func(t *bolt.Tx) error { - // gets an index - var idx [][]byte - err := get(t, bucketUserTokens, []byte(token.Login), &idx) - if err != nil && err != ErrKeyNotFound { - return err - } - // pushes to the index - idx = append(idx, key) - err = update(t, bucketUserTokens, []byte(token.Login), &idx) + err := push(t, bucketUserTokens, []byte(token.Login), key) if err != nil { return err } - return insert(t, bucketTokens, key, token) }) } @@ -45,20 +34,7 @@ func (db *DB) InsertToken(token *common.Token) error { func (db *DB) DeleteToken(token *common.Token) error { key := []byte(token.Login + "/" + token.Label) return db.Update(func(t *bolt.Tx) error { - // gets an index - var idx [][]byte - err := get(t, bucketUserTokens, []byte(token.Login), &idx) - if err != nil && err != ErrKeyNotFound { - return err - } - // pushes to the index - for i, val := range idx { - if bytes.Equal(val, key) { - idx = idx[:i+copy(idx[i:], idx[i+1:])] - break - } - } - err = update(t, bucketUserTokens, []byte(token.Login), &idx) + err := splice(t, bucketUserTokens, []byte(token.Login), key) if err != nil { return err } diff --git a/datastore/bolt/util.go b/datastore/bolt/util.go index d373bbfa5..68d468350 100644 --- a/datastore/bolt/util.go +++ b/datastore/bolt/util.go @@ -1,6 +1,8 @@ package bolt import ( + "bytes" + "github.com/boltdb/bolt" "github.com/youtube/vitess/go/bson" ) @@ -55,3 +57,28 @@ func insert(t *bolt.Tx, bucket, key []byte, v interface{}) error { func delete(t *bolt.Tx, bucket, key []byte) error { return t.Bucket(bucket).Delete(key) } + +func push(t *bolt.Tx, bucket, index, value []byte) error { + var keys [][]byte + err := get(t, bucket, index, &keys) + if err != nil && err != ErrKeyNotFound { + return err + } + keys = append(keys, value) + return update(t, bucket, index, &keys) +} + +func splice(t *bolt.Tx, bucket, index, value []byte) error { + var keys [][]byte + err := get(t, bucket, index, &keys) + if err != nil && err != ErrKeyNotFound { + return err + } + for i, key := range keys { + if bytes.Equal(key, value) { + keys = keys[:i+copy(keys[i:], keys[i+1:])] + break + } + } + return update(t, bucket, index, &keys) +}