...

Source file src/github.com/sassoftware/relic/cmdline/shared/util.go

Documentation: github.com/sassoftware/relic/cmdline/shared

     1  //
     2  // Copyright (c) SAS Institute Inc.
     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 shared
    18  
    19  import (
    20  	"errors"
    21  	"fmt"
    22  	"os"
    23  
    24  	"github.com/sassoftware/relic/config"
    25  	"github.com/sassoftware/relic/lib/dlog"
    26  )
    27  
    28  func InitConfig() error {
    29  	return initConfig(false)
    30  }
    31  
    32  func InitClientConfig() error {
    33  	return initConfig(true)
    34  }
    35  
    36  func initConfig(client bool) error {
    37  	if CurrentConfig != nil {
    38  		return nil
    39  	}
    40  	dlog.SetLevel(ArgDebug)
    41  	usedDefault := false
    42  	if ArgConfig == "" {
    43  		ArgConfig = config.DefaultConfig()
    44  		usedDefault = true
    45  	}
    46  	if client && usedDefault {
    47  		cfg, err := config.FromEnvironment()
    48  		if err != nil {
    49  			return err
    50  		} else if cfg != nil {
    51  			CurrentConfig = cfg
    52  			return nil
    53  		}
    54  	}
    55  	if ArgConfig == "" {
    56  		return errors.New("--config not specified")
    57  	}
    58  	cfg, err := config.ReadFile(ArgConfig)
    59  	if err != nil {
    60  		if os.IsNotExist(err) && usedDefault {
    61  			if client {
    62  				// try to use environment
    63  				cfg, err = config.FromEnvironment()
    64  				if err != nil {
    65  					return err
    66  				} else if cfg != nil {
    67  					CurrentConfig = cfg
    68  					return nil
    69  				}
    70  			}
    71  			return fmt.Errorf("--config not specified and default config at %s does not exist", ArgConfig)
    72  		}
    73  		return err
    74  	}
    75  	CurrentConfig = cfg
    76  	return nil
    77  }
    78  
    79  func OpenFile(path string) (*os.File, error) {
    80  	if path == "-" {
    81  		return os.Stdin, nil
    82  	}
    83  	return os.Open(path)
    84  }
    85  
    86  func Fail(err error) error {
    87  	if err != nil {
    88  		fmt.Fprintln(os.Stderr, "ERROR:", err)
    89  		os.Exit(70)
    90  	}
    91  	return err
    92  }
    93  

View as plain text