Skip to content

Instantly share code, notes, and snippets.

@RhetTbull
Last active June 30, 2024 15:55
Show Gist options
  • Save RhetTbull/474d931eebeb0047cc3a0b46d29d7f6d to your computer and use it in GitHub Desktop.
Save RhetTbull/474d931eebeb0047cc3a0b46d29d7f6d to your computer and use it in GitHub Desktop.
Resolve macOS alias path in Python
"""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