-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpathbridge.py
More file actions
648 lines (529 loc) · 20 KB
/
pathbridge.py
File metadata and controls
648 lines (529 loc) · 20 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
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
#!/usr/bin/env python3
"""
PathBridge - Universal Path Translator
Seamlessly convert paths between Windows, WSL, and Unix formats.
One path to rule them all!
Features:
- Auto-detect input format (Windows, WSL, Unix)
- Smart output format (opposite of input, or specify)
- Clipboard integration (--clipboard flag)
- Batch mode (process multiple paths)
- Python API for integration into other tools
- Zero dependencies (Python stdlib only)
Author: ATLAS (Team Brain)
For: Logan Smith / Metaphy LLC
Version: 1.0.0
Date: January 23, 2026
License: MIT
Usage:
pathbridge "D:\\BEACON_HQ\\file.txt" # Auto-converts to WSL
pathbridge "/mnt/d/BEACON_HQ/file.txt" # Auto-converts to Windows
pathbridge --to wsl "D:\\BEACON_HQ" # Force WSL output
pathbridge --to win "/mnt/d/BEACON_HQ" # Force Windows output
pathbridge --clipboard # Convert clipboard contents
echo "path1\\npath2" | pathbridge # Batch mode via stdin
Python API:
from pathbridge import PathBridge
pb = PathBridge()
result = pb.convert("D:\\\\BEACON_HQ\\\\file.txt")
print(result) # /mnt/d/BEACON_HQ/file.txt
"""
import argparse
import os
import re
import sys
from pathlib import Path
from typing import Optional, Literal, Tuple
__version__ = "1.0.0"
__author__ = "ATLAS (Team Brain)"
# Type definitions
PathFormat = Literal["windows", "wsl", "unix", "unknown"]
class PathBridge:
"""
Universal path translator for Windows, WSL, and Unix paths.
Automatically detects path format and converts to the target format.
If no target is specified, converts between Windows and WSL (the most
common use case in Team Brain workflows).
Attributes:
custom_mappings: Optional dict of custom drive letter mappings
Example:
>>> pb = PathBridge()
>>> pb.convert("D:\\\\BEACON_HQ\\\\file.txt")
'/mnt/d/BEACON_HQ/file.txt'
>>> pb.convert("/mnt/d/BEACON_HQ/file.txt")
'D:\\\\BEACON_HQ\\\\file.txt'
"""
# Regex patterns for path detection
WINDOWS_PATTERN = re.compile(r'^[A-Za-z]:[\\\/]')
WSL_PATTERN = re.compile(r'^/mnt/[a-z]/')
UNIX_PATTERN = re.compile(r'^/(?!mnt/[a-z]/)')
UNC_PATTERN = re.compile(r'^\\\\')
def __init__(self, custom_mappings: Optional[dict] = None):
"""
Initialize PathBridge.
Args:
custom_mappings: Optional dict mapping drive letters to WSL mount points.
Default maps X: to /mnt/x/
"""
self.custom_mappings = custom_mappings or {}
def detect_format(self, path: str) -> PathFormat:
"""
Detect the format of a given path.
Args:
path: The path string to analyze
Returns:
One of: "windows", "wsl", "unix", "unknown"
Example:
>>> pb = PathBridge()
>>> pb.detect_format("D:\\\\BEACON_HQ")
'windows'
>>> pb.detect_format("/mnt/d/BEACON_HQ")
'wsl'
>>> pb.detect_format("/home/user/file.txt")
'unix'
"""
if not path or not isinstance(path, str):
return "unknown"
path = path.strip()
# Check for UNC paths (\\server\share)
if self.UNC_PATTERN.match(path):
return "windows"
# Check for Windows drive letter paths (C:\, D:\, etc.)
if self.WINDOWS_PATTERN.match(path):
return "windows"
# Check for WSL mount paths (/mnt/c/, /mnt/d/, etc.)
if self.WSL_PATTERN.match(path):
return "wsl"
# Check for Unix-style paths (starts with / but not /mnt/x/)
if self.UNIX_PATTERN.match(path):
return "unix"
# Relative paths or unknown
if '\\' in path:
return "windows"
elif '/' in path:
return "unix"
return "unknown"
def windows_to_wsl(self, path: str) -> str:
"""
Convert a Windows path to WSL format.
Args:
path: Windows path (e.g., "D:\\BEACON_HQ\\file.txt")
Returns:
WSL path (e.g., "/mnt/d/BEACON_HQ/file.txt")
Example:
>>> pb = PathBridge()
>>> pb.windows_to_wsl("D:\\\\BEACON_HQ\\\\file.txt")
'/mnt/d/BEACON_HQ/file.txt'
"""
if not path:
return path
path = path.strip()
# Handle drive letter (C:, D:, etc.)
if len(path) >= 2 and path[1] == ':':
drive_letter = path[0].lower()
rest = path[2:]
# Check for custom mapping
if drive_letter.upper() in self.custom_mappings:
mount_point = self.custom_mappings[drive_letter.upper()]
else:
mount_point = f"/mnt/{drive_letter}"
# Convert backslashes to forward slashes
rest = rest.replace('\\', '/')
# Remove leading slash if present (we'll add the mount point)
rest = rest.lstrip('/')
return f"{mount_point}/{rest}" if rest else mount_point
# If no drive letter, just convert slashes
return path.replace('\\', '/')
def wsl_to_windows(self, path: str) -> str:
"""
Convert a WSL path to Windows format.
Args:
path: WSL path (e.g., "/mnt/d/BEACON_HQ/file.txt")
Returns:
Windows path (e.g., "D:\\BEACON_HQ\\file.txt")
Example:
>>> pb = PathBridge()
>>> pb.wsl_to_windows("/mnt/d/BEACON_HQ/file.txt")
'D:\\\\BEACON_HQ\\\\file.txt'
"""
if not path:
return path
path = path.strip()
# Check for /mnt/x/ pattern
match = re.match(r'^/mnt/([a-z])(/.*)?$', path)
if match:
drive_letter = match.group(1).upper()
rest = match.group(2) or ''
# Convert forward slashes to backslashes
rest = rest.replace('/', '\\')
return f"{drive_letter}:{rest}"
# Check for custom mappings (reverse lookup)
for drive, mount in self.custom_mappings.items():
if path.startswith(mount):
rest = path[len(mount):]
rest = rest.replace('/', '\\')
return f"{drive}:{rest}"
# If not a mount path, just convert slashes
return path.replace('/', '\\')
def unix_to_wsl(self, path: str) -> str:
"""
Convert a Unix path to WSL format.
Note: Pure Unix paths (like /home/user) remain unchanged in WSL
since WSL has its own filesystem. This method is included for
completeness and future expansion.
Args:
path: Unix path (e.g., "/home/user/file.txt")
Returns:
WSL path (same as input for pure Unix paths)
"""
# Unix paths are already valid in WSL
return path
def convert(self, path: str, target: Optional[PathFormat] = None) -> str:
"""
Convert a path to the specified target format.
If no target is specified, intelligently converts:
- Windows -> WSL
- WSL -> Windows
- Unix -> unchanged (or WSL if specified)
Args:
path: The path to convert
target: Target format ("windows", "wsl", "unix", or None for auto)
Returns:
Converted path string
Raises:
ValueError: If path is empty or None
Example:
>>> pb = PathBridge()
>>> pb.convert("D:\\\\BEACON_HQ")
'/mnt/d/BEACON_HQ'
>>> pb.convert("/mnt/d/BEACON_HQ")
'D:\\\\BEACON_HQ'
>>> pb.convert("D:\\\\BEACON_HQ", target="wsl")
'/mnt/d/BEACON_HQ'
"""
if not path:
raise ValueError("Path cannot be empty or None")
source = self.detect_format(path)
# Auto-detect target if not specified
if target is None:
if source == "windows":
target = "wsl"
elif source == "wsl":
target = "windows"
elif source == "unix":
target = "wsl" # Unix paths stay the same in WSL
else:
# Unknown format, return as-is
return path
# Convert based on source and target
if source == "windows":
if target == "wsl" or target == "unix":
return self.windows_to_wsl(path)
else:
return path # Already Windows
elif source == "wsl":
if target == "windows":
return self.wsl_to_windows(path)
else:
return path # Already WSL
elif source == "unix":
if target == "windows":
# Pure Unix paths can't be converted to Windows
return path
else:
return path # Already Unix/WSL compatible
# Unknown source, return as-is
return path
def convert_batch(self, paths: list, target: Optional[PathFormat] = None) -> list:
"""
Convert multiple paths at once.
Args:
paths: List of path strings
target: Target format (optional, auto-detects if None)
Returns:
List of converted path strings
Example:
>>> pb = PathBridge()
>>> pb.convert_batch(["D:\\\\a", "D:\\\\b"])
['/mnt/d/a', '/mnt/d/b']
"""
return [self.convert(p, target) for p in paths if p]
def get_info(self, path: str) -> dict:
"""
Get detailed information about a path.
Args:
path: The path to analyze
Returns:
Dictionary with path information including:
- original: The original path
- format: Detected format
- windows: Windows version
- wsl: WSL version
- exists: Whether path exists (if detectable)
Example:
>>> pb = PathBridge()
>>> info = pb.get_info("D:\\\\BEACON_HQ")
>>> info['format']
'windows'
"""
source = self.detect_format(path)
info = {
"original": path,
"format": source,
"windows": None,
"wsl": None,
"unix": None,
"exists": None
}
# Generate all versions
if source == "windows":
info["windows"] = path
info["wsl"] = self.windows_to_wsl(path)
elif source == "wsl":
info["wsl"] = path
info["windows"] = self.wsl_to_windows(path)
elif source == "unix":
info["unix"] = path
info["wsl"] = path
# Check if path exists (Windows paths on Windows, etc.)
try:
if info["windows"] and os.path.exists(info["windows"]):
info["exists"] = True
elif info["wsl"] and os.path.exists(info["wsl"]):
info["exists"] = True
elif info["unix"] and os.path.exists(info["unix"]):
info["exists"] = True
else:
info["exists"] = False
except Exception:
info["exists"] = None
return info
def get_clipboard_content() -> Optional[str]:
"""
Get content from the system clipboard.
Uses platform-specific methods without external dependencies.
Returns:
Clipboard content as string, or None if unavailable
"""
import subprocess
try:
if sys.platform == 'win32':
# Windows: Use PowerShell
result = subprocess.run(
['powershell', '-command', 'Get-Clipboard'],
capture_output=True,
text=True,
timeout=5
)
return result.stdout.strip() if result.returncode == 0 else None
elif sys.platform == 'darwin':
# macOS: Use pbpaste
result = subprocess.run(
['pbpaste'],
capture_output=True,
text=True,
timeout=5
)
return result.stdout.strip() if result.returncode == 0 else None
else:
# Linux: Try xclip or xsel
for cmd in [['xclip', '-selection', 'clipboard', '-o'], ['xsel', '--clipboard', '--output']]:
try:
result = subprocess.run(
cmd,
capture_output=True,
text=True,
timeout=5
)
if result.returncode == 0:
return result.stdout.strip()
except FileNotFoundError:
continue
return None
except Exception:
return None
def set_clipboard_content(content: str) -> bool:
"""
Set content to the system clipboard.
Args:
content: String to copy to clipboard
Returns:
True if successful, False otherwise
"""
import subprocess
try:
if sys.platform == 'win32':
# Windows: Use PowerShell
result = subprocess.run(
['powershell', '-command', f'Set-Clipboard -Value "{content}"'],
capture_output=True,
timeout=5
)
return result.returncode == 0
elif sys.platform == 'darwin':
# macOS: Use pbcopy
result = subprocess.run(
['pbcopy'],
input=content,
text=True,
timeout=5
)
return result.returncode == 0
else:
# Linux: Try xclip or xsel
for cmd in [['xclip', '-selection', 'clipboard'], ['xsel', '--clipboard', '--input']]:
try:
result = subprocess.run(
cmd,
input=content,
text=True,
timeout=5
)
if result.returncode == 0:
return True
except FileNotFoundError:
continue
return False
except Exception:
return False
def create_parser() -> argparse.ArgumentParser:
"""Create and return the argument parser."""
parser = argparse.ArgumentParser(
prog='pathbridge',
description='PathBridge - Universal Path Translator. One path to rule them all!',
formatter_class=argparse.RawDescriptionHelpFormatter,
epilog="""
Examples:
pathbridge "D:\\BEACON_HQ\\file.txt" # Auto-convert to WSL
pathbridge "/mnt/d/BEACON_HQ/file.txt" # Auto-convert to Windows
pathbridge --to wsl "D:\\BEACON_HQ" # Force WSL output
pathbridge --to win "/mnt/d/BEACON_HQ" # Force Windows output
pathbridge --clipboard # Convert clipboard contents
pathbridge --info "D:\\BEACON_HQ" # Show path information
echo "D:\\path1" | pathbridge # Pipe mode
Supported Formats:
windows Windows paths (C:\\Users\\..., D:\\BEACON_HQ\\...)
wsl WSL mount paths (/mnt/c/Users/..., /mnt/d/BEACON_HQ/...)
unix Pure Unix paths (/home/user/..., /opt/...)
For more information: https://github.com/DonkRonk17/PathBridge
"""
)
parser.add_argument(
'path',
nargs='?',
help='Path to convert (or use --clipboard, or pipe via stdin)'
)
parser.add_argument(
'--to', '-t',
choices=['windows', 'win', 'wsl', 'unix'],
dest='target',
help='Target format (windows/win, wsl, unix). Default: auto-detect opposite'
)
parser.add_argument(
'--clipboard', '-c',
action='store_true',
help='Read path from clipboard and copy result back'
)
parser.add_argument(
'--info', '-i',
action='store_true',
help='Show detailed information about the path'
)
parser.add_argument(
'--quiet', '-q',
action='store_true',
help='Only output the converted path (no labels)'
)
parser.add_argument(
'--version', '-v',
action='version',
version=f'PathBridge {__version__}'
)
return parser
def normalize_target(target: Optional[str]) -> Optional[PathFormat]:
"""Normalize target format string."""
if target is None:
return None
target = target.lower()
if target in ('windows', 'win'):
return 'windows'
elif target == 'wsl':
return 'wsl'
elif target == 'unix':
return 'unix'
return None
def main():
"""Main CLI entry point."""
parser = create_parser()
args = parser.parse_args()
pb = PathBridge()
target = normalize_target(args.target)
# Determine input source
paths_to_convert = []
if args.clipboard:
# Read from clipboard
content = get_clipboard_content()
if content is None:
print("[X] Error: Could not read from clipboard", file=sys.stderr)
sys.exit(1)
paths_to_convert = [line.strip() for line in content.split('\n') if line.strip()]
elif args.path:
# Use provided path argument
paths_to_convert = [args.path]
elif not sys.stdin.isatty():
# Read from stdin (pipe mode)
paths_to_convert = [line.strip() for line in sys.stdin if line.strip()]
else:
# No input provided
parser.print_help()
sys.exit(0)
# Process paths
results = []
for path in paths_to_convert:
try:
if args.info:
# Show detailed info
info = pb.get_info(path)
if args.quiet:
print(f"Format: {info['format']}")
if info['windows']:
print(f"Windows: {info['windows']}")
if info['wsl']:
print(f"WSL: {info['wsl']}")
else:
print(f"\n[INFO] Path Information")
print(f" Original: {info['original']}")
print(f" Format: {info['format']}")
if info['windows']:
print(f" Windows: {info['windows']}")
if info['wsl']:
print(f" WSL: {info['wsl']}")
if info['unix']:
print(f" Unix: {info['unix']}")
if info['exists'] is not None:
exists_str = "[OK] Exists" if info['exists'] else "[X] Not found"
print(f" Status: {exists_str}")
else:
# Convert path
result = pb.convert(path, target)
results.append(result)
if args.quiet:
print(result)
else:
source_format = pb.detect_format(path)
result_format = pb.detect_format(result)
print(f"[OK] {source_format} -> {result_format}: {result}")
except Exception as e:
print(f"[X] Error converting '{path}': {e}", file=sys.stderr)
sys.exit(1)
# Copy results to clipboard if --clipboard was used
if args.clipboard and results and not args.info:
combined = '\n'.join(results)
if set_clipboard_content(combined):
if not args.quiet:
print(f"\n[OK] Copied to clipboard")
else:
if not args.quiet:
print(f"\n[!] Warning: Could not copy to clipboard", file=sys.stderr)
if __name__ == "__main__":
main()