Skip to content

Commit b3f39c4

Browse files
vergenztnedbat
authored andcommittedApr 26, 2024·
refactor: add ruff linting & fix initial violations
1 parent 48557d0 commit b3f39c4

File tree

8 files changed

+79
-72
lines changed

8 files changed

+79
-72
lines changed
 

‎.github/workflows/ci.yml

+6
Original file line numberDiff line numberDiff line change
@@ -25,6 +25,12 @@ jobs:
2525
with:
2626
args: 'format --check'
2727

28+
lint:
29+
runs-on: ubuntu-latest
30+
steps:
31+
- uses: actions/checkout@v4
32+
- uses: chartboost/ruff-action@v1
33+
2834
tests:
2935
name: "Python ${{ matrix.python }} on ${{ matrix.os }}"
3036
runs-on: "${{ matrix.os }}-${{ matrix.os-version || 'latest' }}"

‎.pre-commit-config.yaml

+1
Original file line numberDiff line numberDiff line change
@@ -4,3 +4,4 @@ repos:
44
rev: v0.4.1
55
hooks:
66
- id: ruff-format
7+
- id: ruff

‎cogapp/__init__.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -4,4 +4,4 @@
44
Copyright 2004-2024, Ned Batchelder.
55
"""
66

7-
from .cogapp import Cog, CogUsageError, main
7+
from .cogapp import Cog as Cog, CogUsageError as CogUsageError, main as main

‎cogapp/cogapp.py

+48-48
Original file line numberDiff line numberDiff line change
@@ -114,11 +114,11 @@ def __init__(self, options=None):
114114
self.lines = []
115115
self.options = options or CogOptions()
116116

117-
def parseMarker(self, l):
118-
self.markers.append(l)
117+
def parseMarker(self, line):
118+
self.markers.append(line)
119119

120-
def parseLine(self, l):
121-
self.lines.append(l.strip("\n"))
120+
def parseLine(self, line):
121+
self.lines.append(line.strip("\n"))
122122

123123
def getCode(self):
124124
"""Extract the executable Python code from the generator."""
@@ -127,8 +127,8 @@ def getCode(self):
127127
# then remove it from all the lines.
128128
prefIn = commonPrefix(self.markers + self.lines)
129129
if prefIn:
130-
self.markers = [l.replace(prefIn, "", 1) for l in self.markers]
131-
self.lines = [l.replace(prefIn, "", 1) for l in self.lines]
130+
self.markers = [line.replace(prefIn, "", 1) for line in self.markers]
131+
self.lines = [line.replace(prefIn, "", 1) for line in self.lines]
132132

133133
return reindentBlock(self.lines, "")
134134

@@ -160,7 +160,7 @@ def evaluate(self, cog, globals, fname):
160160
eval(code, globals)
161161
except CogError:
162162
raise
163-
except:
163+
except: # noqa: E722 (we're just wrapping in CogUserException and rethrowing)
164164
typ, err, tb = sys.exc_info()
165165
frames = (tuple(fr) for fr in traceback.extract_tb(tb.tb_next))
166166
frames = find_cog_source(frames, prologue)
@@ -433,106 +433,106 @@ def processFile(self, fIn, fOut, fname=None, globals=None):
433433
globals.update(self.options.defines)
434434

435435
# loop over generator chunks
436-
l = fIn.readline()
437-
while l:
436+
line = fIn.readline()
437+
while line:
438438
# Find the next spec begin
439-
while l and not self.isBeginSpecLine(l):
440-
if self.isEndSpecLine(l):
439+
while line and not self.isBeginSpecLine(line):
440+
if self.isEndSpecLine(line):
441441
raise CogError(
442442
f"Unexpected {self.options.sEndSpec!r}",
443443
file=sFileIn,
444444
line=fIn.linenumber(),
445445
)
446-
if self.isEndOutputLine(l):
446+
if self.isEndOutputLine(line):
447447
raise CogError(
448448
f"Unexpected {self.options.sEndOutput!r}",
449449
file=sFileIn,
450450
line=fIn.linenumber(),
451451
)
452-
fOut.write(l)
453-
l = fIn.readline()
454-
if not l:
452+
fOut.write(line)
453+
line = fIn.readline()
454+
if not line:
455455
break
456456
if not self.options.bDeleteCode:
457-
fOut.write(l)
457+
fOut.write(line)
458458

459459
# l is the begin spec
460460
gen = CogGenerator(options=self.options)
461461
gen.setOutput(stdout=self.stdout)
462-
gen.parseMarker(l)
462+
gen.parseMarker(line)
463463
firstLineNum = fIn.linenumber()
464464
self.cogmodule.firstLineNum = firstLineNum
465465

466466
# If the spec begin is also a spec end, then process the single
467467
# line of code inside.
468-
if self.isEndSpecLine(l):
469-
beg = l.find(self.options.sBeginSpec)
470-
end = l.find(self.options.sEndSpec)
468+
if self.isEndSpecLine(line):
469+
beg = line.find(self.options.sBeginSpec)
470+
end = line.find(self.options.sEndSpec)
471471
if beg > end:
472472
raise CogError(
473473
"Cog code markers inverted", file=sFileIn, line=firstLineNum
474474
)
475475
else:
476-
sCode = l[beg + len(self.options.sBeginSpec) : end].strip()
476+
sCode = line[beg + len(self.options.sBeginSpec) : end].strip()
477477
gen.parseLine(sCode)
478478
else:
479479
# Deal with an ordinary code block.
480-
l = fIn.readline()
480+
line = fIn.readline()
481481

482482
# Get all the lines in the spec
483-
while l and not self.isEndSpecLine(l):
484-
if self.isBeginSpecLine(l):
483+
while line and not self.isEndSpecLine(line):
484+
if self.isBeginSpecLine(line):
485485
raise CogError(
486486
f"Unexpected {self.options.sBeginSpec!r}",
487487
file=sFileIn,
488488
line=fIn.linenumber(),
489489
)
490-
if self.isEndOutputLine(l):
490+
if self.isEndOutputLine(line):
491491
raise CogError(
492492
f"Unexpected {self.options.sEndOutput!r}",
493493
file=sFileIn,
494494
line=fIn.linenumber(),
495495
)
496496
if not self.options.bDeleteCode:
497-
fOut.write(l)
498-
gen.parseLine(l)
499-
l = fIn.readline()
500-
if not l:
497+
fOut.write(line)
498+
gen.parseLine(line)
499+
line = fIn.readline()
500+
if not line:
501501
raise CogError(
502502
"Cog block begun but never ended.",
503503
file=sFileIn,
504504
line=firstLineNum,
505505
)
506506

507507
if not self.options.bDeleteCode:
508-
fOut.write(l)
509-
gen.parseMarker(l)
508+
fOut.write(line)
509+
gen.parseMarker(line)
510510

511-
l = fIn.readline()
511+
line = fIn.readline()
512512

513513
# Eat all the lines in the output section. While reading past
514514
# them, compute the md5 hash of the old output.
515515
previous = []
516516
hasher = md5()
517-
while l and not self.isEndOutputLine(l):
518-
if self.isBeginSpecLine(l):
517+
while line and not self.isEndOutputLine(line):
518+
if self.isBeginSpecLine(line):
519519
raise CogError(
520520
f"Unexpected {self.options.sBeginSpec!r}",
521521
file=sFileIn,
522522
line=fIn.linenumber(),
523523
)
524-
if self.isEndSpecLine(l):
524+
if self.isEndSpecLine(line):
525525
raise CogError(
526526
f"Unexpected {self.options.sEndSpec!r}",
527527
file=sFileIn,
528528
line=fIn.linenumber(),
529529
)
530-
previous.append(l)
531-
hasher.update(l.encode("utf-8"))
532-
l = fIn.readline()
530+
previous.append(line)
531+
hasher.update(line.encode("utf-8"))
532+
line = fIn.readline()
533533
curHash = hasher.hexdigest()
534534

535-
if not l and not self.options.bEofCanBeEnd:
535+
if not line and not self.options.bEofCanBeEnd:
536536
# We reached end of file before we found the end output line.
537537
raise CogError(
538538
f"Missing {self.options.sEndOutput!r} before end of file.",
@@ -557,7 +557,7 @@ def processFile(self, fIn, fOut, fname=None, globals=None):
557557
bSawCog = True
558558

559559
# Write the ending output line
560-
hashMatch = self.reEndOutput.search(l)
560+
hashMatch = self.reEndOutput.search(line)
561561
if self.options.bHashOutput:
562562
if hashMatch:
563563
oldHash = hashMatch["hash"]
@@ -568,20 +568,20 @@ def processFile(self, fIn, fOut, fname=None, globals=None):
568568
line=fIn.linenumber(),
569569
)
570570
# Create a new end line with the correct hash.
571-
endpieces = l.split(hashMatch.group(0), 1)
571+
endpieces = line.split(hashMatch.group(0), 1)
572572
else:
573573
# There was no old hash, but we want a new hash.
574-
endpieces = l.split(self.options.sEndOutput, 1)
575-
l = (self.sEndFormat % newHash).join(endpieces)
574+
endpieces = line.split(self.options.sEndOutput, 1)
575+
line = (self.sEndFormat % newHash).join(endpieces)
576576
else:
577577
# We don't want hashes output, so if there was one, get rid of
578578
# it.
579579
if hashMatch:
580-
l = l.replace(hashMatch["hashsect"], "", 1)
580+
line = line.replace(hashMatch["hashsect"], "", 1)
581581

582582
if not self.options.bDeleteCode:
583-
fOut.write(l)
584-
l = fIn.readline()
583+
fOut.write(line)
584+
line = fIn.readline()
585585

586586
if not bSawCog and self.options.bWarnEmpty:
587587
self.showWarning(f"no cog code found in {sFileIn}")
@@ -712,9 +712,9 @@ def processFileList(self, sFileList):
712712
flist = self.openInputFile(sFileList)
713713
lines = flist.readlines()
714714
flist.close()
715-
for l in lines:
715+
for line in lines:
716716
# Use shlex to parse the line like a shell.
717-
lex = shlex.shlex(l, posix=True)
717+
lex = shlex.shlex(line, posix=True)
718718
lex.whitespace_split = True
719719
lex.commenters = "#"
720720
# No escapes, so that backslash can be part of the path

‎cogapp/test_cogapp.py

+14-14
Original file line numberDiff line numberDiff line change
@@ -709,7 +709,7 @@ def setUp(self):
709709
# the functions we're going to use.
710710
self.gen = CogGenerator()
711711
self.m = self.gen.parseMarker
712-
self.l = self.gen.parseLine
712+
self.parseLine = self.gen.parseLine
713713

714714
def testEmpty(self):
715715
self.m("// [[[cog")
@@ -718,50 +718,50 @@ def testEmpty(self):
718718

719719
def testSimple(self):
720720
self.m("// [[[cog")
721-
self.l(' print "hello"')
722-
self.l(' print "bye"')
721+
self.parseLine(' print "hello"')
722+
self.parseLine(' print "bye"')
723723
self.m("// ]]]")
724724
self.assertEqual(self.gen.getCode(), 'print "hello"\nprint "bye"')
725725

726726
def testCompressed1(self):
727727
# For a while, I supported compressed code blocks, but no longer.
728728
self.m('// [[[cog: print """')
729-
self.l("// hello")
730-
self.l("// bye")
729+
self.parseLine("// hello")
730+
self.parseLine("// bye")
731731
self.m('// """)]]]')
732732
self.assertEqual(self.gen.getCode(), "hello\nbye")
733733

734734
def testCompressed2(self):
735735
# For a while, I supported compressed code blocks, but no longer.
736736
self.m('// [[[cog: print """')
737-
self.l("hello")
738-
self.l("bye")
737+
self.parseLine("hello")
738+
self.parseLine("bye")
739739
self.m('// """)]]]')
740740
self.assertEqual(self.gen.getCode(), "hello\nbye")
741741

742742
def testCompressed3(self):
743743
# For a while, I supported compressed code blocks, but no longer.
744744
self.m("// [[[cog")
745-
self.l('print """hello')
746-
self.l("bye")
745+
self.parseLine('print """hello')
746+
self.parseLine("bye")
747747
self.m('// """)]]]')
748748
self.assertEqual(self.gen.getCode(), 'print """hello\nbye')
749749

750750
def testCompressed4(self):
751751
# For a while, I supported compressed code blocks, but no longer.
752752
self.m('// [[[cog: print """')
753-
self.l("hello")
754-
self.l('bye""")')
753+
self.parseLine("hello")
754+
self.parseLine('bye""")')
755755
self.m("// ]]]")
756756
self.assertEqual(self.gen.getCode(), 'hello\nbye""")')
757757

758758
def testNoCommonPrefixForMarkers(self):
759759
# It's important to be able to use #if 0 to hide lines from a
760760
# C++ compiler.
761761
self.m("#if 0 //[[[cog")
762-
self.l("\timport cog, sys")
763-
self.l("")
764-
self.l("\tprint sys.argv")
762+
self.parseLine("\timport cog, sys")
763+
self.parseLine("")
764+
self.parseLine("\tprint sys.argv")
765765
self.m("#endif //]]]")
766766
self.assertEqual(self.gen.getCode(), "import cog, sys\n\nprint sys.argv")
767767

‎cogapp/test_makefiles.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -26,7 +26,7 @@ def exists(self, dname, fname):
2626
def checkFilesExist(self, d, dname):
2727
for fname in d.keys():
2828
assert self.exists(dname, fname)
29-
if type(d[fname]) == type({}):
29+
if isinstance(d[fname], dict):
3030
self.checkFilesExist(d[fname], os.path.join(dname, fname))
3131

3232
def checkFilesDontExist(self, d, dname):

‎cogapp/utils.py

+3-3
Original file line numberDiff line numberDiff line change
@@ -44,10 +44,10 @@ def __init__(self, f):
4444
self.n = 0
4545

4646
def readline(self):
47-
l = self.f.readline()
48-
if l:
47+
line = self.f.readline()
48+
if line:
4949
self.n += 1
50-
return l
50+
return line
5151

5252
def linenumber(self):
5353
return self.n

‎cogapp/whiteutils.py

+5-5
Original file line numberDiff line numberDiff line change
@@ -43,12 +43,12 @@ def reindentBlock(lines, newIndent=""):
4343
lines = lines.split(sep)
4444
oldIndent = whitePrefix(lines)
4545
outLines = []
46-
for l in lines:
46+
for line in lines:
4747
if oldIndent:
48-
l = l.replace(oldIndent, nothing, 1)
49-
if l and newIndent:
50-
l = newIndent + l
51-
outLines.append(l)
48+
line = line.replace(oldIndent, nothing, 1)
49+
if line and newIndent:
50+
line = newIndent + line
51+
outLines.append(line)
5252
return sep.join(outLines)
5353

5454

0 commit comments

Comments
 (0)
Please sign in to comment.