从Git提交获取数据并将其放入YAMLGitlab

问题描述

标题所示,我想读取git commit的信息(用户ID,消息)并将其放入yaml文件,该文件将在我当前的项目文件夹中创建,并将对yaml文件的更改推送到git中。我认为我必须使用GITLAB API,但不确定如何。

听起来很复杂,但是其想法是使用每次提交的信息保存yaml文件,这些文件将被添加到另一个更改列表中。

到目前为止,这是我的代码,我刚刚实现了input选项,但是我希望它自动填充。 有人知道吗?

import yaml

data = dict(
    gittag='',gittagdate='',userID=str(input('autor: ')),change_id=str(input('change_id: ')),message=str(input('description: ')),)
with open('test.yml','w') as outfile:
    yaml.dump(data,outfile,default_flow_style=False)

解决方法

您可以像这样直接使用Gitlab commits API:

import yaml
import requests

access_token = "YOUR_ACCESS_TOKEN"
gitlab_host = "your.gitlab.host" #gitlab.com or your.host for gitlab CE
project_id = "24" #change this with your project id

r = requests.get(f"https://{gitlab_host}/api/v4/projects/{project_id}/repository/commits",params = {
        "per_page": 100
    },headers= {
        "Authorization": f"Bearer {access_token}"
})
commits = r.json()

print(len(commits))
with open('commits.yml','w') as outfile:
    yaml.dump(commits,outfile,default_flow_style=False)

这将在yaml文件中写入提交列表:

- author_email: user@acme.com
  author_name: user123
  authored_date: '2020-09-16T15:03:20.000+02:00'
  committed_date: '2020-09-16T15:03:20.000+02:00'
  committer_email: user@acme.com
  committer_name: user123
  created_at: '2020-09-16T15:03:20.000+02:00'
  id: b076af18c1db5b15714cd78714a674d4cc97605f
  message: 'version 1.5.1

    '
  parent_ids:
  - 53aa56f53aadf3eb709d799cdda2ad852c50aa3a
  short_id: b076af17
  title: version 1.5.1
- .......

您还需要create a personal access token in Gitlab并获得project id

上面的代码为您提供了最后100次提交,为了分页显示结果,您需要检查Link标头并进行解析。但是有this python Gitlab library个文档here

为您做到了

以下内容将遍历所有提交并创建yaml文件:

import yaml
import gitlab

gl = gitlab.Gitlab('https://your.gitlab.host',private_token='YOUR_ACCESS_TOKEN')
commits_obj = gl.projects.get(24).commits.list(all=True)
commits = [t.attributes for t in commits_obj]
print(len(commits))
with open('commits.yml',default_flow_style=False)

也结帐this

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...