-
-
Notifications
You must be signed in to change notification settings - Fork 402
Expand file tree
/
Copy pathbuild.py
More file actions
281 lines (221 loc) · 8.95 KB
/
build.py
File metadata and controls
281 lines (221 loc) · 8.95 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
"""
Block List Project - Build CLI
Command-line interface for building blocklists.
Usage:
python build.py # Build all lists
python build.py --list ads # Build specific list
python build.py --dry-run # Preview without writing
python build.py --validate # Run validation checks
python build.py --verbose # Show detailed output
"""
import sys
import time
from pathlib import Path
import click
# Add src to path for imports
sys.path.insert(0, str(Path(__file__).parent / "src"))
from pipeline import (
BuildResult,
PipelineResult,
build_list,
run_pipeline,
verify_output_consistency,
)
from config import load_config, get_list_names
# Project root is where this script lives
PROJECT_ROOT = Path(__file__).parent
@click.group(invoke_without_command=True)
@click.option("--list", "-l", "list_name", multiple=True, help="Specific list(s) to build")
@click.option("--dry-run", "-n", is_flag=True, help="Preview without writing files")
@click.option("--validate", "-v", is_flag=True, help="Run validation checks")
@click.option("--verbose", is_flag=True, help="Show detailed output")
@click.option("--strict", is_flag=True, help="Fail on warnings")
@click.option("--output-dir", "-o", type=click.Path(), help="Output directory (default: project root)")
@click.pass_context
def cli(ctx, list_name, dry_run, validate, verbose, strict, output_dir):
"""Block List Project - Build Tool
Build and format blocklists for various DNS blocking applications.
"""
ctx.ensure_object(dict)
ctx.obj["dry_run"] = dry_run
ctx.obj["validate"] = validate
ctx.obj["verbose"] = verbose
ctx.obj["strict"] = strict
ctx.obj["output_dir"] = Path(output_dir) if output_dir else PROJECT_ROOT
# If no subcommand, run build
if ctx.invoked_subcommand is None:
ctx.invoke(build, list_name=list_name)
@cli.command()
@click.option("--list", "-l", "list_name", multiple=True, help="Specific list(s) to build")
@click.pass_context
def build(ctx, list_name):
"""Build blocklists from source files."""
start_time = time.time()
dry_run = ctx.obj.get("dry_run", False)
validate = ctx.obj.get("validate", False)
verbose = ctx.obj.get("verbose", False)
strict = ctx.obj.get("strict", False)
output_dir = ctx.obj.get("output_dir", PROJECT_ROOT)
if dry_run:
click.secho("DRY RUN - no files will be written", fg="yellow")
# Config is always in PROJECT_ROOT/config
config_path = PROJECT_ROOT / "config" / "lists.yml"
if not config_path.exists():
click.secho(f"Error: Config file not found: {config_path}", fg="red")
sys.exit(1)
# Determine which lists to build
config = load_config(config_path)
if list_name:
lists_to_build = list(list_name)
# Validate list names
available = get_list_names(config)
for name in lists_to_build:
if name not in available:
click.secho(f"Error: Unknown list '{name}'", fg="red")
click.echo(f"Available lists: {', '.join(sorted(available))}")
sys.exit(1)
else:
lists_to_build = None # Build all
# Run the pipeline
if verbose:
click.echo(f"Building lists: {lists_to_build or 'all'}")
click.echo(f"Output directory: {output_dir}")
result = run_pipeline(
config_path=config_path,
base_dir=output_dir,
lists=lists_to_build,
dry_run=dry_run,
validate=validate,
)
# Display results
_display_results(result, verbose, strict)
elapsed = time.time() - start_time
click.echo(f"\nCompleted in {elapsed:.2f}s")
# Exit with error if strict mode and there were warnings/errors
if strict and (result.errors or result.warnings):
sys.exit(1)
@cli.command()
@click.argument("list_name")
@click.pass_context
def single(ctx, list_name):
"""Build a single blocklist."""
output_dir = ctx.obj.get("output_dir", PROJECT_ROOT)
dry_run = ctx.obj.get("dry_run", False)
validate = ctx.obj.get("validate", False)
verbose = ctx.obj.get("verbose", False)
config_path = PROJECT_ROOT / "config" / "lists.yml"
config = load_config(config_path)
available = get_list_names(config)
if list_name not in available:
click.secho(f"Error: Unknown list '{list_name}'", fg="red")
click.echo(f"Available lists: {', '.join(sorted(available))}")
sys.exit(1)
result = build_list(
config=config,
list_name=list_name,
base_dir=output_dir,
dry_run=dry_run,
validate=validate,
)
_display_build_result(result, verbose)
@cli.command()
@click.pass_context
def verify(ctx):
"""Verify all output formats are consistent."""
output_dir = ctx.obj.get("output_dir", PROJECT_ROOT)
click.echo("Verifying output consistency...")
inconsistencies = verify_output_consistency(output_dir)
if not inconsistencies:
click.secho("\nAll outputs are consistent!", fg="green")
else:
for list_name, error_msg in inconsistencies:
click.secho(f" ✗ {list_name}: {error_msg}", fg="red")
click.secho("\nSome outputs are inconsistent!", fg="red")
sys.exit(1)
@cli.command("list")
def list_available():
"""Show available blocklists."""
config_path = PROJECT_ROOT / "config" / "lists.yml"
config = load_config(config_path)
click.echo("\nAvailable blocklists:\n")
lists = config.get("lists", {})
for name, info in sorted(lists.items()):
status = info.get("status", "unknown")
status_color = {"stable": "green", "beta": "yellow", "deprecated": "red"}.get(status, "white")
categories = ", ".join(info.get("categories", []))
click.echo(f" {name}")
click.secho(f" Status: {status}", fg=status_color)
if categories:
click.echo(f" Categories: {categories}")
if "description" in info:
click.echo(f" {info['description']}")
click.echo(f"\nTotal: {len(lists)} lists")
@cli.command()
@click.pass_context
def stats(ctx):
"""Show statistics for built lists."""
output_dir = ctx.obj.get("output_dir", PROJECT_ROOT)
config_path = PROJECT_ROOT / "config" / "lists.yml"
config = load_config(config_path)
lists = get_list_names(config)
click.echo("\nBlocklist Statistics:\n")
click.echo(f"{'List':<20} {'Domains':>12} {'Status':<10}")
click.echo("-" * 45)
total_domains = 0
for list_name in sorted(lists):
# Check the hosts format file (root directory)
hosts_file = output_dir / f"{list_name}.txt"
if hosts_file.exists():
with open(hosts_file, "r", encoding="utf-8") as f:
# Count non-comment, non-empty lines
count = sum(1 for line in f if line.strip() and not line.startswith("#"))
status = click.style("✓", fg="green")
else:
count = 0
status = click.style("✗", fg="red")
total_domains += count
click.echo(f"{list_name:<20} {count:>12,} {status}")
click.echo("-" * 45)
click.echo(f"{'Total':<20} {total_domains:>12,}")
def _display_results(result: PipelineResult, verbose: bool, strict: bool):
"""Display pipeline results."""
click.echo("\n" + "=" * 50)
click.echo("Build Summary")
click.echo("=" * 50)
# Success count (use the pre-computed values from PipelineResult)
successful = result.successful
failed = result.failed
if failed == 0:
click.secho(f"✓ {successful} lists built successfully", fg="green")
else:
click.secho(f"✓ {successful} lists built successfully", fg="green")
click.secho(f"✗ {failed} lists failed", fg="red")
# Total domains
total_domains = sum(r.domain_count for r in result.results)
click.echo(f"Total domains: {total_domains:,}")
# Errors
if result.errors:
click.secho(f"\nErrors ({len(result.errors)}):", fg="red")
for error in result.errors[:10]:
click.echo(f" - {error}")
if len(result.errors) > 10:
click.echo(f" ... and {len(result.errors) - 10} more")
# Verbose: show each list
if verbose:
click.echo("\nPer-list details:")
for r in result.results:
_display_build_result(r, verbose=False)
def _display_build_result(result: BuildResult, verbose: bool):
"""Display a single build result."""
# Successful if it has domains
is_success = result.domain_count > 0
if is_success:
status = click.style("✓", fg="green")
else:
status = click.style("✗", fg="red")
click.echo(f" {status} {result.name}: {result.domain_count:,} domains")
if result.validation_errors and verbose:
click.secho(f" {result.validation_errors} validation errors", fg="yellow")
if __name__ == "__main__":
cli(obj={})