Coverage for src/mkdocs_gallery/downloads.py: 100%
22 statements
« prev ^ index » next coverage.py v7.6.1, created at 2024-09-30 08:26 +0000
« prev ^ index » next coverage.py v7.6.1, created at 2024-09-30 08:26 +0000
1# Authors: Sylvain MARIE <sylvain.marie@se.com>
2# + All contributors to <https://github.com/smarie/mkdocs-gallery>
3#
4# Original idea and code: sphinx-gallery, <https://sphinx-gallery.github.io>
5# License: 3-clause BSD, <https://github.com/smarie/mkdocs-gallery/blob/master/LICENSE>
6"""
7Utilities for downloadable items
8"""
10from __future__ import absolute_import, division, print_function
12from pathlib import Path
13from typing import List
14from zipfile import ZipFile
16from .gen_data_model import Gallery
17from .utils import _new_file, _replace_by_new_if_needed
20def python_zip(file_list: List[Path], gallery: Gallery, extension=".py"):
21 """Stores all files in file_list with modified extension `extension` into an zip file
23 Parameters
24 ----------
25 file_list : List[Path]
26 Holds all the files to be included in zip file. Note that if extension
27 is set to
29 gallery : Gallery
30 gallery for which to create the zip file
32 extension : str
33 The replacement extension for files in file_list. '.py' or '.ipynb'.
34 In order to deal with downloads of python sources and jupyter notebooks,
35 since we know that there is one notebook for each python file.
37 Returns
38 -------
39 zipfile : Path
40 zip file, written as `<target_dir>_{python,jupyter}.zip` depending on the extension
41 """
42 zipfile = gallery.zipfile_python if extension == ".py" else gallery.zipfile_jupyter
44 # Create the new zip
45 zipfile_new = _new_file(zipfile)
46 with ZipFile(str(zipfile_new), mode="w") as zipf:
47 for file in file_list:
48 file_src = file.with_suffix(extension)
49 zipf.write(file_src, file_src.relative_to(gallery.generated_dir))
51 # Replace the old one if needed
52 _replace_by_new_if_needed(zipfile_new)
54 return zipfile
57def generate_zipfiles(gallery: Gallery):
58 """
59 Collects all Python source files and Jupyter notebooks in
60 gallery_dir and makes zipfiles of them
62 Parameters
63 ----------
64 gallery : Gallery
65 path of the gallery to collect downloadable sources
67 Return
68 ------
69 download_md: str
70 Markdown to include download buttons to the generated files
71 """
72 # Collect the files to include in the zip
73 listdir = gallery.list_downloadable_sources(recurse=True)
75 # Create the two zip files
76 python_zip(listdir, gallery, extension=".py")
77 python_zip(listdir, gallery, extension=".ipynb")
79 icon = ":fontawesome-solid-download:"
80 dw_md = f"""
81<div id="download_links"></div>
83[{icon} Download all examples in Python source code: {gallery.zipfile_python.name}](./{gallery.zipfile_python_rel_index_md}){{ .md-button .center}}
85[{icon} Download all examples in Jupyter notebooks: {gallery.zipfile_jupyter.name}](./{gallery.zipfile_jupyter_rel_index_md}){{ .md-button .center}}
86""" # noqa
87 return dw_md