Last active
June 20, 2020 23:25
-
-
Save creallfluharty/0f7bce0a80642fbf685466ba4500ede1 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
""" | |
Python implementation of the `which` program. (Searches $PATH for the first file with a given name) | |
""" | |
from typing import List, Iterator | |
from os import environ as env | |
from operator import methodcaller | |
import os | |
class Dir: | |
def __init__(self, path): | |
self.path = path | |
self.contents = os.listdir(path) | |
def __contains__(self, file_name): | |
return file_name in self.contents | |
def join(self, path): | |
return os.path.join(self.path, path) | |
class ProgramNotFoundError(ValueError): | |
""" Raised when program could not be found in path """ | |
def which(prog_name) -> str: | |
path = env['PATH'] | |
paths = path.split(':') | |
valid_paths = ( | |
path for path in paths | |
if os.path.isdir(path) | |
) | |
dirs = (Dir(path) for path in valid_paths) | |
dirs_containing_prog = ( | |
directory for directory in dirs | |
if prog_name in directory | |
) | |
matches = (dir.join(prog_name) for dir in dirs_containing_prog) | |
try: | |
return next(matches) | |
except StopIteration: | |
raise ProgramNotFoundError(f'no {prog_name} in {path}') |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment