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