github.com/fabianvf/ocp-release-operator-sdk@v0.0.0-20190426141702-57620ee2f090/internal/util/yamlutil/scan.go (about) 1 // Copyright 2018 The Operator-SDK 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 yamlutil 16 17 import ( 18 "bufio" 19 "bytes" 20 "io" 21 22 k8syaml "k8s.io/apimachinery/pkg/util/yaml" 23 ) 24 25 const maxExecutiveEmpties = 100 26 27 // Scanner scans a yaml manifest file for manifest tokens delimited by "---". 28 // See bufio.Scanner for semantics. 29 type Scanner struct { 30 reader *k8syaml.YAMLReader 31 token []byte // Last token returned by split. 32 err error // Sticky error. 33 empties int // Count of successive empty tokens. 34 done bool // Scan has finished. 35 } 36 37 func NewYAMLScanner(b []byte) *Scanner { 38 r := bufio.NewReader(bytes.NewBuffer(b)) 39 return &Scanner{reader: k8syaml.NewYAMLReader(r)} 40 } 41 42 func (s *Scanner) Err() error { 43 if s.err == io.EOF { 44 return nil 45 } 46 return s.err 47 } 48 49 func (s *Scanner) Scan() bool { 50 if s.done { 51 return false 52 } 53 54 var ( 55 tok []byte 56 err error 57 ) 58 59 for { 60 tok, err = s.reader.Read() 61 if err != nil { 62 if err == io.EOF { 63 s.done = true 64 } 65 s.err = err 66 return false 67 } 68 if len(bytes.TrimSpace(tok)) == 0 { 69 s.empties++ 70 if s.empties > maxExecutiveEmpties { 71 panic("yaml.Scan: too many empty tokens without progressing") 72 } 73 continue 74 } 75 s.empties = 0 76 s.token = tok 77 return true 78 } 79 } 80 81 func (s *Scanner) Text() string { 82 return string(s.token) 83 } 84 85 func (s *Scanner) Bytes() []byte { 86 return s.token 87 }