Blob: blob.py
Blob id: a950dae0239a3c0602f4a7c71ce48a54547c1e70
Size: 1.7 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 | import pygit2 as git from highlight import highlight_code # retrieves a blob content for given ref and path def get_blob(repo_path, ref="HEAD", blob_path=""): repo = git.Repository(repo_path) obj = repo.revparse_single(ref) if obj.type == git.GIT_OBJECT_COMMIT: tree = obj.tree elif obj.type == git.GIT_OBJECT_TREE: tree = obj else: commit = obj.peel(git.GIT_OBJECT_COMMIT) tree = commit.tree # traverse to the blob path # TODO: improve the code, just quick and dirty if blob_path: parts = blob_path.rstrip('/').split('/') for part in parts: found = False for entry in tree: if entry.name == part: if entry.type == git.GIT_OBJECT_BLOB: blob = repo.get(entry.id) content = blob.data.decode('utf-8', errors='replace') result = { 'name': entry.name, 'id': str(entry.id), 'path': blob_path, 'size': blob.size, 'is_binary': blob.is_binary, 'content': content } # add highlighted content if not blob.is_binary: result['highlighted'] = highlight_code(content, entry.name) return result elif entry.type == git.GIT_OBJECT_TREE: tree = repo.get(entry.id) found = True break if not found: return None # path not found return None # blob not found |