1# Copyright 2022 The PDFium Authors 2# Use of this source code is governed by a BSD-style license that can be 3# found in the LICENSE file. 4"""Utilities for working with the PDFium tree's root directory.""" 5 6import os 7import sys 8 9 10class RootDirectoryFinder: 11 """Finds the PDFium tree's root directories. 12 13 The implementation expects that either: 14 1. PDFium is a standalone checkout. 15 2. PDFium is part of another tree within a "third_party/pdfium" directory. 16 17 Attributes: 18 pdfium_root: The path to the root of the PDFium tree. 19 source_root: The path to the root of the source tree. May differ from 20 `pdfium_root` if PDFium is a third-party dependency in another tree. 21 """ 22 23 def __init__(self): 24 # Expect `self_dir` to be ".../testing/tools". 25 self_dir = os.path.dirname(os.path.realpath(__file__)) 26 27 self.pdfium_root = _remove_path_suffix(self_dir, ('testing', 'tools')) 28 if not self.pdfium_root: 29 raise Exception('Cannot find testing/tools within PDFium root directory') 30 31 # In a Chromium checkout, expect `self.pdfium_root` to be 32 # ".../third_party/pdfium". 33 self.source_root = _remove_path_suffix(self.pdfium_root, 34 ('third_party', 'pdfium')) 35 if not self.source_root: 36 self.source_root = self.pdfium_root 37 38 39def _remove_path_suffix(path, expected_suffix): 40 for expected_part in reversed(expected_suffix): 41 if os.path.basename(path) != expected_part: 42 return None 43 path = os.path.dirname(path) 44 return path 45 46 47def add_source_directory_to_import_path(source_directory_path): 48 """Adds a source root-relative directory to end of the import path.""" 49 root_finder = RootDirectoryFinder() 50 path = os.path.realpath( 51 os.path.join(root_finder.source_root, source_directory_path)) 52 if path not in sys.path: 53 sys.path.append(path) 54