Imported Upstream version 1.25.0
[platform/core/ml/nnfw.git] / compiler / one-cmds / onelib / backends.py
1 #!/usr/bin/env python
2
3 # Copyright (c) 2023 Samsung Electronics Co., Ltd. All Rights Reserved
4 #
5 # Licensed under the Apache License, Version 2.0 (the "License");
6 # you may not use this file except in compliance with the License.
7 # You may obtain a copy of the License at
8 #
9 #    http://www.apache.org/licenses/LICENSE-2.0
10 #
11 # Unless required by applicable law or agreed to in writing, software
12 # distributed under the License is distributed on an "AS IS" BASIS,
13 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 # See the License for the specific language governing permissions and
15 # limitations under the License.
16
17 import glob
18 import ntpath
19 import os
20 """
21 [one hierarchy]
22 one
23 ├── backends
24 ├── bin
25 ├── doc
26 ├── include
27 ├── lib
28 ├── optimization
29 └── test
30
31 The list where `one-XXXX` finds its backends
32 - `bin` folder where `one-XXXX` exists
33 - `backends` folder
34
35 NOTE If there are backends of the same name in different places,
36     the closer to the top in the list, the higher the priority.
37 """
38
39
40 def get_list(cmdname):
41     dir_path = os.path.dirname(os.path.realpath(__file__))
42     backend_set = set()
43
44     # bin folder
45     files = [f for f in glob.glob(dir_path + '/../*-' + cmdname)]
46     # backends folder
47     files += [
48         f
49         for f in glob.glob(dir_path + '/../../backends/**/*-' + cmdname, recursive=True)
50     ]
51     # TODO find backends in `$PATH`
52
53     backends_list = []
54     for cand in files:
55         base = ntpath.basename(cand)
56         if (not base in backend_set) and os.path.isfile(cand) and os.access(
57                 cand, os.X_OK):
58             backend_set.add(base)
59             backends_list.append(cand)
60
61     return backends_list
62
63
64 def search_driver(driver):
65     dir_path = os.path.dirname(os.path.realpath(__file__))
66
67     # CASE 1: one/bin/{driver} is found
68     driver_path = dir_path + '/../' + driver
69     if os.path.isfile(driver_path) and os.access(driver_path, os.X_OK):
70         return driver_path
71
72     # CASE 2: one/backends/**/bin/{driver} is found
73     for driver_path in glob.glob(
74             dir_path + '/../../backends/**/bin/' + driver, recursive=True):
75         if os.path.isfile(driver_path) and os.access(driver_path, os.X_OK):
76             return driver_path
77
78     # CASE 3: {driver} is found in nowhere
79     return None