Statistics
| Branch: | Tag: | Revision:

root / autotools / convert-constants @ d99d1e36

History | View | Annotate | Download (2.3 kB)

1
#!/usr/bin/python
2
#
3

    
4
# Copyright (C) 2011 Google Inc.
5
#
6
# This program is free software; you can redistribute it and/or modify
7
# it under the terms of the GNU General Public License as published by
8
# the Free Software Foundation; either version 2 of the License, or
9
# (at your option) any later version.
10
#
11
# This program is distributed in the hope that it will be useful, but
12
# WITHOUT ANY WARRANTY; without even the implied warranty of
13
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
14
# General Public License for more details.
15
#
16
# You should have received a copy of the GNU General Public License
17
# along with this program; if not, write to the Free Software
18
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
19
# 02110-1301, USA.
20

    
21
"""Script for converting Python constants to Haskell code fragments.
22

    
23
"""
24

    
25
import re
26

    
27
from ganeti import constants
28

    
29
CONSTANT_RE = re.compile("^[A-Z][A-Z0-9_]+$")
30

    
31

    
32
def NameRules(name):
33
  """Converts the upper-cased Python name to Haskell camelCase.
34

    
35
  """
36
  elems = name.split("_")
37
  return elems[0].lower() + "".join(e.capitalize() for e in elems[1:])
38

    
39

    
40
def StringValueRules(value):
41
  """Converts a string value from Python to Haskell.
42

    
43
  """
44
  value = value.encode("string_escape") # escapes backslashes
45
  value = value.replace("\"", "\\\"")
46
  return value
47

    
48

    
49
def Convert():
50
  """Converts the constants to Haskell.
51

    
52
  """
53
  lines = [""]
54

    
55
  all_names = dir(constants)
56

    
57
  for name in all_names:
58
    value = getattr(constants, name)
59
    hs_name = NameRules(name)
60
    if not CONSTANT_RE.match(name):
61
      lines.append("-- Skipped %s, not constant" % name)
62
    elif isinstance(value, basestring):
63
      lines.append("%s :: String" % hs_name)
64
      lines.append("%s = \"%s\"" % (hs_name, StringValueRules(value)))
65
    elif isinstance(value, int):
66
      lines.append("%s :: Int" % hs_name)
67
      lines.append("%s = %d" % (hs_name, value))
68
    elif isinstance(value, long):
69
      lines.append("%s :: Integer" % hs_name)
70
      lines.append("%s = %d" % (hs_name, value))
71
    elif isinstance(value, float):
72
      lines.append("%s :: Double" % hs_name)
73
      lines.append("%s = %f" % (hs_name, value))
74
    else:
75
      lines.append("-- Skipped %s, %s not handled" % (name, type(value)))
76
    lines.append("")
77

    
78
  return "\n".join(lines)
79

    
80

    
81
def main():
82
  print Convert()
83

    
84

    
85
if __name__ == "__main__":
86
  main()