info <archive>: use Archive.info() for both JSON and human display

This commit is contained in:
Marian Beermann 2017-02-23 21:34:13 +01:00
parent 8cdf192511
commit 4f1db82f6d
3 changed files with 35 additions and 24 deletions

View File

@ -28,7 +28,7 @@ from .helpers import Chunk, ChunkIteratorFileWrapper, open_item
from .helpers import Error, IntegrityError from .helpers import Error, IntegrityError
from .helpers import uid2user, user2uid, gid2group, group2gid from .helpers import uid2user, user2uid, gid2group, group2gid
from .helpers import parse_timestamp, to_localtime from .helpers import parse_timestamp, to_localtime
from .helpers import format_time, format_timedelta, format_file_size, file_status from .helpers import format_time, format_timedelta, format_file_size, file_status, FileSize
from .helpers import safe_encode, safe_decode, make_path_safe, remove_surrogates from .helpers import safe_encode, safe_decode, make_path_safe, remove_surrogates
from .helpers import StableDict from .helpers import StableDict
from .helpers import bin_to_hex from .helpers import bin_to_hex
@ -70,9 +70,9 @@ class Statistics:
def as_dict(self): def as_dict(self):
return { return {
'original_size': self.osize, 'original_size': FileSize(self.osize),
'compressed_size': self.csize, 'compressed_size': FileSize(self.csize),
'deduplicated_size': self.usize, 'deduplicated_size': FileSize(self.usize),
'nfiles': self.nfiles, 'nfiles': self.nfiles,
} }
@ -379,6 +379,7 @@ class Archive:
'command_line': self.metadata.cmdline, 'command_line': self.metadata.cmdline,
'hostname': self.metadata.hostname, 'hostname': self.metadata.hostname,
'username': self.metadata.username, 'username': self.metadata.username,
'comment': self.metadata.get('comment', ''),
}) })
return info return info

View File

@ -17,7 +17,7 @@ import textwrap
import time import time
import traceback import traceback
from binascii import unhexlify from binascii import unhexlify
from datetime import datetime from datetime import datetime, timedelta
from itertools import zip_longest from itertools import zip_longest
from .logger import create_logger, setup_logging from .logger import create_logger, setup_logging
@ -37,7 +37,8 @@ from .helpers import EXIT_SUCCESS, EXIT_WARNING, EXIT_ERROR
from .helpers import Error, NoManifestError from .helpers import Error, NoManifestError
from .helpers import location_validator, archivename_validator, ChunkerParams, CompressionSpec from .helpers import location_validator, archivename_validator, ChunkerParams, CompressionSpec
from .helpers import PrefixSpec, SortBySpec, HUMAN_SORT_KEYS from .helpers import PrefixSpec, SortBySpec, HUMAN_SORT_KEYS
from .helpers import BaseFormatter, ItemFormatter, ArchiveFormatter, format_time, format_file_size, format_archive from .helpers import BaseFormatter, ItemFormatter, ArchiveFormatter
from .helpers import format_time, format_timedelta, format_file_size, format_archive
from .helpers import safe_encode, remove_surrogates, bin_to_hex, prepare_dump_dict from .helpers import safe_encode, remove_surrogates, bin_to_hex, prepare_dump_dict
from .helpers import prune_within, prune_split from .helpers import prune_within, prune_split
from .helpers import to_localtime, timestamp from .helpers import to_localtime, timestamp
@ -52,7 +53,7 @@ from .helpers import parse_pattern, PatternMatcher, PathPrefixPattern
from .helpers import signal_handler, raising_signal_handler, SigHup, SigTerm from .helpers import signal_handler, raising_signal_handler, SigHup, SigTerm
from .helpers import ErrorIgnoringTextIOWrapper from .helpers import ErrorIgnoringTextIOWrapper
from .helpers import ProgressIndicatorPercent from .helpers import ProgressIndicatorPercent
from .helpers import BorgJsonEncoder, basic_json_data, json_print from .helpers import basic_json_data, json_print
from .item import Item from .item import Item
from .key import key_creator, tam_required_file, tam_required, RepoKey, PassphraseKey from .key import key_creator, tam_required_file, tam_required, RepoKey, PassphraseKey
from .keymanager import KeyManager from .keymanager import KeyManager
@ -997,25 +998,29 @@ class Archiver:
for i, archive_name in enumerate(archive_names, 1): for i, archive_name in enumerate(archive_names, 1):
archive = Archive(repository, key, manifest, archive_name, cache=cache, archive = Archive(repository, key, manifest, archive_name, cache=cache,
consider_part_files=args.consider_part_files) consider_part_files=args.consider_part_files)
info = archive.info()
if args.json: if args.json:
output_data.append(archive.info()) output_data.append(info)
else: else:
stats = archive.calc_stats(cache) info['duration'] = format_timedelta(timedelta(seconds=info['duration']))
print('Archive name: %s' % archive.name) info['command_line'] = format_cmdline(info['command_line'])
print('Archive fingerprint: %s' % archive.fpr) print(textwrap.dedent("""
print('Comment: %s' % archive.metadata.get('comment', '')) Archive name: {name}
print('Hostname: %s' % archive.metadata.hostname) Archive fingerprint: {id}
print('Username: %s' % archive.metadata.username) Comment: {comment}
print('Time (start): %s' % format_time(to_localtime(archive.ts))) Hostname: {hostname}
print('Time (end): %s' % format_time(to_localtime(archive.ts_end))) Username: {username}
print('Duration: %s' % archive.duration_from_meta) Time (start): {start}
print('Number of files: %d' % stats.nfiles) Time (end): {end}
print('Command line: %s' % format_cmdline(archive.metadata.cmdline)) Duration: {duration}
print('Utilization of max. archive size: %d%%' % (100 * cache.chunks[archive.id].csize / MAX_DATA_SIZE)) Number of files: {stats[nfiles]}
print(DASHES) Command line: {command_line}
print(STATS_HEADER) Utilization of max. archive size: {limits[max_archive_size]:.0%}
print(str(stats)) ------------------------------------------------------------------------------
print(str(cache)) Original size Compressed size Deduplicated size
This archive: {stats[original_size]:>20s} {stats[compressed_size]:>20s} {stats[deduplicated_size]:>20s}
{cache}
""").strip().format(cache=cache, **info))
if self.exit_code: if self.exit_code:
break break
if not args.json and len(archive_names) - i: if not args.json and len(archive_names) - i:

View File

@ -831,6 +831,11 @@ def format_file_size(v, precision=2, sign=False):
return sizeof_fmt_decimal(v, suffix='B', sep=' ', precision=precision, sign=sign) return sizeof_fmt_decimal(v, suffix='B', sep=' ', precision=precision, sign=sign)
class FileSize(int):
def __format__(self, format_spec):
return format_file_size(int(self)).__format__(format_spec)
def parse_file_size(s): def parse_file_size(s):
"""Return int from file size (1234, 55G, 1.7T).""" """Return int from file size (1234, 55G, 1.7T)."""
if not s: if not s: