def tree_to_github( tree: git.Tree, target_subdir: str, gh_repo: GithubRepo ) -> Dict[str, InputGitTreeElement]: """Extrae los contenidos de un commit de Git en formato Tree de Github. Returns: un diccionario donde las claves son rutas en el repo, y los valores el InputGitTreeElement que los modifica. """ odb = tree.repo.odb target_subdir = target_subdir.rstrip("/") + "/" entries = traverse_tree_recursive(odb, tree.binsha, target_subdir) contents = {} for sha, mode, path in entries: # TODO: get exclusion list from repos.yml if path.endswith("README.md"): continue fileobj = io.BytesIO() stream_copy(odb.stream(sha), fileobj) fileobj.seek(0) try: text = fileobj.read().decode("utf-8") input_elem = InputGitTreeElement(path, f"{mode:o}", "blob", text) except UnicodeDecodeError: # POST /trees solo permite texto, hay que crear un blob para binario. fileobj.seek(0) data = base64.b64encode(fileobj.read()) blob = gh_repo.create_git_blob(data.decode("ascii"), "base64") input_elem = InputGitTreeElement(path, f"{mode:o}", "blob", sha=blob.sha) finally: contents[path] = input_elem return contents
def push_files(self, repo: Repository, files_list, push_msg, branch='master', dir=''): ''' Push a list of files to a specific directory in a specific branch of a specific repository. ''' if dir != '': dir += '/' branch_ref = repo.get_git_ref('heads/' + branch) branch_sha = branch_ref.object.sha master_sha = repo.get_git_ref('heads/' + branch).object.sha base_tree = repo.get_git_tree(master_sha, recursive=True) element_list = list() for entry in files_list: with open(entry, 'rb') as input_file: data = input_file.read() if entry.endswith('.pth'): data = base64.b64encode(data) block = data.decode("utf-8") blob = repo.create_git_blob(block, "base64") element = InputGitTreeElement(dir + os.path.basename(entry), '100644', 'blob', sha=blob.sha) element_list.append(element) if len(element_list) != 0: tree = repo.create_git_tree(element_list, base_tree) parent = repo.get_git_commit(branch_sha) commit = repo.create_git_commit(push_msg, tree, [parent]) branch_ref.edit(commit.sha) self.log_commit('commit.txt', files_list) print('\t Done.', end=' ') return len(element_list)