Skip to content

Commit 641a9a6

Browse files
committed
style: Add pre-commit ruff and meta hooks, format
1 parent 9bf3594 commit 641a9a6

9 files changed

+1021
-483
lines changed

.pre-commit-config.yaml

+9
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,10 @@
11
# See https://pre-commit.com for more information
22
---
33
repos:
4+
- repo: meta
5+
hooks:
6+
- id: check-hooks-apply
7+
- id: check-useless-excludes
48
- repo: https://github.com/pre-commit/pre-commit-hooks
59
rev: v4.6.0
610
hooks:
@@ -20,3 +24,8 @@ repos:
2024
rev: v3.17.0
2125
hooks:
2226
- id: pyupgrade
27+
- repo: https://github.com/astral-sh/ruff-pre-commit
28+
rev: v0.6.3
29+
hooks:
30+
- id: ruff
31+
- id: ruff-format

normfn

+13-29
Original file line numberDiff line numberDiff line change
@@ -57,8 +57,7 @@ def main(argv, syserr_handler):
5757
"--verbose",
5858
action="count",
5959
default=0,
60-
help="Add debugging output. "
61-
"Using this twice makes it doubly verbose.",
60+
help="Add debugging output. " "Using this twice makes it doubly verbose.",
6261
)
6362

6463
_ = parser.add_argument(
@@ -201,9 +200,7 @@ def main(argv, syserr_handler):
201200
"This is the default.",
202201
)
203202

204-
parser.set_defaults(
205-
time_option="earliest", undo_log_file=get_default_log_file()
206-
)
203+
parser.set_defaults(time_option="earliest", undo_log_file=get_default_log_file())
207204

208205
class FilenamesAction(argparse.Action):
209206
# pylint: disable=too-few-public-methods
@@ -376,11 +373,7 @@ def datetime_prefix(args, non_extension: str, filename: str):
376373
if matchobj.group("prefix") != ""
377374
else ""
378375
)
379-
+ (
380-
matchobj.group("suffix")
381-
if matchobj.group("suffix") != ""
382-
else ""
383-
)
376+
+ (matchobj.group("suffix") if matchobj.group("suffix") != "" else "")
384377
)
385378

386379
logger.debug("replacement() returned: " + replaceValue)
@@ -407,7 +400,9 @@ def datetime_prefix(args, non_extension: str, filename: str):
407400
DATE_TIME_SEPARATOR = r"([-_T\s]|\sat\s|,\s)"
408401

409402
REGEX = (
410-
r"^(?P<prefix>.*?)[-_]?" + r"(" +
403+
r"^(?P<prefix>.*?)[-_]?"
404+
+ r"("
405+
+
411406
# Y-M-D style
412407
r"(?P<year1>"
413408
+ YEAR
@@ -473,13 +468,10 @@ def datetime_prefix(args, non_extension: str, filename: str):
473468

474469
if args.add_time:
475470
newname = (
476-
timetouse.strftime("%Y-%m-%dT%H-%M-%S")
477-
+ newname_with_dash_if_needed
471+
timetouse.strftime("%Y-%m-%dT%H-%M-%S") + newname_with_dash_if_needed
478472
)
479473
else:
480-
newname = (
481-
timetouse.strftime("%Y-%m-%d") + newname_with_dash_if_needed
482-
)
474+
newname = timetouse.strftime("%Y-%m-%d") + newname_with_dash_if_needed
483475

484476
return newname
485477

@@ -493,9 +485,7 @@ def process_filename(filename: str, args):
493485
if not args.all:
494486
(exclude, why) = should_exclude(filename, basename)
495487
if exclude:
496-
logger.info(
497-
f"Skipping {filename.strip()} as it matches pattern {why}"
498-
)
488+
logger.info(f"Skipping {filename.strip()} as it matches pattern {why}")
499489
return filename
500490

501491
(non_extension, extension) = os.path.splitext(basename)
@@ -506,9 +496,7 @@ def process_filename(filename: str, args):
506496

507497
original_filename = filename
508498
filename = os.path.join(os.path.dirname(original_filename), newname)
509-
logger.debug(
510-
f"Potential new filename for {original_filename} is {filename}"
511-
)
499+
logger.debug(f"Potential new filename for {original_filename} is {filename}")
512500

513501
if filename == original_filename:
514502
logger.debug("New filename would be identical, skipping.")
@@ -586,7 +574,7 @@ def validate_move(args, original_filename: str, filename: str) -> None:
586574
)
587575

588576

589-
def rlinput(prompt: str, prefill: str=""):
577+
def rlinput(prompt: str, prefill: str = ""):
590578
if os.name == "nt":
591579
return input(prompt)
592580
else:
@@ -629,9 +617,7 @@ def shiftfile(args, source: str, target: str):
629617
def check_undo_log_file_header(args):
630618
if not os.path.exists(args.undo_log_file):
631619
with open(args.undo_log_file, "w") as log_file:
632-
wrapper = textwrap.TextWrapper(
633-
initial_indent="# ", subsequent_indent="# "
634-
)
620+
wrapper = textwrap.TextWrapper(initial_indent="# ", subsequent_indent="# ")
635621
log_file.write("#!/bin/sh\n")
636622
log_file.write(
637623
wrapper.fill(
@@ -700,9 +686,7 @@ def readchar():
700686

701687

702688
def insensitiveize(string: str) -> str:
703-
return "".join(
704-
map(lambda char: ("[" + char.lower() + char.upper() + "]"), string)
705-
)
689+
return "".join(map(lambda char: ("[" + char.lower() + char.upper() + "]"), string))
706690

707691

708692
class FatalException(Exception):

tests/BaseTestClasses.py

+48-17
Original file line numberDiff line numberDiff line change
@@ -16,33 +16,48 @@
1616

1717

1818
class NormalizeFilenameTestCase(unittest.TestCase):
19-
COMMAND = os.path.normpath(os.path.join(os.getcwd(), 'normfn'))
19+
COMMAND = os.path.normpath(os.path.join(os.getcwd(), "normfn"))
2020

2121
def setUp(self):
2222
self.workingDir = tempfile.mkdtemp()
2323

2424
def getDatePrefix(self, postfixDash=True):
25-
if (postfixDash is True):
25+
if postfixDash is True:
2626
return datetime.now().strftime("%Y-%m-%d-")
2727
else:
2828
return datetime.now().strftime("%Y-%m-%d")
2929

3030
def directoryFileCount(self, directory):
31-
return len([item for item in os.listdir(directory) if os.path.isfile(os.path.join(directory, item))])
31+
return len(
32+
[
33+
item
34+
for item in os.listdir(directory)
35+
if os.path.isfile(os.path.join(directory, item))
36+
]
37+
)
3238

3339
def directoryDirCount(self, directory):
34-
return len([item for item in os.listdir(directory) if os.path.isdir(os.path.join(directory, item))])
40+
return len(
41+
[
42+
item
43+
for item in os.listdir(directory)
44+
if os.path.isdir(os.path.join(directory, item))
45+
]
46+
)
3547

3648
def getOriginalScriptPath(self):
3749
module_path = inspect.getfile(inspect.currentframe())
38-
module_path = os.path.join(os.path.dirname(os.path.dirname(module_path)), 'normfn')
50+
module_path = os.path.join(
51+
os.path.dirname(os.path.dirname(module_path)), "normfn"
52+
)
3953

4054
return module_path
4155

4256
def invokeDirectly(self, inputFiles, extraParams=[]):
4357
import importlib.machinery
58+
4459
module_path = self.getOriginalScriptPath()
45-
loader = importlib.machinery.SourceFileLoader('normfn', module_path)
60+
loader = importlib.machinery.SourceFileLoader("normfn", module_path)
4661
spec = spec_from_loader(os.path.basename(module_path), loader)
4762
normalize_filename = module_from_spec(spec)
4863
spec.loader.exec_module(normalize_filename)
@@ -51,11 +66,11 @@ def invokeDirectly(self, inputFiles, extraParams=[]):
5166

5267
options.extend(inputFiles)
5368
options.extend(extraParams)
54-
options.extend(['--no-undo-log-file'])
69+
options.extend(["--no-undo-log-file"])
5570

5671
stream = io.StringIO()
5772
handler = logging.StreamHandler(stream)
58-
log = logging.getLogger('normfn')
73+
log = logging.getLogger("normfn")
5974
log.propagate = False
6075
log.setLevel(logging.DEBUG)
6176
log.addHandler(handler)
@@ -70,21 +85,29 @@ def invokeDirectly(self, inputFiles, extraParams=[]):
7085

7186
return error
7287

73-
def invokeAsSubprocess(self, inputFiles, extraParams=[], feedInput=None, cwd=None, expectOutput=False, useUndoFile=False):
88+
def invokeAsSubprocess(
89+
self,
90+
inputFiles,
91+
extraParams=[],
92+
feedInput=None,
93+
cwd=None,
94+
expectOutput=False,
95+
useUndoFile=False,
96+
):
7497
if cwd is None:
7598
cwd = self.workingDir
7699

77100
with tempfile.NamedTemporaryFile(delete=False) as undo_log_file:
78101
undo_log_file.close()
79102

80103
if os.name == "nt":
81-
options = ['python', NormalizeFilenameTestCase.COMMAND]
104+
options = ["python", NormalizeFilenameTestCase.COMMAND]
82105
else:
83106
options = [NormalizeFilenameTestCase.COMMAND]
84107

85108
options.extend(inputFiles)
86109
options.extend(extraParams)
87-
options.extend(['--undo-log-file=' + undo_log_file.name])
110+
options.extend(["--undo-log-file=" + undo_log_file.name])
88111

89112
if feedInput:
90113
p = Popen(options, stdin=PIPE, stdout=PIPE, stderr=PIPE, cwd=cwd)
@@ -122,13 +145,19 @@ def executeUndoCommands(self, commands):
122145
return maxReturnCode
123146

124147
@contextmanager
125-
def invokeAsPexpect(self, inputFiles, extraParams=[], expectedExitStatus=None, expectedOutputRegex=None):
148+
def invokeAsPexpect(
149+
self,
150+
inputFiles,
151+
extraParams=[],
152+
expectedExitStatus=None,
153+
expectedOutputRegex=None,
154+
):
126155
options = [NormalizeFilenameTestCase.COMMAND]
127156
options.extend(inputFiles)
128157
options.extend(extraParams)
129-
options.extend(['--no-undo-log-file'])
158+
options.extend(["--no-undo-log-file"])
130159

131-
command = ' '.join(options)
160+
command = " ".join(options)
132161

133162
stream = io.BytesIO()
134163

@@ -144,18 +173,20 @@ def invokeAsPexpect(self, inputFiles, extraParams=[], expectedExitStatus=None, e
144173
self.assertEqual(expectedExitStatus, child.exitstatus)
145174

146175
if expectedOutputRegex is not None:
147-
self.assertRegex(str(child.logfile_read.getvalue(), 'utf-8'), expectedOutputRegex)
176+
self.assertRegex(
177+
str(child.logfile_read.getvalue(), "utf-8"), expectedOutputRegex
178+
)
148179

149180
def touch(self, fname):
150181
os.makedirs(os.path.dirname(fname), exist_ok=True)
151-
open(fname, 'w').close()
182+
open(fname, "w").close()
152183

153184
def remove_dir_write_permissions(self, fname):
154185
os.chmod(fname, S_IRUSR | S_IXUSR)
155186

156187
def writeFile(self, fname, contents):
157188
os.makedirs(os.path.dirname(fname), exist_ok=True)
158-
with open(fname, 'w') as filename:
189+
with open(fname, "w") as filename:
159190
filename.write(contents)
160191

161192
def readFile(self, fname):

tests/Direct/test_Direct_Arguments.py

+3-3
Original file line numberDiff line numberDiff line change
@@ -8,11 +8,11 @@ def setUp(self):
88
super().setUp()
99

1010
def test_targetfile_exists_with_force(self):
11-
filename = os.path.join(self.workingDir, 'blah.txt')
11+
filename = os.path.join(self.workingDir, "blah.txt")
1212
self.writeFile(filename, "original")
13-
filename2 = os.path.join(self.workingDir, self.getDatePrefix() + 'blah.txt')
13+
filename2 = os.path.join(self.workingDir, self.getDatePrefix() + "blah.txt")
1414
self.writeFile(filename2, "new")
15-
self.invokeDirectly([filename], extraParams=['--force'])
15+
self.invokeDirectly([filename], extraParams=["--force"])
1616
self.assertFalse(os.path.exists(filename))
1717
self.assertTrue(os.path.exists(filename2))
1818
self.assertEqual(self.readFile(filename2), "original")

0 commit comments

Comments
 (0)