Skip to content

Instantly share code, notes, and snippets.

@robopuff
Created November 26, 2024 14:28
Show Gist options
  • Save robopuff/3ba4824cbb7eaec62577658d3600937f to your computer and use it in GitHub Desktop.
Save robopuff/3ba4824cbb7eaec62577658d3600937f to your computer and use it in GitHub Desktop.
Codeowners in CLI
#!/usr/bin/env python3
import os
import re
import argparse
import fnmatch
def find_codeowners_file(base_path):
for root, dirs, files in os.walk(base_path):
# Check only the first level of directories
for dir in dirs:
codeowners_path = os.path.join(root, dir, "CODEOWNERS")
if os.path.isfile(codeowners_path):
return codeowners_path
break
return None
def parse_codeowners(file_path):
sections = {}
current_owner = None
with open(file_path, 'r') as file:
for line in file:
line = line.strip()
if line.startswith('[') and line.endswith(']'):
current_owner = None # Reset owner for a new section
elif '@' in line:
# Set the current owner for the following paths
current_owner = line.strip()
elif current_owner is not None:
if not line.startswith('#') and line != "":
current = line
if not current.startswith('/') and not current.startswith('*'):
current = f'*{current}'
sections[current] = current_owner
return sections
def get_owner(base_path, target):
codeowners_file = find_codeowners_file(base_path)
if not codeowners_file:
return None
sections = parse_codeowners(codeowners_file)
# Normalize the target folder
target = target.strip('/')
for path, owner in reversed(sections.items()):
if target == path or f'/{target}/*/' == path or fnmatch.fnmatch(target, path):
return owner
return None
def main():
parser = argparse.ArgumentParser(description='Find the owner of a given folder from a CODEOWNERS file.')
parser.add_argument('target_folder', type=str, help='Folder to find the owner of')
args = parser.parse_args()
base_path = os.getcwd()
owner = get_owner(base_path, args.target_folder)
if owner:
print(owner)
if __name__ == '__main__':
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment