[file_utils] dirpacker: rework message printing

This commit is contained in:
Matteo Cypriani 2014-06-01 21:26:00 -04:00
parent ace92010ec
commit 235a22aba1
1 changed files with 33 additions and 20 deletions

View File

@ -33,6 +33,7 @@
import argparse import argparse
import os import os
import shutil import shutil
import sys
from collections import defaultdict from collections import defaultdict
import math import math
@ -52,12 +53,12 @@ class Bin:
def print(self): def print(self):
"""Displays the contents of the bin. """Displays the contents of the bin.
""" """
print("\n### {} ###\n# List of files:".format(self.name())) print("\n### {} ###\nList of files:".format(self.name()))
for filename, size in sorted(self.files.items()): for filename, size in sorted(self.files.items()):
print("{} # {:.2f} MiB".format(filename, size)) print("{:12.2f} MiB\t{}".format(size, filename))
print("# This bin's size: {:.2f} MiB".format(self.size))
sizefree = options.maxbinsize - self.size sizefree = options.maxbinsize - self.size
print("# Free space: {:.2f} MiB".format(sizefree)) print("This bin's size: {:.2f} MiB".format(self.size))
print("Unused: {:.2f} MiB".format(sizefree))
def name(self): def name(self):
"""Returns the bin's name' """Returns the bin's name'
@ -70,6 +71,19 @@ class Bin:
return list(self.files.keys()) return list(self.files.keys())
def warn(*message, prefix="Warning!", **args):
"""Prints the message on the error output, prepended by 'prefix'.
The standard output is flushed prior to printing the error message, to
enable the messages to be displayed in the right order.
This function is a simple wrapper around print(), and you can use any
keyword argument you would use with print().
"""
sys.stdout.flush()
print(prefix, *message, file=sys.stderr, **args)
def du(basepath): def du(basepath):
""" Returns the size of the file of directory `basepath`, in MiB. """ Returns the size of the file of directory `basepath`, in MiB.
""" """
@ -134,7 +148,7 @@ options = arg_parser.parse_args()
### Preliminary statistics ### ### Preliminary statistics ###
if options.verbose: if options.verbose:
print("# Maximum size of a bin: {:.2f} MiB".format(options.maxbinsize)) print("Maximum size of a bin: {:.2f} MiB".format(options.maxbinsize))
# Compute the size of all the files # Compute the size of all the files
sizes = defaultdict(list) sizes = defaultdict(list)
@ -143,20 +157,20 @@ ignored_files = False
for filename in options.filenames: for filename in options.filenames:
size = du(filename) size = du(filename)
if (size > options.maxbinsize): if (size > options.maxbinsize):
print('# WARNING! "{}" is {:.2f} MiB, which exceeds the maximum size of' warn('"{}" is {:.2f} MiB, which exceeds the maximum size of a bin:'
' a bin: ignoring.' ' ignoring.'
.format(filename, size)) .format(filename, size))
ignored_files = True ignored_files = True
continue continue
sizes[size].append(filename) sizes[size].append(filename)
totalsize += size totalsize += size
if options.verbose: if options.verbose:
print("# Total size of the input files: {:.2f} MiB".format(totalsize)) print("Total size of the input files: {:.2f} MiB".format(totalsize))
minbins = math.ceil(totalsize / options.maxbinsize) minbins = math.ceil(totalsize / options.maxbinsize)
print("# Minimal (optimal) number of bins required: ", minbins) print("Minimal (optimal) number of bins required: ", minbins)
sizefree = minbins * options.maxbinsize - totalsize sizefree = minbins * options.maxbinsize - totalsize
print("# Theoretical unused space with {} bins: {:.2f} MiB" print("Theoretical unused space with {} bins: {:.2f} MiB"
.format(minbins, sizefree)) .format(minbins, sizefree))
@ -175,8 +189,8 @@ binscreated = binnumber - 1
if options.verbose: if options.verbose:
sizefree = binscreated * options.maxbinsize - totalsize sizefree = binscreated * options.maxbinsize - totalsize
print("""\ print("""\
# {} bins created. {} bins created.
# Actual unused space over the {} bins created: {:.2f} MiB""" Actual unused space over the {} bins created: {:.2f} MiB"""
.format(binscreated, binscreated, sizefree)) .format(binscreated, binscreated, sizefree))
@ -193,17 +207,16 @@ if options.move:
for b in bins: for b in bins:
dirname = b.name() dirname = b.name()
if os.path.exists(dirname) and not os.path.isdir(dirname): if os.path.exists(dirname) and not os.path.isdir(dirname):
print('# WARNING! File "{}" exists but is not a directory:' warn('File "{}" exists but is not a directory: skipping bin #{}.'
' skipping bin #{}.' .format(dirname, b.id))
.format(dirname, b.id))
continue continue
# Create the target directory: # Create the target directory:
try: try:
os.makedirs(dirname, exist_ok=True) os.makedirs(dirname, exist_ok=True)
except FileExistsError: except FileExistsError:
print('# WARNING! Directory "{}" already exists with different' warn('Directory "{}" already exists with different permissions'
' permissions (mode). Proceeding anyway.' ' (mode). Proceeding anyway.'
.format(dirname)) .format(dirname))
# Move the files in the directory: # Move the files in the directory:
for filename in b.list_files(): for filename in b.list_files():
shutil.move(filename, dirname) shutil.move(filename, dirname)
@ -212,4 +225,4 @@ if options.move:
### Wrapping-up ### ### Wrapping-up ###
if (ignored_files): if (ignored_files):
print("\n# WARNING! There were ignored files, see at the top of this log.") warn("There were ignored files (see prior messages).")