add ut for consul config info
[msb/service-mesh.git] / msb2pilot / src / msb2pilot / util / common.go
1 /**
2  * Copyright (c) 2018 ZTE Corporation.
3  * All rights reserved. This program and the accompanying materials
4  * are made available under the terms of the Eclipse Public License v1.0
5  * and the Apache License 2.0 which both accompany this distribution,
6  * and are available at http://www.eclipse.org/legal/epl-v10.html
7  * and http://www.apache.org/licenses/LICENSE-2.0
8  *
9  * Contributors:
10  *     ZTE - initial Project
11  */
12 package util
13
14 import (
15         "os"
16         "path/filepath"
17         "strings"
18 )
19
20 const (
21         ConfigPath = "conf"
22         PathSep    = string(os.PathSeparator)
23 )
24
25 func GetCfgPath() string {
26         appPath, err := filepath.Abs(filepath.Dir(os.Args[0]))
27         if err != nil {
28                 panic(err)
29         }
30
31         workPath, err := os.Getwd()
32         if err != nil {
33                 panic(err)
34         }
35
36         result := filepath.Join(workPath, ConfigPath)
37
38         if !FileExists(result) {
39                 result = filepath.Join(appPath, ConfigPath)
40                 if !FileExists(result) {
41                         goPaths := GetGoPath()
42                         for _, path := range goPaths {
43                                 result = filepath.Join(path, "src", "msb2pilot", ConfigPath)
44                                 if FileExists(result) {
45                                         return result
46                                 }
47                         }
48                         result = "/"
49                 }
50         }
51
52         return result
53
54 }
55
56 func GetGoPath() []string {
57         paths := os.Getenv("GOPATH")
58         if strings.Contains(paths, ";") { // windows
59                 return strings.Split(paths, ";")
60         } else if strings.Contains(paths, ":") { // linux
61                 return strings.Split(paths, ":")
62         } else if paths != "" { // only one
63                 path := make([]string, 1, 1)
64                 path[0] = paths
65                 return path
66         } else {
67                 return make([]string, 0, 0)
68         }
69 }
70
71 func FileExists(path string) bool {
72         if _, err := os.Stat(path); err != nil {
73                 if os.IsNotExist(err) {
74                         return false
75                 }
76         }
77         return true
78 }