-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpaths.py
More file actions
214 lines (173 loc) · 6.99 KB
/
Copy pathpaths.py
File metadata and controls
214 lines (173 loc) · 6.99 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
"""Shared ARGUS path layout for curated data vs raw runtime artifacts.
Version-worthy outputs live under ``data/argus``.
Heavy, sensitive, or ephemeral runtime artifacts live under ``artifacts/argus``.
"""
from __future__ import annotations
import hashlib
import shutil
from dataclasses import dataclass, field
from pathlib import Path
from typing import Dict, Iterable, List, Tuple
ROOT = Path(__file__).resolve().parents[2]
# ──── Versionable ARGUS data ───────────────────────────────────────────────────
DATA_DIR = ROOT / "data" / "argus"
SELECTORS_DIR = DATA_DIR / "selectors"
PROTOS_DIR = DATA_DIR / "protos"
REGISTRY_PATH = DATA_DIR / "registry.json"
FEATURE_FLAGS_PATH = DATA_DIR / "feature_flags.json"
HAR_SCAN_REPORT_PATH = DATA_DIR / "har_scan_report.json"
SDK_AUDIT_REPORT_PATH = DATA_DIR / "sdk_audit.json"
# ──── Ignored raw/runtime ARGUS artifacts ──────────────────────────────────────
RAW_DIR = ROOT / "artifacts" / "argus"
HAR_DIR = RAW_DIR / "har"
SCREENSHOTS_DIR = RAW_DIR / "screenshots"
REPORTS_DIR = RAW_DIR / "reports"
CAPTURES_DIR = RAW_DIR / "captures"
HEAP_DIR = RAW_DIR / "heaps"
PAYLOADS_DIR = RAW_DIR / "payloads"
PCAP_DIR = RAW_DIR / "pcap"
TOKENS_DIR = RAW_DIR / "tokens"
HISTORY_DIR = RAW_DIR / "history"
STATE_DIR = RAW_DIR / "state"
TLS_DIR = RAW_DIR / "tls"
BROWSER_PROFILES_DIR = RAW_DIR / "browser_profiles"
CHROME_PROFILE_DIR = BROWSER_PROFILES_DIR / "chrome_profile"
SSLKEYS_PATH = TLS_DIR / "sslkeys.log"
NLM_PIPELINE_STATE_PATH = STATE_DIR / "nlm_pipeline_state.json"
QA_SEEDER_PROGRESS_PATH = STATE_DIR / "qa_seeder_progress.json"
# Versioned helper script; screenshots themselves go to SCREENSHOTS_DIR.
SCREENSHOT_SCRIPT_PATH = ROOT / "scripts" / "argus" / "screenshot.ps1"
def ensure_argus_directories() -> None:
"""Create the ARGUS directory structure if it does not already exist."""
for directory in (
DATA_DIR,
SELECTORS_DIR,
PROTOS_DIR,
RAW_DIR,
HAR_DIR,
SCREENSHOTS_DIR,
REPORTS_DIR,
CAPTURES_DIR,
HEAP_DIR,
PAYLOADS_DIR,
PCAP_DIR,
TOKENS_DIR,
HISTORY_DIR,
STATE_DIR,
TLS_DIR,
BROWSER_PROFILES_DIR,
):
directory.mkdir(parents=True, exist_ok=True)
def history_path(target: str) -> Path:
"""Return the raw runtime history path for a crawler target."""
return HISTORY_DIR / f"{target}_history.json"
@dataclass
class ArtifactMigrationResult:
"""Result of migrating legacy ARGUS artifact locations."""
moved: List[str] = field(default_factory=list)
skipped: List[str] = field(default_factory=list)
errors: List[str] = field(default_factory=list)
removed_legacy: List[str] = field(default_factory=list)
def as_dict(self) -> Dict[str, List[str]]:
"""Return a JSON-serializable summary."""
return {
"moved": list(self.moved),
"skipped": list(self.skipped),
"errors": list(self.errors),
"removed_legacy": list(self.removed_legacy),
}
def _file_digest(path: Path) -> str:
digest = hashlib.sha256()
with path.open("rb") as fh:
for chunk in iter(lambda: fh.read(1024 * 1024), b""):
digest.update(chunk)
return digest.hexdigest()
def _same_file(source: Path, destination: Path) -> bool:
if not source.exists() or not destination.exists():
return False
if source.stat().st_size != destination.stat().st_size:
return False
return _file_digest(source) == _file_digest(destination)
def _unique_destination(destination: Path) -> Path:
if not destination.exists():
return destination
index = 1
while True:
candidate = destination.with_name(
f"{destination.stem}_legacy{index}{destination.suffix}"
)
if not candidate.exists():
return candidate
index += 1
def _move_file(source: Path, destination: Path, result: ArtifactMigrationResult) -> None:
if not source.exists():
return
destination.parent.mkdir(parents=True, exist_ok=True)
try:
if destination.exists():
if _same_file(source, destination):
source.unlink()
result.skipped.append(f"{source} -> {destination} (duplicate)")
return
destination = _unique_destination(destination)
shutil.move(str(source), str(destination))
result.moved.append(f"{source} -> {destination}")
except Exception as exc: # pragma: no cover - defensive
result.errors.append(f"{source} -> {destination}: {exc}")
def _merge_directory(
source: Path,
destination: Path,
result: ArtifactMigrationResult,
) -> None:
if not source.exists():
return
destination.mkdir(parents=True, exist_ok=True)
for child in list(source.iterdir()):
target = destination / child.name
if child.is_dir():
_merge_directory(child, target, result)
else:
_move_file(child, target, result)
try:
source.rmdir()
result.removed_legacy.append(str(source))
except OSError:
# Non-empty or locked; leave it in place and let the caller inspect it.
pass
def _legacy_directory_moves() -> Iterable[Tuple[Path, Path]]:
legacy_data_dir = ROOT / "data"
return (
(legacy_data_dir / "har_files" / "users_dump_folder" / "screenshots", SCREENSHOTS_DIR),
(legacy_data_dir / "har_files", HAR_DIR),
(DATA_DIR / "har", HAR_DIR),
(DATA_DIR / "captures", CAPTURES_DIR),
(DATA_DIR / "heaps", HEAP_DIR),
(DATA_DIR / "reports", REPORTS_DIR),
(DATA_DIR / "payloads", PAYLOADS_DIR),
(DATA_DIR / "tokens", TOKENS_DIR),
(DATA_DIR / "chrome_profile", CHROME_PROFILE_DIR),
)
def _legacy_file_moves() -> Iterable[Tuple[Path, Path]]:
return (
(DATA_DIR / "sslkeys.log", SSLKEYS_PATH),
(DATA_DIR / "nlm_state.png", SCREENSHOTS_DIR / "nlm_state.png"),
(DATA_DIR / "qa_seeder_progress.json", QA_SEEDER_PROGRESS_PATH),
(DATA_DIR / "nlm_pipeline_state.json", NLM_PIPELINE_STATE_PATH),
)
def migrate_legacy_artifacts() -> ArtifactMigrationResult:
"""Move legacy ARGUS raw artifacts into the ignored artifact root.
The migration is best-effort and idempotent:
- files are never overwritten silently
- duplicate files are collapsed
- legacy directories are removed only when emptied
"""
ensure_argus_directories()
result = ArtifactMigrationResult()
for source, destination in _legacy_directory_moves():
_merge_directory(source, destination, result)
for source, destination in _legacy_file_moves():
_move_file(source, destination, result)
for history_file in list(DATA_DIR.glob("*_history.json")):
_move_file(history_file, HISTORY_DIR / history_file.name, result)
return result
ensure_argus_directories()