Skip to content

Commit a558615

Browse files
committed
add sync ci
1 parent 63374e3 commit a558615

File tree

7 files changed

+523
-0
lines changed

7 files changed

+523
-0
lines changed

.github/.DS_Store

6 KB
Binary file not shown.
Lines changed: 185 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,185 @@
1+
#!/usr/bin/env python3
2+
"""
3+
Script to process markdown files before syncing to deploy branch.
4+
5+
This script:
6+
1. Removes YAML frontmatter description sections from MD files
7+
2. Converts level 2 titles to level 1 titles in SUMMARY.md
8+
3. Removes <figure></figure> HTML elements but keeps content inside
9+
4. Converts all GitBook {% %} tags to standard markdown format
10+
"""
11+
12+
import os
13+
import re
14+
import sys
15+
from pathlib import Path
16+
17+
18+
def remove_yaml_frontmatter(content):
19+
"""Remove YAML frontmatter from markdown content."""
20+
# Match YAML frontmatter at the beginning of the file
21+
pattern = r'^---\n.*?\n---\n'
22+
return re.sub(pattern, '', content, flags=re.DOTALL | re.MULTILINE)
23+
24+
25+
def process_summary_titles(content):
26+
"""Convert level 2 titles (##) to level 1 titles (#) in SUMMARY.md."""
27+
# Replace ## with #
28+
return re.sub(r'^## ', '# ', content, flags=re.MULTILINE)
29+
30+
31+
def remove_figure_tags(content):
32+
"""Remove <figure></figure> HTML elements but keep the content inside."""
33+
# Remove opening <figure> tags (with any attributes)
34+
content = re.sub(r'<figure[^>]*>', '', content)
35+
36+
# Remove closing </figure> tags
37+
content = re.sub(r'</figure>', '', content)
38+
39+
# Clean up any extra whitespace that might be left
40+
content = re.sub(r'\n\s*\n\s*\n', '\n\n', content)
41+
42+
return content
43+
44+
45+
def convert_gitbook_tags(content):
46+
"""Convert all GitBook {% %} tags to standard markdown format."""
47+
48+
# Pattern to match {% embed url="..." %} tags
49+
embed_pattern = r'{%\s*embed\s+url="([^"]+)"\s*%}'
50+
51+
# Pattern to match any other {% ... %} tags (like code blocks, hints, etc.)
52+
general_tag_pattern = r'{%\s*([^%]+)\s*%}'
53+
54+
def convert_embed(match):
55+
url = match.group(1)
56+
57+
# Check if it's a YouTube URL and convert to proper markdown
58+
if 'youtube.com' in url or 'youtu.be' in url:
59+
# Extract video ID for YouTube URLs
60+
video_id = None
61+
if 'youtube.com/watch?v=' in url:
62+
video_id = url.split('v=')[1].split('&')[0]
63+
elif 'youtube.com/embed/' in url:
64+
video_id = url.split('/embed/')[1].split('?')[0]
65+
elif 'youtu.be/' in url:
66+
video_id = url.split('youtu.be/')[1].split('?')[0]
67+
68+
if video_id:
69+
# Return markdown format with thumbnail and link
70+
return f"[![YouTube Video](https://img.youtube.com/vi/{video_id}/maxresdefault.jpg)]({url})\n\n[Watch on YouTube]({url})"
71+
else:
72+
return f"[YouTube Video]({url})"
73+
else:
74+
# For non-YouTube URLs, just create a regular link
75+
return f"[View Content]({url})"
76+
77+
def convert_general_tag(match):
78+
tag_content = match.group(1).strip()
79+
80+
# Handle specific GitBook tags
81+
if tag_content.startswith('hint'):
82+
return "> **Note:** "
83+
elif tag_content.startswith('code'):
84+
return "" # Remove code block tags, keep the actual code
85+
elif tag_content.startswith('endcode'):
86+
return "" # Remove end code block tags
87+
elif 'url=' in tag_content and 'embed' not in tag_content:
88+
# Handle other URL-containing tags
89+
url_match = re.search(r'url="([^"]+)"', tag_content)
90+
if url_match:
91+
return f"[Link]({url_match.group(1)})"
92+
93+
# For unrecognized tags, just remove them
94+
return ""
95+
96+
# First handle embed tags specifically
97+
content = re.sub(embed_pattern, convert_embed, content)
98+
99+
# Then handle remaining {% %} tags
100+
content = re.sub(general_tag_pattern, convert_general_tag, content)
101+
102+
return content
103+
104+
105+
def process_markdown_file(file_path):
106+
"""Process a single markdown file."""
107+
try:
108+
with open(file_path, 'r', encoding='utf-8') as f:
109+
content = f.read()
110+
111+
original_content = content
112+
113+
# Apply all transformations
114+
content = remove_yaml_frontmatter(content)
115+
content = remove_figure_tags(content)
116+
content = convert_gitbook_tags(content)
117+
118+
# Special processing for SUMMARY.md
119+
if file_path.name == 'SUMMARY.md':
120+
content = process_summary_titles(content)
121+
122+
# Only write if content changed
123+
if content != original_content:
124+
with open(file_path, 'w', encoding='utf-8') as f:
125+
f.write(content)
126+
print(f"Processed: {file_path}")
127+
return True
128+
else:
129+
print(f"No changes: {file_path}")
130+
return False
131+
132+
except Exception as e:
133+
print(f"Error processing {file_path}: {e}")
134+
return False
135+
136+
137+
def find_markdown_files(src_dir):
138+
"""Find all markdown files in the src directory."""
139+
src_path = Path(src_dir)
140+
if not src_path.exists():
141+
print(f"Source directory {src_dir} does not exist")
142+
return []
143+
144+
markdown_files = list(src_path.rglob('*.md'))
145+
return markdown_files
146+
147+
148+
def main():
149+
"""Main function to process all markdown files."""
150+
# Get the repository root directory
151+
script_dir = Path(__file__).parent
152+
repo_root = script_dir.parent.parent
153+
154+
print(f"Repository root: {repo_root}")
155+
156+
# In main branch, files are in root directory, not src
157+
# In deploy branch, files are in src directory
158+
# Check which structure we're dealing with
159+
src_dir = repo_root / 'src'
160+
if src_dir.exists():
161+
print(f"Found src directory: {src_dir}")
162+
markdown_files = find_markdown_files(src_dir)
163+
else:
164+
print(f"Using root directory: {repo_root}")
165+
markdown_files = find_markdown_files(repo_root)
166+
167+
# Find all markdown files
168+
if not markdown_files:
169+
print("No markdown files found to process")
170+
return 0
171+
172+
print(f"Found {len(markdown_files)} markdown files to process")
173+
174+
# Process each file
175+
processed_count = 0
176+
for file_path in markdown_files:
177+
if process_markdown_file(file_path):
178+
processed_count += 1
179+
180+
print(f"Successfully processed {processed_count} files")
181+
return 0
182+
183+
184+
if __name__ == '__main__':
185+
sys.exit(main())

.github/scripts/quick_test.sh

Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
#!/bin/bash
2+
3+
echo "🔧 Quick validation test..."
4+
5+
# Test 1: Processing works
6+
echo "Test 1: Processing markdown files..."
7+
python .github/scripts/process_markdown.py > /dev/null 2>&1
8+
9+
if git diff --quiet; then
10+
echo "❌ Processing failed - no changes detected"
11+
exit 1
12+
else
13+
echo "✅ Processing successful - files were modified"
14+
fi
15+
16+
# Test 2: Check specific changes
17+
echo "Test 2: Checking SUMMARY.md title conversion..."
18+
if grep -q "^# Developer Guide" SUMMARY.md; then
19+
echo "✅ SUMMARY.md title conversion works"
20+
else
21+
echo "❌ SUMMARY.md title conversion failed"
22+
fi
23+
24+
# Test 3: Check figure tag removal
25+
echo "Test 3: Checking figure tag removal..."
26+
FIGURE_COUNT=$(find . -name "*.md" -exec grep -l "<figure>" {} \; 2>/dev/null | wc -l)
27+
if [ "$FIGURE_COUNT" -eq 0 ]; then
28+
echo "✅ Figure tags removed successfully"
29+
else
30+
echo "❌ Figure tags still present in $FIGURE_COUNT files"
31+
fi
32+
33+
# Test 4: Revert functionality
34+
echo "Test 4: Testing revert functionality..."
35+
git checkout -- README.md SUMMARY.md developer-guide/ developer-resources/ 2>/dev/null
36+
37+
if git diff --quiet --name-only | grep -v ".github" | wc -l | grep -q "0"; then
38+
echo "✅ Revert functionality works"
39+
else
40+
echo "❌ Revert functionality failed"
41+
fi
42+
43+
echo "🎉 All tests completed!"
Lines changed: 77 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,77 @@
1+
#!/bin/bash
2+
3+
# Enhanced test script to simulate the full GitHub Actions workflow
4+
# This tests the complete flow including branch switching and file copying
5+
6+
echo "🧪 Testing complete GitHub Actions workflow simulation..."
7+
8+
# Check current branch and status
9+
ORIGINAL_BRANCH=$(git rev-parse --abbrev-ref HEAD)
10+
echo "Starting on branch: $ORIGINAL_BRANCH"
11+
12+
# Step 1: Simulate checkout main branch
13+
if [ "$ORIGINAL_BRANCH" != "main" ]; then
14+
echo "Switching to main branch..."
15+
git checkout main
16+
fi
17+
18+
echo "📝 Step 1: Processing markdown files on main branch..."
19+
python .github/scripts/process_markdown.py
20+
21+
if git diff --quiet; then
22+
echo "❌ No files were processed"
23+
git checkout "$ORIGINAL_BRANCH"
24+
exit 1
25+
else
26+
echo "✅ Files were successfully processed"
27+
fi
28+
29+
echo "📦 Step 2: Backing up processed files..."
30+
# Simulate the backup step
31+
cp -r src /tmp/processed_src_test
32+
echo "✅ Backup created"
33+
34+
echo "🔄 Step 3: Switching to deploy branch..."
35+
git fetch origin deploy 2>/dev/null || echo "Deploy branch doesn't exist remotely"
36+
if git checkout deploy 2>/dev/null; then
37+
echo "✅ Switched to existing deploy branch"
38+
else
39+
echo "Creating new deploy branch..."
40+
git checkout -b deploy
41+
echo "✅ Created and switched to deploy branch"
42+
fi
43+
44+
echo "🚀 Step 4: Syncing files to deploy branch..."
45+
# Remove existing src if it exists
46+
if [ -d "src" ]; then
47+
rm -rf src
48+
echo "Removed existing src folder"
49+
fi
50+
51+
# Copy from backup
52+
cp -r /tmp/processed_src_test src
53+
echo "✅ Copied processed files to deploy branch"
54+
55+
# Show what would be committed
56+
echo "Files that would be committed to deploy branch:"
57+
git add src
58+
git status --porcelain
59+
60+
echo "🔙 Step 5: Simulating revert on main branch..."
61+
git checkout main
62+
git checkout -- src
63+
echo "✅ Reverted changes on main branch"
64+
65+
# Verify main branch is clean
66+
if git diff --quiet; then
67+
echo "✅ Main branch is clean"
68+
else
69+
echo "❌ Main branch still has changes"
70+
git status --porcelain
71+
fi
72+
73+
echo "🧹 Cleaning up..."
74+
rm -rf /tmp/processed_src_test
75+
git checkout "$ORIGINAL_BRANCH"
76+
77+
echo "✅ Complete workflow test passed!"

.github/scripts/test_processing.sh

Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
#!/bin/bash
2+
3+
# Simple test script to validate the workflow locally
4+
# This simulates what the GitHub Action will do
5+
6+
echo "Testing markdown processing workflow..."
7+
8+
# Save current branch
9+
CURRENT_BRANCH=$(git rev-parse --abbrev-ref HEAD)
10+
echo "Current branch: $CURRENT_BRANCH"
11+
12+
# Test the processing script
13+
echo "Running markdown processing script..."
14+
python .github/scripts/process_markdown.py
15+
16+
# Check if files were modified
17+
if git diff --quiet; then
18+
echo "❌ No files were modified by the script"
19+
exit 1
20+
else
21+
echo "✅ Files were successfully processed"
22+
fi
23+
24+
# Show a sample of changes
25+
echo "Sample changes in SUMMARY.md:"
26+
git diff src/SUMMARY.md | head -20
27+
28+
echo "Sample changes in app-circuit-interface.md:"
29+
git diff src/developer-resources/circuit-sdk-reference/app-circuit-interface.md | head -20
30+
31+
# Test the revert functionality (simulating what happens in CI)
32+
echo "Testing revert functionality..."
33+
git stash push -m "Temporary stash of processed files"
34+
35+
# Simulate switching branches and copying files (like in CI)
36+
echo "Simulating deploy branch sync..."
37+
echo "Files would be copied to deploy branch here..."
38+
39+
# Revert changes (this is what the CI does)
40+
echo "Reverting changes on main branch..."
41+
git stash pop
42+
git checkout -- src
43+
44+
echo "✅ Test completed successfully - changes reverted"

.github/workflows/gh-pages.yml

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
name: Deploy mdBook site to GitHub Pages
2+
3+
on:
4+
push:
5+
branches: ["deploy"]
6+
pull_request:
7+
repository_dispatch:
8+
types: [deploy-pages]
9+
10+
jobs:
11+
deploy:
12+
runs-on: ubuntu-latest
13+
permissions:
14+
contents: write
15+
steps:
16+
- name: Checkout repository
17+
uses: actions/checkout@v4
18+
19+
- name: Setup mdBook
20+
uses: peaceiris/actions-mdbook@v1
21+
with:
22+
mdbook-version: '0.5.0-beta.1' # 建议指定一个稳定版本
23+
24+
- name: Build with mdBook
25+
run: |
26+
mdbook clean
27+
mdbook build
28+
29+
- name: Deploy to GitHub Pages
30+
uses: peaceiris/actions-gh-pages@v3
31+
with:
32+
github_token: ${{ secrets.GITHUB_TOKEN }}
33+
publish_dir: ./book

0 commit comments

Comments
 (0)