Began versioning
[cookbook.git] / bin / cook.py
1 #!/usr/bin/python
2
3 # Copyright
4
5 import os.path
6
7 import cookbook
8 from cookbook import Cookbook
9 from cookbook.mom import MomParser
10 from cookbook.cookbook import test as test_cookbook
11
12 try:
13     import cherrypy
14     from cookbook.server import Server
15     from cookbook.server import test as test_server
16 except ImportError, e:
17     cherrypy = e
18     def test_server():
19         pass
20
21
22 if __name__ == '__main__':
23     import optparse
24     import sys
25
26     # HACK! to ensure we *always* get utf-8 output
27     p = optparse.OptionParser()
28     p.add_option('-t', '--test', dest='test', default=False,
29                  action='store_true', help='run internal tests and exit')
30     p.add_option('-m', '--mom', dest='mom', metavar='PATH',
31                  help="load Mom's cookbook")
32     p.add_option('-s', '--serve', dest='serve', default=False,
33                  action='store_true', help='serve cookbook')
34     p.add_option('-a', '--address', dest='address', default='127.0.0.1',
35                  metavar='ADDR', help='address that the server will bind to')
36     p.add_option('-p', '--port', dest='port', default='8080',
37                  metavar='PORT', help='port that the server will listen on')
38
39     options,arguments = p.parse_args()
40
41     if options.test == True:
42         test_cookbook()
43         test_server()
44         sys.exit(0)
45
46     if isinstance(cherrypy, ImportError):
47         raise cherrypy
48
49     sys.stderr.write('Loading cookbook\n')
50     if options.mom == None:
51         c = Cookbook()
52         c.load()
53     else:
54         p = MomParser()
55         c = p.parse(options.mom)
56
57     if options.serve == False:
58         sys.stderr.write('Saving cookbook\n')
59         c.save('new-recipe')
60     else:
61         #reload(sys)
62         #sys.setdefaultencoding('utf-8')
63         sys.stderr.write('Serving cookbook\n')
64         module_dir = os.path.dirname(os.path.abspath(cookbook.__file__))
65         static_dir = os.path.join(module_dir, 'static')
66         template_dir = os.path.join(module_dir, 'template')
67         config = os.path.join(module_dir, 'config')
68         s = Server(c, template_dir)
69         cherrypy.config.update({ # http://www.cherrypy.org/wiki/ConfigAPI
70                 'server.socket_host': options.address,
71                 'server.socket_port': int(options.port),
72                 'tools.encode.on': True,
73                 'tools.encode.encoding': 'utf8',
74                 'tools.staticdir.root': static_dir
75                 })
76         app_config = { '/static': { 'tools.staticdir.on': True,
77                                     'tools.staticdir.dir': '', } }
78         cherrypy.quickstart(root=s, config=app_config)
79         sys.stderr.write('Saving cookbook\n')
80         s.cleanup()