# abspath.rb
#
# Copyright (c) 2001 Adam Spiers <adam@spiers.net>. All rights reserved.
# This program is free software; you can redistribute it and/or modify it
# under the same terms as Ruby itself.

def File.abs_path(path)
  path = File.expand_path path

  # Deal with directories first, they're easier.
  if test(?d, path)
    return path unless test(?l, path)

    # It's a link.
    readlink_text = File.readlink path

    # absolute
    return readlink_text if readlink_text =~ %r!^/!
    
    # relative
    return File.expand_path(File.dirname(path) + '/' + readlink_text)
  end

  file = File.basename path
  dir  = File.expand_path File.dirname(path)

  while test(?l, path)
    readlink_text = File.readlink path
    path = (readlink_text =~ %r!^/!) ?
             readlink_text : abs_path(dir) + '/' + readlink_text
    path = File.expand_path path
    file = File.basename path
    dir  = File.expand_path File.dirname(path)
    path = dir + '/' + file
  end

  return dir + '/' + file
end
