github.com/GoogleContainerTools/skaffold@v1.39.18/pkg/skaffold/kubernetes/manifest/namespaces.go (about)

     1  /*
     2  Copyright 2019 The Skaffold 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 manifest
    18  
    19  import (
    20  	"fmt"
    21  	"sort"
    22  	"strings"
    23  
    24  	"k8s.io/apimachinery/pkg/runtime/schema"
    25  )
    26  
    27  // CollectNamespaces returns all the namespaces in the manifests.
    28  func (l *ManifestList) CollectNamespaces() ([]string, error) {
    29  	replacer := newNamespaceCollector()
    30  
    31  	// TODO(aaron-prindle) make sure this is ok?
    32  	rs := &ResourceSelectorImages{}
    33  	if _, err := l.Visit(replacer, rs); err != nil {
    34  		// if _, err := l.Visit(replacer, make(map[schema.GroupKind]latest.ResourceFilter), make(map[schema.GroupKind]latest.ResourceFilter)); err != nil {
    35  		// TODO(aaron-prindle) verify this doesn't need to support allow/deny list, also see if 'nil' is better option for unused inputs
    36  		return nil, fmt.Errorf("collecting namespaces: %w", err)
    37  	}
    38  
    39  	namespaces := make([]string, 0, len(replacer.namespaces))
    40  	for ns := range replacer.namespaces {
    41  		namespaces = append(namespaces, ns)
    42  	}
    43  	sort.Strings(namespaces)
    44  	return namespaces, nil
    45  }
    46  
    47  type namespaceCollector struct {
    48  	namespaces map[string]bool
    49  }
    50  
    51  func newNamespaceCollector() *namespaceCollector {
    52  	return &namespaceCollector{
    53  		namespaces: map[string]bool{},
    54  	}
    55  }
    56  
    57  func (r *namespaceCollector) Visit(gk schema.GroupKind, navpath string, o map[string]interface{}, k string, v interface{}, rs ResourceSelector) bool {
    58  	if k != metadataField {
    59  		return true
    60  	}
    61  
    62  	metadata, ok := v.(map[string]interface{})
    63  	if !ok {
    64  		return true
    65  	}
    66  	if nsValue, present := metadata["namespace"]; present {
    67  		nsString, ok := nsValue.(string)
    68  		if !ok || nsString == "" {
    69  			return true
    70  		}
    71  		if ns := strings.TrimSpace(nsString); ns != "" {
    72  			r.namespaces[ns] = true
    73  		}
    74  	}
    75  	return false
    76  }