]> arthur.barton.de Git - bup.git/blob - lib/bup/cmd/damage.py
damage-cmd: copy to bup.cmd.damage
[bup.git] / lib / bup / cmd / damage.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
19 # Intentionally replace the dirname "$0" that python prepends
20 import os, sys
21 sys.path[0] = [os.path.dirname(os.path.realpath(__file__)) + '/../..']
22
23 import random
24
25 from bup import compat, options
26 from bup.compat import argv_bytes, bytes_from_uint, range
27 from bup.helpers import log
28 from bup.io import path_msg
29
30
31 def randblock(n):
32     return b''.join(bytes_from_uint(random.randrange(0,256)) for i in range(n))
33
34
35 optspec = """
36 bup damage [-n count] [-s maxsize] [-S seed] <filenames...>
37 --
38    WARNING: THIS COMMAND IS EXTREMELY DANGEROUS
39 n,num=   number of blocks to damage
40 s,size=  maximum size of each damaged block
41 percent= maximum size of each damaged block (as a percent of entire file)
42 equal    spread damage evenly throughout the file
43 S,seed=  random number seed (for repeatable tests)
44 """
45 o = options.Options(optspec)
46 opt, flags, extra = o.parse(compat.argv[1:])
47
48 if not extra:
49     o.fatal('filenames expected')
50
51 if opt.seed != None:
52     random.seed(opt.seed)
53
54 for name in extra:
55     name = argv_bytes(name)
56     log('Damaging "%s"...\n' % path_msg(name))
57     with open(name, 'r+b') as f:
58         st = os.fstat(f.fileno())
59         size = st.st_size
60         if opt.percent or opt.size:
61             ms1 = int(float(opt.percent or 0)/100.0*size) or size
62             ms2 = opt.size or size
63             maxsize = min(ms1, ms2)
64         else:
65             maxsize = 1
66         chunks = opt.num or 10
67         chunksize = size // chunks
68         for r in range(chunks):
69             sz = random.randrange(1, maxsize+1)
70             if sz > size:
71                 sz = size
72             if opt.equal:
73                 ofs = r*chunksize
74             else:
75                 ofs = random.randrange(0, size - sz + 1)
76             log('  %6d bytes at %d\n' % (sz, ofs))
77             f.seek(ofs)
78             f.write(randblock(sz))