Skip to content

Commit 2829ef6

Browse files
committed
image/cas/put: Add a PutJSON helper
A fair amount of image setup involves pushing JSON objects to CAS, so provide a convenient wrapper around that. This implementation could be improved, with at least: * Consistent key sorts, etc. to increase the chances of matching an existing CAS blob. * Streaming the marshaled JSON into the engine to avoid serializing it in memory before passing it into Engine.Put. But the API is fine, and we can improve the implementation as we go. Signed-off-by: W. Trevor King <[email protected]>
1 parent 841c361 commit 2829ef6

File tree

1 file changed

+47
-0
lines changed

1 file changed

+47
-0
lines changed

image/cas/put.go

Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
1+
// Copyright 2016 The Linux Foundation
2+
//
3+
// Licensed under the Apache License, Version 2.0 (the "License");
4+
// you may not use this file except in compliance with the License.
5+
// You may obtain a copy of the License at
6+
//
7+
// http://www.apache.org/licenses/LICENSE-2.0
8+
//
9+
// Unless required by applicable law or agreed to in writing, software
10+
// distributed under the License is distributed on an "AS IS" BASIS,
11+
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12+
// See the License for the specific language governing permissions and
13+
// limitations under the License.
14+
15+
package cas
16+
17+
import (
18+
"bytes"
19+
"encoding/json"
20+
21+
"github.com/opencontainers/image-spec/specs-go"
22+
"golang.org/x/net/context"
23+
)
24+
25+
// PutJSON writes a generic JSON object to content-addressable storage
26+
// and returns a Descriptor referencing it.
27+
func PutJSON(ctx context.Context, engine Engine, data interface{}, mediaType string) (descriptor *specs.Descriptor, err error) {
28+
jsonBytes, err := json.Marshal(data)
29+
if err != nil {
30+
return nil, err
31+
}
32+
size := len(jsonBytes)
33+
size64 := int64(size) // panics on overflow
34+
35+
reader := bytes.NewReader(jsonBytes)
36+
digest, err := engine.Put(ctx, reader)
37+
if err != nil {
38+
return nil, err
39+
}
40+
41+
descriptor = &specs.Descriptor{
42+
MediaType: mediaType,
43+
Digest: digest,
44+
Size: size64,
45+
}
46+
return descriptor, nil
47+
}

0 commit comments

Comments
 (0)