Skip to content

Commit ea5f349

Browse files
committed
Remove begin/end spec as part of the common prefix
When we define our own --markers='x-begin x-middle x-end', and our code contains as a first character `x`, then that character will be considered part of the common prefix and be removed from the code. Here's an example. // cog-begin // cog.outl('hello world') // cog-middle // cog-end The common prefix for this code is `// cog`, which makes the code generator fail because python will receive the code `.outl('hello world')`, which makes no sense. This issue is especially cumbersome to work with if you're invoking a module, for instance: // cog-begin // codegen.generate_some_code() // cog-middle // cog-end Here the python interpeter will receive `degen.generate_some_code()`. This patch removes the begin and end specs from the marker line to avoid this issue.
1 parent 3e0634b commit ea5f349

File tree

2 files changed

+26
-0
lines changed

2 files changed

+26
-0
lines changed

cogapp/cogapp.py

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -125,6 +125,8 @@ def get_code(self):
125125
# If the markers and lines all have the same prefix
126126
# (end-of-line comment chars, for example),
127127
# then remove it from all the lines.
128+
for idx, marker in enumerate(self.markers):
129+
self.markers[idx] = marker.replace(self.options.begin_spec, "").replace(self.options.end_spec, "")
128130
pref_in = common_prefix(self.markers + self.lines)
129131
if pref_in:
130132
self.markers = [line.replace(pref_in, "", 1) for line in self.markers]

cogapp/test_cogapp.py

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -254,6 +254,30 @@ def test_prefixed_indented_code(self):
254254
infile = reindent_block(infile)
255255
self.assertEqual(Cog().process_string(infile), infile)
256256

257+
def test_markers_overlapping_prefix(self):
258+
infile = """\
259+
// cog-begin
260+
// cog.outl('lorem ipsum')
261+
// cog-middle
262+
// cog-end
263+
"""
264+
265+
outfile = """\
266+
// cog-begin
267+
// cog.outl('lorem ipsum')
268+
// cog-middle
269+
lorem ipsum
270+
// cog-end
271+
"""
272+
273+
infile = reindent_block(infile)
274+
outfile = reindent_block(outfile)
275+
cog = Cog()
276+
cog.options.begin_spec = 'cog-begin'
277+
cog.options.end_spec = 'cog-middle'
278+
cog.options.end_output = 'cog-end'
279+
self.assertEqual(cog.process_string(infile), outfile)
280+
257281
def test_bogus_prefix_match(self):
258282
infile = """\
259283
prologue

0 commit comments

Comments
 (0)