Updated MSpec source to 1c3ee1c8.
[rbx.git] / stdlib / ext / iconv / charset_alias.rb
blobaed464429000437cad3279b1c4ed5a342ae8ec32
1 #! /usr/bin/ruby
2 # :stopdoc:
3 require 'rbconfig'
4 require 'optparse'
6 # http://www.ctan.org/tex-archive/macros/texinfo/texinfo/intl/config.charset
7 # Fri, 30 May 2003 00:09:00 GMT'
9 OS = Config::CONFIG["target_os"]
10 SHELL = Config::CONFIG['SHELL']
12 class Hash::Ordered < Hash
13   def [](key)
14     val = super and val.last
15   end
16   def []=(key, val)
17     ary = fetch(key) {return super(key, [self.size, key, val])} and
18       ary << val
19   end
20   def sort
21     values.sort.collect {|i, *rest| rest}
22   end
23   def each(&block)
24     sort.each(&block)
25   end
26 end
28 def charset_alias(config_charset, mapfile, target = OS)
29   map = Hash::Ordered.new
30   comments = []
31   open(config_charset) do |input|
32     input.find {|line| /^case "\$os" in/ =~ line} or break
33     input.find {|line|
34       /^\s*([-\w\*]+(?:\s*\|\s*[-\w\*]+)*)(?=\))/ =~ line and
35       $&.split('|').any? {|pattern| File.fnmatch?(pattern.strip, target)}
36     } or break
37     input.find do |line|
38       case line
39       when /^\s*echo "(?:\$\w+\.)?([-\w*]+)\s+([-\w]+)"/
40         sys, can = $1, $2
41         can.downcase!
42         map[can] = sys
43         false
44       when /^\s*;;/
45         true
46       else
47         false
48       end
49     end
50   end
51   case target
52   when /linux|-gnu/
53     # map.delete('ascii')
54   when /cygwin|os2-emx/
55     # get rid of tilde/yen problem.
56     map['shift_jis'] = 'cp932'
57   end
58   st = Hash.new(0)
59   map = map.sort.collect do |can, *sys|
60     if sys.grep(/^en_us(?=.|$)/i) {break true} == true
61       noen = %r"^(?!en_us)\w+_\w+#{Regexp.new($')}$"i #"
62       sys.reject! {|s| noen =~ s}
63     end
64     sys = sys.first
65     st[sys] += 1
66     [can, sys]
67   end
68   st.delete_if {|sys, i| i == 1}.empty?
69   st.keys.each {|sys| st[sys] = nil}
70   st.default = nil
71   writer = proc do |f|
72     f.puts("require 'iconv.so'")
73     f.puts
74     f.puts(comments)
75     f.puts("class Iconv")
76     i = 0
77     map.each do |can, sys|
78       if s = st[sys]
79         sys = s
80       elsif st.key?(sys)
81         sys = (st[sys] = "sys#{i+=1}") + " = '#{sys}'.freeze"
82       else
83         sys = "'#{sys}'.freeze"
84       end
85       f.puts("  charset_map['#{can}'] = #{sys}")
86     end
87     f.puts("end")
88   end
89   if mapfile
90     open(mapfile, "w", &writer)
91   else
92     writer[STDOUT]
93   end
94 end
96 target = OS
97 opt = nil
98 ARGV.options do |opt|
99   opt.banner << " config.status map.rb"
100   opt.on("--target OS") {|t| target = t}
101   opt.parse! and (1..2) === ARGV.size
102 end or abort opt.to_s
103 charset_alias(ARGV[0], ARGV[1], target)