Created
May 27, 2024 00:21
-
-
Save RhetTbull/6f72f1546174f91d30b35ec013589fd7 to your computer and use it in GitHub Desktop.
Resolve path to original file pointed to by macOS alias
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
"""Resolve path to original file pointed to by macOS alias | |
To use: | |
pip install pyobjc-core | |
python3 resolve_macos_alias_path.py /path/to/alias | |
""" | |
from Foundation import ( | |
NSURL, | |
NSData, | |
NSError, | |
NSURLBookmarkResolutionWithoutMounting, | |
NSURLBookmarkResolutionWithoutUI, | |
) | |
def resolve_alias_path(alias_path: str) -> str: | |
"""Given a path to a macOS alias file, return the resolved path to the original file""" | |
options = NSURLBookmarkResolutionWithoutUI | NSURLBookmarkResolutionWithoutMounting | |
alias_url = NSURL.fileURLWithPath_(alias_path) | |
bookmark, error = NSURL.bookmarkDataWithContentsOfURL_error_(alias_url, None) | |
if error: | |
raise ValueError(f"Error creating bookmark data: {error}") | |
resolved_url, is_stale, error = ( | |
NSURL.URLByResolvingBookmarkData_options_relativeToURL_bookmarkDataIsStale_error_( | |
bookmark, options, None, None, None | |
) | |
) | |
if error: | |
raise ValueError(f"Error resolving bookmark data: {error}") | |
return str(resolved_url.path()) | |
if __name__ == "__main__": | |
import sys | |
if len(sys.argv) < 2: | |
print("Usage: python alias.py <alias_path>") | |
sys.exit(1) | |
alias_path = sys.argv[1] | |
resolved_path = resolve_alias_path(alias_path) | |
print(f"alias: {alias_path}\noriginal: {resolved_path}") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment