Module: Pycf

Defined in:
lib/pycf/dump.rb,
lib/pycf/load.rb,
lib/pycf/error.rb,
lib/pycf/version.rb

Overview

Defined Under Namespace

Classes: MissingSectionHeaderError, ParsingError

Constant Summary collapse

SECTCRE =
/\A\[(?<header>[^\]]+)\]/
OPTCRE_NV =
/\A(?<option>[^:=\s][^:=]*)\s*(?:(?<vi>[:=])\s*(?<value>.*))?\z/
KEYCRE =
/(\A|.)%\(([^)]+)\)s/
VERSION =
'0.1.2'

Class Method Summary collapse

Class Method Details

.dump(hash) ⇒ Object



4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
# File 'lib/pycf/dump.rb', line 4

def dump(hash)
  unless hash.is_a?(Hash)
    raise TypeError, "wrong argument type #{hash.class} (expected Hash)"
  end

  python_config = []

  hash.each do |section, key_values|
    python_config << "[#{section}]"

    key_values.each do |key, value|
      value = value.to_s.gsub("\n", "\n\t")
      value = '""' if value.empty?
      python_config << "#{key} = #{value}"
    end
  end

  python_config.join("\n")
end

.load(python_config, option = {}) ⇒ Object



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
# File 'lib/pycf/load.rb', line 8

def load(python_config, option = {})
  hash = {}

  cursect = nil
  optname = nil

  python_config.split("\n").each_with_index do |line, lineno_minus_1|
    lineno = lineno_minus_1 + 1

    if line.split.empty? or line =~ /\A[#;]/
      next
    end

    if line =~ /\Arem\s+/i
      next
    end

    if line =~ /\A\s/ and cursect and optname
      line.strip!
      cursect[optname] << "\n#{line}" unless line.empty?
    else
      if line =~ SECTCRE
        sectname = $~[:header]

        unless hash.has_key?(sectname)
          hash[sectname] = {}
        end

        cursect = hash[sectname]
        optname = nil
      elsif not cursect
        raise MissingSectionHeaderError.new(lineno, line)
      else
        if line =~ OPTCRE_NV
          optname = $~[:option].downcase.rstrip
          vi = $~[:vi]
          optval = $~[:value]

          if optval
            if %w(= :).include?(vi)
              optval.sub!(/\s;.*\z/, '')
            end

            optval.strip!

            if optval == '""'
              optval = ''
            end
          elsif not option[:allow_no_value]
            raise ParsingError.new(lineno, line)
          end

          cursect[optname] = optval
        else
          raise ParsingError.new(lineno, line)
        end
      end
    end
  end

  if option[:interpolation]
    hash.each do |section, key_values|
      key_values.each do |key, value|
        value.gsub!(KEYCRE) do
          preword = $1
          key = $2

          if preword == '%'
            "%(#{key})s"
          else
            key_values[key.downcase]
          end
        end
      end
    end
  end

  hash
end