comparison piecrust/main.py @ 38:091f99bfbe44

Fix running `chef` outside of a website. Slightly better error reporting.
author Ludovic Chabant <ludovic@chabant.com>
date Thu, 21 Aug 2014 10:56:17 -0700
parents 343d08ef5668
children 2f717f961996
comparison
equal deleted inserted replaced
37:afcfecd3bf92 38:091f99bfbe44
47 self.env = StandardEnvironment() 47 self.env = StandardEnvironment()
48 self.env.initialize(self) 48 self.env.initialize(self)
49 49
50 50
51 def main(): 51 def main():
52 start_time = time.clock() 52 argv = sys.argv
53 pre_args = _pre_parse_chef_args(argv)
54 try:
55 return _run_chef(pre_args)
56 except Exception as ex:
57 if pre_args.debug:
58 logger.exception(ex)
59 else:
60 logger.error(str(ex))
53 61
62
63 class PreParsedChefArgs(object):
64 def __init__(self, root=None, cache=True, debug=False, quiet=False,
65 log_file=None, config_variant=None):
66 self.root = root
67 self.cache = cache
68 self.debug = debug
69 self.quiet = quiet
70 self.log_file = log_file
71 self.config_variant = config_variant
72
73
74 def _pre_parse_chef_args(argv):
54 # We need to parse some arguments before we can build the actual argument 75 # We need to parse some arguments before we can build the actual argument
55 # parser, because it can affect which plugins will be loaded. Also, log- 76 # parser, because it can affect which plugins will be loaded. Also, log-
56 # related arguments must be parsed first because we want to log everything 77 # related arguments must be parsed first because we want to log everything
57 # from the beginning. 78 # from the beginning.
58 root = None 79 res = PreParsedChefArgs()
59 cache = True
60 debug = False
61 quiet = False
62 log_file = None
63 config_variant = None
64 i = 1 80 i = 1
65 while i < len(sys.argv): 81 while i < len(argv):
66 arg = sys.argv[i] 82 arg = argv[i]
67 if arg.startswith('--root='): 83 if arg.startswith('--root='):
68 root = os.path.expanduser(arg[len('--root='):]) 84 res.root = os.path.expanduser(arg[len('--root='):])
69 elif arg == '--root': 85 elif arg == '--root':
70 root = sys.argv[i + 1] 86 res.root = argv[i + 1]
71 ++i 87 ++i
72 elif arg.startswith('--config='): 88 elif arg.startswith('--config='):
73 config_variant = arg[len('--config='):] 89 res.config_variant = arg[len('--config='):]
74 elif arg == '--config': 90 elif arg == '--config':
75 config_variant = sys.argv[i + 1] 91 res.config_variant = argv[i + 1]
76 ++i 92 ++i
77 elif arg == '--log': 93 elif arg == '--log':
78 log_file = sys.argv[i + 1] 94 res.log_file = argv[i + 1]
79 ++i 95 ++i
80 elif arg == '--no-cache': 96 elif arg == '--no-cache':
81 cache = False 97 res.cache = False
82 elif arg == '--debug': 98 elif arg == '--debug':
83 debug = True 99 res.debug = True
84 elif arg == '--quiet': 100 elif arg == '--quiet':
85 quiet = True 101 res.quiet = True
86 102
87 if arg[0] != '-': 103 if arg[0] != '-':
88 break 104 break
89 105
90 i = i + 1 106 i = i + 1
91 107
92 # Setup the logger. 108 # Setup the logger.
93 if debug and quiet: 109 if res.debug and res.quiet:
94 raise Exception("You can't specify both --debug and --quiet.") 110 raise Exception("You can't specify both --debug and --quiet.")
95 111
96 colorama.init() 112 colorama.init()
97 root_logger = logging.getLogger() 113 root_logger = logging.getLogger()
98 root_logger.setLevel(logging.INFO) 114 root_logger.setLevel(logging.INFO)
99 log_handler = logging.StreamHandler(sys.stdout) 115 log_handler = logging.StreamHandler(sys.stdout)
100 if debug: 116 if res.debug:
101 root_logger.setLevel(logging.DEBUG) 117 root_logger.setLevel(logging.DEBUG)
102 log_handler.setFormatter(ColoredFormatter("[%(name)s] %(message)s")) 118 log_handler.setFormatter(ColoredFormatter("[%(name)s] %(message)s"))
103 else: 119 else:
104 if quiet: 120 if res.quiet:
105 root_logger.setLevel(logging.WARNING) 121 root_logger.setLevel(logging.WARNING)
106 log_handler.setFormatter(ColoredFormatter("%(message)s")) 122 log_handler.setFormatter(ColoredFormatter("%(message)s"))
107 root_logger.addHandler(log_handler) 123 root_logger.addHandler(log_handler)
108 if log_file: 124 if res.log_file:
109 root_logger.addHandler(logging.FileHandler(log_file)) 125 root_logger.addHandler(logging.FileHandler(res.log_file))
110 126
127 return res
128
129
130 def _run_chef(pre_args):
111 # Setup the app. 131 # Setup the app.
132 start_time = time.clock()
133 root = pre_args.root
112 if root is None: 134 if root is None:
113 root = find_app_root() 135 try:
136 root = find_app_root()
137 except SiteNotFoundError:
138 root = None
114 139
115 if not root: 140 if not root:
116 app = NullPieCrust() 141 app = NullPieCrust()
117 else: 142 else:
118 app = PieCrust(root, cache=cache) 143 app = PieCrust(root, cache=pre_args.cache)
119 144
120 # Handle a configuration variant. 145 # Handle a configuration variant.
121 if config_variant is not None: 146 if pre_args.config_variant is not None:
122 if not root: 147 if not root:
123 raise SiteNotFoundError() 148 raise SiteNotFoundError("Can't apply any variant.")
124 app.config.applyVariant('variants/' + config_variant) 149 app.config.applyVariant('variants/' + pre_args.config_variant)
125 150
126 # Setup the arg parser. 151 # Setup the arg parser.
127 parser = argparse.ArgumentParser( 152 parser = argparse.ArgumentParser(
128 description="The PieCrust chef manages your website.") 153 description="The PieCrust chef manages your website.")
129 parser.add_argument('--version', action='version', version=('%(prog)s ' + APP_VERSION)) 154 parser.add_argument('--version', action='version', version=('%(prog)s ' + APP_VERSION))
142 c.setupParser(p, app) 167 c.setupParser(p, app)
143 p.set_defaults(func=c._runFromChef) 168 p.set_defaults(func=c._runFromChef)
144 169
145 # Parse the command line. 170 # Parse the command line.
146 result = parser.parse_args() 171 result = parser.parse_args()
147 logger.debug(format_timed(start_time, 'initialized PieCrust')) 172 logger.debug(format_timed(start_time, 'initialized PieCrust', colored=False))
148 173
149 # Run the command! 174 # Run the command!
150 exit_code = result.func(app, result) 175 exit_code = result.func(app, result)
151 return exit_code 176 return exit_code
152 177