github.com/oam-dev/kubevela@v1.9.11/references/appfile/template/manager.go (about)

     1  /*
     2  Copyright 2021 The KubeVela 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 template
    18  
    19  import (
    20  	"github.com/oam-dev/kubevela/apis/types"
    21  	"github.com/oam-dev/kubevela/pkg/utils/common"
    22  	"github.com/oam-dev/kubevela/references/docgen"
    23  )
    24  
    25  // Manager defines a manager for template
    26  type Manager interface {
    27  	IsTrait(key string) bool
    28  	LoadTemplate(key string) (tmpl string)
    29  }
    30  
    31  // Load will load all installed capabilities and create a manager
    32  func Load(namespace string, c common.Args) (Manager, error) {
    33  	caps, err := docgen.LoadAllInstalledCapability(namespace, c)
    34  	if err != nil {
    35  		return nil, err
    36  	}
    37  	m := newManager()
    38  	for _, cap := range caps {
    39  		t := &Template{}
    40  		t.Captype = cap.Type
    41  		t.Raw = cap.CueTemplate
    42  		m.Templates[cap.Name] = t
    43  	}
    44  	return m, nil
    45  }
    46  
    47  // Template defines a raw template struct
    48  type Template struct {
    49  	Captype types.CapType
    50  	Raw     string
    51  }
    52  
    53  type manager struct {
    54  	Templates map[string]*Template
    55  }
    56  
    57  func newManager() *manager {
    58  	return &manager{
    59  		Templates: make(map[string]*Template),
    60  	}
    61  }
    62  
    63  func (m *manager) IsTrait(key string) bool {
    64  	t, ok := m.Templates[key]
    65  	if !ok {
    66  		return false
    67  	}
    68  	return t.Captype == types.TypeTrait
    69  }
    70  
    71  func (m *manager) LoadTemplate(key string) string {
    72  	t, ok := m.Templates[key]
    73  	if !ok {
    74  		return ""
    75  	}
    76  	return t.Raw
    77  }