-
-
Notifications
You must be signed in to change notification settings - Fork 9
Expand file tree
/
Copy pathmake-archive.py
More file actions
executable file
·228 lines (180 loc) · 7.09 KB
/
make-archive.py
File metadata and controls
executable file
·228 lines (180 loc) · 7.09 KB
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
222
223
224
225
226
227
228
#!/usr/bin/env python3
# Mostly written by Claude.ai.
import os
import sys
import glob
import shutil
import argparse
import tempfile
import subprocess
import time
from pathlib import Path
import unittest
from typing import List, Optional
def main() -> None:
"""Main function to process command line arguments and create release archives."""
args = parse_arguments()
validate_arguments(args)
if args.working_directory:
os.chdir(args.working_directory)
archive_name = get_archive_name(
args.executable_name, args.target, args.archive_name
)
archive_file = create_archive_path(archive_name)
executable_name = get_executable_name(args.executable_name)
found_files = find_executable(executable_name, args.target)
found_files.extend(gather_additional_files(args.extra_files, args.changes_file))
create_archive(archive_file, found_files, executable_name)
write_github_output(archive_file)
def parse_arguments() -> argparse.Namespace:
"""Parse and return command line arguments."""
parser = argparse.ArgumentParser()
parser.add_argument("--executable-name", required=True)
parser.add_argument("--target")
parser.add_argument("--archive-name")
parser.add_argument("--changes-file", default="Changes.md")
parser.add_argument("--extra-files")
parser.add_argument("--working-directory")
return parser.parse_args()
def validate_arguments(args: argparse.Namespace) -> None:
"""Validate command line arguments."""
if not args.executable_name:
sys.exit("You must provide an executable-name when using this action.")
if not (args.target or args.archive_name):
sys.exit(
"You must provide either a target or archive-name when using this action."
)
if not args.extra_files:
if args.changes_file and not Path(args.changes_file).is_file():
sys.exit(f"Changes file '{args.changes_file}' does not exist.")
def get_archive_name(
executable_name: str, target: Optional[str], archive_name: Optional[str]
) -> str:
"""Generate the archive name based on inputs."""
if archive_name:
return archive_name
return (
f"{executable_name}-{target_to_archive_name(target)}"
if target
else executable_name
)
def create_archive_path(archive_name: str) -> str:
"""Create and return the full archive path with appropriate extension."""
archive_extension = (
".zip" if os.environ.get("RUNNER_OS") == "Windows" else ".tar.gz"
)
return str(Path.cwd() / f"{archive_name}{archive_extension}")
def get_executable_name(base_name: str) -> str:
"""Get the platform-appropriate executable name."""
return f"{base_name}.exe" if os.environ.get("RUNNER_OS") == "Windows" else base_name
def find_executable(executable_name: str, target: Optional[str]) -> List[str]:
"""Find the executable in possible locations."""
look_for = [
Path("target") / target / "release" / executable_name if target else None,
Path("target") / "release" / executable_name,
]
look_for = [str(p) for p in look_for if p]
for file in look_for:
if Path(file).is_file():
print(f"Found executable at {file}")
return [file]
msg = "Could not find executable in any of:\n"
msg += "\n".join(f" {f}" for f in look_for)
sys.exit(msg)
def gather_additional_files(
extra_files: Optional[str], changes_file: Optional[str]
) -> List[str]:
"""Gather additional files to include in the archive."""
if extra_files:
return list(filter(None, map(str.strip, extra_files.splitlines())))
files = []
if changes_file:
files.append(changes_file)
files.extend(glob.glob("README*"))
return files
def create_archive(
archive_file: str, found_files: List[str], executable_name: str
) -> None:
"""Create the archive with the specified files."""
td = None
try:
td = tempfile.mkdtemp()
for file in found_files:
shutil.copy2(file, td)
# Set executable permissions
exec_path = Path(td) / executable_name
if exec_path.exists():
exec_path.chmod(0o755)
# Create archive
original_dir = os.getcwd()
try:
os.chdir(td)
if os.environ.get("RUNNER_OS") == "Windows":
cmd = ["7z", "a", archive_file] + glob.glob("*")
result = subprocess.run(cmd, capture_output=True, text=True)
if result.returncode != 0:
sys.exit(f"Failed to create archive. Error: {result.stderr}")
else:
cmd = ["tar", "czf", archive_file] + glob.glob("*")
result = subprocess.run(cmd, capture_output=True, text=True)
if result.returncode != 0:
sys.exit(f"Failed to create archive. Error: {result.stderr}")
print(f"Created archive at {archive_file}")
finally:
os.chdir(original_dir)
finally:
if td:
# Retry cleanup a few times on Windows
for _ in range(3):
try:
shutil.rmtree(td, ignore_errors=True)
break
except Exception:
if os.environ.get("RUNNER_OS") == "Windows":
time.sleep(1)
else:
raise
def write_github_output(archive_file: str) -> None:
"""Write the archive information to GitHub Actions output."""
output_file = os.environ.get("GITHUB_OUTPUT", os.devnull)
if not output_file:
sys.exit("GITHUB_OUTPUT environment variable not set.")
with open(output_file, "a") as f:
print(f"archive-file={Path(archive_file).name}", file=f)
def target_to_archive_name(target: str) -> str:
"""Convert a Rust target triple to an archive name segment."""
parts = target.split("-")
cpu = parts.pop(0).replace("aarch64", "arm64")
if parts[0] in ("apple", "pc", "sun", "unknown"):
parts.pop(0)
os_name = parts.pop(0)
# If there's more it's something like "-gnu" or "-msvc"
if parts:
os_name = f"{os_name}-{parts[0]}"
os_mappings = {
"darwin": "macOS",
"freebsd": "FreeBSD",
"ios": "iOS",
"netbsd": "NetBSD",
"openbsd": "OpenBSD",
}
os_name = os_mappings.get(os_name, os_name.capitalize())
return f"{os_name}-{cpu}"
class TestTargetToArchiveName(unittest.TestCase):
"""Test cases for target_to_archive_name function."""
def test_target_conversion(self):
tests = {
"aarch64-apple-darwin": "macOS-arm64",
"x86_64-apple-darwin": "macOS-x86_64",
"x86_64-pc-windows-msvc": "Windows-msvc-x86_64",
"i686-unknown-linux-gnu": "Linux-gnu-i686",
# ... other test cases ...
}
for target, expected in tests.items():
with self.subTest(target=target):
self.assertEqual(target_to_archive_name(target), expected)
if __name__ == "__main__":
if len(os.sys.argv) > 1 and os.sys.argv[1] == "--test":
unittest.main(argv=["unittest"])
else:
main()