2015-06-11 2 views
1

StandardAdditions имеет команду path to, и мы можем использовать ее для получения известных мест.Развернуть путь POSIX с префиксом «~» (используя AppleScript)

Например, path to home folder возвращает ссылку на файл в user folder и если мы хотим posix path, мы можем сделать POSIX path of ((path to home folder) as text).


В Terminal.app мы можем использовать символ тильды (~) представлять home folder.

Как мы можем это сделать tilde expanding в AppleScript?

ответ

0

Более скоро


Как расширить posix path, который может начать с tilde характер ~?
(~ представляет home folder)

Вот сценарий + демо:

# 

demo() 

# ------------------------------------------------------------ 
# 
# expandTildeInPath (localPath, outputStyle) 
# 
# ------------------------------------------------------------ 
# When outputStyle is true : returns posix path 
# When outputStyle is false : returns alias 
# ------------------------------------------------------------ 
# localPath format: 
# ------------------------------------------------------------ 
# • posix path - a posix path (can start with a tilde "~") 
# • alias 
# • path (text) with ":" => (alias as text) produces this 
# ------------------------------------------------------------ 
on expandTildeInPath(localPath, outputStyle) 

    # ------------------------------------------------------------ 
    # If necessary, convert localPath to text and posix path: 
    # ------------------------------------------------------------ 

    if (class of localPath is alias) then 
     # alias 
     set localPath to POSIX path of (localPath as text) 
    else if (class of localPath is text) and (localPath contains ":") then 
     # (fileAlias as text) produces such a colon delimited path: 
     set localPath to POSIX path of localPath 
    end if 

    set resultPath to localPath 

    # ------------------------------- 
    # If necessary, expand tilde: 
    # ------------------------------- 

    if localPath starts with "~" then 

     # input is like: "~", "~/" or something with a sub path, like "~/Movies" 
     set homeFolder to POSIX path of ((path to home folder) as text) 
     if (localPath = "~") or (localPath = "~/") then 
      # no sub-path 
      set resultPath to homeFolder 
     else 
      if not (localPath starts with "~/") then 
       # this is not a valid path to expand but an item that starts with "~" 
       return localPath 
      end if 
      # add sub-path 
      set subPath to ((characters 3 thru -1) of aPath) as text 
      set sDel to "/" 
      if (subPath starts with sDel) then set sDel to "" 
      set resultPath to homeFolder & sDel & subPath 
     end if 
    end if 

    # ------------------------------- 
    # return posix path or alias: 
    # ------------------------------- 

    if outputStyle then 
     return (POSIX path of resultPath) 
    else 
     # the location must exist or "as alias" throws an error. 
     try 
      set a to (resultPath as POSIX file) as alias 
      return a 
     on error 
      log "*** Error ***" & resultPath & " does not exist" 
      return localPath 
     end try 
    end if 

end expandTildeInPath 





# ------------------------------------------------------------ 
# Sub Routines for Demo 
# ------------------------------------------------------------ 

on demo() 

    set asAlias to false 
    set asPosixPath to true 

    # Does not expand since its a name that starts with "~": 
    logDemo("~testFile", asAlias) 

    # FolderThatDoesNotExist: 
    logDemo("~/FolderThatDoesNotExist", asAlias) # this throws an error (in the log) and returns the unchanged input 
    logDemo("~/FolderThatDoesNotExist", asPosixPath) # returns expanded posix path (existing or not) 

    # Main Usage 
    logDemo("~", asPosixPath) 
    logDemo("~", asAlias) 
    logDemo("~/", asPosixPath) 
    logDemo("~/", asAlias) 

    logDemo("~/Documents/", asPosixPath) 
    logDemo("~/Documents/", asAlias) 

    # convert a posix path like "/Applications" to alias 
    logDemo("/Applications", asAlias) 

    set input to "~/Music/iTunes/iTunes Library.xml" 

    set filePosixPath to expandTildeInPath(input, asPosixPath) 
    set fileAlias to expandTildeInPath(input, asAlias) 

    log quoted form of input 
    log quoted form of filePosixPath 
    log fileAlias 
    logLine() 

    # Using alias with Finder is so easy: 
    tell application "Finder" 
     if exists fileAlias then 
      # activate 
      # reveal fileAlias 
     end if 
    end tell 


    # -------------------------- 
    # Other input formats: 
    # -------------------------- 
    # This is also possible (not intended but it works): 

    # we can use text paths (containing ":"): 
    logDemo((path to documents folder as text), false) 

    # we can use aliases: 
    # (makes no sense at all when we return an alias but this is to show that it works) 
    logDemo((path to documents folder), false) 

    # Same as above but output as posix path: 
    logDemo((path to documents folder as text), true) 
    logDemo((path to documents folder), true) 

end demo 

on logLine() 
    log "---------------------------------------------" 
end logLine 

on logDemo(inputPath, outputStyle) 
    set a to expandTildeInPath(inputPath, outputStyle) 
    if outputStyle then 
     log "input: " & inputPath & " output: " & quoted form of a 
    else 
     log "input: " & inputPath & "  output (next line): " 
     log a # don't mix with text or it does not show the "alias" in the log 
    end if 
    logLine() 
end logDemo 

# ------------------------------------------------------------ 

Вот немного дополнение, чтобы показать системные атрибуты:

set saList to system attribute 
repeat with sa in saList 
    log quoted form of sa & " = " & quoted form of (system attribute sa) 
end repeat 
1

Нулевая

Существует более чем один способ кожи, который кошка. Как вы отметили, или с простым:

"HOME"system attribute

А затем сцепить на оставшейся части пути.

+0

Прохладный | Примечание: 'system attribute' получает список всех определенных переменных среды. –

4

работы с OS X 10.10 вы можете легко получить доступ к Cocoa classes и их функции и свойства:

use framework "Foundation" 

expandTilde("~/Desktop") 

on expandTilde(givenPath) 
    -- create a temporary Obj-C/Cocoa NSString object with the givenPath 
    set tempCocoaString to current application's NSString's stringWithString:givenPath 
    -- call the object's stringByExpandingTildeInPath method 
    -- to create a new path with expanded tilde 
    return (tempCocoaString's stringByExpandingTildeInPath) as string 
end expandTilde 

В 10.9 вы должны определить такие обработчики в Scripting Libraries, это менее приятно, чем это звучит. Но в 10.10 это получается из коробки!

Смежные вопросы