Skip to content

Commit bf483b6

Browse files
committed
Enhance clone speed by caching toolchain and tarballs
- Replace Repo tool with custom python implementation - Cache static toolchains such as clang and rust uniquely in Github Releases to bypass cache restrictions - Use pre-cached toochains and tarballs to maximise setup speed and reduce clone and build time - Add a workflow to pre-cache toolchains
1 parent fa13f3e commit bf483b6

4 files changed

Lines changed: 400 additions & 40 deletions

File tree

Lines changed: 12 additions & 36 deletions
Original file line numberDiff line numberDiff line change
@@ -42,6 +42,9 @@ inputs:
4242
required: false
4343
type: boolean
4444
default: false
45+
github_token:
46+
description: 'GitHub Token'
47+
required: true
4548

4649
outputs:
4750
kernel_version:
@@ -298,6 +301,8 @@ runs:
298301
run: |
299302
set -euo pipefail
300303
CONFIG="$OP_MODEL"
304+
echo "Creating folder for configuration: $CONFIG"
305+
mkdir -p "$CONFIG"
301306
echo "CONFIG=$CONFIG" >> "$GITHUB_ENV"
302307
REPO="/usr/local/bin/repo"
303308
if [ ! -x "$REPO" ]; then
@@ -314,42 +319,13 @@ runs:
314319
git config --global core.fsmonitor true
315320
git config --global pack.sparse true
316321
317-
- name: Initialize and Sync Kernel Source
318-
shell: bash
319-
run: |
320-
set -euo pipefail
321-
echo "::group::Initialize kernel source"
322-
echo "Creating folder for configuration: $CONFIG"
323-
mkdir -p "$CONFIG"
324-
cd "$CONFIG"
325-
echo "Initializing and syncing kernel source..."
326-
327-
if [[ "$OP_MANIFEST" == https://* ]]; then
328-
mkdir -p .repo/manifests
329-
curl --fail --show-error --location --proto '=https' "$OP_MANIFEST" -o .repo/manifests/temp_manifest.xml
330-
"$REPO" init -u https://github.com/OnePlusOSS/kernel_manifest.git -b "oneplus/sm8650" -m temp_manifest.xml --repo-rev=v2.16 --depth=1 --no-clone-bundle --no-tags
331-
elif [[ "$OP_BRANCH" == wild/* ]]; then
332-
mkdir -p .repo/manifests
333-
cp "../manifests/$(echo "$OP_OS_VERSION" | tr '[:upper:]' '[:lower:]')/$OP_MANIFEST" .repo/manifests/temp_manifest.xml
334-
"$REPO" init -u https://github.com/OnePlusOSS/kernel_manifest.git -b "oneplus/sm8650" -m temp_manifest.xml --repo-rev=v2.16 --depth=1 --no-clone-bundle --no-tags
335-
else
336-
"$REPO" init -u https://github.com/OnePlusOSS/kernel_manifest.git -b "$OP_BRANCH" -m "$OP_MANIFEST" --repo-rev=v2.16 --depth=1 --no-clone-bundle --no-tags
337-
fi
338-
339-
"$REPO" --version
340-
success=false
341-
for i in 1 2 3; do
342-
if "$REPO" sync -c --no-clone-bundle --no-tags --optimized-fetch \
343-
-j"$(nproc --all)" --fail-fast; then
344-
success=true
345-
break
346-
fi
347-
echo "⚠️ repo sync attempt $i failed; retrying..."
348-
sleep 30
349-
done
350-
$success || { echo "::error::repo sync failed after 3 attempts"; exit 1; }
351-
echo "✅ Kernel source synced"
352-
echo "::endgroup::"
322+
- name: Sync Kernel Source
323+
id: sync-kernel-source
324+
uses: ./.github/actions/kernel-source-sync
325+
with:
326+
source_location: ${{ env.CONFIG }}
327+
github_token: ${{ inputs.github_token }}
328+
debug: ${{ inputs.debug }}
353329

354330
- name: Set Dir Paths
355331
shell: bash
Lines changed: 229 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,229 @@
1+
name: 'Download and configure Kernel Source code'
2+
3+
inputs:
4+
source_location:
5+
description: 'Folder path to save Kernel source'
6+
required: true
7+
type: string
8+
github_token:
9+
description: 'GitHub Token'
10+
required: true
11+
debug:
12+
description: 'Enable Logs'
13+
required: false
14+
type: boolean
15+
default: false
16+
17+
runs:
18+
using: 'composite'
19+
steps:
20+
- name: Download and Prepare Manifest
21+
shell: bash
22+
working-directory: ${{ inputs.source_location }}
23+
run: |
24+
# Download and Prepare Manifest
25+
if [[ "$OP_MANIFEST" == https://* ]]; then
26+
curl --fail --show-error --location --proto '=https' "$OP_MANIFEST" -o manifest.xml
27+
elif [[ "$OP_BRANCH" == wild/* ]]; then
28+
cp "../manifests/$(echo "$OP_OS_VERSION" | tr '[:upper:]' '[:lower:]')/$OP_MANIFEST" manifest.xml
29+
else
30+
curl --fail --show-error --location --proto '=https' "https://raw.githubusercontent.com/OnePlusOSS/kernel_manifest/refs/heads/$OP_BRANCH/$OP_MANIFEST" -o manifest.xml
31+
fi
32+
33+
- name: Download Manifest Archives
34+
shell: python
35+
env:
36+
PYTHONUNBUFFERED: "1"
37+
GITHUB_TOKEN: ${{ inputs.github_token }}
38+
DEBUG: ${{ inputs.debug }}
39+
working-directory: ${{ inputs.source_location }}
40+
run: |
41+
# Download Manifest Archives
42+
import xml.etree.ElementTree as ET
43+
import subprocess
44+
import os, shutil
45+
import time
46+
import glob
47+
from concurrent.futures import ThreadPoolExecutor
48+
import requests
49+
50+
MAX_WORKERS = (os.cpu_count() or 2) * 4
51+
TARGET_REPO = "${{ github.repository }}"
52+
TOOLCHAIN_KEYWORDS = ["clang", "rust"]
53+
DEBUG = os.environ.get("DEBUG", "false").lower() == "true"
54+
aria_quiet_flags = "--quiet --summary-interval=0" if not DEBUG else ""
55+
56+
print("::group::Download Manifest Archives")
57+
58+
def get_release_parts(label, rev):
59+
url = f"https://api.github.com/repos/{TARGET_REPO}/releases"
60+
headers = {
61+
"Authorization": f"token {os.environ['GITHUB_TOKEN']}",
62+
"Accept": "application/vnd.github.v3+json"
63+
}
64+
65+
for attempt in range(3):
66+
try:
67+
response = requests.get(url, headers=headers)
68+
response.raise_for_status()
69+
releases = response.json()
70+
release = next((r for r in releases if r['name'] == "Toolchains Mirror Cache" or r['tag_name'] == "toolchain-cache"), None)
71+
if not release: return []
72+
73+
prefix = f"{label}-{rev}.tar.gz"
74+
return [(a['name'], a['url']) for a in release['assets'] if a['name'].startswith(prefix)]
75+
except Exception as e:
76+
print(f" [RETRY {attempt+1}] API failed: {e}")
77+
time.sleep(2)
78+
return []
79+
80+
def sync_project(task):
81+
name, path, url, strip, rev = task
82+
if path not in ["./", "."]:
83+
os.makedirs(path, exist_ok=True)
84+
85+
headers = (
86+
"-H 'User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36' "
87+
"-H 'Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,*/*;q=0.8' "
88+
"-H 'Accept-Encoding: gzip, deflate, br' "
89+
"-H 'Connection: keep-alive' "
90+
"--tcp-fastopen"
91+
)
92+
93+
print(f"Syncing: {name} -> {path}")
94+
start_time = time.time()
95+
print(f" [PENDING] {name}")
96+
try:
97+
match = next((x for x in TOOLCHAIN_KEYWORDS if x in name.lower()), None)
98+
if match:
99+
label = match
100+
base_filename = f"{label}-{rev}.tar.gz"
101+
102+
asset_data = get_release_parts(label, rev)
103+
104+
if not asset_data:
105+
print(f" [ERROR] No assets found for {base_filename} in release!")
106+
return False
107+
108+
if DEBUG:
109+
print(f" [CACHE] Fetching {label} toolchain: {base_filename}...")
110+
111+
for asset_name, api_url in asset_data:
112+
aria_cmd = (
113+
f"aria2c -x16 -s16 -k1M --file-allocation=none {aria_quiet_flags} "
114+
f"--header='Authorization: token {os.environ['GITHUB_TOKEN']}' "
115+
f"--header='Accept: application/octet-stream' "
116+
f"-o {asset_name} {api_url}"
117+
)
118+
subprocess.run(aria_cmd, shell=True, check=True, capture_output=not DEBUG)
119+
120+
parts = sorted(glob.glob(f"{base_filename}.part*"))
121+
if parts:
122+
if DEBUG:
123+
print(f" [MERGE] Combining {len(parts)} parts for {rev}...")
124+
with open(base_filename, 'wb') as outfile:
125+
for part in parts:
126+
with open(part, 'rb') as infile:
127+
shutil.copyfileobj(infile, outfile)
128+
os.remove(part)
129+
130+
if not os.path.exists(base_filename):
131+
print(f" [ERROR] {base_filename} was not found after download/merge!")
132+
return False
133+
134+
subprocess.run(f"tar -I pigz -x -f {base_filename} -C {path} {strip}", shell=True, check=True)
135+
if os.path.exists(base_filename):
136+
os.remove(base_filename)
137+
else:
138+
cmd = f"curl -LfsS {headers} --retry 5 --connect-timeout 30 '{url}' | tar -I pigz -x -C {path} {strip}"
139+
subprocess.run(cmd, shell=True, check=True)
140+
141+
duration = time.time() - start_time
142+
print(f"Synced {name} successfully! ({duration:.2f}s)")
143+
return True
144+
except subprocess.CalledProcessError as e:
145+
print(f" [ERROR] Command failed for {name}: {e.cmd}")
146+
print(f" Stderr: {e.stderr.decode() if e.stderr else 'No stderr'}")
147+
return False
148+
except Exception as e:
149+
print(f" [ERROR] Failed to sync {name}")
150+
return False
151+
152+
global_start = time.time()
153+
154+
with open('manifest.xml', 'r') as f:
155+
manifest_content = f.read()
156+
157+
root = ET.fromstring(manifest_content)
158+
top_dir = os.getcwd()
159+
160+
remotes = {r.get('name'): r.get('fetch').rstrip('/') for r in root.findall('remote')}
161+
default = root.find('default')
162+
def_remote = default.get('remote') if default is not None else None
163+
def_rev = default.get('revision') if default is not None else None
164+
165+
sync_tasks = []
166+
post_process_data = []
167+
168+
for project in root.findall('project'):
169+
name = project.get('name')
170+
path = project.get('path', name)
171+
remote_name = project.get('remote', def_remote)
172+
rev = project.get('revision', def_rev)
173+
base_url = remotes.get(remote_name)
174+
175+
if not base_url: continue
176+
177+
if "github.com" in base_url:
178+
url = f"{base_url}/{name}/archive/{rev}.tar.gz"
179+
strip = "--strip-components=1"
180+
elif "googlesource.com" in base_url:
181+
url = f"{base_url}/{name}/+archive/{rev}.tar.gz"
182+
strip = ""
183+
elif "git.codelinaro.org" in base_url:
184+
url = f"{base_url}/{name}/-/archive/{rev}.tar.gz"
185+
strip = "--strip-components=1"
186+
else:
187+
continue
188+
189+
sync_tasks.append((name, path, url, strip, rev))
190+
191+
for child in project:
192+
if child.tag in ['linkfile', 'copyfile']:
193+
post_process_data.append((path, child))
194+
195+
if DEBUG:
196+
print(f"Starting parallel sync of {len(sync_tasks)} projects...")
197+
with ThreadPoolExecutor(max_workers=MAX_WORKERS) as executor:
198+
success_list = list(executor.map(sync_project, sync_tasks))
199+
200+
if not all(success_list):
201+
print("::error::One or more projects failed to sync!")
202+
print("::endgroup::")
203+
exit(1)
204+
205+
print("Processing linkfiles and copyfiles...")
206+
for path, child in post_process_data:
207+
src_rel = child.get('src')
208+
dest_rel = child.get('dest')
209+
if not src_rel or not dest_rel: continue
210+
211+
src_path = os.path.join(top_dir, path, src_rel)
212+
dest_path = os.path.join(top_dir, dest_rel)
213+
os.makedirs(os.path.dirname(dest_path), exist_ok=True)
214+
215+
if child.tag == 'linkfile':
216+
if os.path.lexists(dest_path): os.remove(dest_path)
217+
rel_target = os.path.relpath(src_path, os.path.dirname(dest_path))
218+
os.symlink(rel_target, dest_path)
219+
print(f" [Link] {dest_rel} -> {src_rel}")
220+
elif child.tag == 'copyfile':
221+
shutil.copy2(src_path, dest_path)
222+
print(f" [Copy] {dest_rel} from {src_rel}")
223+
224+
225+
total_duration = time.time() - global_start
226+
minutes = int(total_duration // 60)
227+
seconds = total_duration % 60
228+
print(f"Kernel Sync completed in {minutes}m {seconds:.2f}s")
229+
print("::endgroup::")

.github/workflows/build-kernel-release.yml

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -56,11 +56,11 @@ on:
5656
android12-5_10_susfs_branch_or_commit:
5757
description: 'Enter SusFS Branch or commit hash for android12-5.10'
5858
type: string
59-
default: ''
59+
default: ''
6060
android13-5_15_susfs_branch_or_commit:
6161
description: 'Enter SusFS Branch or commit hash for android13-5.15'
6262
type: string
63-
default: ''
63+
default: ''
6464
android14-6_1_susfs_branch_or_commit:
6565
description: 'Enter SusFS Branch or commit hash for android14-6.1'
6666
type: string
@@ -571,7 +571,7 @@ jobs:
571571
sudo DEBIAN_FRONTEND=noninteractive apt-get install -y --no-install-recommends \
572572
git curl ca-certificates build-essential clang lld flex bison \
573573
libelf-dev libssl-dev libncurses-dev zlib1g-dev liblz4-tool \
574-
libxml2-utils rsync unzip dwarves file python3 ccache jq bc dos2unix kmod libdw-dev elfutils
574+
libxml2-utils rsync unzip dwarves file python3 ccache jq bc dos2unix kmod libdw-dev elfutils pigz
575575
sudo apt-get clean
576576
echo "✅ Dependencies installed"
577577
echo "::endgroup::"
@@ -604,7 +604,7 @@ jobs:
604604
605605
- name: 🔨 Build Kernel
606606
id: build
607-
uses: ./.github/actions
607+
uses: ./.github/actions/build-kernel
608608
with:
609609
op_config_json: ${{ steps.prepare_config.outputs.config_json }}
610610
ksu_type: ${{ matrix.ksu_type }}
@@ -614,6 +614,7 @@ jobs:
614614
build_timestamp: ${{ inputs.build_timestamp }}
615615
clean: ${{ inputs.clean_build }}
616616
debug: ${{ inputs.debug }}
617+
github_token: ${{ secrets.GITHUB_TOKEN }}
617618

618619
- name: 📊 Build statistics
619620
id: build-stat

0 commit comments

Comments
 (0)