go.chromium.org/luci@v0.0.0-20240309015107-7cdc2e660f33/cipd/appengine/impl/testutil/zip.go (about)

     1  // Copyright 2018 The LUCI Authors.
     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 testutil
    16  
    17  import (
    18  	"archive/zip"
    19  	"bytes"
    20  	"sort"
    21  )
    22  
    23  // MakeZip produces a zip archive with given files.
    24  //
    25  // Can be used to test reading of CIPD packages.
    26  func MakeZip(files map[string]string) []byte {
    27  	buf := bytes.NewBuffer(nil)
    28  	w := zip.NewWriter(buf)
    29  
    30  	names := make([]string, 0, len(files))
    31  	for k := range files {
    32  		names = append(names, k)
    33  	}
    34  	sort.Strings(names)
    35  
    36  	for _, name := range names {
    37  		fw, err := w.Create(name)
    38  		if err != nil {
    39  			panic(err)
    40  		}
    41  		_, err = fw.Write([]byte(files[name]))
    42  		if err != nil {
    43  			panic(err)
    44  		}
    45  	}
    46  
    47  	if err := w.Close(); err != nil {
    48  		panic(err)
    49  	}
    50  	return buf.Bytes()
    51  }