Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python script to delete old SVN files lacks permission

I'm trying to delete old SVN files from directory tree. shutil.rmtree and os.unlink raise WindowsErrors, because the script doesn't have permissions to delete them. How can I get around that?

Here is the script:

# Delete all files of a certain type from a direcotry

import os
import shutil

dir = "c:\\"

verbosity = 0;

def printCleanMsg(dir_path):
    if verbosity:
        print "Cleaning %s\n" % dir_path

def cleandir(dir_path):
    printCleanMsg(dir_path)
    toDelete = []
    dirwalk = os.walk(dir_path)
    for root, dirs, files in dirwalk:
        printCleanMsg(root)
        toDelete.extend([root + os.sep + dir for dir in dirs if '.svn' == dir])
        toDelete.extend([root + os.sep + file for file in files if 'svn' in file])

    print "Items to be deleted:"
    for candidate in toDelete:
        print candidate
    print "Delete all %d items? [y|n]" % len(toDelete)

    choice = raw_input()

    if choice == 'y':
        deleted = 0
        for filedir in toDelete:
            if os.path.exists(filedir): # could have been deleted already by rmtree
                try:
                    if os.path.isdir(filedir):
                        shutil.rmtree(filedir)
                    else:
                        os.unlink(filedir)
                    deleted += 1
                except WindowsError:
                    print "WindowsError: Couldn't delete '%s'" % filedir

    print "\nDeleted %d/%d files." % (deleted, len(toDelete))
    exit()

if __name__ == "__main__":
    cleandir(dir)

Not a single file is able to be deleted. What am I doing wrong?

like image 253
Nick Heiner Avatar asked Dec 23 '22 02:12

Nick Heiner


2 Answers

To remove recursively all .svn I use this script. May be it will help someone.

import os, shutil, stat

def del_evenReadonly(action, name, exc):
    os.chmod(name, stat.S_IWRITE)
    os.remove(name)

for root, subFolders, files in os.walk(os.getcwd()):
    if '.svn' in subFolders:
      shutil.rmtree(root+'\.svn',onerror=del_evenReadonly)
like image 171
Irina Leo Avatar answered Dec 26 '22 11:12

Irina Leo


Subversion usually makes all the .svn directories (and everything in them) write protected. Probably you have to remove the write protection before you can remove the files.

I'm not really sure how to do this best with Windows, but you should be able to use os.chmod() with the stat.S_IWRITE flag. Probably you have to iterate through all the files in the .svn directories and make them all writable individually.

like image 42
sth Avatar answered Dec 26 '22 10:12

sth