使用Git Action自动初始化Gitalk评论
  前一篇
因为每个页面的Gitalk评论都需要初始化一次才能正常评论,因此可以借助git action在提交时自动进行初始化
直接贴代码
# CI文件
gitalkcomment.yml
name: Execute python script to create github issue
on: [push]
jobs:
  build:
    runs-on: ubuntu-latest
    steps:
      - name: checkout actions
        uses: actions/checkout@v1        
      - name: Set up Python 3.7
        uses: actions/setup-python@v1
        with:
          python-version: 3.7
      - name: Create github issue
        env:
            GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
        run: |
          pip install requests
          cd tools/自动创建评论
          GITHUB_TOKEN=${GITHUB_TOKEN} python GtalkComment.py
 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
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
# python脚本文件
import requests
import subprocess
import os
import time
def get_issues_titles(repo_owner, repo_name, token):
    url = f"https://api.github.com/repos/{repo_owner}/{repo_name}/issues"
    headers = {
        'Authorization': f'token {token}',
        'Accept': 'application/vnd.github.v3+json'
    }
    titles = []
    page = 1
    while True:
        response = requests.get(url, headers=headers, params={'page': page, 'per_page': 100})
        if response.status_code != 200:
            print(f"Error: Unable to fetch issues (Status code: {response.status_code})")
            break
        issues = response.json()
        if not issues:
            break
        for issue in issues:
            titles.append(issue['title'])
        
        page += 1
    return titles
def create_github_issue(repo_owner, repo_name, token, issue_title, issue_body="", labels=[]):
    url = f"https://api.github.com/repos/{repo_owner}/{repo_name}/issues"
    headers = {
        'Authorization': f'token {token}',
        'Accept': 'application/vnd.github.v3+json'
    }
    payload = {
        'title': issue_title,
        'body': issue_body,
        'labels': labels  # 标签名称列表,如 ['bug', 'enhancement']
    }
    response = requests.post(url, headers=headers, json=payload)
    if response.status_code == 201:
        print(f"Issue {issue_title} created successfully: {response.json()['html_url']}")
    else:
        print(f"Failed to create issue (Status code: {response.status_code})")
        print(f"Error message: {response.text}")
def find_md_files(directory):
    md_files = []  # 存储所有找到的 .md 文件路径
    # 使用 os.walk 遍历指定目录及其子目录
    for root, dirs, files in os.walk(directory):
        for file in files:
            if file.endswith('.md'):  # 找到后缀为 .md 的文件
                file_path = os.path.join(root, file)
                md_files.append(file_path)
    return md_files
def check_is_file_suffix_is_md(file_list):
    md_list = []
    for file_name in file_list:
        if file_name.endswith('.md'):
            md_list += [file_name]
    return md_list
def Get_file_title(file_name):
    # 获取文件标题
    with open(file_name, 'r', encoding='utf-8') as f:
        lines = f.readlines()
        for line in lines:
            if line.startswith('title:'):
                return line.strip('title:').strip()
def Get_file_permalink(file_name):
    # 获取文件链接
    with open(file_name, 'r', encoding='utf-8') as f:
        lines = f.readlines()
        for line in lines:
            if line.startswith('permalink:'):
                return line.strip('permalink:').strip()
def CreateNewCommentIssue(repo_owner, repo_name, token):
    # 获取前一次提交的文件列表
    file_list = find_md_files("../../beiklive/")
    # 筛选出md文件
    md_list = check_is_file_suffix_is_md(file_list)
    # 获取已经创建的issue列表
    issue_list = get_issues_titles(repo_owner, repo_name, token)
    for file_name in md_list:
        print("------------------------------------")
        title = Get_file_title(file_name)
        # print(title)
        if None != title:
            search_str = '「评论」' + title
            if search_str in issue_list:
                print(f"Issue already exists for {title}")
                pass
            else:
                print(f"Issue not exists for {title}")
                permalink = Get_file_permalink(file_name)
                print(permalink)
                issue_title = search_str    # 新Issue的标题
                issue_body = f"页面: https://beiklive.github.io/vuepresswiki{permalink}"  # 新Issue的内容(可选)
                labels = ["Comment", "Gitalk", permalink]    # 要添加的标签列表
                create_github_issue(repo_owner, repo_name, token, issue_title, issue_body, labels)
        time.sleep(10)
if __name__ == "__main__":
    repo_owner = "beiklive"  # 替换为仓库所有者
    repo_name = "vuepresswiki"    # 替换为仓库名称
    token=os.environ.get('GITHUB_TOKEN') #申请的github访问口令
    CreateNewCommentIssue(repo_owner, repo_name, token);
 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
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
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
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
编辑  (opens new window)
  上次更新: 2024/05/16, 18:48:50