create-leetcode.py (2068B)
1 import os 2 import re 3 import sys 4 5 # This assumes the CWD is laid out as follows: 6 7 # PROBLEM-NAME 8 # -> PROBLEM-NAMEV1.py 9 # -> PROBLEM-NAMEV2.py 10 # -> PROBLEM-NAMEVN.py 11 # PROBLEM-NAME 12 # -> PROBLEM-NAMEV1.py 13 # -> PROBLEM-NAMEV2.py 14 # -> PROBLEM-NAMEVN.py 15 # PROBLEM-NAME 16 # -> PROBLEM-NAMEV1.py 17 # -> PROBLEM-NAMEV2.py 18 # -> PROBLEM-NAMEVN.py 19 20 def create_directory(problem_name) -> str: 21 os.makedirs(problem_name, exist_ok=True) 22 return problem_name 23 24 def get_file_name(problem_name, dir_name, extension : str): 25 26 assert os.path.exists(dir_name), "Directory should exist when invoking get_file_name." 27 28 done = False 29 count = 0 30 31 # problem_name = problem_name[:10] 32 33 while not done: 34 35 count += 1 36 current = problem_name + "V" + str(count) + "." + extension 37 current_path = os.path.join(dir_name, current) 38 39 if os.path.exists(current_path): 40 continue 41 else: 42 return current 43 44 def create_file(dir_name, name): 45 file_path = os.path.join(dir_name, name) 46 open(file_path, 'a').close() 47 return file_path 48 49 50 def parse_url(url): 51 match = re.search(r"leetcode\.com/problems/([^/]+)", url) 52 if match: 53 problem_name = match.group(1) 54 return problem_name 55 else: 56 raise ValueError("Unexpected URL format in input #1: " + url) 57 58 59 if __name__ == "__main__": 60 """Creates and opens file based on LC URL in $1 and the file extension in $2.""" 61 62 try: 63 problem_name = parse_url(sys.argv[1]) 64 file_extension = sys.argv[2] 65 66 if file_extension == "": 67 raise ValueError(f'Please specify the file extension from the cli.') 68 69 except IndexError as e: 70 raise ValueError(f'Please specify the filename and file extension from the cli: {e}') 71 72 dir_name = create_directory(problem_name) 73 74 name = get_file_name(problem_name, dir_name, file_extension) 75 file_path = create_file(dir_name, name) 76 77 # send file path to stdout. 78 # this will be piped into xargs to open the file with your 79 # preferred text editor. 80 81 print(file_path)