public
Description: Yet Another Planet Refactoring
Homepage: http://intertwingly.net/blog/2007/12/19/Yet-Another-Planet-Refactoring
Clone URL: git://github.com/rubys/mars.git
Search Repo:
Sam Ruby (author)
Fri Apr 04 04:46:55 -0700 2008
commit  41bfc6f06cfe0c6dc83a5ed719f9f6e0ed0205c0
tree    5507df06619ff6a5b35fa2230330ac4892f46d68
parent  594cd30192668c6310b3236b978d5d4a6d706fb7
mars / planet / config.rb
100644 95 lines (76 sloc) 2.37 kb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
require 'delegate'
require 'planet/log'
 
module Planet
 
  def Planet.config
    @@config
  end
 
  # Configuration parser compatible with the data format supported by Python:
  # http://docs.python.org/lib/module-ConfigParser.html
  class PythonConfigParser < DelegateClass(Hash)
 
    DEFAULTSECT = "DEFAULT"
 
    SECTRE = /
\[ # [
([^\]]+) # very permissive!
\] # ]
/x
 
    OPTCRE = /
([^:=\s][^:=]*) # very permissive!
\s*[:=]\s* # any number of space chars,
# followed by separator
# (either : or =), followed
# by any # space chars
(.*)$ # everything up to eol
/x
 
    def initialize
      @sections = {}
      @sections[DEFAULTSECT] = {}
      super(@sections)
    end
 
    def read filename
      File.open(filename) do |config|
        cursect = nil
        optname = nil
        lineno = 0
        while line = config.gets
          lineno += 1
          next if line.strip.empty? or '#;'.include?(line[0])
          next if line =~ /^rem(\s|$)/i
 
          if line =~ /^\s/ and cursect and optname:
            # continuation line
            value = line.strip
            cursect[optname] += "\n#{value}" if value
 
          elsif line =~ SECTRE
            # section header
            sectname = $1
            @sections[sectname] ||= {'__name__' => sectname}
            cursect = @sections[sectname]
            optname = nil
 
          elsif not cursect
            raise Exception.new('Missing section header')
 
          elsif line =~ OPTCRE
            # option line
            optname, optval = $1, $2
            optval.sub(/\s;.*/, '')
            optval = '' if optval == '""'
            cursect[optname.downcase.strip] = optval
 
          else
            raise Exception.new('Invalid syntax on line #{lineno}')
          end
        end
      end
    end
  end
 
  class ConfigParser < PythonConfigParser
    def initialize
      super
      self['Planet'] = {}
    end
 
    def read filename
      super(filename)
 
      planet = self['Planet']
 
      Planet.log_format planet['log_format'] if planet['log_format']
      Planet.log_level planet['log_level'] if planet['log_level']
    end
  end
 
  @@config = ConfigParser.new
end