由于Python脚本和项目没有放在一个目录下面,所以每次在执行git相关命令之前都需要先cd到目标项目目录下。而分别执行git命令的时候使用subprocess.getstatusoutput()来执行,方便获取标准化输出的结果。这里之所以不使用os.system来执行命令,是因为os.system运行命令的返回值里面包括两个部分,第一部分是命令的结果输出,第二部分是结果是否成功的标识符。
例如执行os.system("git branch | sed -n '/* /s///p'")会返回如下内容:
feature/ST-247 0第一行是我们获取到的分支名,第二行是成功的标识符,0表示命令没有任何问题。
所以我考虑使用subprocess.getstatusoutput来运行命令,这个函数会分别返回结果标识和输出,方便得到想要的执行输出结果。
虽然代码还可以进一步优化,但是已经能满足我的需求了,运行这个脚本就能得到如下的输出结果:
[~Harry] *Changes made has been committed to feature/ST-247* - https://git.xxxxx.com/someproject/subname/-/commit/d21033057677e6d49d9cea07c64c49e35529545dx *Details* - Remove some invalid logic Please check it if you have free time, thanks.如果改写成面向对象的方式会更好,调用更简单,传递参数也更少,采用Python3语法编写的代码如下所示:
#coding=utf-8 #!/usr/bin/python import os import subprocess import random class CommitComment: def __init__(self, project_path: str, reviewers: list, thanks_words: list): self.project_path = project_path self.reviewers = reviewers self.thanks_words = thanks_words # use subprocess to get the current branch name from output def get_branch_name(self) -> str: os.chdir(self.project_path) status, branch_name = subprocess.getstatusoutput("git branch | sed -n '/\* /s///p'") return branch_name # use subprocess to get the latest commit message from git log def get_latest_git_log(self) -> str: os.chdir(self.project_path) status, log_info = subprocess.getstatusoutput("git log --pretty=format:\"%s\" -1") return log_info # use subprocess to get the latest commit id from git log def get_latest_commit_id(self) -> str: os.chdir(self.project_path) status, commit_id = subprocess.getstatusoutput("git rev-parse HEAD") return commit_id def get_reviewer_by_random(self) -> str: return random.choice(self.reviewers) def get_thanks_words_by_random(self) -> str: return random.choice(self.thanks_words) def create_comment(self): print(self.get_reviewer_by_random()) print("*Changes has been committed to " + self.get_branch_name() + "*") print("- https://git.xxxx.com/MyProject/ProjectName/-/commit/" + self.get_latest_commit_id()) print("*Details*") print("-" + self.get_latest_git_log()) print(self.get_thanks_words_by_random()) thanks_words = [ 'Review it please, thanks.', 'Actually, I am glad to see you have time to review it, thanks a lot.', 'Please check it if you have free time, thanks.', 'Check it please.' 'Waiting for your code review, thank you.' ] reviewers = [ '[~Harry]', '[~Tom]' ] comment = CommitComment('/Users/tony/www/autoWork', reviewers, thanks_words) comment.create_comment() # will print out the complete commentthanks_words列表可以在增加多一点,这样随机获取之下重复的概率会更少。当然最后一段也可以自己每次diy,毕竟感谢要发自内心的最好。
这种简化工作流的脚本本质是减少重复性劳动,特别是一天完成了很多个任务的时候。但是反思本身是无法被简化的,不做工作的奴隶,而是工作的主人。
抛砖引玉,希望对自己和未来的自己也是一个还原镜像。