Jenkins_Pipeline_Library/resources/uploadApk.py
2026-05-09 11:45:40 +08:00

115 lines
3.6 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import argparse
import os
import sys
from pathlib import Path
DEFAULT_TOKEN_FILE = Path(r"d:\Github\devops\access_token.txt")
DEFAULT_TIMEOUT = 300
def build_parser() -> argparse.ArgumentParser:
parser = argparse.ArgumentParser(description="Upload APK to the Byway server.")
parser.add_argument("--upload-url", required=True, help="APK upload endpoint URL.")
parser.add_argument("--apk-path", required=True, type=Path, help="Path to the APK file.")
parser.add_argument("--env", dest="upload_env", required=True, help="Environment value sent as the env form field.")
parser.add_argument(
"--package-type",
dest="package_type",
required=True,
choices=["with_sdk", "without_sdk"],
help="Package type sent as the packageType form field.",
)
parser.add_argument("--version", default="", help="Optional version form field.")
parser.add_argument("--token", default="", help="Upload token. Defaults to APK_UPLOAD_TOKEN or token file.")
parser.add_argument(
"--token-file",
type=Path,
default=DEFAULT_TOKEN_FILE,
help="Fallback file path used when no token argument or environment variable is provided.",
)
parser.add_argument("--timeout", type=int, default=DEFAULT_TIMEOUT, help="Request timeout in seconds.")
return parser
def load_upload_token(cli_token: str, token_file: Path) -> str:
direct_token = cli_token.strip()
if direct_token:
return direct_token
env_token = os.getenv("APK_UPLOAD_TOKEN", "").strip()
if env_token:
return env_token
if token_file.exists():
file_token = token_file.read_text(encoding="utf-8").strip()
if file_token:
return file_token
raise ValueError(
"未找到上传 token。请通过 --token、环境变量 APK_UPLOAD_TOKEN或 token 文件提供 token。"
)
def main(argv: list[str] | None = None) -> int:
parser = build_parser()
args = parser.parse_args(argv)
try:
import requests
except ImportError:
sys.stderr.write("Python package 'requests' is not installed.\n")
return 2
try:
upload_token = load_upload_token(args.token, args.token_file)
except ValueError as exc:
sys.stderr.write(f"{exc}\n")
return 2
if not args.apk_path.exists():
sys.stderr.write(f"APK 文件不存在: {args.apk_path}\n")
return 2
form_data = {
"env": args.upload_env,
"packageType": args.package_type,
}
if args.version:
form_data["version"] = args.version
print(f"Uploading {args.apk_path.name} to {args.upload_url}")
print(
f" env={args.upload_env} packageType={args.package_type} version={args.version or '<none>'}"
)
try:
with args.apk_path.open("rb") as apk_file:
response = requests.post(
args.upload_url,
headers={"X-Apk-Upload-Token": upload_token},
data=form_data,
files={
"file": (
args.apk_path.name,
apk_file,
"application/vnd.android.package-archive",
)
},
timeout=args.timeout,
)
except requests.RequestException as exc:
sys.stderr.write(f"APK upload request failed: {exc}\n")
return 1
print("status_code:", response.status_code)
try:
print(response.json())
except ValueError:
print(response.text)
return 0 if response.ok else 1
if __name__ == "__main__":
sys.exit(main())