import os
import sys
from pathlib import Path
# 目标目录(通常是 gh-pages 分支的根目录)
output_dir = Path(sys.argv[1]) if len(sys.argv) > 1 else Path('.')
# 要扫描的仓库根目录(相对于脚本位置)
repo_root_dir = Path(__file__).parent.parent # 指向 Sleeping-Cup-Testcases 根目录
# 要扫描的子目录(相对于仓库根目录),可以留空 '' 表示扫描整个仓库
# 如果你的测试用例都在某个子文件夹下,比如 'testcases',可以设为 'testcases'
SCAN_SUBDIR = ''
start_path = repo_root_dir / SCAN_SUBDIR
output_file = output_dir / "index.html"
html_content = """<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Sleeping Cup Testcases Directory</title>
<style>
body { font-family: sans-serif; padding: 20px; }
ul { list-style-type: none; padding-left: 20px; }
li { margin-bottom: 8px; }
a { text-decoration: none; color: #0366d6; }
a:hover { text-decoration: underline; }
.dir { font-weight: bold; }
</style>
</head>
<body>
<h1>Sleeping Cup Testcases Directory</h1>
<ul>
"""
def generate_links(current_path, base_path, indent_level=0):
nonlocal html_content
prefix = str(current_path.relative_to(base_path))
if prefix: # Avoid empty prefix for the root scan dir
# 构建相对于 gh-pages 分支根目录的链接前缀
# 如果 SCAN_SUBDIR 不为空,需要加上它
link_prefix = (SCAN_SUBDIR + '/' + prefix) if SCAN_SUBDIR else prefix
link_prefix = link_prefix.replace('\\', '/') # 确保使用 / 作为路径分隔符
html_content += '<li><span class="dir">' + prefix.split('/')[-1] + '/</span>\n<ul>\n' # Display current dir name
items = sorted(list(current_path.iterdir()), key=lambda x: (not x.is_dir(), x.name.lower()))
for item in items:
relative_item_path = item.relative_to(base_path)
link_path = (SCAN_SUBDIR + '/' + str(relative_item_path)).replace('\\', '/')
if link_path.startswith("//"): # Handle case where SCAN_SUBDIR is empty and prefix is also empty initially
link_path = link_path[1:]
if item.is_dir():
# Recursive call for subdirectories, adding the subdir name to the link path
subdir_link_path = link_path + '/'
html_content += f'<li><span class="dir"><a href="{subdir_link_path}">{item.name}/</a></span></li>\n'
# Note: uncomment below for full recursive listing within the HTML itself
# generate_links(item, base_path, indent_level + 1)
else:
html_content += f'<li><a href="{link_path}">{item.name}</a></li>\n'
html_content += '</ul>\n</li>\n'
else: # Handle the root directory itself if SCAN_SUBDIR is empty
items = sorted(list(current_path.iterdir()), key=lambda x: (not x.is_dir(), x.name.lower()))
for item in items:
link_path = item.name.replace('\\', '/')
if item.is_dir():
subdir_link_path = link_path + '/'
html_content += f'<li><span class="dir"><a href="{subdir_link_path}">{item.name}/</a></span></li>\n'
else:
html_content += f'<li><a href="{link_path}">{item.name}</a></li>\n'
# --- Main Execution ---
# Ensure output directory exists
output_dir.mkdir(parents=True, exist_ok=True)
# Generate the HTML listing
# We scan starting from repo_root_dir, but the links should be relative to the Pages root (gh-pages branch)
# The script itself should run from the repo root, generating index.html in the target deploy location
# Correct approach: Scan the actual repo content, create links relative to the gh-pages root
# Let's simplify: Assume script runs locally, scans the repo, and creates index.html in ./dist/gh-pages/
# The GitHub Action will then copy ./dist/gh-pages content to the actual gh-pages branch.
# Simpler script logic for demonstration: generates a flat list or requires manual setup
# A truly robust solution often involves generating nested lists or using JS on the client side.
# Let's refine the script to generate a *single* index.html at the root of gh-pages
# It needs to list the contents *of the repo*
# Re-thinking: The script should run locally, scan the repo content, and create the index.html
# that will be deployed. Let's put the index.html directly into the repo structure
# that will be pushed to gh-pages.
# Simpler approach: Generate index.html in the root of the repo, commit it, and let Pages serve it from gh-pages branch.
final_html_content = """<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Sleeping Cup Testcases Directory</title>
<style>
body { font-family: Arial, sans-serif; margin: 20px; }
h1 { border-bottom: 1px solid #ccc; padding-bottom: 10px; }
ul { padding-left: 25px; }
li { margin-bottom: 5px; }
.folder { font-weight: bold; }
</style>
</head>
<body>
<h1>Repository Contents: Sleeping-Cup-Testcases</h1>
<ul>
"""
# Walk through the specified subdirectory (relative to repo root)
current_level_path = repo_root_dir / SCAN_SUBDIR
# Use os.walk to get directory structure
for root, dirs, files in os.walk(current_level_path, topdown=True):
# Calculate the relative path from the SCAN_SUBDIR start point
rel_path = os.path.relpath(root, current_level_path)
# Create list item for the current directory if it's not the starting point itself
# Or if it's the starting point and not empty
if rel_path != '.':
dir_display_name = os.path.basename(root)
# Link path should be relative to the repo root that gets deployed to gh-pages
link_path = os.path.join(SCAN_SUBDIR, rel_path)
link_path = link_path.replace(os.sep, '/') # Use forward slashes
if not link_path.startswith('/'): # Ensure leading slash if needed by context
link_path = '/' + link_path
final_html_content += f'<li class="folder"><a href="{link_path}/">{dir_display_name}/</a></li>\n'
# Add files for the current directory
# Sort dirs and files for consistent order
dirs.sort(key=lambda d: d.lower())
files.sort(key=lambda f: f.lower())
for name in dirs:
link_path = os.path.join(SCAN_SUBDIR, rel_path, name)
link_path = link_path.replace(os.sep, '/')
if not link_path.startswith('/'):
link_path = '/' + link_path
# Add directory link (parent directory link is already added above)
# This basic script doesn't build nested lists easily, so maybe just list dirs/files at top level
pass # Directories are handled when os.walk enters them
for name in files:
link_path = os.path.join(SCAN_SUBDIR, rel_path, name)
link_path = link_path.replace(os.sep, '/')
if not link_path.startswith('/'):
link_path = '/' + link_path
final_html_content += f'<li><a href="{link_path}">{name}</a></li>\n'
# --- Refined Script Logic ---
# Let's use a simpler approach: Just list files and top-level directories
# The user can navigate manually.
html_output = Path("./index.html") # Create in the current directory where script is run
with open(html_output, "w", encoding="utf-8") as f:
f.write("""<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Sleeping Cup Testcases</title>
<style>
body { font-family: sans-serif; padding: 20px; }
ul { list-style-type: none; padding-left: 0; }
li { margin-bottom: 10px; }
a { text-decoration: none; color: #0366d6; }
a:hover { text-decoration: underline; }
.folder::before { content: "📁 "; } /* Folder icon */
.file::before { content: "📄 "; } /* File icon */
</style>
</head>
<body>
<h1>Sleeping Cup Testcases</h1>
<ul>
""")
repo_root = Path('.') # Assume script is run from the repo root for simplicity now
# List top-level items
items = sorted(list(repo_root.iterdir()), key=lambda x: (not x.is_dir(), x.name.lower()))
for item in items:
# Skip the script file itself and common repo files/folders if desired
if item.name in ['.git', '.github', 'scripts', 'generate_index.py', 'index.html', 'README.md']:
# Check if the item is inside the SCAN_SUBDIR path we decided to serve
# This script logic needs careful thought based on *what* gets deployed
# Let's assume we deploy the *entire* repo content to gh-pages
continue # Skip non-content files/dirs
link_path = item.name.replace('\\', '/')
if item.is_dir():
# For directories, we might want a link to a page *listing its contents*
# Or just link to the directory itself if Pages handles it (it doesn't by default)
# Best bet is to link to the directory path, assuming the structure is mirrored
# For this simple approach, let's just list it. A nested JS solution is better for real browsing.
f.write(f'<li class="folder"><a href="{link_path}/">{item.name}/</a></li>\n')
else:
f.write(f'<li class="file"><a href="{link_path}">{item.name}</a></li>\n')
f.write("""
</ul>
</body>
</html>
""")
print(f"Generated {html_output}")
# Add script execution logic within the workflow later
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Sleeping Cup Testcases Directory</title>
<style>
body { font-family: sans-serif; padding: 20px; }
ul { list-style-type: none; padding-left: 20px; }
li { margin-bottom: 8px; }
a { text-decoration: none; color: #0366d6; }
a:hover { text-decoration: underline; }
.loading, .error { color: grey; }
.folder::before { content: "📁 "; }
.file::before { content: "📄 "; }
</style>
</head>
<body>
<h1>Sleeping Cup Testcases</h1>
<div id="directory-listing">
<p class="loading">Loading directory structure...</p>
</div>
<script>
const GITHUB_API_URL = 'https://api.github.com/repos/035966-L3/Sleeping-Cup-Testcases/contents';
const listingDiv = document.getElementById('directory-listing');
// 你可以指定一个子目录来开始扫描,例如 'testcases'
const startPath = ''; // 或者 'testcases' 等
function fetchDirectory(path = '') {
let apiUrl = GITHUB_API_URL;
if (path) {
// GitHub API uses URL encoding for paths, but often works okay without explicit encoding for simple names
// Ensure path starts correctly relative to the base URL
apiUrl += '/' + path.split('/').filter(p => p !== '').join('/');
}
// Add query parameter to avoid caching issues if path is the same but content changed
// Not strictly necessary for basic listing but good practice if structure updates often
// apiUrl += '?t=' + Date.now();
fetch(apiUrl, {
headers: {
'Accept': 'application/vnd.github.v3+json',
// Add a basic User-Agent as required by GitHub API
'User-Agent': 'GitHubPagesDirectoryLister'
}
})
.then(response => {
if (!response.ok) {
throw new Error(`GitHub API error: ${response.status} ${response.statusText}`);
}
return response.json();
})
.then(data => {
if (!Array.isArray(data)) {
// Handle cases where the API returns an object for a file, not an array
// This shouldn't happen if the initial call is for a directory.
if (data.type === 'file') {
// Render just this file if it was the target? Unlikely for directory listing.
listingDiv.innerHTML = `<p class="error">Expected directory, got file.</p>`;
return;
}
throw new Error("Unexpected API response format.");
}
// Sort items: directories first, then alphabetically
data.sort((a, b) => {
if (a.type === b.type) {
return a.name.localeCompare(b.name);
}
return a.type === 'dir' ? -1 : 1;
});
let html = '<ul>';
data.forEach(item => {
const currentItemPath = path ? `${path}/${item.name}` : item.name;
const linkPath = currentItemPath.replace(/\\/g, '/'); // Ensure forward slashes
if (item.type === 'dir') {
// For directories, create a link that calls this function recursively
// Need to handle the starting path correctly
const dirName = item.name;
html += `<li class="folder"><a href="javascript:void(0)" onclick="displaySubdir('${linkPath}')">${dirName}/</a></li>`;
} else {
// For files, create a direct link
html += `<li class="file"><a href="${item.download_url || item.html_url}">${item.name}</a></li>`;
}
});
html += '</ul>';
listingDiv.innerHTML = html;
})
.catch(error => {
console.error('Error fetching directory:', error);
listingDiv.innerHTML = `<p class="error">Failed to load directory. ${error.message}</p>`;
});
}
// Function to display subdirectory contents
function displaySubdir(subdirPath) {
// Maybe update a breadcrumb here? For simplicity, just reload content.
listingDiv.innerHTML = `<p class="loading">Loading ${subdirPath}...</p>`;
fetchDirectory(subdirPath);
}
// Initial call to load the root or specified startPath
document.addEventListener('DOMContentLoaded', () => {
fetchDirectory(startPath);
});
</script>
</body>
</html>