Debian Codegraph @

cmdline/shared/util.go

raw symbols SCIP
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/v7/config"
25 "github.com/sassoftware/relic/v7/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 OpenForPatching(inpath, outpath string) (*os.File, error) {
87 switch {
88 case inpath == "-":
89 return os.Stdin, nil
90 case inpath == outpath:
91 // open for writing so in-place patch works
92 return os.OpenFile(inpath, os.O_RDWR, 0)
93 default:
94 return os.Open(inpath)
95 }
96 }
97
98 func Fail(err error) error {
99 if err != nil {
100 fmt.Fprintln(os.Stderr, "ERROR:", err)
101 os.Exit(70)
102 }
103 return err
104 }