i
[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 nuescape
14     s = @path.gsub(/([\/%]+)/n){
15       "%" + $1.unpack("H2" * $1.size).join("%").upcase
16     }
17     Pathname.new(s)
18   end
19
20   def escape
21 #    s = self.basename.to_s.gsub(/([\/%<>*?]+)/n){
22     s = self.basename.to_s.gsub(/([\/<>*?]+)/n){
23       "%" + $1.unpack("H2" * $1.size).join("%").upcase
24     }
25     Pathname.new(self.dirname+s)
26   end
27
28   def unescape # copied from cgi.rb
29     s = @path.tr("+", " ").gsub(/((?:%[0-9a-fA-F]{2})+)/n) {
30       [$1.delete("%")].pack("H*")
31     }
32     Pathname.new(s)
33   end
34
35   # translate file name for deal with the restriction of Windows file system.
36   def unix_to_win
37     win = @path.gsub(/</, "(")
38     win = win.gsub(/>/, ")")
39     win = win.gsub(/\*/, "+")
40     win = win.gsub(/\?/, "!")
41     Pathname.new(win)
42   end
43
44   def win_to_unix
45     unix = @path.gsub(/\)/, ">")
46     unix = unix.gsub(/\(/, "<")
47     unix = unix.gsub(/\!/, "?")
48     unix = unix.gsub(/\+/, "*")
49     Pathname.new(unix)
50   end
51
52   def escape_win_filename
53     return self.unix_to_win if CHISE.windows?
54     self
55   end
56
57   def unescape_win_filename
58     return self.win_to_unix if CHISE.windows?
59     self
60   end
61 end