markdown_convert 1.2.13__tar.gz → 1.2.15__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: markdown_convert
3
- Version: 1.2.13
3
+ Version: 1.2.15
4
4
  Summary: Convert Markdown files to PDF from your command line.
5
5
  Project-URL: homepage, https://github.com/Julynx/markdown_convert
6
6
  Author-email: Julio Cabria <juliocabria@tutanota.com>
@@ -0,0 +1,96 @@
1
+ #!/usr/bin/env python3
2
+
3
+ """
4
+ CLI interface to convert markdown files to pdf.
5
+ Author: @julynx
6
+ """
7
+
8
+
9
+ from sys import exit as sys_exit
10
+
11
+ from argsdict import args
12
+ from .modules.constants import RED, OPTIONS, OPTIONS_MODES
13
+ from .modules.convert import convert, live_convert
14
+ from .modules.resources import get_css_path, get_output_path, get_usage
15
+ from .modules.utils import color
16
+ from .modules.validate import (validate_css_path, validate_markdown_path,
17
+ validate_output_path)
18
+
19
+
20
+ def main():
21
+ """
22
+ Convert a markdown file to a pdf file.
23
+ """
24
+ try:
25
+ # Load and validate arguments
26
+ arg = args(["markdown_file_path"])
27
+ for key in set(arg.keys()) - set(OPTIONS):
28
+ raise IndexError(f"Invalid option: '{key}'")
29
+
30
+ # Get the markdown path
31
+ try:
32
+ md_path = arg["markdown_file_path"]
33
+ validate_markdown_path(md_path)
34
+ except KeyError as key_err:
35
+ raise IndexError("Missing 'markdown_file_path' argument.") \
36
+ from key_err
37
+ except Exception as exc:
38
+ raise IndexError(f"Invalid 'markdown_file_path' argument: {exc}") \
39
+ from exc
40
+
41
+ # Get the mode
42
+ try:
43
+ mode = arg["--mode"]
44
+ if mode not in OPTIONS_MODES:
45
+ raise ValueError(f"Invalid mode: '{mode}'")
46
+ except KeyError:
47
+ mode = "once"
48
+
49
+ # Get the CSS path
50
+ try:
51
+ css_path = arg["--css"]
52
+ validate_css_path(css_path)
53
+ except KeyError:
54
+ css_path = get_css_path()
55
+ except Exception as exc:
56
+ raise IndexError(f"Invalid 'css_file_path' argument: {exc}") \
57
+ from exc
58
+
59
+ # Get the output path
60
+ output_path = None
61
+ try:
62
+ output_path = arg["--out"]
63
+ validate_output_path(output_path)
64
+ output_path = get_output_path(md_path, output_path)
65
+ except KeyError:
66
+ output_path = get_output_path(md_path, None)
67
+ except Exception as exc:
68
+ raise IndexError(f"Invalid 'output_path' argument: {exc}") \
69
+ from exc
70
+
71
+ # Compile the markdown file
72
+ print(f'\nGenerating PDF file from \'{md_path}\'...\n')
73
+ if mode == "once":
74
+ convert(md_path, css_path, output_path)
75
+ else:
76
+ live_convert(md_path, css_path, output_path)
77
+
78
+ sys_exit(0)
79
+
80
+ except Exception as err:
81
+
82
+ asked_for_help = "--help" in arg or "-h" in arg
83
+ show_usage = (isinstance(err, (IndexError, ValueError))
84
+ or asked_for_help)
85
+
86
+ if show_usage:
87
+ print(get_usage())
88
+
89
+ if not asked_for_help:
90
+ print(color(RED, f"ERROR: {err}\n"))
91
+
92
+ sys_exit(1)
93
+
94
+
95
+ if __name__ == '__main__':
96
+ main()
@@ -0,0 +1,4 @@
1
+ """
2
+ Empty file to make the folder a package.
3
+ Author: @julynx
4
+ """
@@ -0,0 +1,26 @@
1
+ """
2
+ This module contains the constants used in the markdown_convert package.
3
+ Author: @julynx
4
+ """
5
+
6
+ RED = '31'
7
+ GREEN = '32'
8
+ YELLOW = '33'
9
+ BLUE = '34'
10
+ MAGENTA = '35'
11
+ CYAN = '36'
12
+
13
+ OPTIONS = ('markdown_file_path',
14
+ "--mode",
15
+ '--css',
16
+ "--out",
17
+ "-h", "--help")
18
+
19
+ OPTIONS_MODES = ('once', 'live')
20
+
21
+ MD_EXTENSIONS = {
22
+ "fenced-code-blocks": None,
23
+ "header-ids": None,
24
+ "breaks": {"on_newline": True},
25
+ "tables": None
26
+ }
@@ -0,0 +1,247 @@
1
+ """
2
+ Module to convert a markdown file to a pdf file.
3
+ Author: @julynx
4
+ """
5
+
6
+ import os
7
+ import sys
8
+ import time
9
+ import warnings
10
+ from contextlib import redirect_stderr, redirect_stdout
11
+ from datetime import datetime
12
+ from io import StringIO
13
+ from pathlib import Path
14
+
15
+ import markdown2
16
+ import weasyprint
17
+
18
+ from .resources import get_css_path, get_code_css_path, get_output_path
19
+ from .utils import drop_duplicates
20
+ from .constants import MD_EXTENSIONS
21
+
22
+
23
+ def _suppress_warnings():
24
+ """
25
+ Suppress all warnings in production while preserving critical error handling.
26
+ Only errors and exceptions will be shown.
27
+ """
28
+ # Suppress all warnings but keep errors
29
+ warnings.filterwarnings('ignore', category=UserWarning)
30
+ warnings.filterwarnings('ignore', category=DeprecationWarning)
31
+ warnings.filterwarnings('ignore', category=FutureWarning)
32
+ warnings.filterwarnings('ignore', category=PendingDeprecationWarning)
33
+ warnings.filterwarnings('ignore', category=ImportWarning)
34
+ warnings.filterwarnings('ignore', category=ResourceWarning)
35
+
36
+
37
+ def _silent_pdf_generation(func, *args, **kwargs):
38
+ """
39
+ Execute PDF generation function while suppressing all non-critical output.
40
+ Preserves exceptions and critical errors.
41
+ """
42
+ _suppress_warnings()
43
+
44
+ # Capture stdout and stderr to filter out warnings
45
+ stdout_capture = StringIO()
46
+ stderr_capture = StringIO()
47
+
48
+ try:
49
+ with redirect_stdout(stdout_capture), redirect_stderr(stderr_capture):
50
+ result = func(*args, **kwargs)
51
+
52
+ # Check if there were any critical errors in stderr
53
+ stderr_content = stderr_capture.getvalue()
54
+ if stderr_content and any(keyword in stderr_content.lower()
55
+ for keyword in ['error', 'exception', 'traceback', 'failed']):
56
+ # Print only critical errors, not warnings
57
+ print(stderr_content, file=sys.stderr)
58
+
59
+ return result
60
+
61
+ except Exception as exc:
62
+ # Always re-raise actual exceptions
63
+ raise exc
64
+
65
+
66
+ def convert(md_path, css_path=None, output_path=None,
67
+ *, extend_default_css=True):
68
+ """
69
+ Convert a markdown file to a pdf file.
70
+
71
+ Args:
72
+ md_path (str): Path to the markdown file.
73
+ css_path (str=None): Path to the CSS file.
74
+ output_path (str=None): Path to the output file.
75
+ extend_default_css (bool=True): Extend the default CSS file.
76
+ """
77
+ if css_path is None:
78
+ css_path = get_css_path()
79
+
80
+ if output_path is None:
81
+ output_path = get_output_path(md_path, None)
82
+
83
+ if extend_default_css:
84
+ css_sources = [get_code_css_path(), get_css_path(), css_path]
85
+ else:
86
+ css_sources = [get_code_css_path(), css_path]
87
+
88
+ css_sources = drop_duplicates(css_sources)
89
+
90
+ try:
91
+ html = markdown2.markdown_path(md_path,
92
+ extras=MD_EXTENSIONS)
93
+
94
+ # Use silent PDF generation to suppress warnings
95
+ _silent_pdf_generation(
96
+ lambda: weasyprint
97
+ .HTML(string=html, base_url='.')
98
+ .write_pdf(target=output_path,
99
+ stylesheets=list(css_sources))
100
+ )
101
+
102
+ except Exception as exc:
103
+ raise RuntimeError(exc) from exc
104
+
105
+
106
+ def live_convert(md_path, css_path=None, output_path=None,
107
+ *, extend_default_css=True):
108
+ """
109
+ Convert a markdown file to a pdf file and watch for changes.
110
+
111
+ Args:
112
+ md_path (str): Path to the markdown file.
113
+ css_path (str=None): Path to the CSS file.
114
+ output_path (str=None): Path to the output file.
115
+ extend_default_css (bool=True): Extend the default CSS file.
116
+ """
117
+ if css_path is None:
118
+ css_path = get_css_path()
119
+
120
+ if output_path is None:
121
+ output_path = get_output_path(md_path, None)
122
+
123
+ live_converter = LiveConverter(md_path, css_path, output_path,
124
+ extend_default_css=extend_default_css,
125
+ loud=True)
126
+ live_converter.observe()
127
+
128
+
129
+ def convert_text(md_text, css_text=None,
130
+ *, extend_default_css=True):
131
+ """
132
+ Convert markdown text to a pdf file.
133
+
134
+ Args:
135
+ md_text (str): Markdown text.
136
+ css_text (str=None): CSS text.
137
+ extend_default_css (bool=True): Extend the default CSS file.
138
+
139
+ Returns:
140
+ PDF file as bytes.
141
+ """
142
+ default_css = Path(get_css_path()).read_text(encoding='utf-8')
143
+ code_css = Path(get_code_css_path()).read_text(encoding='utf-8')
144
+
145
+ if css_text is None:
146
+ css_text = default_css
147
+
148
+ if extend_default_css:
149
+ css_sources = [code_css, default_css, css_text]
150
+ else:
151
+ css_sources = [code_css, css_text]
152
+
153
+ css_sources = [weasyprint.CSS(string=css)
154
+ for css in drop_duplicates(css_sources)]
155
+
156
+ try:
157
+ html = markdown2.markdown(md_text,
158
+ extras=MD_EXTENSIONS)
159
+
160
+ # Use silent PDF generation to suppress warnings
161
+ return _silent_pdf_generation(
162
+ lambda: weasyprint
163
+ .HTML(string=html, base_url='.')
164
+ .write_pdf(stylesheets=css_sources)
165
+ )
166
+
167
+ except Exception as exc:
168
+ raise RuntimeError(exc) from exc
169
+
170
+
171
+ class LiveConverter():
172
+ """
173
+ Class to convert a markdown file to a pdf file and watch for changes.
174
+ """
175
+
176
+ def __init__(self, md_path, css_path, output_path,
177
+ *, extend_default_css=True,
178
+ loud=False):
179
+ """
180
+ Initialize the LiveConverter class.
181
+
182
+ Args:
183
+ md_path (str): Path to the markdown file.
184
+ css_path (str): Path to the CSS file.
185
+ output_path (str): Path to the output file.
186
+ extend_default_css (bool): Extend the default CSS file.
187
+ """
188
+ self.md_path = Path(md_path).absolute()
189
+ self.css_path = Path(css_path).absolute()
190
+ self.output_path = output_path
191
+ self.extend_default_css = extend_default_css
192
+ self.loud = loud
193
+
194
+ self.md_last_modified = None
195
+ self.css_last_modified = None
196
+
197
+ def get_last_modified_date(self, file_path):
198
+ """
199
+ Get the last modified date of a file.
200
+
201
+ Args:
202
+ file_path (str): Path to the file.
203
+
204
+ Returns:
205
+ Last modified date of the file.
206
+ """
207
+ return os.path.getmtime(file_path)
208
+
209
+ def write_pdf(self):
210
+ """
211
+ Write the pdf file.
212
+ """
213
+ convert(self.md_path, self.css_path, self.output_path,
214
+ extend_default_css=self.extend_default_css)
215
+ if self.loud:
216
+ print(f"- PDF file updated: {datetime.now()}", flush=True)
217
+
218
+ def observe(self, poll_interval=1):
219
+ """
220
+ Observe the markdown and CSS files. Calls write_pdf() when a file is
221
+ modified.
222
+ """
223
+ self.write_pdf()
224
+
225
+ self.md_last_modified = self.get_last_modified_date(self.md_path)
226
+ self.css_last_modified = self.get_last_modified_date(self.css_path)
227
+
228
+ try:
229
+ while True:
230
+
231
+ md_modified = self.get_last_modified_date(self.md_path)
232
+ css_modified = self.get_last_modified_date(self.css_path)
233
+
234
+ if md_modified != self.md_last_modified or \
235
+ css_modified != self.css_last_modified:
236
+
237
+ self.write_pdf()
238
+
239
+ self.md_last_modified = md_modified
240
+ self.css_last_modified = css_modified
241
+
242
+ time.sleep(poll_interval)
243
+
244
+ except KeyboardInterrupt:
245
+ if self.loud:
246
+ print("\nInterrupted by user.\n", flush=True)
247
+ return
@@ -0,0 +1,92 @@
1
+ """
2
+ This module contains functions that are used to get the output path, the CSS
3
+ path, and the usage message.
4
+ Author: @julynx
5
+ """
6
+
7
+ from pathlib import Path
8
+
9
+ try:
10
+ # Python 3.9+
11
+ from importlib.resources import files
12
+ except ImportError:
13
+ # Fallback for older Python versions
14
+ from importlib_resources import files
15
+
16
+ from .constants import BLUE, CYAN, GREEN, YELLOW, OPTIONS, OPTIONS_MODES
17
+ from .utils import color
18
+
19
+
20
+ def get_output_path(md_path, output_dir=None):
21
+ """
22
+ Get the output path for the pdf file.
23
+
24
+ Args:
25
+ md_path (str): The path to the markdown file.
26
+ output_dir (str): The output directory.
27
+
28
+ Returns:
29
+ str: The output path.
30
+ """
31
+ md_path = Path(md_path)
32
+
33
+ if output_dir is None:
34
+ return md_path.parent / f"{md_path.stem}.pdf"
35
+
36
+ output_dir = Path(output_dir)
37
+
38
+ if output_dir.suffix == ".pdf":
39
+ return output_dir
40
+
41
+ return output_dir.parent / f"{Path(md_path).stem}.pdf"
42
+
43
+
44
+ def get_css_path():
45
+ """
46
+ Get the path to the default CSS file.
47
+
48
+ Returns:
49
+ str: The path to the default CSS file.
50
+ """
51
+ package_files = files('markdown_convert')
52
+ css_file = package_files / 'default.css'
53
+ return str(css_file)
54
+
55
+
56
+ def get_code_css_path():
57
+ """
58
+ Get the path to the code CSS file.
59
+
60
+ Returns:
61
+ str: The path to the code CSS file.
62
+ """
63
+ package_files = files('markdown_convert')
64
+ css_file = package_files / 'code.css'
65
+ return str(css_file)
66
+
67
+
68
+ def get_usage():
69
+ """
70
+ Returns a message describing how to use the program.
71
+
72
+ Returns:
73
+ str: The usage message.
74
+ """
75
+ commd = (f"{color(GREEN, 'markdown-convert')} "
76
+ f"[{color(YELLOW, OPTIONS[0])}] [{color(BLUE, 'options')}]")
77
+ opt_1 = f"{color(BLUE, OPTIONS[1])}{color(CYAN, '=')}{color(CYAN, '|'.join(OPTIONS_MODES))}"
78
+ opt_2 = f"{color(BLUE, OPTIONS[2])}{color(CYAN, '=')}[{color(CYAN, 'css_file_path')}]"
79
+ opt_3 = f"{color(BLUE, OPTIONS[3])}{color(CYAN, '=')}[{color(CYAN, 'output_file_path')}]"
80
+
81
+ usage = ("\n"
82
+ "Usage:\n"
83
+ f" {commd}\n"
84
+ "\n"
85
+ "Options:\n"
86
+ f" {opt_1}\n"
87
+ " Convert the markdown file once (default) or live.\n"
88
+ f" {opt_2}\n"
89
+ " Use a custom CSS file.\n"
90
+ f" {opt_3}\n"
91
+ " Specify the output file path.\n")
92
+ return usage
@@ -0,0 +1,38 @@
1
+ """
2
+ Utility functions for string manipulation.
3
+ Author: @julynx
4
+ """
5
+
6
+ import platform
7
+
8
+
9
+ def color(color_code, text):
10
+ """
11
+ Colorize text.
12
+
13
+ Args:
14
+ text (str): The text to colorize.
15
+ color (str): The color code.
16
+
17
+ Returns:
18
+ str: The colorized text.
19
+ """
20
+
21
+ # Disable if running on Windows
22
+ if platform.system() == "Windows":
23
+ return text
24
+
25
+ return f"\033[{color_code}m{text}\033[0m"
26
+
27
+
28
+ def drop_duplicates(lst):
29
+ """
30
+ Drops duplicates from the given list.
31
+
32
+ Args:
33
+ lst: List to remove duplicates from.
34
+
35
+ Returns:
36
+ List without duplicates.
37
+ """
38
+ return list(dict.fromkeys(lst))
@@ -0,0 +1,61 @@
1
+ """
2
+ This module contains functions to validate the input paths.
3
+ Author: @julynx
4
+ """
5
+
6
+ from pathlib import Path
7
+
8
+
9
+ def validate_markdown_path(md_path):
10
+ """
11
+ Validate the markdown file path.
12
+
13
+ Args:
14
+ md_path (str): The path to the markdown file.
15
+
16
+ Raises:
17
+ FileNotFoundError: If the file is not found.
18
+ ValueError: If the file is not a Markdown file.
19
+ """
20
+ if not Path(md_path).is_file():
21
+ raise FileNotFoundError(f"File not found: '{md_path}'")
22
+
23
+ if not md_path.endswith(".md"):
24
+ raise ValueError("File must be a Markdown file.")
25
+
26
+
27
+ def validate_css_path(css_path):
28
+ """
29
+ Validate the CSS file path.
30
+
31
+ Args:
32
+ css_path (str): The path to the CSS file.
33
+
34
+ Raises:
35
+ FileNotFoundError: If the file is not found.
36
+ ValueError: If the file is not a CSS file.
37
+ """
38
+ if not Path(css_path).is_file():
39
+ raise FileNotFoundError(f"File not found: '{css_path}'")
40
+
41
+ if not css_path.endswith(".css"):
42
+ raise ValueError("File must be a CSS file.")
43
+
44
+
45
+ def validate_output_path(output_dir):
46
+ """
47
+ Validate the output directory path.
48
+
49
+ Args:
50
+ output_dir (str): The path to the output directory.
51
+
52
+ Raises:
53
+ FileNotFoundError: If the directory is not found.
54
+ """
55
+ check_dir = Path(output_dir)
56
+
57
+ if output_dir.endswith(".pdf"):
58
+ check_dir = check_dir.parent
59
+
60
+ if not check_dir.is_dir():
61
+ raise FileNotFoundError(f"Directory not found: '{check_dir}'")
@@ -4,7 +4,7 @@ build-backend = "hatchling.build"
4
4
 
5
5
  [project]
6
6
  name = "markdown_convert"
7
- version = "1.2.13"
7
+ version = "1.2.15"
8
8
  description = "Convert Markdown files to PDF from your command line."
9
9
  authors = [
10
10
  { name = "Julio Cabria", email = "juliocabria@tutanota.com" },
@@ -32,9 +32,27 @@ markdown-convert = "markdown_convert.__main__:main"
32
32
 
33
33
  [tool.hatch.build.targets.sdist]
34
34
  include = [
35
+ "markdown_convert/__main__.py",
35
36
  "markdown_convert/default.css",
36
37
  "markdown_convert/code.css",
38
+ "markdown_convert/modules/__init__.py",
39
+ "markdown_convert/modules/constants.py",
40
+ "markdown_convert/modules/convert.py",
41
+ "markdown_convert/modules/resources.py",
42
+ "markdown_convert/modules/utils.py",
43
+ "markdown_convert/modules/validate.py",
37
44
  ]
38
45
 
39
46
  [tool.hatch.build.targets.wheel]
40
47
  packages = ["markdown_convert"]
48
+ include = [
49
+ "markdown_convert/__main__.py",
50
+ "markdown_convert/default.css",
51
+ "markdown_convert/code.css",
52
+ "markdown_convert/modules/__init__.py",
53
+ "markdown_convert/modules/constants.py",
54
+ "markdown_convert/modules/convert.py",
55
+ "markdown_convert/modules/resources.py",
56
+ "markdown_convert/modules/utils.py",
57
+ "markdown_convert/modules/validate.py",
58
+ ]