github.com/mre-fog/trillianxx@v1.1.2-0.20180615153820-ae375a99d36a/util/flagsaver/flagsaver.go (about)

     1  // Copyright 2017 Google Inc. All Rights Reserved.
     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 flagsaver provides a simple way to save and restore flag values.
    16  // TODO(RJPercival): Move this to its own GitHub project.
    17  //
    18  // Example:
    19  //   func TestFoo(t *testing.T) {
    20  //     defer flagsaver.Save().Restore()
    21  //     // Test code that changes flags
    22  //   } // flags are reset to their original values here.
    23  package flagsaver
    24  
    25  import "flag"
    26  
    27  // Stash holds flag values so that they can be restored at the end of a test.
    28  type Stash struct {
    29  	flags map[string]string
    30  }
    31  
    32  // Restore sets all non-hidden flags to the values they had when the Stash was created.
    33  func (s *Stash) Restore() {
    34  	for name, value := range s.flags {
    35  		flag.Set(name, value)
    36  	}
    37  }
    38  
    39  // Save returns a Stash that captures the current value of all non-hidden flags.
    40  func Save() *Stash {
    41  	s := Stash{
    42  		flags: make(map[string]string, flag.NFlag()),
    43  	}
    44  
    45  	flag.VisitAll(func(f *flag.Flag) {
    46  		s.flags[f.Name] = f.Value.String()
    47  	})
    48  
    49  	return &s
    50  }