Skip to content

Commit f34934e

Browse files
author
Jonathan Kamens
committed
Flake8
1 parent ec94502 commit f34934e

File tree

5 files changed

+93
-32
lines changed

5 files changed

+93
-32
lines changed

delete

Lines changed: 12 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -4,14 +4,14 @@ import logging
44
import optparse
55
import os
66
import shutil
7-
import stat
87
import sys
98

9+
import libdelete
10+
from libdelete import perror
11+
1012
logger = logging.getLogger('delete')
1113
whoami = os.path.basename(sys.argv[0])
1214

13-
import libdelete
14-
from libdelete import perror
1515

1616
def debug_callback(option, opt_str, value, parser):
1717
"""
@@ -28,6 +28,7 @@ def debug_callback(option, opt_str, value, parser):
2828
for l in loggers:
2929
logging.getLogger(l).setLevel(logging.DEBUG)
3030

31+
3132
def ask(question, *args, **kwargs):
3233
"""
3334
Ask a question, possibly prepended with the name of the program
@@ -41,6 +42,7 @@ def ask(question, *args, **kwargs):
4142
except KeyboardInterrupt:
4243
sys.exit(0)
4344

45+
4446
def actually_delete(filename, options):
4547
"""
4648
Actually delete the file.
@@ -55,7 +57,8 @@ def actually_delete(filename, options):
5557
filename):
5658
return False
5759
if options.noop:
58-
print >>sys.stderr, "{0}: {1} would be removed".format(whoami, filename)
60+
print >>sys.stderr, "{0}: {1} would be removed".format(
61+
whoami, filename)
5962
return True
6063
(dirname, basename) = os.path.split(filename)
6164
newname = os.path.join(dirname, '.#' + basename)
@@ -73,6 +76,7 @@ def actually_delete(filename, options):
7376
os.utime(newname, None)
7477
return True
7578

79+
7680
def delete(filename, options):
7781
logger.debug("delete(%s)", filename)
7882
if not os.path.lexists(filename):
@@ -123,6 +127,7 @@ def delete(filename, options):
123127
else:
124128
return actually_delete(filename, options)
125129

130+
126131
def main():
127132
parser = optparse.OptionParser(usage="%prog [options] filename ...")
128133
# This is probably a terrible idea, but the old code did it
@@ -155,7 +160,8 @@ def main():
155160
default=linked_to_rmdir,
156161
help="Only remove empty directories (refuse to remove files)")
157162
parser.add_option(
158-
"--debug", action="callback", type='string', help="Enable debugging (logger target or 'all')",
163+
"--debug", action="callback", type='string',
164+
help="Enable debugging (logger target or 'all')",
159165
callback=debug_callback, metavar='target')
160166
(options, args) = parser.parse_args()
161167
if options.filesonly and options.directoriesonly:
@@ -176,6 +182,7 @@ def main():
176182
errors = 1
177183
return errors
178184

185+
179186
if __name__ == "__main__":
180187
logging.basicConfig(level=logging.WARNING)
181188
sys.exit(main())

expunge

Lines changed: 16 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,7 @@ confirmation = "Do you wish to continue [return = no]? "
1818
logger = logging.getLogger('expunge')
1919
whoami = os.path.basename(sys.argv[0])
2020

21+
2122
def debug_callback(option, opt_str, value, parser):
2223
"""
2324
An OptionParser callback that enables debugging.
@@ -33,6 +34,7 @@ def debug_callback(option, opt_str, value, parser):
3334
for l in loggers:
3435
logging.getLogger(l).setLevel(logging.DEBUG)
3536

37+
3638
def ask(question, *args, **kwargs):
3739
"""
3840
Ask a question, possibly prepended with the name of the program
@@ -46,10 +48,12 @@ def ask(question, *args, **kwargs):
4648
except KeyboardInterrupt:
4749
sys.exit(0)
4850

51+
4952
def getsize(path):
5053
size = os.path.getsize(path)
5154
return (size, "(%dKB)" % (libdelete.to_kb(size),))
5255

56+
5357
def expunge(deleted_files, options):
5458
expunged_size = 0
5559
errors = 0
@@ -87,7 +91,11 @@ def expunge(deleted_files, options):
8791
# We exit here, not keep going, as the original code did
8892
sys.exit(errors)
8993
if options.verbose:
90-
print "{whoami}: {path} {size} {maybe}expunged ({total}KB total)".format(whoami=whoami, path=f, size=size_str, maybe='would be ' if options.noop else '', total=libdelete.to_kb(expunged_size))
94+
print("{whoami}: {path} {size} {maybe}expunged "
95+
"({total}KB total)".format(
96+
whoami=whoami, path=f, size=size_str,
97+
maybe='would be ' if options.noop else '',
98+
total=libdelete.to_kb(expunged_size)))
9199
if not options.noop:
92100
if os.path.isdir(f) and not os.path.islink(f):
93101
logger.debug("rmdir: %s", f)
@@ -100,6 +108,7 @@ def expunge(deleted_files, options):
100108
print "Total expunged: {0}KB".format(libdelete.to_kb(expunged_size))
101109
return errors
102110

111+
103112
def parse_options():
104113
parser = optparse.OptionParser(usage="%prog [options] filename ...")
105114
parser.add_option(
@@ -133,14 +142,16 @@ def parse_options():
133142
"-m", dest="f_mounts", action="store_true", default=False,
134143
help="Follow mount points")
135144
parser.add_option(
136-
"--debug", action="callback", type='string', help="Enable debugging (logger target or 'all')",
145+
"--debug", action="callback", type='string',
146+
help="Enable debugging (logger target or 'all')",
137147
callback=debug_callback, metavar='target')
138148
(options, args) = parser.parse_args()
139149
if options.noop:
140150
# -n implies -v
141151
options.verbose = True
142152
return (options, args)
143153

154+
144155
def main():
145156
rv = 0
146157
if ((whoami == "purge") and len(sys.argv) > 1):
@@ -175,11 +186,13 @@ def main():
175186
# Doesn't cover all corner cases, but covers everything the old
176187
# code supported. In particular, weird symlinks will make this
177188
# sad
178-
deleted_files.sort(reverse=True, key=lambda x: x.count(os.path.sep))
189+
deleted_files.sort(reverse=True,
190+
key=lambda x: x.count(os.path.sep))
179191
rv += expunge(deleted_files, options)
180192

181193
return rv
182194

195+
183196
if __name__ == "__main__":
184197
logging.basicConfig(level=logging.WARNING)
185198
sys.exit(main())

libdelete.py

Lines changed: 39 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,6 @@
1010
import re
1111
import time
1212
import sys
13-
import stat
1413

1514
WILDCARDS_RE = re.compile('([*?[])')
1615
KILO = 1024
@@ -19,9 +18,11 @@
1918
_have_AFS = None
2019
whoami = os.path.basename(sys.argv[0])
2120

21+
2222
class DeleteError(Exception):
2323
pass
2424

25+
2526
def perror(message, **kwargs):
2627
"""
2728
Format an error message, log it in the debug log
@@ -33,12 +34,14 @@ def perror(message, **kwargs):
3334
if should_print:
3435
print >>sys.stderr, msg
3536

37+
3638
def chunks(seq, size):
3739
"""
3840
Break a sequence up into size chunks
3941
"""
4042
return (seq[pos:pos + size] for pos in xrange(0, len(seq), size))
4143

44+
4245
def format_columns(items, singlecol=False, width=80):
4346
"""
4447
Pretty-print in optional multi-column format, with padding/spread.
@@ -59,6 +62,7 @@ def format_columns(items, singlecol=False, width=80):
5962
rv.append("".join(item.ljust(col_width + padding) for item in c))
6063
return "\n".join(rv)
6164

65+
6266
def have_AFS():
6367
global _have_AFS, afs
6468

@@ -71,6 +75,7 @@ def have_AFS():
7175
_have_AFS = False
7276
return _have_AFS
7377

78+
7479
def is_mountpoint(path):
7580
if os.path.ismount(path):
7681
return True
@@ -82,35 +87,41 @@ def is_mountpoint(path):
8287
logger.debug("Got exception while checking mount point: %s", e)
8388
return False
8489

90+
8591
def has_wildcards(string):
8692
return WILDCARDS_RE.search(string) is not None
8793

94+
8895
def is_deleted(path):
8996
"""
9097
Return True if the file has been 'deleted' by delete(1)
9198
"""
9299
return os.path.basename(path).startswith('.#')
93100

101+
94102
def dir_listing(path):
95103
"""
96104
A directory listing with the full path.
97105
"""
98106
return [os.path.join(path, x) for x in os.listdir(path)]
99107

108+
100109
def empty_directory(path):
101110
"""
102111
Return True if the directory is "empty" (that is, any entries
103112
in it have been deleted)
104113
"""
105114
return all(is_deleted(x) for x in dir_listing(path))
106115

116+
107117
def relpath(path):
108118
"""
109119
For relative paths that begin with '.', strip off the leading
110120
stuff.
111121
"""
112122
return path[2:] if path.startswith('./') else path
113123

124+
114125
def undeleted_name(path):
115126
"""
116127
Return the undeleted name of a file. Only the last component
@@ -124,6 +135,7 @@ def undeleted_name(path):
124135
else:
125136
return path
126137

138+
127139
def n_days_old(path, n):
128140
if n < 0:
129141
raise ValueError("n must not be negative")
@@ -134,27 +146,34 @@ def n_days_old(path, n):
134146
logger.debug("%s modified %d sec ago", path, mtime)
135147
return ((time.time() - mtime) >= (86400 * n))
136148

149+
137150
def escape_meta(path):
138151
return WILDCARDS_RE.sub(r'[\1]', path)
139152

153+
140154
def to_kb(size):
141155
return int(round(float(size) / KILO))
142156

157+
143158
def find_deleted_files(file_or_pattern, follow_links=False,
144159
follow_mounts=False, recurse_undeleted_subdirs=None,
145160
recurse_deleted_subdirs=None, n_days=0):
146161

147-
logger.debug("find_deleted_files(%s, links=%s, mounts=%s, recurse_un=%s, recurse_del=%s, ndays=%s)",
148-
file_or_pattern, follow_links, follow_mounts, recurse_undeleted_subdirs,
149-
recurse_deleted_subdirs, n_days)
162+
logger.debug("find_deleted_files(%s, links=%s, mounts=%s, recurse_un=%s, "
163+
"recurse_del=%s, ndays=%s)",
164+
file_or_pattern, follow_links, follow_mounts,
165+
recurse_undeleted_subdirs, recurse_deleted_subdirs, n_days)
150166
rv = []
151167
# In AFS, without tokens, this is very slow. "Don't do that."
152168
# The old code called readdir() and lstat'd everything before following.
153-
# The old code also re-implemented glob() with BREs, and we're not doing that.
169+
# The old code also re-implemented glob() with BREs, and we're not doing
170+
# that.
154171
file_list = glob.glob(file_or_pattern) + glob.glob('.#' + file_or_pattern)
155172
if len(file_list) == 0:
156-
raise DeleteError("{0}: {1}".format(file_or_pattern,
157-
"No match" if has_wildcards(file_or_pattern) else os.strerror(errno.ENOENT)))
173+
raise DeleteError("{0}: {1}".format(
174+
file_or_pattern,
175+
"No match" if has_wildcards(file_or_pattern)
176+
else os.strerror(errno.ENOENT)))
158177

159178
for filename in file_list:
160179
logger.debug("Examining %s", filename)
@@ -166,21 +185,26 @@ def find_deleted_files(file_or_pattern, follow_links=False,
166185
if is_mountpoint(filename) and not follow_mounts:
167186
logger.debug("Skipping mountpoint: %s", filename)
168187
continue
169-
if ((is_deleted(filename) and (recurse_deleted_subdirs != False)) or \
170-
(not is_deleted(filename) and (recurse_undeleted_subdirs != False))):
171-
# NOTE: recurse_undeleted_subdirs is being abused as a tristate with 'None'
172-
# meaning "do it on the first time only.
188+
if ((is_deleted(filename) and
189+
(recurse_deleted_subdirs is not False)) or
190+
(not is_deleted(filename) and
191+
(recurse_undeleted_subdirs is not False))):
192+
# NOTE: recurse_undeleted_subdirs is being abused as a tristate
193+
# with 'None' meaning "do it on the first time only.
173194
logger.debug("Recursing into %sdeleted directory: %s",
174195
"un" if not is_deleted(filename) else "",
175196
filename)
176197
try:
177198
for item in dir_listing(filename):
178199
# Escape metachars before recursing because filenames
179200
# can in fact contain metacharacters.
180-
rv += find_deleted_files(escape_meta(item), follow_links, follow_mounts,
181-
False if recurse_undeleted_subdirs is None else recurse_undeleted_subdirs,
182-
False if recurse_deleted_subdirs is None else recurse_deleted_subdirs,
183-
n_days)
201+
rv += find_deleted_files(
202+
escape_meta(item), follow_links, follow_mounts,
203+
False if recurse_undeleted_subdirs is None
204+
else recurse_undeleted_subdirs,
205+
False if recurse_deleted_subdirs is None
206+
else recurse_deleted_subdirs,
207+
n_days)
184208
except OSError as e:
185209
perror('{filename}: {error}', filename=e.filename,
186210
error=e.strerror)

lsdel

Lines changed: 11 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,7 @@ from libdelete import perror
1111
logger = logging.getLogger('lsdel')
1212
whoami = os.path.basename(sys.argv[0])
1313

14+
1415
def debug_callback(option, opt_str, value, parser):
1516
"""
1617
An OptionParser callback that enables debugging.
@@ -26,6 +27,7 @@ def debug_callback(option, opt_str, value, parser):
2627
for l in loggers:
2728
logging.getLogger(l).setLevel(logging.DEBUG)
2829

30+
2931
def parse_options():
3032
parser = optparse.OptionParser(usage="%prog [options] filename ...")
3133
parser.add_option(
@@ -53,7 +55,8 @@ def parse_options():
5355
"-m", dest="f_mounts", action="store_true", default=False,
5456
help="Follow mount points")
5557
parser.add_option(
56-
"--debug", action="callback", type='string', help="Enable debugging (logger target or 'all')",
58+
"--debug", action="callback", type='string',
59+
help="Enable debugging (logger target or 'all')",
5760
callback=debug_callback, metavar='target')
5861
(options, args) = parser.parse_args()
5962
if options.singlecolumn and options.multicolumn:
@@ -64,6 +67,7 @@ def parse_options():
6467
delattr(options, 'multicolumn')
6568
return (options, args)
6669

70+
6771
def main():
6872
rv = 0
6973
(options, args) = parse_options()
@@ -77,7 +81,7 @@ def main():
7781
follow_links=options.f_links,
7882
follow_mounts=options.f_mounts,
7983
recurse_undeleted_subdirs=options.recursive or None,
80-
recurse_deleted_subdirs= not options.dirsonly,
84+
recurse_deleted_subdirs=not options.dirsonly,
8185
n_days=options.timev)
8286
except libdelete.DeleteError as e:
8387
perror(e.message)
@@ -97,11 +101,14 @@ def main():
97101
rv = 1
98102

99103
if total is None:
100-
perror('Unable to display total size: errors occurred during calculation.')
104+
perror('Unable to display total size: errors occurred during '
105+
'calculation.')
101106
else:
102-
print "\nTotal space taken up by files: %dKB" % round((float(total) / 1024))
107+
print("\nTotal space taken up by files: %dKB" %
108+
round((float(total) / 1024)))
103109
return rv
104110

111+
105112
if __name__ == "__main__":
106113
logging.basicConfig(level=logging.WARNING)
107114
sys.exit(main())

0 commit comments

Comments
 (0)