summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorJonathan Maw <jonathan.maw@codethink.co.uk>2018-10-31 13:55:55 +0000
committerJonathan Maw <jonathan.maw@codethink.co.uk>2018-12-11 12:56:32 +0000
commit7892287a53c5ec3259fcd6f14736805b26b285b8 (patch)
treea05808b0eae13ed88076d16ad9c7f837e51038b0
parent717c10d1d871342e8fddcc4af9ff7a50320989c1 (diff)
downloadbuildstream-7892287a53c5ec3259fcd6f14736805b26b285b8.tar.gz
utils.py: Add a helper for searching upwards for files
i.e. with a given directory and filename, check parent directories until either a directory with the filename is found, or you reach the root of the filesystem. This is a part of #222
-rw-r--r--buildstream/utils.py31
1 files changed, 31 insertions, 0 deletions
diff --git a/buildstream/utils.py b/buildstream/utils.py
index 2fe9ab7dc..4da29c259 100644
--- a/buildstream/utils.py
+++ b/buildstream/utils.py
@@ -1259,3 +1259,34 @@ def _message_digest(message_buffer):
digest.hash = sha.hexdigest()
digest.size_bytes = len(message_buffer)
return digest
+
+
+# _search_upward_for_files()
+#
+# Searches upwards (from directory, then directory's parent directory...)
+# for any of the files listed in `filenames`.
+#
+# If multiple filenames are specified, and present in the same directory,
+# the first filename in the list will be returned.
+#
+# Args:
+# directory (str): The directory to begin searching for files from
+# filenames (list of str): The names of files to search for
+#
+# Returns:
+# (str): The directory a file was found in, or None
+# (str): The name of the first file that was found in that directory, or None
+#
+def _search_upward_for_files(directory, filenames):
+ directory = os.path.abspath(directory)
+ while True:
+ for filename in filenames:
+ file_path = os.path.join(directory, filename)
+ if os.path.isfile(file_path):
+ return directory, filename
+
+ parent_dir = os.path.dirname(directory)
+ if directory == parent_dir:
+ # i.e. we've reached the root of the filesystem
+ return None, None
+ directory = parent_dir