]> arthur.barton.de Git - bup.git/blob - lib/cmd/damage-cmd.py
Prefer python 3, and mention intent to drop python 2 support
[bup.git] / lib / cmd / damage-cmd.py
1 #!/bin/sh
2 """": # -*-python-*-
3 # https://sourceware.org/bugzilla/show_bug.cgi?id=26034
4 export "BUP_ARGV_0"="$0"
5 arg_i=1
6 for arg in "$@"; do
7     export "BUP_ARGV_${arg_i}"="$arg"
8     shift
9     arg_i=$((arg_i + 1))
10 done
11 # Here to end of preamble replaced during install
12 bup_python="$(dirname "$0")/../../config/bin/python" || exit $?
13 exec "$bup_python" "$0"
14 """
15 # end of bup preamble
16
17 from __future__ import absolute_import
18 import os, random, sys
19
20 sys.path[:0] = [os.path.dirname(os.path.realpath(__file__)) + '/..']
21
22 from bup import compat, options
23 from bup.compat import argv_bytes, bytes_from_uint, range
24 from bup.helpers import log
25 from bup.io import path_msg
26
27
28 def randblock(n):
29     return b''.join(bytes_from_uint(random.randrange(0,256)) for i in range(n))
30
31
32 optspec = """
33 bup damage [-n count] [-s maxsize] [-S seed] <filenames...>
34 --
35    WARNING: THIS COMMAND IS EXTREMELY DANGEROUS
36 n,num=   number of blocks to damage
37 s,size=  maximum size of each damaged block
38 percent= maximum size of each damaged block (as a percent of entire file)
39 equal    spread damage evenly throughout the file
40 S,seed=  random number seed (for repeatable tests)
41 """
42 o = options.Options(optspec)
43 opt, flags, extra = o.parse(compat.argv[1:])
44
45 if not extra:
46     o.fatal('filenames expected')
47
48 if opt.seed != None:
49     random.seed(opt.seed)
50
51 for name in extra:
52     name = argv_bytes(name)
53     log('Damaging "%s"...\n' % path_msg(name))
54     with open(name, 'r+b') as f:
55         st = os.fstat(f.fileno())
56         size = st.st_size
57         if opt.percent or opt.size:
58             ms1 = int(float(opt.percent or 0)/100.0*size) or size
59             ms2 = opt.size or size
60             maxsize = min(ms1, ms2)
61         else:
62             maxsize = 1
63         chunks = opt.num or 10
64         chunksize = size // chunks
65         for r in range(chunks):
66             sz = random.randrange(1, maxsize+1)
67             if sz > size:
68                 sz = size
69             if opt.equal:
70                 ofs = r*chunksize
71             else:
72                 ofs = random.randrange(0, size - sz + 1)
73             log('  %6d bytes at %d\n' % (sz, ofs))
74             f.seek(ofs)
75             f.write(randblock(sz))