From b946fccbd8f2de141a638e247a83cdaaf887d7f8 Mon Sep 17 00:00:00 2001 From: Kevin Robert Stravers Date: Sun, 11 May 2025 22:15:06 -0400 Subject: [PATCH] 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. --- cogapp/cogapp.py | 4 ++++ cogapp/test_cogapp.py | 24 ++++++++++++++++++++++++ 2 files changed, 28 insertions(+) diff --git a/cogapp/cogapp.py b/cogapp/cogapp.py index b463f87..ffa2470 100644 --- a/cogapp/cogapp.py +++ b/cogapp/cogapp.py @@ -125,6 +125,10 @@ def get_code(self): # If the markers and lines all have the same prefix # (end-of-line comment chars, for example), # then remove it from all the lines. + for idx, marker in enumerate(self.markers): + self.markers[idx] = marker.replace(self.options.begin_spec, "").replace( + self.options.end_spec, "" + ) pref_in = common_prefix(self.markers + self.lines) if pref_in: self.markers = [line.replace(pref_in, "", 1) for line in self.markers] diff --git a/cogapp/test_cogapp.py b/cogapp/test_cogapp.py index 1ab7969..783d827 100644 --- a/cogapp/test_cogapp.py +++ b/cogapp/test_cogapp.py @@ -254,6 +254,30 @@ def test_prefixed_indented_code(self): infile = reindent_block(infile) self.assertEqual(Cog().process_string(infile), infile) + def test_markers_overlapping_prefix(self): + infile = """\ + // cog-begin + // cog.outl('lorem ipsum') + // cog-middle + // cog-end + """ + + outfile = """\ + // cog-begin + // cog.outl('lorem ipsum') + // cog-middle + lorem ipsum + // cog-end + """ + + infile = reindent_block(infile) + outfile = reindent_block(outfile) + cog = Cog() + cog.options.begin_spec = "cog-begin" + cog.options.end_spec = "cog-middle" + cog.options.end_output = "cog-end" + self.assertEqual(cog.process_string(infile), outfile) + def test_bogus_prefix_match(self): infile = """\ prologue