Refs #18325 -- Removed unnecessary line endings in management commands.

The OutputWrapper automatically adds \n when it’s not present.
This commit is contained in:
François Freitag 2020-04-25 15:51:17 +02:00 committed by Mariusz Felisiak
parent abea86f9e4
commit 71d9876e39
15 changed files with 51 additions and 47 deletions

View File

@ -44,7 +44,7 @@ class Command(BaseCommand):
except UserModel.DoesNotExist: except UserModel.DoesNotExist:
raise CommandError("user '%s' does not exist" % username) raise CommandError("user '%s' does not exist" % username)
self.stdout.write("Changing password for user '%s'\n" % u) self.stdout.write("Changing password for user '%s'" % u)
MAX_TRIES = 3 MAX_TRIES = 3
count = 0 count = 0
@ -54,7 +54,7 @@ class Command(BaseCommand):
p1 = self._get_pass() p1 = self._get_pass()
p2 = self._get_pass("Password (again): ") p2 = self._get_pass("Password (again): ")
if p1 != p2: if p1 != p2:
self.stdout.write("Passwords do not match. Please try again.\n") self.stdout.write('Passwords do not match. Please try again.')
count += 1 count += 1
# Don't validate passwords that don't match. # Don't validate passwords that don't match.
continue continue

View File

@ -71,7 +71,7 @@ This list doesn't include any cascade deletions to data outside of Django's
models (uncommon). models (uncommon).
Are you sure you want to delete these content types? Are you sure you want to delete these content types?
If you're unsure, answer 'no'.\n""" % content_type_display) If you're unsure, answer 'no'.""" % content_type_display)
ok_to_delete = input("Type 'yes' to continue, or 'no' to cancel: ") ok_to_delete = input("Type 'yes' to continue, or 'no' to cancel: ")
else: else:
ok_to_delete = 'yes' ok_to_delete = 'yes'

View File

@ -130,4 +130,4 @@ class Command(BaseCommand):
rev_mapping[ogr_fld], ogr_fld) for ogr_fld in ds[options['layer_key']].fields rev_mapping[ogr_fld], ogr_fld) for ogr_fld in ds[options['layer_key']].fields
) )
output.extend([" '%s': '%s'," % (options['geom_name'], mapping_dict[options['geom_name']]), '}']) output.extend([" '%s': '%s'," % (options['geom_name'], mapping_dict[options['geom_name']]), '}'])
return '\n'.join(output) + '\n' return '\n'.join(output)

View File

@ -15,5 +15,7 @@ class Command(BaseCommand):
try: try:
engine.SessionStore.clear_expired() engine.SessionStore.clear_expired()
except NotImplementedError: except NotImplementedError:
self.stderr.write("Session engine '%s' doesn't support clearing " self.stderr.write(
"expired sessions.\n" % settings.SESSION_ENGINE) "Session engine '%s' doesn't support clearing expired "
"sessions." % settings.SESSION_ENGINE
)

View File

@ -190,9 +190,10 @@ class Command(BaseCommand):
post_processed_count = len(collected['post_processed']) post_processed_count = len(collected['post_processed'])
if self.verbosity >= 1: if self.verbosity >= 1:
template = ("\n%(modified_count)s %(identifier)s %(action)s" summary = (
"%(destination)s%(unmodified)s%(post_processed)s.\n") "\n%(modified_count)s %(identifier)s %(action)s"
summary = template % { "%(destination)s%(unmodified)s%(post_processed)s."
) % {
'modified_count': modified_count, 'modified_count': modified_count,
'identifier': 'static file' + ('' if modified_count == 1 else 's'), 'identifier': 'static file' + ('' if modified_count == 1 else 's'),
'action': 'symlinked' if self.symlink else 'copied', 'action': 'symlinked' if self.symlink else 'copied',

View File

@ -474,7 +474,7 @@ class BaseCommand:
} }
) )
) )
self.stdout.write(self.style.NOTICE("Run 'python manage.py migrate' to apply them.\n")) self.stdout.write(self.style.NOTICE("Run 'python manage.py migrate' to apply them."))
def handle(self, *args, **options): def handle(self, *args, **options):
""" """

View File

@ -122,7 +122,7 @@ class Command(BaseCommand):
futures = [] futures = []
for i, (dirpath, f) in enumerate(locations): for i, (dirpath, f) in enumerate(locations):
if self.verbosity > 0: if self.verbosity > 0:
self.stdout.write('processing file %s in %s\n' % (f, dirpath)) self.stdout.write('processing file %s in %s' % (f, dirpath))
po_path = os.path.join(dirpath, f) po_path = os.path.join(dirpath, f)
if has_bom(po_path): if has_bom(po_path):
self.stderr.write( self.stderr.write(

View File

@ -68,7 +68,7 @@ Are you sure you want to do this?
" * At least one of the expected database tables doesn't exist.\n" " * At least one of the expected database tables doesn't exist.\n"
" * The SQL was invalid.\n" " * The SQL was invalid.\n"
"Hint: Look at the output of 'django-admin sqlflush'. " "Hint: Look at the output of 'django-admin sqlflush'. "
"That's the SQL this command wasn't able to run.\n" % ( "That's the SQL this command wasn't able to run." % (
connection.settings_dict['NAME'], connection.settings_dict['NAME'],
) )
) from exc ) from exc
@ -79,4 +79,4 @@ Are you sure you want to do this?
# respond as if the database had been migrated from scratch. # respond as if the database had been migrated from scratch.
emit_post_migrate_signal(verbosity, interactive, database) emit_post_migrate_signal(verbosity, interactive, database)
else: else:
self.stdout.write("Flush cancelled.\n") self.stdout.write('Flush cancelled.')

View File

@ -31,7 +31,7 @@ class Command(BaseCommand):
def handle(self, **options): def handle(self, **options):
try: try:
for line in self.handle_inspection(options): for line in self.handle_inspection(options):
self.stdout.write("%s\n" % line) self.stdout.write(line)
except NotImplementedError: except NotImplementedError:
raise CommandError("Database inspection isn't supported for the currently selected database backend.") raise CommandError("Database inspection isn't supported for the currently selected database backend.")

View File

@ -130,7 +130,7 @@ class Command(BaseCommand):
sequence_sql = connection.ops.sequence_reset_sql(no_style(), self.models) sequence_sql = connection.ops.sequence_reset_sql(no_style(), self.models)
if sequence_sql: if sequence_sql:
if self.verbosity >= 2: if self.verbosity >= 2:
self.stdout.write("Resetting sequences\n") self.stdout.write('Resetting sequences')
with connection.cursor() as cursor: with connection.cursor() as cursor:
for line in sequence_sql: for line in sequence_sql:
cursor.execute(line) cursor.execute(line)

View File

@ -337,7 +337,7 @@ class Command(BaseCommand):
if self.verbosity > 1: if self.verbosity > 1:
self.stdout.write( self.stdout.write(
'examining files with the extensions: %s\n' 'examining files with the extensions: %s'
% get_text_list(list(self.extensions), 'and') % get_text_list(list(self.extensions), 'and')
) )
@ -384,7 +384,7 @@ class Command(BaseCommand):
# Build po files for each selected locale # Build po files for each selected locale
for locale in locales: for locale in locales:
if self.verbosity > 0: if self.verbosity > 0:
self.stdout.write("processing locale %s\n" % locale) self.stdout.write('processing locale %s' % locale)
for potfile in potfiles: for potfile in potfiles:
self.write_po_file(potfile, locale) self.write_po_file(potfile, locale)
finally: finally:
@ -462,7 +462,7 @@ class Command(BaseCommand):
os.path.join(os.path.abspath(dirpath), dirname) in ignored_roots): os.path.join(os.path.abspath(dirpath), dirname) in ignored_roots):
dirnames.remove(dirname) dirnames.remove(dirname)
if self.verbosity > 1: if self.verbosity > 1:
self.stdout.write('ignoring directory %s\n' % dirname) self.stdout.write('ignoring directory %s' % dirname)
elif dirname == 'locale': elif dirname == 'locale':
dirnames.remove(dirname) dirnames.remove(dirname)
self.locale_paths.insert(0, os.path.join(os.path.abspath(dirpath), dirname)) self.locale_paths.insert(0, os.path.join(os.path.abspath(dirpath), dirname))
@ -471,7 +471,7 @@ class Command(BaseCommand):
file_ext = os.path.splitext(filename)[1] file_ext = os.path.splitext(filename)[1]
if file_ext not in self.extensions or is_ignored_path(file_path, self.ignore_patterns): if file_ext not in self.extensions or is_ignored_path(file_path, self.ignore_patterns):
if self.verbosity > 1: if self.verbosity > 1:
self.stdout.write('ignoring file %s in %s\n' % (filename, dirpath)) self.stdout.write('ignoring file %s in %s' % (filename, dirpath))
else: else:
locale_dir = None locale_dir = None
for path in self.locale_paths: for path in self.locale_paths:
@ -504,7 +504,7 @@ class Command(BaseCommand):
build_files = [] build_files = []
for translatable in files: for translatable in files:
if self.verbosity > 1: if self.verbosity > 1:
self.stdout.write('processing file %s in %s\n' % ( self.stdout.write('processing file %s in %s' % (
translatable.file, translatable.dirpath translatable.file, translatable.dirpath
)) ))
if self.domain not in ('djangojs', 'django'): if self.domain not in ('djangojs', 'django'):
@ -649,7 +649,7 @@ class Command(BaseCommand):
if m: if m:
plural_form_line = m.group('value') plural_form_line = m.group('value')
if self.verbosity > 1: if self.verbosity > 1:
self.stdout.write("copying plural forms: %s\n" % plural_form_line) self.stdout.write('copying plural forms: %s' % plural_form_line)
lines = [] lines = []
found = False found = False
for line in msgs.splitlines(): for line in msgs.splitlines():

View File

@ -190,7 +190,7 @@ class Command(BaseCommand):
directory_created = {} directory_created = {}
for app_label, app_migrations in changes.items(): for app_label, app_migrations in changes.items():
if self.verbosity >= 1: if self.verbosity >= 1:
self.stdout.write(self.style.MIGRATE_HEADING("Migrations for '%s':" % app_label) + "\n") self.stdout.write(self.style.MIGRATE_HEADING("Migrations for '%s':" % app_label))
for migration in app_migrations: for migration in app_migrations:
# Describe the migration # Describe the migration
writer = MigrationWriter(migration, self.include_header) writer = MigrationWriter(migration, self.include_header)
@ -203,9 +203,9 @@ class Command(BaseCommand):
migration_string = writer.path migration_string = writer.path
if migration_string.startswith('..'): if migration_string.startswith('..'):
migration_string = writer.path migration_string = writer.path
self.stdout.write(" %s\n" % self.style.MIGRATE_LABEL(migration_string)) self.stdout.write(' %s\n' % self.style.MIGRATE_LABEL(migration_string))
for operation in migration.operations: for operation in migration.operations:
self.stdout.write(" - %s\n" % operation.describe()) self.stdout.write(' - %s' % operation.describe())
if not self.dry_run: if not self.dry_run:
# Write the migrations file to the disk. # Write the migrations file to the disk.
migrations_directory = os.path.dirname(writer.path) migrations_directory = os.path.dirname(writer.path)
@ -224,9 +224,9 @@ class Command(BaseCommand):
# will output the migrations to stdout rather than saving # will output the migrations to stdout rather than saving
# the file to the disk. # the file to the disk.
self.stdout.write(self.style.MIGRATE_HEADING( self.stdout.write(self.style.MIGRATE_HEADING(
"Full migrations file '%s':" % writer.filename) + "\n" "Full migrations file '%s':" % writer.filename
) ))
self.stdout.write("%s\n" % writer.as_string()) self.stdout.write(writer.as_string())
def handle_merge(self, loader, conflicts): def handle_merge(self, loader, conflicts):
""" """
@ -272,7 +272,7 @@ class Command(BaseCommand):
for migration in merge_migrations: for migration in merge_migrations:
self.stdout.write(self.style.MIGRATE_LABEL(" Branch %s" % migration.name)) self.stdout.write(self.style.MIGRATE_LABEL(" Branch %s" % migration.name))
for operation in migration.merged_operations: for operation in migration.merged_operations:
self.stdout.write(" - %s\n" % operation.describe()) self.stdout.write(' - %s' % operation.describe())
if questioner.ask_merge(app_label): if questioner.ask_merge(app_label):
# If they still want to merge it, then write out an empty # If they still want to merge it, then write out an empty
# file depending on the migrations needing merging. # file depending on the migrations needing merging.
@ -305,6 +305,6 @@ class Command(BaseCommand):
# will output the merge migrations to stdout rather than saving # will output the merge migrations to stdout rather than saving
# the file to the disk. # the file to the disk.
self.stdout.write(self.style.MIGRATE_HEADING( self.stdout.write(self.style.MIGRATE_HEADING(
"Full merge migrations file '%s':" % writer.filename) + "\n" "Full merge migrations file '%s':" % writer.filename
) ))
self.stdout.write("%s\n" % writer.as_string()) self.stdout.write(writer.as_string())

View File

@ -331,7 +331,7 @@ class Command(BaseCommand):
# Create the tables for each model # Create the tables for each model
if self.verbosity >= 1: if self.verbosity >= 1:
self.stdout.write(" Creating tables...\n") self.stdout.write(' Creating tables...')
with connection.schema_editor() as editor: with connection.schema_editor() as editor:
for app_name, model_list in manifest.items(): for app_name, model_list in manifest.items():
for model in model_list: for model in model_list:
@ -340,15 +340,15 @@ class Command(BaseCommand):
continue continue
if self.verbosity >= 3: if self.verbosity >= 3:
self.stdout.write( self.stdout.write(
" Processing %s.%s model\n" % (app_name, model._meta.object_name) ' Processing %s.%s model' % (app_name, model._meta.object_name)
) )
if self.verbosity >= 1: if self.verbosity >= 1:
self.stdout.write(" Creating table %s\n" % model._meta.db_table) self.stdout.write(' Creating table %s' % model._meta.db_table)
editor.create_model(model) editor.create_model(model)
# Deferred SQL is executed when exiting the editor's context. # Deferred SQL is executed when exiting the editor's context.
if self.verbosity >= 1: if self.verbosity >= 1:
self.stdout.write(" Running deferred SQL...\n") self.stdout.write(' Running deferred SQL...')
@staticmethod @staticmethod
def describe_operation(operation, backwards): def describe_operation(operation, backwards):

View File

@ -124,7 +124,7 @@ class Command(BaseCommand):
self.stdout.write(( self.stdout.write((
"Django version %(version)s, using settings %(settings)r\n" "Django version %(version)s, using settings %(settings)r\n"
"Starting development server at %(protocol)s://%(addr)s:%(port)s/\n" "Starting development server at %(protocol)s://%(addr)s:%(port)s/\n"
"Quit the server with %(quit_command)s.\n" "Quit the server with %(quit_command)s."
) % { ) % {
"version": self.get_version(), "version": self.get_version(),
"settings": settings.SETTINGS_MODULE, "settings": settings.SETTINGS_MODULE,

View File

@ -85,13 +85,14 @@ class TemplateCommand(BaseCommand):
for file in options['files']: for file in options['files']:
extra_files.extend(map(lambda x: x.strip(), file.split(','))) extra_files.extend(map(lambda x: x.strip(), file.split(',')))
if self.verbosity >= 2: if self.verbosity >= 2:
self.stdout.write("Rendering %s template files with " self.stdout.write(
"extensions: %s\n" % 'Rendering %s template files with extensions: %s'
(app_or_project, ', '.join(extensions))) % (app_or_project, ', '.join(extensions))
self.stdout.write("Rendering %s template files with " )
"filenames: %s\n" % self.stdout.write(
(app_or_project, ', '.join(extra_files))) 'Rendering %s template files with filenames: %s'
% (app_or_project, ', '.join(extra_files))
)
base_name = '%s_name' % app_or_project base_name = '%s_name' % app_or_project
base_subdir = '%s_template' % app_or_project base_subdir = '%s_template' % app_or_project
base_directory = '%s_directory' % app_or_project base_directory = '%s_directory' % app_or_project
@ -162,7 +163,7 @@ class TemplateCommand(BaseCommand):
shutil.copyfile(old_path, new_path) shutil.copyfile(old_path, new_path)
if self.verbosity >= 2: if self.verbosity >= 2:
self.stdout.write("Creating %s\n" % new_path) self.stdout.write('Creating %s' % new_path)
try: try:
shutil.copymode(old_path, new_path) shutil.copymode(old_path, new_path)
self.make_writeable(new_path) self.make_writeable(new_path)
@ -174,7 +175,7 @@ class TemplateCommand(BaseCommand):
if self.paths_to_remove: if self.paths_to_remove:
if self.verbosity >= 2: if self.verbosity >= 2:
self.stdout.write("Cleaning up temporary files.\n") self.stdout.write('Cleaning up temporary files.')
for path_to_remove in self.paths_to_remove: for path_to_remove in self.paths_to_remove:
if os.path.isfile(path_to_remove): if os.path.isfile(path_to_remove):
os.remove(path_to_remove) os.remove(path_to_remove)
@ -259,7 +260,7 @@ class TemplateCommand(BaseCommand):
filename, display_url = cleanup_url(url) filename, display_url = cleanup_url(url)
if self.verbosity >= 2: if self.verbosity >= 2:
self.stdout.write("Downloading %s\n" % display_url) self.stdout.write('Downloading %s' % display_url)
try: try:
the_path, info = urlretrieve(url, os.path.join(tempdir, filename)) the_path, info = urlretrieve(url, os.path.join(tempdir, filename))
except OSError as e: except OSError as e:
@ -313,7 +314,7 @@ class TemplateCommand(BaseCommand):
tempdir = tempfile.mkdtemp(prefix=prefix, suffix='_extract') tempdir = tempfile.mkdtemp(prefix=prefix, suffix='_extract')
self.paths_to_remove.append(tempdir) self.paths_to_remove.append(tempdir)
if self.verbosity >= 2: if self.verbosity >= 2:
self.stdout.write("Extracting %s\n" % filename) self.stdout.write('Extracting %s' % filename)
try: try:
archive.extract(filename, tempdir) archive.extract(filename, tempdir)
return tempdir return tempdir