Repository: mwouts/jupytext
Pull request #479 (2020-04-03 23:29:46)

Fix active cells in the py:percent format
This PR reproduces the issue documented at #477 

codecov[bot]: # [Codecov](https://codecov.io/gh/mwouts/jupytext/pull/479?src=pr&el=h1) Report
> Merging [#479](https://codecov.io/gh/mwouts/jupytext/pull/479?src=pr&el=desc) into [master](https://codecov.io/gh/mwouts/jupytext/commit/6c0f027be0d20d914bd49f05e2eaa8e1898bd27b&el=desc) will **decrease** coverage by `0.00%`.
> The diff coverage is `95.65%`.

[![Impacted file tree graph](https://codecov.io/gh/mwouts/jupytext/pull/479/graphs/tree.svg?width=650&height=150&src=pr&token=a1pNjsiILi)](https://codecov.io/gh/mwouts/jupytext/pull/479?src=pr&el=tree)

```diff
@@            Coverage Diff             @@
##           master     #479      +/-   ##
==========================================
- Coverage   98.82%   98.81%   -0.01%     
==========================================
  Files          80       80              
  Lines        8005     8025      +20     
==========================================
+ Hits         7911     7930      +19     
- Misses         94       95       +1     
```


| [Impacted Files](https://codecov.io/gh/mwouts/jupytext/pull/479?src=pr&el=tree) | Coverage Δ | |
|---|---|---|
| [jupytext/cell\_reader.py](https://codecov.io/gh/mwouts/jupytext/pull/479/diff?src=pr&el=tree#diff-anVweXRleHQvY2VsbF9yZWFkZXIucHk=) | `96.63% <75.00%> (-0.16%)` | :arrow_down: |
| [jupytext/cell\_to\_text.py](https://codecov.io/gh/mwouts/jupytext/pull/479/diff?src=pr&el=tree#diff-anVweXRleHQvY2VsbF90b190ZXh0LnB5) | `97.31% <100.00%> (ø)` | |
| [tests/test\_active\_cells.py](https://codecov.io/gh/mwouts/jupytext/pull/479/diff?src=pr&el=tree#diff-dGVzdHMvdGVzdF9hY3RpdmVfY2VsbHMucHk=) | `100.00% <100.00%> (ø)` | |

------

[Continue to review full report at Codecov](https://codecov.io/gh/mwouts/jupytext/pull/479?src=pr&el=continue).
> **Legend** - [Click here to learn more](https://docs.codecov.io/docs/codecov-delta)
> `Δ = absolute <relative> (impact)`, `ø = not affected`, `? = missing data`
> Powered by [Codecov](https://codecov.io/gh/mwouts/jupytext/pull/479?src=pr&el=footer). Last update [6c0f027...d1dd130](https://codecov.io/gh/mwouts/jupytext/pull/479?src=pr&el=lastupdated). Read the [comment docs](https://docs.codecov.io/docs/pull-request-comments).


Patch:
diff --git a/CHANGELOG.md b/CHANGELOG.md
index a8667a1b..5db3fc22 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -13,6 +13,7 @@
 - Fixed the CLI example for not commenting out magic commands: `--opt comment_magics=false`. In addition, most of the `jupytext` commands in `using-cli.md` are now tested! (#465)
 - `jupytext.read` and `jupytext.write` now give more meaningful errors when the format information is incorrect (#462)
 - Multiline comments starting with quadruple quotes should not cause issues anymore (#460)
+- Fixed active cells in the py:percent format (#477)
 
 1.4.1 (2020-03-19)
 ------------------
diff --git a/jupytext/cell_reader.py b/jupytext/cell_reader.py
index 7bb10ef0..831676a4 100644
--- a/jupytext/cell_reader.py
+++ b/jupytext/cell_reader.py
@@ -689,6 +689,10 @@ class DoublePercentScriptCellReader(LightScriptCellReader):
 
         if self.metadata and 'cell_type' in self.metadata:
             self.cell_type = self.metadata.pop('cell_type')
+        elif not is_active('.ipynb', self.metadata):
+            if self.metadata.get('active') == '':
+                del self.metadata['active']
+            self.cell_type = 'raw'
         else:
             self.cell_type = 'code'
 
diff --git a/jupytext/cell_to_text.py b/jupytext/cell_to_text.py
index 71a23354..5f02ad69 100644
--- a/jupytext/cell_to_text.py
+++ b/jupytext/cell_to_text.py
@@ -377,20 +377,20 @@ class DoublePercentCellExporter(BaseCellExporter):  # pylint: disable=W0223
 
     def cell_to_text(self):
         """Return the text representation for the cell"""
-        if self.cell_type != 'code':
-            self.metadata['cell_type'] = self.cell_type
-
         active = is_active(self.ext, self.metadata, same_language(self.language, self.default_language))
         if self.cell_type == 'raw' and 'active' in self.metadata and self.metadata['active'] == '':
             del self.metadata['active']
 
+        if not self.is_code():
+            self.metadata['cell_type'] = self.cell_type
+
         options = metadata_to_double_percent_options(self.metadata, self.cell_metadata_json)
         if options.startswith('%') or not options:
             lines = [self.comment + ' %%' + options]
         else:
             lines = [self.comment + ' %% ' + options]
 
-        if self.cell_type == 'code' and active:
+        if self.is_code() and active:
             source = copy(self.source)
             comment_magic(source, self.language, self.comment_magics)
             if source == ['']:


Test patch:
diff --git a/tests/test_active_cells.py b/tests/test_active_cells.py
index 712c9c3d..b360cd7f 100644
--- a/tests/test_active_cells.py
+++ b/tests/test_active_cells.py
@@ -243,3 +243,43 @@ ACTIVE_NOT_INCLUDE_RMD = {'.py': """# + tags=["remove_cell"] active="Rmd"
 @pytest.mark.parametrize('ext', ['.Rmd', '.py', '.R'])
 def test_active_not_include_rmd(ext, no_jupytext_version_number):
     check_active_cell(ext, ACTIVE_NOT_INCLUDE_RMD)
+
+
+def test_active_cells_from_py_percent(text="""# %% active="py"
+print('should only be displayed in py file')
+
+# %% tags=["active-py"]
+print('should only be displayed in py file')
+
+# %% active="ipynb"
+# print('only in jupyter')
+"""):
+    """Example taken from https://github.com/mwouts/jupytext/issues/477"""
+    nb = jupytext.reads(text, 'py:percent')
+    assert nb.cells[0].cell_type == 'raw'
+    assert nb.cells[1].cell_type == 'raw'
+    assert nb.cells[2].cell_type == 'code'
+    assert nb.cells[2].source == "print('only in jupyter')"
+
+    text2 = jupytext.writes(nb, 'py:percent')
+    compare(text2, text)
+
+
+def test_active_cells_from_py_light(text="""# + active="py"
+print('should only be displayed in py file')
+
+# + tags=["active-py"]
+print('should only be displayed in py file')
+
+# + active="ipynb"
+# print('only in jupyter')
+"""):
+    """Example adapted from https://github.com/mwouts/jupytext/issues/477"""
+    nb = jupytext.reads(text, 'py')
+    assert nb.cells[0].cell_type == 'raw'
+    assert nb.cells[1].cell_type == 'raw'
+    assert nb.cells[2].cell_type == 'code'
+    assert nb.cells[2].source == "print('only in jupyter')"
+
+    text2 = jupytext.writes(nb, 'py')
+    compare(text2, text)