update.
[chise/ruby.git] / chise / path.rb
1 # Copyright (C) 2002-2004 Kouichirou Eto, All rights reserved.
2
3 require "pathname"
4 require "chise/config"
5
6 class String
7   def path
8     Pathname.new(self)
9   end
10 end
11
12 class Pathname
13   def escape
14     s = self.to_s.gsub(/([\/%]+)/n){
15       "%" + $1.unpack("H2" * $1.size).join("%").upcase
16     }
17     Pathname.new(s)
18   end
19
20   def unescape # copied from cgi.rb
21     s = @path.tr("+", " ").gsub(/((?:%[0-9a-fA-F]{2})+)/n) {
22       [$1.delete("%")].pack("H*")
23     }
24     Pathname.new(s)
25   end
26
27   # translate file name for deal with the restriction of Windows file system.
28   def unix_to_win
29     win = @path.gsub(/</, "(")
30     win = win.gsub(/>/, ")")
31     win = win.gsub(/\*/, "+")
32     win = win.gsub(/\?/, "!")
33     Pathname.new(win)
34   end
35
36   def win_to_unix
37     unix = @path.gsub(/\)/, ">")
38     unix = unix.gsub(/\(/, "<")
39     unix = unix.gsub(/\!/, "?")
40     unix = unix.gsub(/\+/, "*")
41     Pathname.new(unix)
42   end
43
44   def escape_win_filename
45     return self.unix_to_win if CHISE.windows?
46     self
47   end
48
49   def unescape_win_filename
50     return self.win_to_unix if CHISE.windows?
51     self
52   end
53 end