Safely removes content from a given directory
(directory)
| 20 | from thirdparty.six import unichr as _unichr |
| 21 | |
| 22 | def purge(directory): |
| 23 | """ |
| 24 | Safely removes content from a given directory |
| 25 | """ |
| 26 | |
| 27 | if not os.path.isdir(directory): |
| 28 | warnMsg = "skipping purging of directory '%s' as it does not exist" % directory |
| 29 | logger.warning(warnMsg) |
| 30 | return |
| 31 | |
| 32 | infoMsg = "purging content of directory '%s'..." % directory |
| 33 | logger.info(infoMsg) |
| 34 | |
| 35 | filepaths = [] |
| 36 | dirpaths = [] |
| 37 | |
| 38 | for rootpath, directories, filenames in os.walk(directory): |
| 39 | dirpaths.extend(os.path.abspath(os.path.join(rootpath, _)) for _ in directories) |
| 40 | filepaths.extend(os.path.abspath(os.path.join(rootpath, _)) for _ in filenames) |
| 41 | |
| 42 | logger.debug("changing file attributes") |
| 43 | for filepath in filepaths: |
| 44 | try: |
| 45 | os.chmod(filepath, stat.S_IREAD | stat.S_IWRITE) |
| 46 | except: |
| 47 | pass |
| 48 | |
| 49 | logger.debug("writing random data to files") |
| 50 | for filepath in filepaths: |
| 51 | try: |
| 52 | filesize = os.path.getsize(filepath) |
| 53 | with openFile(filepath, "w+b") as f: |
| 54 | f.write("".join(_unichr(random.randint(0, 255)) for _ in xrange(filesize))) |
| 55 | except: |
| 56 | pass |
| 57 | |
| 58 | logger.debug("truncating files") |
| 59 | for filepath in filepaths: |
| 60 | try: |
| 61 | with open(filepath, 'w') as f: |
| 62 | pass |
| 63 | except: |
| 64 | pass |
| 65 | |
| 66 | logger.debug("renaming filenames to random values") |
| 67 | for filepath in filepaths: |
| 68 | try: |
| 69 | os.rename(filepath, os.path.join(os.path.dirname(filepath), "".join(random.sample(string.ascii_letters, random.randint(4, 8))))) |
| 70 | except: |
| 71 | pass |
| 72 | |
| 73 | dirpaths.sort(key=functools.cmp_to_key(lambda x, y: y.count(os.path.sep) - x.count(os.path.sep))) |
| 74 | |
| 75 | logger.debug("renaming directory names to random values") |
| 76 | for dirpath in dirpaths: |
| 77 | try: |
| 78 | os.rename(dirpath, os.path.join(os.path.dirname(dirpath), "".join(random.sample(string.ascii_letters, random.randint(4, 8))))) |
| 79 | except: |
no test coverage detected
searching dependent graphs…