接上一篇本地圖片自動上傳以及替換路徑,繼續解決使用API發佈博客的版本控制問題。
當本地文檔修訂更新之後,如何發現版本更新,並自動發佈到博客呢?個人解決方案是使用同一的git版本控制系統來實現版本監控。經過對比上一次發佈的版本(commit版本),以及當前的版本(commit版本),發現兩個版本間的文件差異,提供自動新建博文,或者更新博文的依據。python
# encoding=utf-8 #!/bin/sh python3 import git #gitpython import inspect class RepoScanner(): def __init__(self, repopath, branch): self._root = repopath self._branch = branch try: self._repo = git.Repo(self._root) except git.exc.NoSuchPathError as error: #若是沒有git庫,先建立git庫 self._repo = git.Repo.init(path=self._root) except: raise Exception('Fail to open git repo at: %s' % (repopath)) heads = self._repo.heads gotbranch = False for head in heads: if head.name == branch: gotbranch = True self.head = head break if not gotbranch: print('create branch:', branch) self.head = self._repo.create_head(branch) def scanFiles(self, begin_hexsha=None): all_commits = list(self._repo.iter_commits(self.head.name)) begin_commit = None for commit in all_commits: if commit.hexsha == begin_hexsha: begin_commit = commit break sourceFiles = {} if begin_commit: beginIndexFile = git.IndexFile.from_tree(self._repo, begin_commit) for (path, stage), entry in beginIndexFile.entries.items(): sourceFiles[path] = entry.hexsha indexFile = git.IndexFile.from_tree(self._repo, self.head.commit) files = {} for (path, stage), entry in indexFile.entries.items(): if path in sourceFiles: if entry.hexsha != sourceFiles[path]: files[path] = { "hexsha": entry.hexsha, "from_hexsha": sourceFiles[path], "change": 'modify'} else: files[path] = { "hexsha": entry.hexsha, "change": 'new'} return { "head": self.head.commit.hexsha, "files": files }