paths_finder.py 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101
  1. #!/usr/bin/env -S python3 -B
  2. # Copyright (c) 2023 Project CHIP Authors
  3. #
  4. # Licensed under the Apache License, Version 2.0 (the "License");
  5. # you may not use this file except in compliance with the License.
  6. # You may obtain a copy of the License at
  7. #
  8. # http://www.apache.org/licenses/LICENSE-2.0
  9. #
  10. # Unless required by applicable law or agreed to in writing, software
  11. # distributed under the License is distributed on an "AS IS" BASIS,
  12. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. # See the License for the specific language governing permissions and
  14. # limitations under the License.
  15. import os
  16. import tempfile
  17. from pathlib import Path
  18. import click
  19. from diskcache import Cache
  20. _PATHS_CACHE_NAME = 'yaml_runner_cache'
  21. _PATHS_CACHE = Cache(os.path.join(tempfile.gettempdir(), _PATHS_CACHE_NAME))
  22. DEFAULT_CHIP_ROOT = os.path.abspath(
  23. os.path.join(os.path.dirname(__file__), '..', '..', '..'))
  24. class PathsFinder:
  25. def __init__(self, root_dir: str = DEFAULT_CHIP_ROOT):
  26. self.__root_dir = root_dir
  27. def get(self, target_name: str) -> str:
  28. path = _PATHS_CACHE.get(target_name)
  29. if path and Path(path).is_file():
  30. return path
  31. if path:
  32. del _PATHS_CACHE[target_name]
  33. for path in Path(self.__root_dir).rglob(target_name):
  34. if not path.is_file() or path.name != target_name:
  35. continue
  36. _PATHS_CACHE[target_name] = str(path)
  37. return str(path)
  38. return None
  39. @click.group()
  40. def finder():
  41. pass
  42. @finder.command()
  43. def view():
  44. """View the cache entries."""
  45. for name in _PATHS_CACHE:
  46. print(click.style(f'{name}', bold=True) + f':\t{_PATHS_CACHE[name]}')
  47. @finder.command()
  48. @click.argument('key', type=str)
  49. @click.argument('value', type=str)
  50. def add(key: str, value: str):
  51. """Add a cache entry."""
  52. _PATHS_CACHE[key] = value
  53. @finder.command()
  54. @click.argument('name', type=str)
  55. def delete(name: str):
  56. """Delete a cache entry."""
  57. if name in _PATHS_CACHE:
  58. del _PATHS_CACHE[name]
  59. @finder.command()
  60. def reset():
  61. """Delete all cache entries."""
  62. for name in _PATHS_CACHE:
  63. del _PATHS_CACHE[name]
  64. @finder.command()
  65. @click.argument('name', type=str)
  66. def search(name: str):
  67. """Search for a target and add it to the cache."""
  68. paths_finder = PathsFinder()
  69. path = paths_finder.get(name)
  70. if path:
  71. print(f'The target "{name}" has been added with the value "{path}".')
  72. else:
  73. print(f'The target "{name}" was not found.')
  74. if __name__ == '__main__':
  75. finder()