Adrian Nier Code

Back to overview

Relative POSIX path

Last modification: Saturday, November 14, 2009 11:23 pm

Examines two posix paths and returns the relative path that leads from the first path to the second.

Required parameters
Parameter 1 (string)
Starting posix path

Parameter 2 (string)
Ending posix path

Implementation

on relativePosixPath(_path1, _path2)
   
   -- Break paths into components
   set _prvDlmt to text item delimiters
   set text item delimiters to "/"
   set _components1 to text items of _path1
   set _components2 to text items of _path2
   set text item delimiters to _prvDlmt
   
   -- Compare components of both paths and determine at which point they differ
   repeat with _i from 1 to count of _components1
      try
         if item _i of _components1 is not item _i of _components2 then exit repeat
      on error
         exit repeat
      end try
   end repeat
   
   -- If necessary, create a path prefix to go up the hierarchy
   set _pathPrefix to ""
   repeat ((count of _components1) - _i) times
      set _pathPrefix to _pathPrefix & "../"
   end repeat
   
   -- Combine components
   if _i > (count of _components2) then set _i to count of _components2
   set _prvDlmt to text item delimiters
   set text item delimiters to "/"
   set _relativePath to items _i thru -1 of _components2 as string
   set text item delimiters to _prvDlmt
   
   -- Return relative path 
   return _pathPrefix & _relativePath
   
   
end relativePosixPath