github.com/zhyoulun/cilium@v1.6.12/pkg/revert/revert.go (about) 1 // Copyright 2018 Authors of Cilium 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 revert 16 17 import "fmt" 18 19 // RevertFunc is a function returned by a successful function call, which 20 // reverts the side-effects of the initial function call. A call that returns 21 // an error should return a nil RevertFunc. 22 type RevertFunc func() error 23 24 // RevertStack is a stack of RevertFuncs to be executed in the reverse order 25 // they were pushed. 26 type RevertStack struct { 27 // revertFuncs is the list of revert functions in the order they were 28 // pushed. 29 revertFuncs []RevertFunc 30 } 31 32 // Push pushes the given RevertFunc on top of this stack. If the function is 33 // nil, it is ignored. 34 func (s *RevertStack) Push(revertFunc RevertFunc) { 35 if revertFunc != nil { 36 s.revertFuncs = append(s.revertFuncs, revertFunc) 37 } 38 } 39 40 // Revert executes all the RevertFuncs in the given stack in the reverse order 41 // they were pushed. 42 func (s *RevertStack) Revert() error { 43 for i := len(s.revertFuncs) - 1; i >= 0; i-- { 44 if err := s.revertFuncs[i](); err != nil { 45 return fmt.Errorf("failed to execute revert function; skipping %d revert functions: %s", i, err) 46 } 47 } 48 return nil 49 }