summarylogtreecommitdiffstats
path: root/pkgbuild_helper.py
blob: 359e3279b386c135894a1ff76a704403f1d17e78 (plain)
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
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
#!/usr/bin/env python3

import os
import subprocess
import re
import sys
import json
import argparse

PKGBUILD_FILE = "PKGBUILD"
SRCINFO_FILE = ".SRCINFO"
GITHUB_API_URL = "https://api.github.com/repos/pnpm/pnpm/releases/latest"

def fetch_latest_version():
    """获取 GitHub 最新版本号"""
    try:
        result = subprocess.run(
            ["curl", "-s", GITHUB_API_URL],
            stdout=subprocess.PIPE,
            stderr=subprocess.PIPE,
            text=True
        )

        if result.returncode != 0:
            print(f"Error fetching latest version: {result.stderr}")
            return None

        data = json.loads(result.stdout)
        version = data.get("tag_name", "").lstrip("v")  # 去除可能的 "v" 前缀
        return version
    except Exception as e:
        print(f"Unexpected error fetching latest version: {e}")
        return None

def get_current_version():
    """从 PKGBUILD 中获取当前的版本号"""
    if not os.path.exists(PKGBUILD_FILE):
        print(f"Error: {PKGBUILD_FILE} not found.")
        return None

    try:
        with open(PKGBUILD_FILE, "r") as f:
            content = f.read()

        # 查找 pkgver
        match = re.search(r"^pkgver=(\S+)", content, re.MULTILINE)
        if match:
            return match.group(1)
        else:
            print("Error: pkgver not found in PKGBUILD.")
            return None
    except Exception as e:
        print(f"Unexpected error reading PKGBUILD: {e}")
        return None

def update_pkgbuild(version):
    """更新 PKGBUILD 文件中的 pkgver, pkgrel"""
    if not os.path.exists(PKGBUILD_FILE):
        print(f"Error: {PKGBUILD_FILE} not found.")
        return 1

    try:
        # 读取 PKGBUILD 文件内容
        with open(PKGBUILD_FILE, "r") as f:
            content = f.read()

        # 获取当前版本号
        current_version = get_current_version()
        if current_version == version:
            print("No update needed. Version is already up-to-date.")
            return False  # 版本没有更新

        # 更新 pkgver
        content = re.sub(
            r"^pkgver=.*",
            f"pkgver={version}",
            content,
            flags=re.MULTILINE
        )

        # 更新 pkgrel 为 1
        content = re.sub(
            r"^pkgrel=.*",
            "pkgrel=1",
            content,
            flags=re.MULTILINE
        )

        # 写回更新后的 PKGBUILD 文件
        with open(PKGBUILD_FILE, "w") as f:
            f.write(content)

        print(f"PKGBUILD updated successfully with version {version}.")
        return True  # 返回 True 表示版本已更新
    except Exception as e:
        print(f"Unexpected error updating PKGBUILD: {e}")
        return False

def update_sums():
    """更新 PKGBUILD 文件中的 sums 校验和"""
    if not os.path.exists(PKGBUILD_FILE):
        print(f"Error: {PKGBUILD_FILE} not found.")
        return 1

    try:
        # 读取 PKGBUILD 文件内容
        with open(PKGBUILD_FILE, "r") as f:
            content = f.read()

        # 运行 makepkg -g 来生成新的校验和
        result = subprocess.run(
            ["makepkg", "-g"],
            stdout=subprocess.PIPE,
            stderr=subprocess.PIPE,
            text=True
        )

        if result.returncode != 0:
            print(f"Error generating sums: {result.stderr}")
            return 1

        new_sums = result.stdout.strip()
        if not new_sums:
            print("Error: No sums generated.")
            return 1

        # 清除原有的 sums 行(支持所有架构和多行)
        content = re.sub(
            r"^(\w+sums(\w+)?=)\('\w+'\)$\n?",
            "",
            content,
            flags=re.MULTILINE
        )

        # 插入新的校验和(替换所有架构的 sums)
        content += new_sums

        # 写回更新后的 PKGBUILD 文件
        with open(PKGBUILD_FILE, "w") as f:
            f.write(content)

        print("Sums updated successfully.")
        return 0

    except Exception as e:
        print(f"Unexpected error updating sums: {e}")
        return 1

def generate_srcinfo():
    """生成 .SRCINFO 文件"""
    try:
        # 生成 .SRCINFO 文件
        result = subprocess.run(
            ["makepkg", "--printsrcinfo"],
            stdout=subprocess.PIPE,
            stderr=subprocess.PIPE,
            text=True
        )

        if result.returncode != 0:
            print(f"Error generating .SRCINFO: {result.stderr}")
            return 1

        # 将 .SRCINFO 输出保存到文件
        with open(SRCINFO_FILE, "w") as f:
            f.write(result.stdout)

        print(f"{SRCINFO_FILE} generated successfully.")
        return 0

    except Exception as e:
        print(f"Unexpected error generating .SRCINFO: {e}")
        return 1

def main():
    parser = argparse.ArgumentParser(description="Update PKGBUILD, sums or generate .SRCINFO.")
    
    # 添加命令行选项
    parser.add_argument(
        "--version", action="store_true", help="Fetch the latest version and update PKGBUILD"
    )
    parser.add_argument(
        "--sums", action="store_true", help="Update the sums in PKGBUILD"
    )
    parser.add_argument(
        "--info", action="store_true", help="Generate the .SRCINFO file"
    )

    args = parser.parse_args()

    # 如果没有任何参数,则执行所有任务
    if not any(vars(args).values()):
        args.version = args.sums = args.info = True

    # 如果更新版本,则更新 pkgver
    version_updated = False
    if args.version:
        latest_version = fetch_latest_version()
        if not latest_version:
            print("Failed to fetch the latest version.")
            return 1

        print(f"Latest version: {latest_version}")
        version_updated = update_pkgbuild(latest_version)

    # 如果版本已更新或需要单独更新 sums
    if args.sums:
        # 只在版本更新时才更新 sums
        if version_updated:
            update_sums()
        elif not args.version:  # 如果是单独执行 sums,则直接更新 sums
            update_sums()

    # 如果需要生成 .SRCINFO 文件
    if args.info:
        generate_srcinfo()

    return 0

if __name__ == "__main__":
    sys.exit(main())