Skip to content

Instantly share code, notes, and snippets.

@TTTPOB
Last active May 30, 2023 05:03
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save TTTPOB/1a03b10d8de06833dfefd34d2c627ebb to your computer and use it in GitHub Desktop.
Save TTTPOB/1a03b10d8de06833dfefd34d2c627ebb to your computer and use it in GitHub Desktop.
A Python script that recursively searches for a parent directory containing specific marker files (.git, .here, etc.). The script prints the relative path of the current directory or specified files to this parent directory. Useful for generating relative paths within structured projects or repositories.
#!/usr/bin/env python
import os
import sys
def eprint(*args, **kwargs):
print(*args, file=sys.stderr, **kwargs)
def find_marker_dir(start_path, markers):
current_dir = (
start_path
if os.path.isdir(os.path.realpath(start_path))
else os.path.dirname(start_path)
)
while True:
if any(marker in os.listdir(current_dir) for marker in markers):
break
else:
parent_dir = os.path.dirname(current_dir)
if parent_dir == current_dir: # We've reached the root directory
return None
current_dir = parent_dir
return os.path.relpath(start_path, current_dir)
markers = [".git", ".here"] # add or remove markers here as needed
# if no argument is passed, use current directory
pwd = os.getenv("PWD")
if len(sys.argv) == 1:
relative_path = find_marker_dir(pwd, markers)
if relative_path is None:
eprint(
"No directory found in the ancestry of the current directory with the following markers:",
markers,
)
else:
print(relative_path)
# if there are arguments, treat them as files
else:
for filename in sys.argv[1:]:
relative_path = find_marker_dir(os.path.join(pwd, filename), markers)
if relative_path is None:
eprint(
f"No directory found in the ancestry of the file {filename} with the following markers: {markers}"
)
else:
print(relative_path)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment