github.com/wmuizelaar/kpt@v0.0.0-20221018115725-bd564717b2ed/internal/util/stack/stack.go (about) 1 // Copyright 2019 Google LLC 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 stack 16 17 import ( 18 "fmt" 19 20 "github.com/GoogleContainerTools/kpt/internal/pkg" 21 ) 22 23 // New returns a new stack for elements of string type. 24 func New() *Stack { 25 return &Stack{} 26 } 27 28 type Stack struct { 29 slice []string 30 } 31 32 func (s *Stack) Push(str string) { 33 s.slice = append(s.slice, str) 34 } 35 36 func (s *Stack) Pop() string { 37 l := len(s.slice) 38 if l == 0 { 39 panic(fmt.Errorf("can't pop an empty stack")) 40 } 41 str := s.slice[l-1] 42 s.slice = s.slice[:l-1] 43 return str 44 } 45 46 func (s *Stack) Len() int { 47 return len(s.slice) 48 } 49 50 // NewPkgStack returns a new stack for elements of *pkg.Pkg type. 51 func NewPkgStack() *PkgStack { 52 return &PkgStack{} 53 } 54 55 type PkgStack struct { 56 slice []*pkg.Pkg 57 } 58 59 func (ps *PkgStack) Push(p *pkg.Pkg) { 60 ps.slice = append(ps.slice, p) 61 } 62 63 func (ps *PkgStack) PushAll(pkgs []*pkg.Pkg) { 64 for i := range pkgs { 65 p := pkgs[i] 66 ps.Push(p) 67 } 68 } 69 70 func (ps *PkgStack) Pop() *pkg.Pkg { 71 l := len(ps.slice) 72 if l == 0 { 73 panic(fmt.Errorf("can't pop an empty stack")) 74 } 75 p := ps.slice[l-1] 76 ps.slice = ps.slice[:l-1] 77 return p 78 } 79 80 func (ps *PkgStack) Len() int { 81 return len(ps.slice) 82 }