Add Cross SDKs support (part 2)
[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         "github.com/iotbzh/xds-server/lib/common"
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                         }
43                         s.Sdks = append(s.Sdks, *sdk)
44                 }
45         }
46
47         log.Debugf("SDKs: %d cross sdks found", len(s.Sdks))
48
49         return &s, nil
50 }
51
52 // GetAll returns all existing SDKs
53 func (s *SDKs) GetAll() []SDK {
54         s.mutex.Lock()
55         defer s.mutex.Unlock()
56         res := s.Sdks
57         return res
58 }
59
60 // Get returns an SDK from id
61 func (s *SDKs) Get(id int) SDK {
62         s.mutex.Lock()
63         defer s.mutex.Unlock()
64
65         if id < 0 || id > len(s.Sdks) {
66                 return SDK{}
67         }
68         res := s.Sdks[id]
69         return res
70 }
71
72 // GetEnvCmd returns the command used to initialized the environment for an SDK
73 func (s *SDKs) GetEnvCmd(id string, defaultID string) string {
74         if id == "" && defaultID == "" {
75                 // no env cmd
76                 return ""
77         }
78
79         s.mutex.Lock()
80         defer s.mutex.Unlock()
81         defaultEnv := ""
82         for _, sdk := range s.Sdks {
83                 if sdk.ID == id {
84                         return sdk.GetEnvCmd()
85                 }
86                 if sdk.ID == defaultID {
87                         defaultEnv = sdk.GetEnvCmd()
88                 }
89         }
90         // Return default env that may be empty
91         return defaultEnv
92 }