aboutsummaryrefslogtreecommitdiff
blob: 4d2a6864b115c174155a2f6acc342b4485ed4f33 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
# Copyright(c) 2009-2010, Gentoo Foundation
#
# Licensed under the GNU General Public License, v2
#
# $Header: $

"""Print total size of files contained in a given package"""

__docformat__ = 'epytext'

# =======
# Imports
# =======

import sys
from getopt import gnu_getopt, GetoptError

import gentoolkit.pprinter as pp
from gentoolkit.equery import format_options, mod_usage, CONFIG
from gentoolkit.helpers import do_lookup

# =======
# Globals
# =======

QUERY_OPTS = {
	"includeInstalled": True,
	"includePortTree": False,
	"includeOverlayTree": False,
	"includeMasked": True,
	"isRegex": False,
	"matchExact": False,
	"printMatchInfo": False,
	"sizeInBytes": False
}

# =========
# Functions
# =========

def print_help(with_description=True):
	"""Print description, usage and a detailed help message.

	@type with_description: bool
	@param with_description: if true, print module's __doc__ string
	"""

	if with_description:
		print __doc__.strip()
		print

	# Deprecation warning added by djanderson, 12/2008
	depwarning = (
		"Default action for this module has changed in Gentoolkit 0.3.",
		"Use globbing to simulate the old behavior (see man equery).",
		"Use '*' to check all installed packages.",
		"Use 'foo-bar/*' to filter by category."
	)
	for line in depwarning:
		sys.stderr.write(pp.warn(line))
	print

	print mod_usage(mod_name="size")
	print
	print pp.command("options")
	print format_options((
		(" -h, --help", "display this help message"),
		(" -b, --bytes", "report size in bytes"),
		(" -f, --full-regex", "query is a regular expression")
	))


def display_size(match_set):
	"""Display the total size of all accessible files owned by packages.

	@type match_set: list
	@param match_set: package cat/pkg-ver strings
	"""

	for pkg in match_set:
		size, files, uncounted = pkg.size()

		if CONFIG['verbose']:
			print " * %s" % pp.cpv(str(pkg.cpv))
			print "Total files : %s".rjust(25) % pp.number(str(files))

			if uncounted:
				print ("Inaccessible files : %s".rjust(25) %
					pp.number(str(uncounted)))

			if QUERY_OPTS["sizeInBytes"]:
				size_str = pp.number(str(size))
			else:
				size_str = "%s %s" % format_bytes(size)

			print "Total size  : %s".rjust(25) % size_str
		else:
			info = "%s: total(%d), inaccessible(%d), size(%s)"
			print info % (str(pkg.cpv), files, uncounted, size)


def format_bytes(bytes_, precision=2):
	"""Format bytes into human-readable format (IEC naming standard).

	@see: http://mail.python.org/pipermail/python-list/2008-August/503423.html
	@rtype: tuple
	@return: (str(num), str(label))
	"""

	labels = (
		(1<<40L, 'TiB'),
		(1<<30L, 'GiB'),
		(1<<20L, 'MiB'),
		(1<<10L, 'KiB'),
		(1, 'bytes')
	)

	if bytes_ == 0:
		return (pp.number('0'), 'bytes')
	elif bytes_ == 1:
		return (pp.number('1'), 'byte')

	for factor, label in labels:
		if not bytes_ >= factor:
			continue

		float_split = str(bytes_/float(factor)).split('.')
		integer = float_split[0]
		decimal = float_split[1]
		if int(decimal[0:precision]):
			float_string = '.'.join([integer, decimal[0:precision]])
		else:
			float_string = integer

		return (pp.number(float_string), label)


def parse_module_options(module_opts):
	"""Parse module options and update QUERY_OPTS"""

	opts = (x[0] for x in module_opts)
	for opt in opts:
		if opt in ('-h', '--help'):
			print_help()
			sys.exit(0)
		elif opt in ('-b', '--bytes'):
			QUERY_OPTS["sizeInBytes"] = True
		elif opt in ('-e', '--exact-name'):
			sys.stderr.write(pp.warn("-e, --exact-name is now default."))
			warning = pp.warn("Use globbing to simulate the old behavior.")
			sys.stderr.write(warning)
			print
		elif opt in ('-f', '--full-regex'):
			QUERY_OPTS['isRegex'] = True


def main(input_args):
	"""Parse input and run the program"""

	# -e, --exact-name is no longer needed. Kept for compatibility.
	# 04/09 djanderson
	short_opts = "hbfe"
	long_opts = ('help', 'bytes', 'full-regex', 'exact-name')

	try:
		module_opts, queries = gnu_getopt(input_args, short_opts, long_opts)
	except GetoptError, err:
		sys.stderr.write(pp.error("Module %s" % err))
		print
		print_help(with_description=False)
		sys.exit(2)

	parse_module_options(module_opts)

	if not queries:
		print_help()
		sys.exit(2)

	first_run = True
	for query in queries:
		if not first_run:
			print

		matches = do_lookup(query, QUERY_OPTS)

		if not matches:
			sys.stderr.write(pp.error("No package found matching %s" % query))

		display_size(matches)

		first_run = False

# vim: set ts=4 sw=4 tw=79: