3 # https://sourceware.org/bugzilla/show_bug.cgi?id=26034
4 export "BUP_ARGV_0"="$0"
7 export "BUP_ARGV_${arg_i}"="$arg"
11 # Here to end of preamble replaced during install
12 bup_python="$(dirname "$0")/bup-python" || exit $?
13 exec "$bup_python" "$0"
17 from __future__ import absolute_import, print_function
18 from binascii import hexlify, unhexlify
19 from collections import defaultdict
20 from itertools import groupby
21 from sys import stderr
22 from time import localtime, strftime, time
25 from bup import compat, git, options
26 from bup.compat import argv_bytes, int_types
27 from bup.gc import bup_gc
28 from bup.helpers import die_if_errors, log, partition, period_as_secs
29 from bup.io import byte_stream
30 from bup.repo import LocalRepo
31 from bup.rm import bup_rm
34 def branches(refnames=tuple()):
35 return ((name[11:], hexlify(sha)) for (name,sha)
36 in git.list_refs(patterns=(b'refs/heads/' + n for n in refnames),
39 def save_name(branch, utc):
40 return branch + b'/' \
41 + strftime('%Y-%m-%d-%H%M%S', localtime(utc)).encode('ascii')
43 def classify_saves(saves, period_start):
44 """For each (utc, id) in saves, yield (True, (utc, id)) if the save
45 should be kept and (False, (utc, id)) if the save should be removed.
46 The ids are binary hashes.
49 def retain_newest_in_region(region):
50 for save in region[0:1]:
52 for save in region[1:]:
55 matches, rest = partition(lambda s: s[0] >= period_start['all'], saves)
59 tm_ranges = ((period_start['dailies'], lambda s: localtime(s[0]).tm_yday),
60 (period_start['monthlies'], lambda s: localtime(s[0]).tm_mon),
61 (period_start['yearlies'], lambda s: localtime(s[0]).tm_year))
63 # Break the decreasing utc sorted saves up into the respective
64 # period ranges (dailies, monthlies, ...). Within each range,
65 # group the saves by the period scale (days, months, ...), and
66 # then yield a "keep" action (True, utc) for the newest save in
67 # each group, and a "drop" action (False, utc) for the rest.
68 for pstart, time_region_id in tm_ranges:
69 matches, rest = partition(lambda s: s[0] >= pstart, rest)
70 for region_id, region_saves in groupby(matches, time_region_id):
71 for action in retain_newest_in_region(list(region_saves)):
74 # Finally, drop any saves older than the specified periods
80 bup prune-older [options...] [BRANCH...]
82 keep-all-for= retain all saves within the PERIOD
83 keep-dailies-for= retain the newest save per day within the PERIOD
84 keep-monthlies-for= retain the newest save per month within the PERIOD
85 keep-yearlies-for= retain the newest save per year within the PERIOD
86 wrt= end all periods at this number of seconds since the epoch
87 pretend don't prune, just report intended actions to standard output
88 gc collect garbage after removals [1]
89 gc-threshold= only rewrite a packfile if it's over this percent garbage [10]
90 #,compress= set compression level to # (0-9, 9 is highest) [1]
91 v,verbose increase log output (can be used more than once)
92 unsafe use the command even though it may be DANGEROUS
95 o = options.Options(optspec)
96 opt, flags, roots = o.parse(compat.argv[1:])
97 roots = [argv_bytes(x) for x in roots]
100 o.fatal('refusing to run dangerous, experimental command without --unsafe')
102 now = int(time()) if opt.wrt is None else opt.wrt
103 if not isinstance(now, int_types):
104 o.fatal('--wrt value ' + str(now) + ' is not an integer')
107 for period, extent in (('all', opt.keep_all_for),
108 ('dailies', opt.keep_dailies_for),
109 ('monthlies', opt.keep_monthlies_for),
110 ('yearlies', opt.keep_yearlies_for)):
112 secs = period_as_secs(extent.encode('ascii'))
114 o.fatal('%r is not a valid period' % extent)
115 period_start[period] = now - secs
118 o.fatal('at least one keep argument is required')
120 period_start = defaultdict(lambda: float('inf'), period_start)
123 epoch_ymd = strftime('%Y-%m-%d-%H%M%S', localtime(0))
124 for kind in ['all', 'dailies', 'monthlies', 'yearlies']:
125 period_utc = period_start[kind]
126 if period_utc != float('inf'):
127 if not (period_utc > float('-inf')):
128 log('keeping all ' + kind)
131 when = strftime('%Y-%m-%d-%H%M%S', localtime(period_utc))
132 log('keeping ' + kind + ' since ' + when + '\n')
133 except ValueError as ex:
135 log('keeping %s since %d seconds before %s\n'
136 %(kind, abs(period_utc), epoch_ymd))
138 log('keeping %s since %d seconds after %s\n'
139 %(kind, period_utc, epoch_ymd))
141 log('keeping %s since %s\n' % (kind, epoch_ymd))
143 git.check_repo_or_die()
145 # This could be more efficient, but for now just build the whole list
146 # in memory and let bup_rm() do some redundant work.
149 author_secs = f.readline().strip()
150 return int(author_secs)
153 out = byte_stream(sys.stdout)
156 for branch, branch_id in branches(roots):
158 saves = ((utc, unhexlify(oidx)) for (oidx, utc) in
159 git.rev_list(branch_id, format=b'%at', parse=parse_info))
160 for keep_save, (utc, id) in classify_saves(saves, period_start):
161 assert(keep_save in (False, True))
162 # FIXME: base removals on hashes
164 out.write(b'+ ' if keep_save else b'- '
165 + save_name(branch, utc) + b'\n')
167 removals.append(save_name(branch, utc))
172 bup_rm(repo, removals, compression=opt.compress, verbosity=opt.verbose)
175 bup_gc(threshold=opt.gc_threshold,
176 compression=opt.compress,
177 verbosity=opt.verbose)