使用Python调用GitHub API无法正确创建目录的问题排查
问题分析与修复方案
原代码存在的核心问题
- 目录层级管理错误:
current_dir列表会无差别追加所有条目(文件和目录),导致路径中混入文件名作为目录,比如生成dir2/file1/file1这种错误路径。 - 未处理同级目录切换:当从
dir2切换到同级的dir3时,没有将current_dir回退到父目录层级,导致dir3被错误嵌套在dir2下。 - 目录创建方式错误:GitHub API 不允许直接创建空目录,原代码试图将目录名作为文件创建(比如
dir1),实际生成的是文件而非目录。 - 根目录处理不当:根目录未被识别为目录结构,而是被当作普通文件创建。
修复方案
关键改进点
- 新增
parse_line函数:解析每行的层级深度、名称和是否为目录,通过标记符(├──/└──)的缩进位置计算层级。 - 正确管理
current_dir:根据当前条目层级截断current_dir到父目录层级,再添加新目录,确保层级结构正确。 - 通过
.gitkeep创建目录:GitHub 需要目录下存在文件才能创建目录,因此在每个目录下生成空的.gitkeep文件。 - 重构
create_file函数:直接接收完整路径,避免路径拼接错误。
完整修复代码
from github import Github import re def create_repository(username, token, repository_name): g = Github(username, token) repo = g.get_user().create_repo(repository_name) print(f"Successfully created repository: {repository_name}") return repo def parse_line(line): line = line.strip() is_directory = line.endswith('/') if line.startswith(('├──', '└──')): name = line[3:].strip().rstrip('/') name = re.sub('[^a-zA-Z0-9.]', '', name) marker_start = line.find('├──') if '├──' in line else line.find('└──') depth = (marker_start // 4) + 1 else: name = line.rstrip('/') name = re.sub('[^a-zA-Z0-9.]', '', name) depth = 0 return depth, name, is_directory def create_file(repo, path): try: repo.create_file(path, 'Initial commit', '') print(f"Successfully created file: {path}") except Exception as e: print(f"Error creating file {path}: {e}") def create_file_structure(repo, file_structure): lines = file_structure.strip().split('\n') current_dir = [] for line in lines: depth, name, is_directory = parse_line(line) if is_directory: parent_path = current_dir[:depth] current_dir = parent_path + [name] dir_path = '/'.join(current_dir + ['.gitkeep']) create_file(repo, dir_path) else: parent_path = current_dir[:depth] file_path = '/'.join(parent_path + [name]) create_file(repo, file_path) print('Successfully created file structure') def main(): username = input('Enter your GitHub username: ') token = input('Enter your GitHub personal access token: ') repository_name = input('Enter the repository name: ') repo = create_repository(username, token, repository_name) print("Paste your file structure (press enter twice to finish):") lines = [] while True: line = input() if line: lines.append(line) else: break file_structure = '\n'.join(lines) create_file_structure(repo, file_structure) if __name__ == '__main__': main()
修复效果
运行修复后的代码,输入预期的文件结构,将生成正确的目录层级:
dir1/(包含.gitkeep)dir2/(包含.gitkeep)file1file2
dir3/(包含.gitkeep)file3file4dir4/(包含.gitkeep)file5
内容的提问来源于stack exchange,提问作者OrbitalMartian
相关产品推荐
相关产品推荐

