sigs.k8s.io/prow@v0.0.0-20240503223140-c5e374dc7eb1/pkg/pod-utils/gcs/metadata.go (about)

     1  /*
     2  Copyright 2018 The Kubernetes Authors.
     3  
     4  Licensed under the Apache License, Version 2.0 (the "License");
     5  you may not use this file except in compliance with the License.
     6  You may obtain a copy of the License at
     7  
     8      http://www.apache.org/licenses/LICENSE-2.0
     9  
    10  Unless required by applicable law or agreed to in writing, software
    11  distributed under the License is distributed on an "AS IS" BASIS,
    12  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    13  See the License for the specific language governing permissions and
    14  limitations under the License.
    15  */
    16  
    17  package gcs
    18  
    19  import (
    20  	"mime"
    21  	"strings"
    22  
    23  	utilpointer "k8s.io/utils/pointer"
    24  	"sigs.k8s.io/prow/pkg/io"
    25  )
    26  
    27  // WriterOptionsFromFileName guesses file attributes from the filename
    28  // and returns the writerOptions and a simplified filename.  For example,
    29  // build-log.txt.gz would be:
    30  //
    31  //	Content-Type: text/plain; charset=utf-8
    32  //	Content-Encoding: gzip
    33  //
    34  // and the simplified filename would be build-log.txt (excluding the
    35  // content encoding extension).
    36  func WriterOptionsFromFileName(filename string) (string, io.WriterOptions) {
    37  	attrs := io.WriterOptions{}
    38  	segments := strings.Split(filename, ".")
    39  	index := len(segments) - 1
    40  	segment := segments[index]
    41  
    42  	// https://www.iana.org/assignments/http-parameters/http-parameters.xhtml#content-coding
    43  	switch segment {
    44  	case "gz", "gzip":
    45  		attrs.ContentEncoding = utilpointer.String("gzip")
    46  	}
    47  
    48  	if attrs.ContentEncoding != nil {
    49  		if index == 0 {
    50  			segment = ""
    51  		} else {
    52  			filename = filename[:len(filename)-len(segment)-1]
    53  			index -= 1
    54  			segment = segments[index]
    55  		}
    56  	}
    57  
    58  	if segment != "" {
    59  		mediaType := mime.TypeByExtension("." + segment)
    60  		if mediaType != "" {
    61  			attrs.ContentType = utilpointer.String(mediaType)
    62  		}
    63  	}
    64  
    65  	if attrs.ContentType == nil && attrs.ContentEncoding != nil && *attrs.ContentEncoding == "gzip" {
    66  		attrs.ContentType = utilpointer.String("application/gzip")
    67  		attrs.ContentEncoding = nil
    68  	}
    69  
    70  	return filename, attrs
    71  }