go.chromium.org/luci@v0.0.0-20240309015107-7cdc2e660f33/auth_service/testsupport/common.go (about)

     1  // Copyright 2023 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 testsupport contains helper functions for testing auth service.
    16  package testsupport
    17  
    18  import (
    19  	"archive/tar"
    20  	"bytes"
    21  	"compress/gzip"
    22  )
    23  
    24  // BuildTargz builds a tar bundle.
    25  func BuildTargz(files map[string][]byte) []byte {
    26  	var buf bytes.Buffer
    27  	gzw := gzip.NewWriter(&buf)
    28  	tw := tar.NewWriter(gzw)
    29  	for name, body := range files {
    30  		hdr := &tar.Header{
    31  			Name: name,
    32  			Mode: 0600,
    33  			Size: int64(len(body)),
    34  		}
    35  		if err := tw.WriteHeader(hdr); err != nil {
    36  			return nil
    37  		}
    38  		if _, err := tw.Write(body); err != nil {
    39  			return nil
    40  		}
    41  	}
    42  	if err := tw.Flush(); err != nil {
    43  		return nil
    44  	}
    45  	if err := tw.Close(); err != nil {
    46  		return nil
    47  	}
    48  	if err := gzw.Flush(); err != nil {
    49  		return nil
    50  	}
    51  	if err := gzw.Close(); err != nil {
    52  		return nil
    53  	}
    54  	return buf.Bytes()
    55  }