【发布时间】:2013-06-25 14:47:34
【问题描述】:
我正在做一个项目,我需要将来自 GitHub 项目的 git log –p 信息放入数据库中。首先,我将git log –p 放入 .txt 文件中,并使用 Python 对其进行扫描。 (Python 对我来说有点新)。
git log –p 的结构如下所示:
commit 5f0883381054b796b643dcff974435633eed8a79
Merge: 4e1d5f7 8ffg9do
Author: name <email>
Date: date of commit
"comment of the commit"
diff --…
index …
--- …
+++ …
@@ …
-…
+…
…
diff --…
index …
--- …
+++ …
@@ …
commit 737044517f403c1080886a674845fad9c42d6bc0
Author: name <email>
Date: date of commit
completion: …
Signed-off-by: name <email>
Signed-off-by: name <email>
commit 6bf931a54fd66826f28d2808b7ad822024764d41
Merge: 727a46b 3646b1a
Author: name <email>
Date: date of commit
Merge branch …
* …:
completion: …
completion: …
completion: …
commit c3c327deeaf018e727a27f5ae88e140ff7a48595
Author: name <email>
Date: date
目前,我很容易使用正则表达式获得提交、合并、作者、日期线。
for line in source:
commit = re.findall('^commit.{41}',line)
merge = re.findall('^Merge:.*',line)
author = re.findall('^Author:.*',line)
date = re.findall('^Date:.*',line)
signed = re.findall('Signed-off-by:.*', line)
diffBlock = re.findall("^['diff''index'+-@].*", line) # bad way, I miss few lines
for commitLine in commit:
print (commitLine)
#post into DB
for mergeLine in merge:
print (mergeLine)
#post into DB
.
.
.
但删除git log -p 的好方法是每次找到提交行时都进行拆分。然后在这些不同的块上工作。
我还需要从提交中获取注释块和所有“差异”块,它们位于多行上。
当我想获取要放入变量的 2 次提交之间的整个文本时,我遇到了一个问题……使用正则表达式将是 ^commit.{41}(.*?)^commit.{41}(我将不得不考虑 git 的最后一次提交日志,因为它不会以提交行结束)。
稍后我需要对diffBlock 使用相同的方法。
我已经尝试了很多东西……例如像这样,但它不能正常工作。它找到了几个集团,但不是全部......(这可能是"\n"的问题,我不知道)
content = open("catchCommitBlock.txt","rt", encoding="ISO-8859-1").read() #testing file
commitBlock = re.compile("^commit.{41}(.*?)^commit.{41}",re.DOTALL|re.M)
i=0
while i < len (commitBlock.findall(content)):
print (commitBlock.findall(content)[i])
i+=1
你知道我该如何解决这个问题吗?
附:如果我有什么不清楚的地方,请告诉我^^
【问题讨论】:
-
确实有效。 2个问题: - 拆分隐藏用于拆分的字符串 - 因为现在每行有一个字符,所以越来越难得到一行:/
标签: python regex text python-3.x