-
Notifications
You must be signed in to change notification settings - Fork 0
/
generate_index.py
251 lines (227 loc) · 8.35 KB
/
generate_index.py
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
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
import os
import time
from datetime import datetime, timezone
# HTML template for the index.html file, with a signature comment
INDEX_HTML_TEMPLATE = """<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="icon" type="image/x-icon"
href="https://res.cloudinary.com/dbriqxpaa/image/upload/v1680096853/Logo/logo-xl-ico_qzbf7d.ico" />
<title>{title}</title>
<link href="https://fonts.googleapis.com/css2?family=Roboto:wght@400;700&display=swap" rel="stylesheet">
<style>
body {{
font-family: 'Roboto', sans-serif;
font-weight: 400;
transition: background-color 0.3s, color 0.3s;
}}
table {{
width: 100%;
border-collapse: collapse;
}}
th, td {{
padding: 8px 13px;
border: 1px solid #ccc;
}}
th {{
background-color: #f2f2f2;
}}
td.icon-col {{
width: 44px;
text-align: center;
}}
a {{
text-decoration: none;
color: #007BFF;
}}
a:hover {{
text-decoration: underline;
}}
.go-back {{
margin-bottom: 22px;
margin-left: 11px;
display: inline-block;
}}
h1 {{
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
font-size: 1.65em;
margin: 0;
padding: 11px;
}}
/* Dark mode styles */
body.dark-mode {{
background-color: #333;
color: #f1f1f1;
}}
body.dark-mode th {{
background-color: #555;
}}
body.dark-mode a {{
color: #1e90ff;
}}
/* Dark mode button styles */
.dark-mode-toggle {{
position: fixed;
bottom: 22px;
right: 22px;
background-color: #007BFF;
color: #fff;
border: none;
padding: 11px 22px;
cursor: pointer;
border-radius: 5.5px;
z-index: 1000;
}}
.dark-mode-toggle:hover {{
background-color: #0056b3;
}}
</style>
</head>
<body>
<h1>{header_text}</h1>
{go_back_link}
<table>
<thead>
<tr>
<th class="icon-col">Icon</th>
<th>Name</th>
<th>Size</th>
<th>Last Modified</th>
</tr>
</thead>
<tbody>
{table_rows}
</tbody>
</table>
<!-- Auto-generated by Python script -->
<button class="dark-mode-toggle" onclick="toggleDarkMode()">🌙 Dark Mode</button>
<script>
function toggleDarkMode() {{
const body = document.body;
const button = document.querySelector('.dark-mode-toggle');
body.classList.toggle('dark-mode');
const isDarkMode = body.classList.contains('dark-mode');
localStorage.setItem('darkMode', isDarkMode);
// Update button text based on current mode
button.textContent = isDarkMode ? '🌞 Light Mode' : '🌙 Dark Mode';
}}
// Load dark mode setting from localStorage
document.addEventListener('DOMContentLoaded', () => {{
const isDarkMode = localStorage.getItem('darkMode') === 'true';
const button = document.querySelector('.dark-mode-toggle');
if (isDarkMode) {{
document.body.classList.add('dark-mode');
button.textContent = '🌞 Light Mode';
}} else {{
button.textContent = '🌙 Dark Mode';
}}
}});
</script>
</body>
</html>
"""
EXCLUDED_DIRS = ['.git', '.github', '__pycache__'] # Exclude certain directories
def is_auto_generated(file_path):
"""Check if the file contains the auto-generated signature"""
if not os.path.exists(file_path):
return False
with open(file_path, 'r', encoding='utf-8') as f:
content = f.read()
return '<!-- Auto-generated by Python script -->' in content
def format_size(size):
"""Convert bytes to a human-readable string"""
for unit in ['B', 'KB', 'MB', 'GB', 'TB']:
if size < 1024.0:
return f"{size:.1f} {unit}"
size /= 1024.0
def format_date(timestamp):
"""Convert a timestamp to a readable date format with local time"""
# Convert timestamp to a datetime object in UTC
dt_utc = datetime.fromtimestamp(timestamp, tz=timezone.utc)
# Convert datetime to local timezone
dt_local = dt_utc.astimezone()
return dt_local.strftime('%Y-%m-%d %H:%M')
def get_full_url(root, folder_path):
"""Generate a full URL based on the directory path relative to the root"""
relative_path = os.path.relpath(root, folder_path)
if relative_path == ".":
return "data.aykhan.net"
return f"data.aykhan.net/{relative_path.replace(os.sep, '/')}"
def to_header_case(s):
"""Convert a string to header case, ensuring it is all lowercase."""
return s.replace('/', ' ').lower().replace(' ', ' ➔ ')
def to_title_case(s):
"""Convert a string to title case, ensuring it is all lowercase."""
return s.replace('/', ' ').lower().replace(' ', ' | ')
def generate_index_html(folder_path):
"""
Recursively generates or updates index.html files in each folder and subfolder,
but skips files not auto-generated by this script and excludes certain folders.
"""
for root, dirs, files in os.walk(folder_path):
# Skip excluded directories
dirs[:] = [d for d in dirs if d not in EXCLUDED_DIRS]
index_file_path = os.path.join(root, 'index.html')
# Skip updating if index.html exists but was not auto-generated
if 'index.html' in files and not is_auto_generated(index_file_path):
print(f'Skipping {index_file_path} (manually created)')
continue
# Determine if we're in the root directory (Home)
if root == folder_path:
header_text = "data.aykhan.net"
title = "data.aykhan.net"
go_back_link = "" # No go-back link on home
else:
full_url = get_full_url(root, folder_path) # Generate full URL for the directory
header_text = to_header_case(full_url)
title = to_title_case(full_url)
go_back_link = '<a href="../index.html" class="go-back">⬅️ Go Back</a>'
# Create list of items (folders and files) for the current folder
table_rows = []
# Add directories to the table
for dir_name in dirs:
dir_path = os.path.join(root, dir_name)
last_modified = format_date(os.path.getmtime(dir_path))
table_rows.append(
f'<tr>'
f'<td class="icon-col">📁</td>'
f'<td><a href="{dir_name}/index.html">{dir_name}/</a></td>'
f'<td>-</td>'
f'<td>{last_modified}</td>'
f'</tr>'
)
# Add files to the table (skip the index.html file)
for file_name in files:
if file_name == "index.html":
continue
file_path = os.path.join(root, file_name)
file_size = format_size(os.path.getsize(file_path))
last_modified = format_date(os.path.getmtime(file_path))
table_rows.append(
f'<tr>'
f'<td class="icon-col">📄</td>'
f'<td><a href="{file_name}">{file_name}</a></td>'
f'<td>{file_size}</td>'
f'<td>{last_modified}</td>'
f'</tr>'
)
# Join the table rows as HTML
table_rows_html = "\n ".join(table_rows)
# Render the final HTML for the index.html file
index_html_content = INDEX_HTML_TEMPLATE.format(
title=title,
header_text=header_text,
table_rows=table_rows_html,
go_back_link=go_back_link
)
# Write or overwrite index.html in the current folder with utf-8 encoding
with open(index_file_path, 'w', encoding='utf-8') as index_file:
index_file.write(index_html_content)
print(f'Updated {index_file_path}')
if __name__ == "__main__":
root_folder = '.'
generate_index_html(root_folder)