Ticket #1491: colourful.diff
File colourful.diff, 30.9 KB (added by , 19 years ago) |
---|
-
termcolors.py
1 #!/usr/bin/python 2 3 """ 4 termcolors.py 5 6 set termcolors.DISABLE = True to disable the whole shebang 7 """ 8 import types 9 10 colour_names = ('black', 'red', 'green', 'yellow', 'blue', 'magenta', 11 'cyan', 'white') 12 foreground = {}; background = {} 13 [ foreground.update({colour_names[x]: '3%s' % x}) for x in range(8) ] 14 [ background.update({colour_names[x]: '4%s' % x}) for x in range(8) ] 15 16 RESET, BOLD, UNDERSCORE, BLINK, REVERSE, CONCEAL = '014578' 17 opt_dict = {'bold': BOLD, 'underscore': UNDERSCORE, 'blink': BLINK, 18 'reverse': REVERSE, 'conceal': CONCEAL,} 19 20 DISABLE = False 21 22 def gfx(text='', opts=(), **kwargs): 23 """Returns your text, enclosed in ANSI graphics codes 24 25 Depends on the keyword arguments 'fgcol' and 'bgcol', and the contents of the 26 opts tuple/list 27 28 With no parameters is a special case - it returns the RESET code 29 30 Valid colours: 31 'black', 'red', 'green', 'yellow', 'blue', 'magenta', 'cyan', 'white' 32 33 Valid options: 34 'bold' 35 'underscore' 36 'blink' 37 'reverse' 38 'conceal' 39 'noreset' - string will not be auto-terminated with the RESET code 40 41 Examples: 42 gfx('hello', fgcol='red', bgcol='blue', opts=('blink',)) 43 gfx() 44 gfx('goodbye', opts=('underscore',)) 45 print gfx('first line', fgcol='red', opts=('noreset',)) 46 print 'this should be red too' 47 print gfx('and so should this') 48 print 'this should not be red' 49 """ 50 text = str(text) 51 if DISABLE: 52 return text 53 code_list = [] 54 if text == '' and len(opts) == 1 and opts[0] == 'reset': 55 return '\x1b[%sm' % RESET 56 for k,v in kwargs.iteritems(): 57 if k == 'fgcol': 58 code_list.append(foreground[v]) 59 elif k == 'bgcol': 60 code_list.append(background[v]) 61 for o in opts: 62 if o in opt_dict: 63 code_list.append(opt_dict[o]) 64 if not ('noreset' in opts): 65 text = text + '\x1b[%sm' % RESET 66 return ('\x1b[%sm' % ';'.join(code_list)) + text 67 68 def make_style(opts=(), **kwargs): 69 """Returns a function with default parameters for gfx() 70 71 Example: 72 bold_red = make_style(opts=('bold',), fgcol='red') 73 print bold_red('hello') 74 75 KEYWORD = make_style(fgcol='yellow') 76 COMMENT = make_style(fgcol='blue', opts=('bold',)) 77 etc 78 """ 79 return lambda text: gfx(text, opts, **kwargs) 80 81 result = '' 82 for a in args: 83 if a.__class__ in types.StringTypes: 84 result += a 85 elif a.__class__ in [types.TupleType, types.ListType]: 86 result += a[0](a[1]) 87 return result 88 -
management.py
4 4 import django 5 5 import os, re, sys, textwrap 6 6 from optparse import OptionParser 7 import termcolors 7 8 9 class dummy: 10 pass 11 12 style = dummy() 13 14 style.ERROR = termcolors.make_style(fgcol='white', bgcol='red', opts=('bold',)) 15 style.ERROR_OUTPUT = termcolors.make_style(fgcol='red', opts=('bold',)) 16 style.OK = termcolors.make_style(fgcol='green', opts=('bold',)) 17 style.SQL_STRING = termcolors.make_style(fgcol='cyan') 18 style.SQL_FIELD = termcolors.make_style(fgcol='green') 19 style.SQL_KEYWORD = termcolors.make_style(fgcol='yellow') 20 style.SQL_NUMBER = style.SQL_STRING 21 style.SQL_TABLE = termcolors.make_style(fgcol='green', opts=('bold',)) 22 style.SQL_TRANS = termcolors.make_style(opts=('bold',)) 23 24 def J(*args): 25 return ''.join(map(str, args)) 26 27 def disable_sql_styles(): 28 l = lambda x: x 29 style.SQL_STRING = l 30 style.SQL_FIELD = l 31 style.SQL_KEYWORD = l 32 style.SQL_TABLE = l 33 34 if (not sys.stdout.isatty()) or (sys.platform == 'win32'): 35 # if somebody's piping our output through to psql or something, 36 # they might be a touch miffed if it's all full of escape chars 37 termcolors.DISABLE = True 38 8 39 # For Python 2.3 9 40 if not hasattr(__builtins__, 'set'): 10 41 from sets import Set as set … … 27 58 28 59 def _get_packages_insert(app_label): 29 60 from django.core.db import db 30 return "INSERT INTO %s (%s, %s) VALUES ('%s', '%s');" % \ 31 (db.quote_name('packages'), db.quote_name('label'), db.quote_name('name'), 32 app_label, app_label) 61 return J(style.SQL_KEYWORD("INSERT INTO")," %s (%s, %s) ", 62 style.SQL_KEYWORD("VALUES")," (%s, %s);") % \ 63 (style.SQL_TABLE(db.quote_name('packages')), 64 style.SQL_FIELD(db.quote_name('label')), 65 style.SQL_FIELD(db.quote_name('name')), 66 style.SQL_STRING("'"+app_label+"'"), 67 style.SQL_STRING("'"+app_label+"'")) 33 68 34 69 def _get_permission_codename(action, opts): 35 70 return '%s_%s' % (action, opts.object_name.lower()) … … 44 79 45 80 def _get_permission_insert(name, codename, opts): 46 81 from django.core.db import db 47 return "INSERT INTO %s (%s, %s, %s) VALUES ('%s', '%s', '%s');" % \ 48 (db.quote_name('auth_permissions'), db.quote_name('name'), db.quote_name('package'), 49 db.quote_name('codename'), name.replace("'", "''"), opts.app_label, codename) 82 return J(style.SQL_KEYWORD("INSERT INTO")," %s (%s, %s, %s) ", 83 style.SQL_KEYWORD("VALUES")," (%s, %s, %s);") % \ 84 (style.SQL_TABLE(db.quote_name('auth_permissions')), 85 style.SQL_FIELD(db.quote_name('name')), 86 style.SQL_FIELD(db.quote_name('package')), 87 style.SQL_FIELD(db.quote_name('codename')), 88 style.SQL_STRING("'"+name.replace("'", "''")+"'"), 89 style.SQL_STRING("'"+opts.app_label+"'"), 90 style.SQL_STRING("'"+codename+"'")) 50 91 51 92 def _get_contenttype_insert(opts): 52 93 from django.core.db import db 53 return "INSERT INTO %s (%s, %s, %s) VALUES ('%s', '%s', '%s');" % \ 54 (db.quote_name('content_types'), db.quote_name('name'), db.quote_name('package'), 55 db.quote_name('python_module_name'), opts.verbose_name, opts.app_label, opts.module_name) 94 return J(style.SQL_KEYWORD("INSERT INTO"), " %s (%s, %s, %s) ", 95 style.SQL_KEYWORD("VALUES"), " (%s, %s, %s);") % \ 96 (style.SQL_TABLE(db.quote_name('content_types')), 97 style.SQL_FIELD(db.quote_name('name')), 98 style.SQL_FIELD(db.quote_name('package')), 99 style.SQL_FIELD(db.quote_name('python_module_name')), 100 style.SQL_STRING("'"+opts.verbose_name.__str__()+"'"), 101 style.SQL_STRING("'"+opts.app_label.__str__()+"'"), 102 style.SQL_STRING("'"+opts.module_name.__str__()+"'")) 56 103 57 104 def _is_valid_dir_name(s): 58 105 return bool(re.search(r'^\w+$', s)) … … 87 134 data_type = f.get_internal_type() 88 135 col_type = db.DATA_TYPES[data_type] 89 136 if col_type is not None: 90 field_output = [db.db.quote_name(f.column), col_type % rel_field.__dict__] 91 field_output.append('%sNULL' % (not f.null and 'NOT ' or '')) 137 field_output = [style.SQL_FIELD(db.db.quote_name(f.column)), 138 col_type % rel_field.__dict__] 139 field_output.append(style.SQL_KEYWORD('%sNULL') % \ 140 (not f.null and 'NOT ' or '')) 92 141 if f.unique: 93 field_output.append( 'UNIQUE')142 field_output.append(style.SQL_KEYWORD('UNIQUE')) 94 143 if f.primary_key: 95 field_output.append( 'PRIMARY KEY')144 field_output.append(style.SQL_KEYWORD('PRIMARY KEY')) 96 145 if f.rel: 97 field_output.append('REFERENCES %s (%s)' % \ 98 (db.db.quote_name(f.rel.to.db_table), 99 db.db.quote_name(f.rel.to.get_field(f.rel.field_name).column))) 146 field_output.append(J(style.SQL_KEYWORD('REFERENCES'), 147 ' %s (%s)') % \ 148 (style.SQL_TABLE(db.db.quote_name(f.rel.to.db_table)), 149 style.SQL_FIELD(db.db.quote_name(f.rel.to.get_field(f.rel.field_name).column)))) 100 150 table_output.append(' '.join(field_output)) 101 151 if opts.order_with_respect_to: 102 table_output.append('%s %s NULL' % (db.db.quote_name('_order'), db.DATA_TYPES['IntegerField'])) 152 table_output.append(J('%s %s ',style.SQL_KEYWORD('NULL')) % \ 153 (style.SQL_FIELD(db.db.quote_name('_order')), 154 db.DATA_TYPES['IntegerField'])) 103 155 for field_constraints in opts.unique_together: 104 table_output.append( 'UNIQUE(%s)' % \105 ", ".join([ db.db.quote_name(opts.get_field(f).column) for f in field_constraints]))156 table_output.append(style.SQL_KEYWORD('UNIQUE')+' (%s)' % \ 157 ", ".join([style.SQL_FIELD(db.db.quote_name(opts.get_field(f).column)) for f in field_constraints])) 106 158 107 full_statement = [ 'CREATE TABLE %s (' % db.db.quote_name(opts.db_table)]159 full_statement = [style.SQL_KEYWORD('CREATE TABLE')+' %s (' % style.SQL_TABLE(db.db.quote_name(opts.db_table))] 108 160 for i, line in enumerate(table_output): # Combine and add commas. 109 161 full_statement.append(' %s%s' % (line, i < len(table_output)-1 and ',' or '')) 110 162 full_statement.append(');') … … 113 165 for klass in mod._MODELS: 114 166 opts = klass._meta 115 167 for f in opts.many_to_many: 116 table_output = ['CREATE TABLE %s (' % db.db.quote_name(f.get_m2m_db_table(opts))] 117 table_output.append(' %s %s NOT NULL PRIMARY KEY,' % (db.db.quote_name('id'), db.DATA_TYPES['AutoField'])) 118 table_output.append(' %s %s NOT NULL REFERENCES %s (%s),' % \ 119 (db.db.quote_name(opts.object_name.lower() + '_id'), 168 table_output = [J(style.SQL_KEYWORD('CREATE TABLE'),' %s (') % \ 169 style.SQL_TABLE(db.db.quote_name(f.get_m2m_db_table(opts)) 170 )] 171 table_output.append(J(' %s %s ', 172 style.SQL_KEYWORD('NOT NULL PRIMARY KEY'),',') % \ 173 (style.SQL_FIELD(db.db.quote_name('id')), 174 db.DATA_TYPES['AutoField'])) 175 table_output.append(J(' %s %s ', 176 style.SQL_KEYWORD('NOT NULL REFERENCES'),' %s (%s),') % \ 177 (style.SQL_FIELD(db.db.quote_name(opts.object_name.lower() + '_id')), 120 178 db.DATA_TYPES[get_rel_data_type(opts.pk)] % opts.pk.__dict__, 121 db.db.quote_name(opts.db_table), 122 db.db.quote_name(opts.pk.column))) 123 table_output.append(' %s %s NOT NULL REFERENCES %s (%s),' % \ 124 (db.db.quote_name(f.rel.to.object_name.lower() + '_id'), 179 style.SQL_TABLE(db.db.quote_name(opts.db_table)), 180 style.SQL_FIELD(db.db.quote_name(opts.pk.column)))) 181 table_output.append(J(' %s %s ', 182 style.SQL_KEYWORD('NOT NULL REFERENCES'),' %s (%s),') % \ 183 (style.SQL_FIELD(db.db.quote_name(f.rel.to.object_name.lower() + '_id')), 125 184 db.DATA_TYPES[get_rel_data_type(f.rel.to.pk)] % f.rel.to.pk.__dict__, 126 db.db.quote_name(f.rel.to.db_table), 127 db.db.quote_name(f.rel.to.pk.column))) 128 table_output.append(' UNIQUE (%s, %s)' % \ 129 (db.db.quote_name(opts.object_name.lower() + '_id'), 130 db.db.quote_name(f.rel.to.object_name.lower() + '_id'))) 185 style.SQL_TABLE(db.db.quote_name(f.rel.to.db_table)), 186 style.SQL_FIELD(db.db.quote_name(f.rel.to.pk.column)))) 187 table_output.append(J(' ',style.SQL_KEYWORD('UNIQUE'), 188 ' (%s, %s)') % \ 189 (style.SQL_FIELD(db.db.quote_name(opts.object_name.lower() + '_id')), 190 style.SQL_FIELD(db.db.quote_name(f.rel.to.object_name.lower() + '_id')))) 131 191 table_output.append(');') 132 192 final_output.append('\n'.join(table_output)) 133 193 return final_output … … 167 227 # The table doesn't exist, so it doesn't need to be dropped. 168 228 db.db.rollback() 169 229 else: 170 output.append("DROP TABLE %s;" % db.db.quote_name(klass._meta.db_table)) 230 output.append(J(style.SQL_KEYWORD("DROP TABLE")," %s;") % \ 231 style.SQL_TABLE(db.db.quote_name(klass._meta.db_table))) 171 232 172 233 # Output DROP TABLE statements for many-to-many tables. 173 234 for klass in mod._MODELS: … … 175 236 for f in opts.many_to_many: 176 237 try: 177 238 if cursor is not None: 178 cursor.execute("SELECT 1 FROM %s LIMIT 1" % db.db.quote_name(f.get_m2m_db_table(opts))) 239 cursor.execute("SELECT 1 FROM %s LIMIT 1" % \ 240 db.db.quote_name(f.get_m2m_db_table(opts))) 179 241 except: 180 242 db.db.rollback() 181 243 else: 182 output.append("DROP TABLE %s;" % db.db.quote_name(f.get_m2m_db_table(opts))) 244 output.append(J(style.SQL_KEYWORD("DROP TABLE")," %s;") % \ 245 style.SQL_TABLE(db.db.quote_name(f.get_m2m_db_table(opts)))) 183 246 184 247 app_label = mod._MODELS[0]._meta.app_label 185 248 186 249 # Delete from packages, auth_permissions, content_types. 187 output.append("DELETE FROM %s WHERE %s = '%s';" % \ 188 (db.db.quote_name('packages'), db.db.quote_name('label'), app_label)) 189 output.append("DELETE FROM %s WHERE %s = '%s';" % \ 190 (db.db.quote_name('auth_permissions'), db.db.quote_name('package'), app_label)) 191 output.append("DELETE FROM %s WHERE %s = '%s';" % \ 192 (db.db.quote_name('content_types'), db.db.quote_name('package'), app_label)) 250 output.append(J(style.SQL_KEYWORD("DELETE FROM")," %s ", 251 style.SQL_KEYWORD("WHERE")," %s = %s;") % \ 252 (style.SQL_TABLE(db.db.quote_name('packages')), 253 style.SQL_FIELD(db.db.quote_name('label')), 254 style.SQL_STRING("'"+app_label+"'"))) 255 output.append(J(style.SQL_KEYWORD("DELETE FROM")," %s ", 256 style.SQL_KEYWORD("WHERE")," %s = %s;") % \ 257 (style.SQL_TABLE(db.db.quote_name('auth_permissions')), 258 style.SQL_FIELD(db.db.quote_name('package')), 259 style.SQL_STRING("'"+app_label+"'"))) 260 output.append(J(style.SQL_KEYWORD("DELETE FROM")," %s ", 261 style.SQL_KEYWORD("WHERE")," %s = %s;") % \ 262 (style.SQL_TABLE(db.db.quote_name('content_types')), 263 style.SQL_FIELD(db.db.quote_name('package')), 264 style.SQL_STRING("'"+app_label+"'"))) 193 265 194 266 # Delete from the admin log. 195 267 if cursor is not None: … … 198 270 db.db.quote_name('package')), [app_label]) 199 271 if admin_log_exists: 200 272 for row in cursor.fetchall(): 201 output.append("DELETE FROM %s WHERE %s = %s;" % \ 202 (db.db.quote_name('django_admin_log'), db.db.quote_name('content_type_id'), row[0])) 273 output.append(J(style.SQL_KEYWORD("DELETE FROM")," %s ", 274 style.SQL_KEYWORD("WHERE")," %s = %s;") % \ 275 (style.SQL_TABLE(db.db.quote_name('django_admin_log')), 276 style.SQL_FIELD(db.db.quote_name('content_type_id')), 277 style.SQL_NUMBER(row[0]))) 203 278 204 279 # Close database connection explicitly, in case this output is being piped 205 280 # directly into a database client, to avoid locking issues. … … 252 327 for klass in mod._MODELS: 253 328 for f in klass._meta.fields: 254 329 if isinstance(f, meta.AutoField): 255 output.append("SELECT setval('%s_%s_seq', (SELECT max(%s) FROM %s));" % \ 256 (klass._meta.db_table, f.column, db.db.quote_name(f.column), 257 db.db.quote_name(klass._meta.db_table))) 330 output.append(J(style.SQL_KEYWORD("SELECT"), 331 " setval('%s_%s_seq', (", 332 style.SQL_KEYWORD("SELECT")," max(%s) ", 333 style.SQL_KEYWORD("FROM")," %s));") % \ 334 (klass._meta.db_table, 335 f.column, 336 style.SQL_FIELD(db.db.quote_name(f.column)), 337 style.SQL_TABLE(db.db.quote_name(klass._meta.db_table)))) 258 338 for f in klass._meta.many_to_many: 259 output.append("SELECT setval('%s_id_seq', (SELECT max(%s) FROM %s));" % \ 260 (f.get_m2m_db_table(klass._meta), db.db.quote_name('id'), f.get_m2m_db_table(klass._meta))) 339 output.append(J(style.SQL_KEYWORD("SELECT"), 340 " setval('%s_id_seq', (", 341 style.SQL_KEYWORD("SELECT")," max(%s) ", 342 style.SQL_KEYWORD("FROM")," %s));") % \ 343 (f.get_m2m_db_table(klass._meta), 344 style.SQL_FIELD(db.db.quote_name('id')), 345 style.SQL_TABLE(f.get_m2m_db_table(klass._meta)))) 261 346 return output 262 347 get_sql_sequence_reset.help_doc = "Prints the SQL statements for resetting PostgreSQL sequences for the given model module name(s)." 263 348 get_sql_sequence_reset.args = APP_ARGS … … 270 355 for f in klass._meta.fields: 271 356 if f.db_index: 272 357 unique = f.unique and "UNIQUE " or "" 273 output.append( "CREATE %sINDEX %s_%s ON %s (%s);"% \358 output.append(J(style.SQL_KEYWORD("CREATE %sINDEX")," %s_%s ",style.SQL_KEYWORD("ON")," %s (%s);") % \ 274 359 (unique, klass._meta.db_table, f.column, 275 db.quote_name(klass._meta.db_table), db.quote_name(f.column))) 360 style.SQL_TABLE(db.quote_name(klass._meta.db_table)), 361 style.SQL_FIELD(db.quote_name(f.column)))) 276 362 return output 277 363 get_sql_indexes.help_doc = "Prints the CREATE INDEX SQL statements for the given model module name(s)." 278 364 get_sql_indexes.args = APP_ARGS … … 337 423 perms_seen[row[0]] 338 424 except KeyError: 339 425 # sys.stderr.write("A permission called '%s.%s' was found in the database but not in the model.\n" % (app_label, row[0])) 340 print "DELETE FROM %s WHERE %s='%s' AND %s = '%s';" % \ 341 (db.db.quote_name('auth_permissions'), db.db.quote_name('package'), 342 app_label, db.db.quote_name('codename'), row[0]) 426 print J(style.SQL_KEYWORD("DELETE FROM"), " %s ", 427 style.SQL_KEYWORD("WHERE"), " %s='%s' ", 428 style.SQL_KEYWORD("AND"), " %s = '%s';") % \ 429 (style.SQL_TABLE(db.db.quote_name('auth_permissions')), 430 style.SQL_FIELD(db.db.quote_name('package')), 431 style.SQL_STRING(app_label), 432 style.SQL_FIELD(db.db.quote_name('codename')), 433 style.SQL_STRING(row[0])) 343 434 344 435 # Check that there aren't any *extra* content types in the DB that the 345 436 # model doesn't know about. … … 351 442 contenttypes_seen[row[0]] 352 443 except KeyError: 353 444 # sys.stderr.write("A content type called '%s.%s' was found in the database but not in the model.\n" % (app_label, row[0])) 354 print "DELETE FROM %s WHERE %s='%s' AND %s = '%s';" % \ 355 (db.db.quote_name('content_types'), db.db.quote_name('package'), 356 app_label, db.db.quote_name('python_module_name'), row[0]) 445 print J(style.SQL_KEYWORD("DELETE FROM")," %s ", 446 style.SQL_KEYWORD("WHERE")," %s='%s' ", 447 style.SQL_KEYWORD("AND")," %s = '%s';") % \ 448 (style.SQL_TABLE(db.db.quote_name('content_types')), 449 style.SQL_FIELD(db.db.quote_name('package')), 450 style.SQL_STRING(app_label), 451 style.SQL_FIELD(db.db.quote_name('python_module_name')), 452 style.SQL_STRING(row[0])) 357 453 database_check.help_doc = "Checks that everything is installed in the database for the given model module name(s) and prints SQL statements if needed." 358 454 database_check.args = APP_ARGS 359 455 … … 381 477 382 478 def init(): 383 479 "Initializes the database with auth and core." 480 disable_sql_styles() 384 481 try: 385 482 from django.core import db, meta 386 483 auth = meta.get_app('auth') … … 392 489 (db.db.quote_name(core.Site._meta.db_table), db.db.quote_name('domain'), 393 490 db.db.quote_name('name'))) 394 491 except Exception, e: 395 sys.stderr.write("Error: The database couldn't be initialized.\n%s\n" % e) 492 sys.stderr.write( 493 J(style.ERROR("Error: The database couldn't be initialized."), 494 "\n",style.ERROR_OUTPUT(e),"\n") 495 ) 396 496 try: 397 497 db.db.rollback() 398 498 except UnboundLocalError: … … 408 508 from cStringIO import StringIO 409 509 mod_name = mod.__name__[mod.__name__.rindex('.')+1:] 410 510 511 disable_sql_styles() 411 512 # First, try validating the models. 412 513 s = StringIO() 413 514 num_errors = get_validation_errors(s) 414 515 if num_errors: 415 sys.stderr.write( "Error: %s couldn't be installed, because there were errors in your model:\n"% mod_name)516 sys.stderr.write(J(style.ERROR("Error: %s couldn't be installed, because there were errors in your model:"),"\n") % mod_name) 416 517 s.seek(0) 417 sys.stderr.write(s .read())518 sys.stderr.write(style.ERROR_OUTPUT(s.read())) 418 519 sys.exit(1) 419 520 sql_list = get_sql_all(mod) 420 521 … … 423 524 for sql in sql_list: 424 525 cursor.execute(sql) 425 526 except Exception, e: 426 sys.stderr.write("""Error: %s couldn't be installed. Possible reasons: 527 sys.stderr.write( 528 J(style.ERROR("Error: %s couldn't be installed. Possible reasons:"), 529 style.ERROR_OUTPUT(""" 427 530 * The database isn't running or isn't configured correctly. 428 531 * At least one of the database tables already exists. 429 532 * The SQL was invalid. 430 533 Hint: Look at the output of 'django-admin.py sqlall %s'. That's the SQL this command wasn't able to run. 431 The full error: %s \n"""% \534 The full error: %s"""),"\n") % \ 432 535 (mod_name, mod_name, e)) 433 536 db.db.rollback() 434 537 sys.exit(1) … … 440 543 "Installs any permissions for the given model, if needed." 441 544 from django.models.auth import permissions 442 545 from django.models.core import packages 546 547 disable_sql_styles() 548 443 549 num_added = 0 444 550 package = packages.get_object(pk=mod._MODELS[0]._meta.app_label) 445 551 for klass in mod._MODELS: … … 450 556 except permissions.PermissionDoesNotExist: 451 557 p = permissions.Permission(name=name, package=package, codename=codename) 452 558 p.save() 453 print "Added permission '%r'." % p559 print style.OK("Added permission '%r'." % p) 454 560 num_added += 1 455 561 if not num_added: 456 print "No permissions were added, because all necessary permissions were already installed."562 print style.OK("No permissions were added, because all necessary permissions were already installed.") 457 563 installperms.help_doc = "Installs any permissions for the given model module name(s), if needed." 458 564 installperms.args = APP_ARGS 459 565 460 566 def _start_helper(app_or_project, name, directory, other_name=''): 461 567 other = {'project': 'app', 'app': 'project'}[app_or_project] 462 568 if not _is_valid_dir_name(name): 463 sys.stderr.write( "Error: %r is not a valid %s name. Please use only numbers, letters and underscores.\n"% (name, app_or_project))569 sys.stderr.write(J(style.ERROR("Error: %r is not a valid %s name. Please use only numbers, letters and underscores."),"\n") % (name, app_or_project)) 464 570 sys.exit(1) 465 571 top_dir = os.path.join(directory, name) 466 572 try: 467 573 os.mkdir(top_dir) 468 574 except OSError, e: 469 sys.stderr.write( "Error: %s\n"% e)575 sys.stderr.write(J(style.ERROR("Error: %s"),"\n") % e) 470 576 sys.exit(1) 471 577 template_dir = PROJECT_TEMPLATE_DIR % app_or_project 472 578 for d, subdirs, files in os.walk(template_dir): … … 489 595 "Creates a Django project for the given project_name in the given directory." 490 596 from random import choice 491 597 if project_name in INVALID_PROJECT_NAMES: 492 sys.stderr.write( "Error: %r isn't a valid project name. Please try another.\n"% project_name)598 sys.stderr.write(J(style.ERROR("Error: %r isn't a valid project name. Please try another."),"\n") % project_name) 493 599 sys.exit(1) 494 600 _start_helper('project', project_name, directory) 495 601 # Create a random SECRET_KEY hash, and put it in the main settings. 496 602 main_settings_file = os.path.join(directory, project_name, 'settings.py') 497 603 settings_contents = open(main_settings_file, 'r').read() 498 604 fp = open(main_settings_file, 'w') 499 secret_key = ''.join([choice('abcdefghijklmnopqrstuvwxyz0123456789!@#$%^&*(-_=+)') for i in range(50)])605 secret_key = J([choice('abcdefghijklmnopqrstuvwxyz0123456789!@#$%^&*(-_=+)') for i in range(50)]) 500 606 settings_contents = re.sub(r"(?<=SECRET_KEY = ')'", secret_key + "'", settings_contents) 501 607 fp.write(settings_contents) 502 608 fp.close() … … 523 629 if not username: 524 630 username = raw_input('Username (only letters, digits and underscores): ') 525 631 if not username.isalnum(): 526 sys.stderr.write( "Error: That username is invalid.\n")632 sys.stderr.write(J(style.ERROR("Error: That username is invalid."),"\n")) 527 633 username = None 528 634 try: 529 635 users.get_object(username__exact=username) 530 636 except users.UserDoesNotExist: 531 637 break 532 638 else: 533 sys.stderr.write( "Error: That username is already taken.\n")639 sys.stderr.write(J(style.ERROR("Error: That username is already taken."),"\n")) 534 640 username = None 535 641 while 1: 536 642 if not email: … … 538 644 try: 539 645 validators.isValidEmail(email, None) 540 646 except validators.ValidationError: 541 sys.stderr.write( "Error: That e-mail address is invalid.\n")647 sys.stderr.write(J(style.ERROR("Error: That e-mail address is invalid."),"\n")) 542 648 email = None 543 649 else: 544 650 break … … 547 653 password = getpass.getpass() 548 654 password2 = getpass.getpass('Password (again): ') 549 655 if password != password2: 550 sys.stderr.write( "Error: Your passwords didn't match.\n")656 sys.stderr.write(J(style.ERROR("Error: Your passwords didn't match."),"\n")) 551 657 password = None 552 658 continue 553 659 if password.strip() == '': 554 sys.stderr.write( "Error: Blank passwords aren't allowed.\n")660 sys.stderr.write(J(style.ERROR("Error: Blank passwords aren't allowed."),"\n")) 555 661 password = None 556 662 continue 557 663 break 558 664 except KeyboardInterrupt: 559 sys.stderr.write( "\nOperation cancelled.\n")665 sys.stderr.write(J('\n',style.ERROR("Operation cancelled."),'\n')) 560 666 sys.exit(1) 561 667 u = users.create_user(username, email, password) 562 668 u.is_staff = True 563 669 u.is_active = True 564 670 u.is_superuser = True 565 671 u.save() 566 print "User created successfully."672 print style.OK("User created successfully.") 567 673 createsuperuser.args = '[username] [email] [password] (Either all or none)' 568 674 569 675 def inspectdb(db_name): … … 798 904 if not addr: 799 905 addr = '127.0.0.1' 800 906 if not port.isdigit(): 801 sys.stderr.write( "Error: %r is not a valid port number.\n" % port)907 sys.stderr.write(style.ERROR("Error: %r is not a valid port number.\n" % port)) 802 908 sys.exit(1) 803 909 def inner_run(): 804 910 from django.conf.settings import SETTINGS_MODULE 805 911 print "Validating models..." 806 912 validate() 807 print "\nDjango version %s, using settings %r" % (get_version(), SETTINGS_MODULE) 808 print "Development server is running at http://%s:%s/" % (addr, port) 913 print 914 print style.OK("Django version %s, using settings %r") % (get_version(), SETTINGS_MODULE) 915 print style.OK("Development server is running at http://%s:%s/" % (addr, port)) 809 916 print "Quit the server with CONTROL-C (Unix) or CTRL-BREAK (Windows)." 810 917 try: 811 918 run(addr, int(port), AdminMediaHandler(WSGIHandler())) … … 820 927 error_text = ERRORS[e.args[0].args[0]] 821 928 except (AttributeError, KeyError): 822 929 error_text = str(e) 823 sys.stderr.write( "Error: %s\n" % error_text)930 sys.stderr.write(style.ERROR("Error: %s\n" % error_text)) 824 931 sys.exit(1) 825 932 except KeyboardInterrupt: 826 933 sys.exit(0) … … 925 1032 return '\n'.join(usage[:-1]) # Cut off last list element, an empty space. 926 1033 927 1034 def print_error(msg, cmd): 928 sys.stderr.write( 'Error: %s\nRun "%s --help" for help.\n'% (msg, cmd))1035 sys.stderr.write(J(style.ERROR('Error: %s'),'\n',style.ERROR_OUTPUT('Run "%s --help" for help.'),'\n') % (msg, cmd)) 929 1036 sys.exit(1) 930 1037 931 1038 def execute_from_command_line(action_mapping=DEFAULT_ACTION_MAPPING): … … 968 1075 if len(args) == 1: # We got no arguments, just the action. 969 1076 action_mapping[action]() 970 1077 else: 971 sys.stderr.write( "Error: %r requires arguments of 'username email password' or no argument at all.\n")1078 sys.stderr.write(J(style.ERROR("Error: %r requires arguments of 'username email password' or no argument at all."),"\n")) 972 1079 sys.exit(1) 973 1080 else: 974 1081 action_mapping[action](username, email, password) … … 985 1092 for line in action_mapping[action](param): 986 1093 print line 987 1094 except NotImplementedError: 988 sys.stderr.write( "Error: %r isn't supported for the currently selected database backend.\n"% action)1095 sys.stderr.write(J(style.ERROR("Error: %r isn't supported for the currently selected database backend."),"\n") % action) 989 1096 sys.exit(1) 990 1097 elif action == 'createcachetable': 991 1098 try: … … 1016 1123 try: 1017 1124 mod_list = [meta.get_app(app_label) for app_label in args[1:]] 1018 1125 except ImportError, e: 1019 sys.stderr.write( "Error: %s. Are you sure your INSTALLED_APPS setting is correct?\n"% e)1126 sys.stderr.write(J(style.ERROR("Error: %s. Are you sure your INSTALLED_APPS setting is correct?"),"\n") % e) 1020 1127 sys.exit(1) 1021 1128 if not mod_list: 1022 1129 parser.print_usage_and_exit() 1023 1130 if action not in NO_SQL_TRANSACTION: 1024 print "BEGIN;"1131 print J(style.SQL_TRANS("BEGIN"), ';') 1025 1132 for mod in mod_list: 1026 1133 output = action_mapping[action](mod) 1027 1134 if output: 1028 1135 print '\n'.join(output) 1029 1136 if action not in NO_SQL_TRANSACTION: 1030 print "COMMIT;"1137 print J(style.SQL_TRANS("COMMIT"),';') 1031 1138 1032 1139 def execute_manager(settings_mod): 1033 1140 # Add this project to sys.path so that it's importable in the conventional