Last active
October 22, 2024 03:11
-
-
Save RhetTbull/474d931eebeb0047cc3a0b46d29d7f6d to your computer and use it in GitHub Desktop.
Resolve macOS alias path in Python
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 macOS alias file | |
Given a path to a file that is a macOS alias, resolve the path to the original file | |
Requires: pip install pyobjc-core | |
""" | |
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