blob: 50c957495f082aded11325e6fb925d1fecf07fc4 [file] [log] [blame]
Serge Bazanski9e861a82020-09-16 13:46:41 +02001# Copyright 2020 The Monogon Project Authors.
2#
3# SPDX-License-Identifier: Apache-2.0
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# Copyright Google Inc.
18# This file's contents are licensed under the Apache License, Version 2.0.
19# See third_party/licenses/LICENSE.APACHE20 file in this repository for a copy
20# of the License.
21
22# This file contains code adapted from github.com/bazelbuiled/rules_foreign_cc:
23# Files:
24# - tools/build_defs/detect_root.bzl
25
26def detect_root(source):
27 """Detects the path to the topmost directory of the 'source' outputs.
28 To be used with external build systems to point to the source code/tools directories.
29"""
30
31 root = ""
32 sources = source.files.to_list()
33 if (root and len(root) > 0) or len(sources) == 0:
34 return root
35
36 root = ""
37 level = -1
38 num_at_level = 0
39
40 # find topmost directory
41 for file in sources:
42 file_level = _get_level(file.path)
43 if level == -1 or level > file_level:
44 root = file.path
45 level = file_level
46 num_at_level = 1
47 elif level == file_level:
48 num_at_level += 1
49
50 if num_at_level == 1:
51 return root
52
53 (before, sep, after) = root.rpartition("/")
54 if before and sep and after:
55 return before
56 return root
57
58def _get_level(path):
59 normalized = path
60 for i in range(len(path)):
61 new_normalized = normalized.replace("//", "/")
62 if len(new_normalized) == len(normalized):
63 break
64 normalized = new_normalized
65
66 return normalized.count("/")