-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgenerate_hotlist.py
More file actions
executable file
·281 lines (233 loc) · 9.45 KB
/
generate_hotlist.py
File metadata and controls
executable file
·281 lines (233 loc) · 9.45 KB
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
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
#!/usr/bin/env python3
"""
MC Hotlist Autogen
Generates the `# autogen begin` ... `# autogen end` section in the Midnight Commander
`hotlist` file (`~/.config/mc/hotlist`).
"""
import fnmatch
import re
import sys
from pathlib import Path
from typing import Any
# Import tomllib (Python 3.11+) or fall back to tomli
if sys.version_info >= (3, 11):
import tomllib
else:
try:
import tomli as tomllib
except ImportError:
print("Error: tomli library required for Python < 3.11", file=sys.stderr)
print("Install with: pip install tomli", file=sys.stderr)
sys.exit(1)
# Constants
HOME = Path.home()
HOTLIST_FILE = HOME / ".config/mc/hotlist"
SCRIPT_DIR = Path(__file__).parent.resolve()
CONFIG_FILE = SCRIPT_DIR / "config.toml"
CONFIG_EXAMPLE_FILE = SCRIPT_DIR / "config.example.toml"
GIT_HOSTS = ["github.com", "gitlab.com"]
AUTOGEN_MARKERS = ("# autogen begin", "# autogen end")
COLLAPSE_SEPARATOR = " ── "
def create_default_config() -> None:
"""Create default config file from example template."""
if not CONFIG_EXAMPLE_FILE.exists():
print(f"Error: Example config file not found: {CONFIG_EXAMPLE_FILE}", file=sys.stderr)
sys.exit(1)
# Copy example config to config.toml
CONFIG_FILE.write_text(
CONFIG_EXAMPLE_FILE.read_text(encoding="utf-8"), encoding="utf-8"
)
print(f"Created default config file: {CONFIG_FILE}")
print("Please edit the config file and run the script again.")
sys.exit(0)
def load_config() -> dict[str, Any]:
"""Load repository configuration from TOML file."""
if not CONFIG_FILE.exists():
create_default_config()
with CONFIG_FILE.open("rb") as f:
config = tomllib.load(f)
# Parse repos_dirs with tilde expansion
repos_dirs_raw = config.get("general", {}).get("repos_dirs", ["~/repos"])
repos_dirs = [Path(d).expanduser() for d in repos_dirs_raw]
return {
"repos_dirs": repos_dirs,
"include": config.get("repositories", {}).get("include", []),
"exclude": config.get("repositories", {}).get("exclude", []),
}
def match_exclude(repo_name: str, patterns: list[str]) -> str | None:
"""Return the first exclusion pattern that matches, or None."""
for p in patterns:
if fnmatch.fnmatch(repo_name, p):
return p
return None
def format_path(path: Path) -> str:
"""Format a path relative to home directory with tilde."""
try:
rel_path = path.relative_to(HOME)
return f"~/{rel_path}"
except ValueError:
# Path is not relative to home, return as-is
return str(path)
def make_entry(label: str, url: str) -> str:
"""Format a single hotlist entry."""
return f'ENTRY "{label}"\t\t\t\t\t\tURL "{url}"'
def match_include(owner: str, repo_name: str, includes: list[str]) -> str | None:
"""Return the first include pattern that matches, or None."""
for inc in includes:
if "/" in inc:
# owner/repo format - match specific repo
if inc == f"{owner}/{repo_name}":
return inc
else:
# owner format - match all repos from this owner
if inc == owner:
return inc
return None
def generate_entries(
host: str,
repos_dirs: list[Path],
includes: list[str],
excludes: list[str],
used_includes: set[str],
used_excludes: set[str],
) -> list[str]:
"""Generate hotlist entries for a specific host, handling filtering and collapsing."""
owner_repos = {}
repo_paths = {} # (owner, repo) -> full_path
# Scan all repos directories
for repos_dir in repos_dirs:
host_dir = repos_dir / host
if not host_dir.exists():
continue
# Scan directories
for owner_path in host_dir.iterdir():
if not owner_path.is_dir():
continue
owner = owner_path.name
repos = []
for repo_path in owner_path.iterdir():
if not repo_path.is_dir():
continue
# Check exclude
exclude_match = match_exclude(repo_path.name, excludes)
if exclude_match:
used_excludes.add(exclude_match)
continue
# Check include
include_match = match_include(owner, repo_path.name, includes)
if not include_match:
continue
used_includes.add(include_match)
repos.append(repo_path.name)
repo_paths[(owner, repo_path.name)] = repo_path
if repos:
# Merge with existing repos for this owner (from other repos_dirs)
existing = owner_repos.get(owner, [])
owner_repos[owner] = sorted(list(set(existing + repos)))
sorted_owners = sorted(owner_repos.keys())
if not sorted_owners:
return []
lines = []
# Check if we can collapse Host -> Owner
if len(sorted_owners) == 1:
owner = sorted_owners[0]
repos = owner_repos[owner]
if len(repos) == 1:
# Collapse Host -> Owner -> Repo (e.g. gitlab.com──user──repo)
repo = repos[0]
label = f"{host}{COLLAPSE_SEPARATOR}{owner}{COLLAPSE_SEPARATOR}{repo}"
path = format_path(repo_paths[(owner, repo)])
lines.append(make_entry(label, path))
return lines
else:
# Collapse Host -> Owner, allowing multiple repos under it
# Host──Owner
# ├── repo1
# └── repo2
label = f"{host}{COLLAPSE_SEPARATOR}{owner}"
# Use parent of first repo path as owner path
first_repo = repos[0]
owner_path = repo_paths[(owner, first_repo)].parent
path = format_path(owner_path)
lines.append(make_entry(label, path))
# List repos as direct children
for j, repo in enumerate(repos):
is_last_repo = j == len(repos) - 1
prefix = "└── " if is_last_repo else "├── "
r_label = f"{prefix}{repo}"
r_path = format_path(repo_paths[(owner, repo)])
lines.append(make_entry(r_label, r_path))
return lines
# Standard Host entry
# Use parent of first owner's first repo path as host path
first_owner = sorted_owners[0]
first_repo = owner_repos[first_owner][0]
host_path = repo_paths[(first_owner, first_repo)].parent.parent
lines.append(make_entry(host, format_path(host_path)))
for i, owner in enumerate(sorted_owners):
repos = owner_repos[owner]
is_last_owner = i == len(sorted_owners) - 1
owner_prefix = "└── " if is_last_owner else "├── "
child_prefix = " " if is_last_owner else "│ "
if len(repos) == 1:
repo = repos[0]
# Collapse Owner -> Repo (e.g. ├── owner──repo)
label = f"{owner_prefix}{owner}{COLLAPSE_SEPARATOR}{repo}"
path = format_path(repo_paths[(owner, repo)])
lines.append(make_entry(label, path))
else:
# Standard Owner entry
first_repo = repos[0]
owner_path = repo_paths[(owner, first_repo)].parent
lines.append(
make_entry(f"{owner_prefix}{owner}", format_path(owner_path))
)
for j, repo in enumerate(repos):
is_last_repo = j == len(repos) - 1
repo_prefix = (
f"{child_prefix}└── " if is_last_repo else f"{child_prefix}├── "
)
lines.append(
make_entry(f"{repo_prefix}{repo}", format_path(repo_paths[(owner, repo)]))
)
return lines
def main() -> None:
"""Main execution entry point."""
config = load_config()
repos_dirs = config["repos_dirs"]
includes = config["include"]
excludes = config["exclude"]
used_includes: set[str] = set()
used_excludes: set[str] = set()
new_content = []
for host in GIT_HOSTS:
new_content.extend(
generate_entries(host, repos_dirs, includes, excludes, used_includes, used_excludes)
)
# Warn about unused patterns
unused_includes = set(includes) - used_includes
unused_excludes = set(excludes) - used_excludes
for pattern in sorted(unused_includes):
if "/" in pattern:
print(f"Warning: repo not found: '{pattern}'", file=sys.stderr)
else:
print(f"Warning: owner not found: '{pattern}'", file=sys.stderr)
for pattern in sorted(unused_excludes):
print(f"Warning: excluded repo '{pattern}' not found", file=sys.stderr)
if not HOTLIST_FILE.exists():
print(f"Error: {HOTLIST_FILE} not found", file=sys.stderr)
sys.exit(1)
content = HOTLIST_FILE.read_text(encoding="utf-8")
if AUTOGEN_MARKERS[0] not in content or AUTOGEN_MARKERS[1] not in content:
# Add markers at the end of file
content = content.rstrip() + f"\n\n{AUTOGEN_MARKERS[0]}\n{AUTOGEN_MARKERS[1]}\n"
print(f"Added autogen markers to {HOTLIST_FILE}")
pattern = re.compile(
f"({re.escape(AUTOGEN_MARKERS[0])}).*?({re.escape(AUTOGEN_MARKERS[1])})", re.DOTALL
)
repl = "\\1\n" + "\n".join(new_content) + "\n\\2"
new_file_content = pattern.sub(repl, content)
HOTLIST_FILE.write_text(new_file_content, encoding="utf-8")
print(f"Updated: {HOTLIST_FILE}")
if __name__ == "__main__":
main()