github.com/opencontainers/umoci@v0.4.8-0.20240508124516-656e4836fb0d/oci/config/generate/save.go (about)

     1  /*
     2   * umoci: Umoci Modifies Open Containers' Images
     3   * Copyright (C) 2016-2020 SUSE LLC
     4   *
     5   * Licensed under the Apache License, Version 2.0 (the "License");
     6   * you may not use this file except in compliance with the License.
     7   * You may obtain a copy of the License at
     8   *
     9   *    http://www.apache.org/licenses/LICENSE-2.0
    10   *
    11   * Unless required by applicable law or agreed to in writing, software
    12   * distributed under the License is distributed on an "AS IS" BASIS,
    13   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    14   * See the License for the specific language governing permissions and
    15   * limitations under the License.
    16   */
    17  
    18  package generate
    19  
    20  import (
    21  	"encoding/json"
    22  	"io"
    23  
    24  	"github.com/pkg/errors"
    25  )
    26  
    27  // fakeBuffer implements the io.Writer interface but just counts the number of
    28  // bytes "written" to it.
    29  type fakeBuffer struct {
    30  	n int64
    31  }
    32  
    33  // Write just counts the number of bytes requested to be written.
    34  func (fb *fakeBuffer) Write(p []byte) (int, error) {
    35  	size := len(p)
    36  	fb.n += int64(size)
    37  	return size, nil
    38  }
    39  
    40  // WriteTo outputs a JSON-marshalled version of the current state of the
    41  // generator. It is not guaranteed that the generator will produce the same
    42  // output given the same state, so it's recommended to only call this function
    43  // once. The JSON is not pretty-printed.
    44  func (g *Generator) WriteTo(w io.Writer) (n int64, err error) {
    45  	// We need to return the number of bytes written, which json.NewEncoder
    46  	// won't give us. So we have to cheat a little to get the answer.
    47  	var fb fakeBuffer
    48  	w = io.MultiWriter(w, &fb)
    49  
    50  	if err := json.NewEncoder(w).Encode(g.image); err != nil {
    51  		return fb.n, errors.Wrap(err, "encode image")
    52  	}
    53  
    54  	return fb.n, nil
    55  }