File tree Expand file tree Collapse file tree
Expand file tree Collapse file tree Original file line number Diff line number Diff line change @@ -136,3 +136,14 @@ This is useful for explaining that the file is autogenerated::
136136 args:
137137 - "--header"
138138 - "THIS FILE IS AUTOGENERATED"
139+
140+ You can also insert the name of the source docx file using Python format string syntax and the ``docx `` template variable::
141+
142+ repos:
143+ - repo: https://github.com/jsickcodes/pre-commit-docx-plain
144+ rev: 0.2.0
145+ hooks:
146+ - id: docxplain
147+ args:
148+ - "--header"
149+ - "This file is autogenerated from {docx}. Do not edit."
Original file line number Diff line number Diff line change @@ -44,7 +44,7 @@ def convert_file(
4444 pypandoc .convert_file (str (docx_path ), "plain" , outputfile = str (plain_path ))
4545
4646 if header :
47- insert_header (plain_path , header )
47+ insert_header (plain_path , header , docx_path . name )
4848
4949 if exists :
5050 final_hash = get_hash (plain_path )
@@ -53,10 +53,11 @@ def convert_file(
5353 return True
5454
5555
56- def insert_header (path : Path , header : str ) -> None :
56+ def insert_header (path : Path , header : str , docx_name : str ) -> None :
5757 """Add a header to the beginning of a plain text file."""
5858 content = path .read_text ()
59- content = "\n \n " .join ((header , content ))
59+ context = {"docx" : docx_name }
60+ content = "\n \n " .join ((header .format (** context ), content ))
6061 path .write_text (content )
6162
6263
Original file line number Diff line number Diff line change @@ -56,3 +56,19 @@ def test_header(tmp_path: Path) -> None:
5656 assert plain_path .is_file ()
5757 content = plain_path .read_text ().splitlines ()
5858 assert content [0 ] == "This file is autogenerated."
59+
60+
61+ def test_header_templating (tmp_path : Path ) -> None :
62+ """Test the case of a templated custom file header that includes the
63+ document name.
64+ """
65+ repo_data = Path (__file__ ).parent .joinpath ("data/new" )
66+ work_dir = tmp_path / "header"
67+ shutil .copytree (repo_data , work_dir )
68+ docxpath = work_dir .joinpath ("test_doc.docx" )
69+ header = "This file is autogenerated from {docx}."
70+ assert convert_file (str (docxpath ), header = header ) is True
71+ plain_path = docxpath .with_suffix (".txt" )
72+ assert plain_path .is_file ()
73+ content = plain_path .read_text ().splitlines ()
74+ assert content [0 ] == "This file is autogenerated from test_doc.docx."
You can’t perform that action at this time.
0 commit comments