35a9998e16d56bdf1308f591dc67367288307e84
[src/xds/xds-server.git] / lib / crosssdk / sdks.go
1 package crosssdk
2
3 import (
4         "path"
5         "path/filepath"
6         "sync"
7
8         "github.com/Sirupsen/logrus"
9         common "github.com/iotbzh/xds-common/golib"
10         "github.com/iotbzh/xds-server/lib/xdsconfig"
11 )
12
13 // SDKs List of installed SDK
14 type SDKs struct {
15         Sdks []SDK
16
17         mutex sync.Mutex
18 }
19
20 // Init creates a new instance of Syncthing
21 func Init(cfg *xdsconfig.Config, log *logrus.Logger) (*SDKs, error) {
22         s := SDKs{}
23
24         // Retrieve installed sdks
25         sdkRD := cfg.FileConf.SdkRootDir
26
27         if common.Exists(sdkRD) {
28
29                 // Assume that SDK install tree is <rootdir>/<profile>/<version>/<arch>
30                 dirs, err := filepath.Glob(path.Join(sdkRD, "*", "*", "*"))
31                 if err != nil {
32                         log.Debugf("Error while retrieving SDKs: dir=%s, error=%s", sdkRD, err.Error())
33                         return &s, err
34                 }
35                 s.mutex.Lock()
36                 defer s.mutex.Unlock()
37
38                 for _, d := range dirs {
39                         sdk, err := NewCrossSDK(d)
40                         if err != nil {
41                                 log.Debugf("Error while processing SDK dir=%s, err=%s", d, err.Error())
42                                 continue
43                         }
44                         s.Sdks = append(s.Sdks, *sdk)
45                 }
46         }
47
48         log.Debugf("SDKs: %d cross sdks found", len(s.Sdks))
49
50         return &s, nil
51 }
52
53 // GetAll returns all existing SDKs
54 func (s *SDKs) GetAll() []SDK {
55         s.mutex.Lock()
56         defer s.mutex.Unlock()
57         res := s.Sdks
58         return res
59 }
60
61 // Get returns an SDK from id
62 func (s *SDKs) Get(id int) SDK {
63         s.mutex.Lock()
64         defer s.mutex.Unlock()
65
66         if id < 0 || id > len(s.Sdks) {
67                 return SDK{}
68         }
69         res := s.Sdks[id]
70         return res
71 }
72
73 // GetEnvCmd returns the command used to initialized the environment for an SDK
74 func (s *SDKs) GetEnvCmd(id string, defaultID string) []string {
75         if id == "" && defaultID == "" {
76                 // no env cmd
77                 return []string{}
78         }
79
80         s.mutex.Lock()
81         defer s.mutex.Unlock()
82         defaultEnv := []string{}
83         for _, sdk := range s.Sdks {
84                 if sdk.ID == id {
85                         return sdk.GetEnvCmd()
86                 }
87                 if sdk.ID == defaultID {
88                         defaultEnv = sdk.GetEnvCmd()
89                 }
90         }
91         // Return default env that may be empty
92         return defaultEnv
93 }