markdown-site-utils 0.2.2__tar.gz → 0.4.0__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.
@@ -0,0 +1,165 @@
1
+ Metadata-Version: 2.4
2
+ Name: markdown-site-utils
3
+ Version: 0.4.0
4
+ Summary: Some utilities for managing Markdown files with metadata.
5
+ Author: Jacob Smullyan
6
+ Author-email: Jacob Smullyan <smulloni@smullyan.org>
7
+ License-Expression: MIT
8
+ License-File: LICENSE
9
+ Classifier: Programming Language :: Python :: 3
10
+ Classifier: Programming Language :: Python :: 3 :: Only
11
+ Classifier: Programming Language :: Python :: 3.11
12
+ Classifier: Programming Language :: Python :: 3.12
13
+ Classifier: Programming Language :: Python :: 3.13
14
+ Classifier: Programming Language :: Python :: 3.14
15
+ Classifier: Programming Language :: Python :: 3.15
16
+ Requires-Dist: markupsafe>=2.1.2
17
+ Requires-Dist: pyyaml>=6.0
18
+ Requires-Dist: markdown2>=2.5.1
19
+ Requires-Python: >=3.11
20
+ Project-URL: Repository, https://github.com/smulloni/markdown_site_utils
21
+ Description-Content-Type: text/markdown
22
+
23
+ # Markdown Site Utils
24
+
25
+ Some utilities for managing Markdown files with metadata.
26
+
27
+ Requires Python 3.11 or later; tested on Python 3.11 through 3.15.
28
+
29
+ ## Installation
30
+
31
+ pip install markdown-site-utils
32
+
33
+ or, in a uv-managed project:
34
+
35
+ uv add markdown-site-utils
36
+
37
+ ## Overview
38
+
39
+ The notion is that a content-oriented website may be written as a
40
+ hierarchical series of Markdown files (with an ".md" extension) underneath
41
+ some data directory, e.g.:
42
+
43
+ DATA_DIR/
44
+ index.md
45
+ foo.md
46
+ bar.md
47
+ subdir/
48
+ index.md
49
+ foo.md
50
+ bar.md
51
+
52
+ Each file may contain metadata, written in TOML in a section at
53
+ the top, bounded by '+++' lines:
54
+
55
+ +++
56
+ title = "My Page Title"
57
+ +++
58
+
59
+ # Some Markdown
60
+
61
+ YAML and JSON may also be used. YAML blocks should start and end with lines
62
+ consisting of three dashes; JSON blocks should consist of a single JSON object
63
+ with opening and closing braces on lines by themselves. The data block is optional
64
+ but if present must begin on the first line of the file.
65
+
66
+ TOML is parsed with the standard library's
67
+ [`tomllib`](https://docs.python.org/3/library/tomllib.html), so the TOML syntax
68
+ accepted is whatever your Python version supports (TOML 1.0, plus TOML 1.1 on
69
+ Python 3.15 and later). If you need to support several Python versions, stick
70
+ to TOML 1.0 syntax.
71
+
72
+ ## Usage
73
+
74
+ To use the library, create an `mdsite.DB` object with the path to your
75
+ data directory:
76
+
77
+ mydb = mdsite.DB("/path/to/data/dir")
78
+
79
+ Then call `get_data(path)` for the path into the directory you want, leaving
80
+ out the `.md` filename suffix, and, if you are looking for an index file, leaving
81
+ out `index.md`:
82
+
83
+ data = mydb.get_data("/node/leaf")
84
+
85
+ The above gets data for `$DATA_DIR/node/leaf.md`, or for
86
+ `$DATA_DIR/node/leaf/index.md`, if that file exists instead. If both
87
+ `node/leaf.md` and a `node/leaf/` directory exist, `mdsite.PathConflict` is
88
+ raised. If nothing exists at the path, an empty dict is returned.
89
+
90
+ The returned dict contains the file's metadata, plus these keys:
91
+
92
+ - `content`: the Markdown rendered to HTML, as a `markupsafe.Markup` string
93
+ - `last_mod`: when the Markdown file last changed, as a timezone-aware
94
+ `datetime` in UTC (by default its modification time; see "Dates from git"
95
+ below). For a directory this is the time of its `index.md` (the same value
96
+ `get_data("/node/leaf/index")` returns), or of the directory itself if it
97
+ has no `index.md`
98
+ - `path`: the normalized path, with a leading slash
99
+ - `id`: the last component of the path, or `"index"` for the root
100
+ - `listing`: for a directory, a `(subdirectories, pages)` tuple of sorted
101
+ names; otherwise `None`
102
+
103
+ `get_recursive_data(path)` returns the data for a directory and every
104
+ directory beneath it, keyed by path relative to the data directory (without a
105
+ leading slash; the root is `""`). It raises `mdsite.PathConflict` if any
106
+ directory in the tree conflicts with a file.
107
+
108
+ ### Dates from git
109
+
110
+ File modification times depend on the checkout: a fresh clone stamps every
111
+ file with the time of the clone. If the data directory is in a git
112
+ repository, `last_mod` can come from its history instead:
113
+
114
+ mydb = mdsite.DB("/path/to/data/dir", last_mod="git")
115
+
116
+ Then `last_mod` is the committer time of the last commit that changed the
117
+ file, so it is the same in every clone. Uncommitted edits don't change it.
118
+ Files git has no history for (untracked files, or a directory without an
119
+ `index.md`) fall back to their modification time.
120
+
121
+ Git history is read once, on first use, by a single `git log`, and kept for
122
+ the life of the `DB`; create a new `DB` to see later commits. If git isn't
123
+ installed, the directory isn't in a repository, or the repository is a
124
+ shallow clone (whose dates would be wrong), `mdsite.GitHistoryError` is
125
+ raised. CI systems often clone shallowly by default; fetch full history
126
+ there (for GitHub Actions, `fetch-depth: 0` on `actions/checkout`).
127
+
128
+ The library also supports hierarchical configuration, also written in TOML,
129
+ YAML, or JSON, stored in files called `config.{toml,yaml,json}` depending on the
130
+ config language employed. `get_config(path)` merges the configuration found in
131
+ the data directory and each directory along `path`, with deeper files
132
+ overriding shallower ones.
133
+
134
+ ## Changes in 0.4.0
135
+
136
+ - `DB(data_dir, last_mod="git")` takes `last_mod` from git history (see
137
+ "Dates from git"). The default, `last_mod="mtime"`, behaves as before.
138
+
139
+ ## Upgrading to 0.3.0
140
+
141
+ - `last_mod` is now a timezone-aware UTC `datetime`. It used to be a naive
142
+ `datetime` (one with no timezone) holding the UTC time. Comparing it with a
143
+ naive `datetime` now raises `TypeError`. Compare it with aware datetimes
144
+ instead, such as `datetime.datetime.now(datetime.UTC)`.
145
+ - For a directory, `last_mod` now comes from its `index.md` rather than the
146
+ directory itself, so editing an index file updates it. It used to change
147
+ only when entries were added to or removed from the directory.
148
+ - TOML is now parsed with `tomllib` instead of the third-party `toml` package.
149
+ Parse errors are `tomllib.TOMLDecodeError` (still a `ValueError` subclass),
150
+ and offset datetimes in TOML metadata use `datetime.timezone.utc`.
151
+
152
+ ## Development
153
+
154
+ The project is managed with [uv](https://docs.astral.sh/uv/) and linted and
155
+ formatted with [ruff](https://docs.astral.sh/ruff/):
156
+
157
+ uv sync # create the virtualenv and install dependencies
158
+ uv run pytest # run the tests
159
+ uv run ruff check . # lint
160
+ uv run ruff format . # format
161
+ uv build # build the sdist and wheel
162
+
163
+ To run the tests against a particular Python version:
164
+
165
+ uv run --isolated --python 3.15 pytest
@@ -0,0 +1,143 @@
1
+ # Markdown Site Utils
2
+
3
+ Some utilities for managing Markdown files with metadata.
4
+
5
+ Requires Python 3.11 or later; tested on Python 3.11 through 3.15.
6
+
7
+ ## Installation
8
+
9
+ pip install markdown-site-utils
10
+
11
+ or, in a uv-managed project:
12
+
13
+ uv add markdown-site-utils
14
+
15
+ ## Overview
16
+
17
+ The notion is that a content-oriented website may be written as a
18
+ hierarchical series of Markdown files (with an ".md" extension) underneath
19
+ some data directory, e.g.:
20
+
21
+ DATA_DIR/
22
+ index.md
23
+ foo.md
24
+ bar.md
25
+ subdir/
26
+ index.md
27
+ foo.md
28
+ bar.md
29
+
30
+ Each file may contain metadata, written in TOML in a section at
31
+ the top, bounded by '+++' lines:
32
+
33
+ +++
34
+ title = "My Page Title"
35
+ +++
36
+
37
+ # Some Markdown
38
+
39
+ YAML and JSON may also be used. YAML blocks should start and end with lines
40
+ consisting of three dashes; JSON blocks should consist of a single JSON object
41
+ with opening and closing braces on lines by themselves. The data block is optional
42
+ but if present must begin on the first line of the file.
43
+
44
+ TOML is parsed with the standard library's
45
+ [`tomllib`](https://docs.python.org/3/library/tomllib.html), so the TOML syntax
46
+ accepted is whatever your Python version supports (TOML 1.0, plus TOML 1.1 on
47
+ Python 3.15 and later). If you need to support several Python versions, stick
48
+ to TOML 1.0 syntax.
49
+
50
+ ## Usage
51
+
52
+ To use the library, create an `mdsite.DB` object with the path to your
53
+ data directory:
54
+
55
+ mydb = mdsite.DB("/path/to/data/dir")
56
+
57
+ Then call `get_data(path)` for the path into the directory you want, leaving
58
+ out the `.md` filename suffix, and, if you are looking for an index file, leaving
59
+ out `index.md`:
60
+
61
+ data = mydb.get_data("/node/leaf")
62
+
63
+ The above gets data for `$DATA_DIR/node/leaf.md`, or for
64
+ `$DATA_DIR/node/leaf/index.md`, if that file exists instead. If both
65
+ `node/leaf.md` and a `node/leaf/` directory exist, `mdsite.PathConflict` is
66
+ raised. If nothing exists at the path, an empty dict is returned.
67
+
68
+ The returned dict contains the file's metadata, plus these keys:
69
+
70
+ - `content`: the Markdown rendered to HTML, as a `markupsafe.Markup` string
71
+ - `last_mod`: when the Markdown file last changed, as a timezone-aware
72
+ `datetime` in UTC (by default its modification time; see "Dates from git"
73
+ below). For a directory this is the time of its `index.md` (the same value
74
+ `get_data("/node/leaf/index")` returns), or of the directory itself if it
75
+ has no `index.md`
76
+ - `path`: the normalized path, with a leading slash
77
+ - `id`: the last component of the path, or `"index"` for the root
78
+ - `listing`: for a directory, a `(subdirectories, pages)` tuple of sorted
79
+ names; otherwise `None`
80
+
81
+ `get_recursive_data(path)` returns the data for a directory and every
82
+ directory beneath it, keyed by path relative to the data directory (without a
83
+ leading slash; the root is `""`). It raises `mdsite.PathConflict` if any
84
+ directory in the tree conflicts with a file.
85
+
86
+ ### Dates from git
87
+
88
+ File modification times depend on the checkout: a fresh clone stamps every
89
+ file with the time of the clone. If the data directory is in a git
90
+ repository, `last_mod` can come from its history instead:
91
+
92
+ mydb = mdsite.DB("/path/to/data/dir", last_mod="git")
93
+
94
+ Then `last_mod` is the committer time of the last commit that changed the
95
+ file, so it is the same in every clone. Uncommitted edits don't change it.
96
+ Files git has no history for (untracked files, or a directory without an
97
+ `index.md`) fall back to their modification time.
98
+
99
+ Git history is read once, on first use, by a single `git log`, and kept for
100
+ the life of the `DB`; create a new `DB` to see later commits. If git isn't
101
+ installed, the directory isn't in a repository, or the repository is a
102
+ shallow clone (whose dates would be wrong), `mdsite.GitHistoryError` is
103
+ raised. CI systems often clone shallowly by default; fetch full history
104
+ there (for GitHub Actions, `fetch-depth: 0` on `actions/checkout`).
105
+
106
+ The library also supports hierarchical configuration, also written in TOML,
107
+ YAML, or JSON, stored in files called `config.{toml,yaml,json}` depending on the
108
+ config language employed. `get_config(path)` merges the configuration found in
109
+ the data directory and each directory along `path`, with deeper files
110
+ overriding shallower ones.
111
+
112
+ ## Changes in 0.4.0
113
+
114
+ - `DB(data_dir, last_mod="git")` takes `last_mod` from git history (see
115
+ "Dates from git"). The default, `last_mod="mtime"`, behaves as before.
116
+
117
+ ## Upgrading to 0.3.0
118
+
119
+ - `last_mod` is now a timezone-aware UTC `datetime`. It used to be a naive
120
+ `datetime` (one with no timezone) holding the UTC time. Comparing it with a
121
+ naive `datetime` now raises `TypeError`. Compare it with aware datetimes
122
+ instead, such as `datetime.datetime.now(datetime.UTC)`.
123
+ - For a directory, `last_mod` now comes from its `index.md` rather than the
124
+ directory itself, so editing an index file updates it. It used to change
125
+ only when entries were added to or removed from the directory.
126
+ - TOML is now parsed with `tomllib` instead of the third-party `toml` package.
127
+ Parse errors are `tomllib.TOMLDecodeError` (still a `ValueError` subclass),
128
+ and offset datetimes in TOML metadata use `datetime.timezone.utc`.
129
+
130
+ ## Development
131
+
132
+ The project is managed with [uv](https://docs.astral.sh/uv/) and linted and
133
+ formatted with [ruff](https://docs.astral.sh/ruff/):
134
+
135
+ uv sync # create the virtualenv and install dependencies
136
+ uv run pytest # run the tests
137
+ uv run ruff check . # lint
138
+ uv run ruff format . # format
139
+ uv build # build the sdist and wheel
140
+
141
+ To run the tests against a particular Python version:
142
+
143
+ uv run --isolated --python 3.15 pytest
@@ -0,0 +1,5 @@
1
+ from mdsite.data import DB, GitHistoryError, PathConflict
2
+
3
+ __all__ = ["DB", "GitHistoryError", "PathConflict"]
4
+
5
+ version = "0.4.0"
@@ -1,26 +1,86 @@
1
- from builtins import object
2
1
  import datetime
3
- import os
4
2
  import json
3
+ import os
4
+ import pathlib
5
+ import subprocess
6
+ import tomllib
5
7
 
6
- from markupsafe import Markup
7
8
  import markdown2
8
9
  import yaml
9
- import toml
10
+ from markupsafe import Markup
10
11
 
11
12
  BEGIN_FILE = 0
12
13
  IN_DATA = 1
13
14
  DATA_DONE = 2
14
15
  DATA_SEPS = {
15
16
  "{": ("}", lambda x: json.loads("{" + x + "}")),
16
- "+++": ("+++", toml.loads),
17
+ "+++": ("+++", tomllib.loads),
17
18
  "---": ("---", yaml.safe_load),
18
19
  }
19
20
 
21
+ LAST_MOD_SOURCES = ("mtime", "git")
22
+
23
+
24
+ class GitHistoryError(RuntimeError):
25
+ """Raised when last_mod="git" but no full git history is available."""
26
+
20
27
 
21
28
  def _getmtime(path):
22
29
  mtime = os.path.getmtime(path)
23
- return datetime.datetime.utcfromtimestamp(mtime)
30
+ return datetime.datetime.fromtimestamp(mtime, tz=datetime.UTC)
31
+
32
+
33
+ def _git(data_dir, *args):
34
+ try:
35
+ result = subprocess.run(
36
+ ["git", "-C", data_dir, *args],
37
+ capture_output=True,
38
+ text=True,
39
+ encoding="utf-8",
40
+ check=True,
41
+ )
42
+ except FileNotFoundError as exc:
43
+ raise GitHistoryError("git is not installed") from exc
44
+ except subprocess.CalledProcessError as exc:
45
+ raise GitHistoryError(
46
+ f"git {args[0]} failed in {data_dir}: {exc.stderr.strip()}"
47
+ ) from exc
48
+ return result.stdout
49
+
50
+
51
+ def _git_commit_times(data_dir):
52
+ """Map each file under data_dir that git has history for (as a POSIX path
53
+ relative to data_dir) to the committer time of the last commit that
54
+ changed it, as an aware UTC datetime."""
55
+ if _git(data_dir, "rev-parse", "--is-shallow-repository").strip() == "true":
56
+ raise GitHistoryError(
57
+ f"{data_dir} is in a shallow clone; its commit dates would be wrong. "
58
+ "Fetch full history (git fetch --unshallow)."
59
+ )
60
+ # %x00 marks each commit's line, so it can't be confused with a path.
61
+ # --relative makes paths relative to data_dir; quotePath=false keeps
62
+ # non-ASCII names unescaped.
63
+ log = _git(
64
+ data_dir,
65
+ "-c",
66
+ "core.quotePath=false",
67
+ "log",
68
+ "--relative",
69
+ "--name-only",
70
+ "--no-renames",
71
+ "--format=%x00%ct",
72
+ "--",
73
+ ".",
74
+ )
75
+ times = {}
76
+ when = None
77
+ for line in log.splitlines():
78
+ if line.startswith("\0"):
79
+ when = datetime.datetime.fromtimestamp(int(line[1:]), tz=datetime.UTC)
80
+ elif line:
81
+ # Newest commits come first, so the first sighting wins.
82
+ times.setdefault(line, when)
83
+ return times
24
84
 
25
85
 
26
86
  def _getlisting(dir):
@@ -35,13 +95,11 @@ def parse_file(file_path):
35
95
  state = BEGIN_FILE
36
96
  end_sep = None
37
97
  data_parser = None
38
- seen_sep = False
39
98
  with open(file_path) as fp:
40
99
  for line in fp:
41
100
  if state == BEGIN_FILE:
42
101
  stripped = line.strip()
43
102
  if stripped in DATA_SEPS:
44
- seen_sep = True
45
103
  state = IN_DATA
46
104
  end_sep, data_parser = DATA_SEPS[stripped]
47
105
  else:
@@ -49,7 +107,7 @@ def parse_file(file_path):
49
107
  content.append(line)
50
108
  elif state == IN_DATA:
51
109
  if line.strip() == end_sep:
52
- state = DATA_DONE
110
+ state = DATA_DONE
53
111
  else:
54
112
  raw_data.append(line)
55
113
  elif state == DATA_DONE:
@@ -75,15 +133,35 @@ class PathConflict(ValueError):
75
133
 
76
134
 
77
135
  CONFIG_FILES = (
78
- ("config.toml", toml.loads),
136
+ ("config.toml", tomllib.loads),
79
137
  ("config.yaml", yaml.safe_load),
80
138
  ("config.json", json.loads),
81
139
  )
82
140
 
83
141
 
84
- class DB(object):
85
- def __init__(self, data_dir):
142
+ class DB:
143
+ def __init__(self, data_dir, last_mod="mtime"):
144
+ """`last_mod` chooses where `last_mod` values come from: "mtime" (the
145
+ file's modification time) or "git" (the committer time of the last
146
+ commit that changed the file; files git doesn't track fall back to
147
+ their mtime). Git history is read once, on first use, per DB."""
148
+ if last_mod not in LAST_MOD_SOURCES:
149
+ raise ValueError(
150
+ f"last_mod must be one of {LAST_MOD_SOURCES}, not {last_mod!r}"
151
+ )
86
152
  self.data_dir = data_dir
153
+ self.last_mod_source = last_mod
154
+ self._commit_times = None
155
+
156
+ def _last_mod(self, fs_path):
157
+ if self.last_mod_source == "git":
158
+ if self._commit_times is None:
159
+ self._commit_times = _git_commit_times(self.data_dir)
160
+ rel = pathlib.Path(os.path.relpath(fs_path, self.data_dir)).as_posix()
161
+ when = self._commit_times.get(rel)
162
+ if when is not None:
163
+ return when
164
+ return _getmtime(fs_path)
87
165
 
88
166
  def get_config(self, path):
89
167
  """Return hierarchically overrideable configuration,
@@ -119,18 +197,21 @@ class DB(object):
119
197
  path, file_path = self._clean_path(path)
120
198
  if os.path.isdir(file_path):
121
199
  if os.path.isfile(file_path + ".md"):
122
- raise PathConflict(
123
- "path {} is both a file and a directory".format(path)
124
- )
200
+ raise PathConflict(f"path {path} is both a file and a directory")
125
201
  if listing is None:
126
202
  listing = _getlisting(file_path)
127
- mtime = _getmtime(file_path)
128
- file_path = os.path.join(file_path, "index.md")
203
+ index_path = os.path.join(file_path, "index.md")
204
+ # Use the index file's time, as get_data("<dir>/index") would;
205
+ # fall back to the directory's mtime if there is no index file.
206
+ mtime = self._last_mod(
207
+ index_path if os.path.exists(index_path) else file_path
208
+ )
209
+ file_path = index_path
129
210
  else:
130
211
  file_path += ".md"
131
212
  if not os.path.exists(file_path):
132
213
  return {}
133
- mtime = _getmtime(file_path)
214
+ mtime = self._last_mod(file_path)
134
215
  if os.path.basename(file_path) == "index.md" and not os.path.exists(file_path):
135
216
  data = {"content": ""}
136
217
  else:
@@ -138,7 +219,7 @@ class DB(object):
138
219
  data["content"] = md_content
139
220
  data["listing"] = listing
140
221
  data["last_mod"] = mtime
141
- data["path"] = "/%s" % path
222
+ data["path"] = f"/{path}"
142
223
  data["id"] = "index" if path == "" else os.path.basename(path)
143
224
  return data
144
225
 
@@ -0,0 +1,241 @@
1
+ import datetime
2
+ import os
3
+ import subprocess
4
+ import tempfile
5
+ import unittest
6
+
7
+ from mdsite.data import DB, GitHistoryError, PathConflict
8
+
9
+
10
+ class DBTests(unittest.TestCase):
11
+ def setUp(self):
12
+ self.data_dir = os.path.join(
13
+ os.path.dirname(os.path.realpath(__file__)), "testdata"
14
+ )
15
+ self.db = DB(self.data_dir)
16
+
17
+ def testParseTOML(self):
18
+ result = self.db.get_data("toml")
19
+ self.assertEqual(result["owner"]["name"], "Tom Preston-Werner")
20
+ self.assertEqual(
21
+ result["owner"]["dob"].isoformat(),
22
+ datetime.datetime(1979, 5, 27, 7, 32, tzinfo=datetime.UTC).isoformat(),
23
+ )
24
+ self.assertIs(result["owner"]["dob"].tzinfo, datetime.UTC)
25
+
26
+ def testParseYAML(self):
27
+ result = self.db.get_data("yaml")
28
+ self.assertEqual(result["owner"]["name"], "YAML Guy")
29
+ self.assertEqual(result["database"]["enabled"], True)
30
+ self.assertEqual(result["database"]["connection_max"], 5000)
31
+
32
+ def testParseJSON(self):
33
+ result = self.db.get_data("json")
34
+ self.assertEqual(result["title"], "Well, Well!")
35
+
36
+ def testConflict(self):
37
+ with self.assertRaises(PathConflict):
38
+ self.db.get_data("conflict")
39
+
40
+ def testConfig(self):
41
+ config = self.db.get_config("/")
42
+ self.assertEqual(config["template"], "base.tmpl")
43
+ config = self.db.get_config("/nougat")
44
+ self.assertEqual(config["template"], "dessert.tmpl")
45
+
46
+ def testListing(self):
47
+ data = self.db.get_data("/")
48
+ self.assertEqual(
49
+ data["listing"],
50
+ (["conflict", "nougat"], ["conflict", "json", "nohead", "toml", "yaml"]),
51
+ )
52
+
53
+ def testRecursiveListing(self):
54
+ listing = self.db.get_recursive_listing("/")
55
+ self.assertEqual(
56
+ listing,
57
+ {
58
+ "": (
59
+ ["conflict", "nougat"],
60
+ ["conflict", "json", "nohead", "toml", "yaml"],
61
+ ),
62
+ "conflict": ([], ["index"]),
63
+ "nougat": ([], []),
64
+ },
65
+ )
66
+
67
+ def testRecursiveData(self):
68
+ all_data = self.db.get_recursive_data("/nougat")
69
+ self.assertEqual(set(all_data), {"nougat"})
70
+
71
+ def testNoDataHeader(self):
72
+ data = self.db.get_data("nohead")
73
+ self.assertTrue(data.get("content", ""))
74
+ self.assertIn("This markdown file", data.get("content", ""))
75
+
76
+ def testLastModIsAwareUTC(self):
77
+ for path in ("toml", "nougat"):
78
+ last_mod = self.db.get_data(path)["last_mod"]
79
+ self.assertEqual(last_mod.tzinfo, datetime.UTC)
80
+ fs_path = os.path.join(self.data_dir, path)
81
+ if not os.path.isdir(fs_path):
82
+ fs_path += ".md"
83
+ self.assertAlmostEqual(
84
+ last_mod.timestamp(), os.path.getmtime(fs_path), delta=1e-6
85
+ )
86
+
87
+ def testDirectoryLastModComesFromIndexFile(self):
88
+ with tempfile.TemporaryDirectory() as data_dir:
89
+ leaf_dir = os.path.join(data_dir, "a", "b")
90
+ os.makedirs(leaf_dir)
91
+ index_path = os.path.join(leaf_dir, "index.md")
92
+ with open(index_path, "w") as fp:
93
+ fp.write("# Leaf\n")
94
+ # Make the index file and its directory disagree, as they do
95
+ # when index.md is edited in place.
96
+ os.utime(index_path, (1_000_000_000, 1_000_000_000))
97
+ os.utime(leaf_dir, (2_000_000_000, 2_000_000_000))
98
+ db = DB(data_dir)
99
+ expected = datetime.datetime.fromtimestamp(1_000_000_000, tz=datetime.UTC)
100
+ self.assertEqual(db.get_data("/a/b/index")["last_mod"], expected)
101
+ self.assertEqual(db.get_data("/a/b")["last_mod"], expected)
102
+
103
+ def testUnknownLastModSourceIsRejected(self):
104
+ with self.assertRaises(ValueError):
105
+ DB(self.data_dir, last_mod="ctime")
106
+
107
+
108
+ T1 = 1_700_000_000
109
+ T2 = 1_710_000_000
110
+ MTIME = 1_000_000_000
111
+
112
+
113
+ def utc(ts):
114
+ return datetime.datetime.fromtimestamp(ts, tz=datetime.UTC)
115
+
116
+
117
+ class GitLastModTests(unittest.TestCase):
118
+ """last_mod="git": each repository is built here, with pinned commit
119
+ dates and no dependence on the user's git configuration."""
120
+
121
+ def setUp(self):
122
+ self._tmp = tempfile.TemporaryDirectory()
123
+ self.addCleanup(self._tmp.cleanup)
124
+ self.repo = os.path.join(self._tmp.name, "repo")
125
+ os.makedirs(self.repo)
126
+ self.git("init", "-q")
127
+
128
+ def git(self, *args, when=None, cwd=None):
129
+ env = {
130
+ "PATH": os.environ["PATH"],
131
+ "HOME": self._tmp.name,
132
+ "GIT_CONFIG_NOSYSTEM": "1",
133
+ "GIT_AUTHOR_NAME": "Test",
134
+ "GIT_AUTHOR_EMAIL": "test@example.com",
135
+ "GIT_COMMITTER_NAME": "Test",
136
+ "GIT_COMMITTER_EMAIL": "test@example.com",
137
+ }
138
+ if when is not None:
139
+ env["GIT_AUTHOR_DATE"] = env["GIT_COMMITTER_DATE"] = f"@{when} +0000"
140
+ subprocess.run(
141
+ ["git", *args],
142
+ cwd=cwd or self.repo,
143
+ env=env,
144
+ check=True,
145
+ capture_output=True,
146
+ )
147
+
148
+ def write(self, rel, text="+++\ntitle = 'x'\n+++\nbody\n"):
149
+ path = os.path.join(self.repo, rel)
150
+ os.makedirs(os.path.dirname(path), exist_ok=True)
151
+ with open(path, "w") as fp:
152
+ fp.write(text)
153
+ # A distinctive mtime, so a fallback to it is visible.
154
+ os.utime(path, (MTIME, MTIME))
155
+ return path
156
+
157
+ def commit(self, when, *paths):
158
+ self.git("add", *paths)
159
+ self.git("commit", "-q", "-m", "c", when=when)
160
+
161
+ def test_last_mod_is_the_last_commit_that_changed_the_file(self):
162
+ self.write("a.md")
163
+ self.write("b.md")
164
+ self.commit(T1, "a.md", "b.md")
165
+ self.write("b.md", "changed\n")
166
+ self.commit(T2, "b.md")
167
+ db = DB(self.repo, last_mod="git")
168
+ self.assertEqual(db.get_data("a")["last_mod"], utc(T1))
169
+ self.assertEqual(db.get_data("b")["last_mod"], utc(T2))
170
+
171
+ def test_uncommitted_edits_keep_the_commit_time(self):
172
+ self.write("a.md")
173
+ self.commit(T1, "a.md")
174
+ self.write("a.md", "edited but not committed\n")
175
+ self.assertEqual(
176
+ DB(self.repo, last_mod="git").get_data("a")["last_mod"], utc(T1)
177
+ )
178
+
179
+ def test_untracked_files_fall_back_to_mtime(self):
180
+ self.write("a.md")
181
+ self.commit(T1, "a.md")
182
+ self.write("new.md")
183
+ db = DB(self.repo, last_mod="git")
184
+ self.assertEqual(db.get_data("new")["last_mod"], utc(MTIME))
185
+
186
+ def test_directory_uses_its_index_commit_time(self):
187
+ self.write("section/index.md")
188
+ self.commit(T1, "section/index.md")
189
+ db = DB(self.repo, last_mod="git")
190
+ self.assertEqual(db.get_data("/section")["last_mod"], utc(T1))
191
+
192
+ def test_data_dir_may_be_a_subdirectory_of_the_repository(self):
193
+ self.write("site/data/a.md")
194
+ self.commit(T1, "site/data/a.md")
195
+ db = DB(os.path.join(self.repo, "site", "data"), last_mod="git")
196
+ self.assertEqual(db.get_data("a")["last_mod"], utc(T1))
197
+
198
+ def test_non_ascii_file_names(self):
199
+ self.write("café.md")
200
+ self.commit(T1, "café.md")
201
+ self.assertEqual(
202
+ DB(self.repo, last_mod="git").get_data("café")["last_mod"], utc(T1)
203
+ )
204
+
205
+ def test_directory_outside_a_repository_is_an_error(self):
206
+ outside = os.path.join(self._tmp.name, "plain")
207
+ os.makedirs(outside)
208
+ with open(os.path.join(outside, "a.md"), "w") as fp:
209
+ fp.write("x\n")
210
+ # Keep git from finding a repository above the temporary directory.
211
+ os.environ["GIT_CEILING_DIRECTORIES"] = self._tmp.name
212
+ self.addCleanup(os.environ.pop, "GIT_CEILING_DIRECTORIES", None)
213
+ with self.assertRaises(GitHistoryError):
214
+ DB(outside, last_mod="git").get_data("a")
215
+
216
+ def test_shallow_clone_is_an_error(self):
217
+ self.write("a.md")
218
+ self.commit(T1, "a.md")
219
+ self.write("a.md", "again\n")
220
+ self.commit(T2, "a.md")
221
+ clone = os.path.join(self._tmp.name, "shallow")
222
+ self.git(
223
+ "clone",
224
+ "-q",
225
+ "--depth",
226
+ "1",
227
+ f"file://{self.repo}",
228
+ clone,
229
+ cwd=self._tmp.name,
230
+ )
231
+ with self.assertRaises(GitHistoryError):
232
+ DB(clone, last_mod="git").get_data("a")
233
+
234
+ def test_mtime_remains_the_default(self):
235
+ self.write("a.md")
236
+ self.commit(T1, "a.md")
237
+ self.assertEqual(DB(self.repo).get_data("a")["last_mod"], utc(MTIME))
238
+
239
+
240
+ if __name__ == "__main__":
241
+ unittest.main()
@@ -0,0 +1,61 @@
1
+ [project]
2
+ name = "markdown-site-utils"
3
+ version = "0.4.0"
4
+ description = "Some utilities for managing Markdown files with metadata."
5
+ readme = "README.md"
6
+ license = "MIT"
7
+ license-files = ["LICENSE"]
8
+ requires-python = ">=3.11"
9
+ classifiers = [
10
+ "Programming Language :: Python :: 3",
11
+ "Programming Language :: Python :: 3 :: Only",
12
+ "Programming Language :: Python :: 3.11",
13
+ "Programming Language :: Python :: 3.12",
14
+ "Programming Language :: Python :: 3.13",
15
+ "Programming Language :: Python :: 3.14",
16
+ "Programming Language :: Python :: 3.15",
17
+ ]
18
+ dependencies = [
19
+ "MarkupSafe>=2.1.2",
20
+ "PyYAML>=6.0",
21
+ "markdown2>=2.5.1",
22
+ ]
23
+
24
+ [[project.authors]]
25
+ name = "Jacob Smullyan"
26
+ email = "smulloni@smullyan.org"
27
+
28
+ [project.urls]
29
+ Repository = "https://github.com/smulloni/markdown_site_utils"
30
+
31
+ [dependency-groups]
32
+ dev = [
33
+ "pytest>=7.3.0",
34
+ "ipython>=8.12.0",
35
+ "ruff>=0.17.6",
36
+ ]
37
+
38
+ [build-system]
39
+ requires = ["uv_build>=0.13.8,<0.14"]
40
+ build-backend = "uv_build"
41
+
42
+ [tool.uv.build-backend]
43
+ module-name = "mdsite"
44
+ module-root = ""
45
+
46
+ [tool.ruff]
47
+ target-version = "py311"
48
+
49
+ [tool.ruff.lint]
50
+ select = [
51
+ "F",
52
+ "E",
53
+ "W",
54
+ "I",
55
+ "UP",
56
+ "B",
57
+ "DTZ",
58
+ ]
59
+
60
+ [tool.pytest.ini_options]
61
+ filterwarnings = ["error"]
@@ -0,0 +1,51 @@
1
+ [project]
2
+ name = "markdown-site-utils"
3
+ version = "0.4.0"
4
+ description = "Some utilities for managing Markdown files with metadata."
5
+ authors = [{ name = "Jacob Smullyan", email = "smulloni@smullyan.org" }]
6
+ readme = "README.md"
7
+ license = "MIT"
8
+ license-files = ["LICENSE"]
9
+ requires-python = ">=3.11"
10
+ classifiers = [
11
+ "Programming Language :: Python :: 3",
12
+ "Programming Language :: Python :: 3 :: Only",
13
+ "Programming Language :: Python :: 3.11",
14
+ "Programming Language :: Python :: 3.12",
15
+ "Programming Language :: Python :: 3.13",
16
+ "Programming Language :: Python :: 3.14",
17
+ "Programming Language :: Python :: 3.15",
18
+ ]
19
+ dependencies = [
20
+ "MarkupSafe>=2.1.2",
21
+ "PyYAML>=6.0",
22
+ "markdown2>=2.5.1",
23
+ ]
24
+
25
+ [project.urls]
26
+ Repository = "https://github.com/smulloni/markdown_site_utils"
27
+
28
+ [dependency-groups]
29
+ dev = [
30
+ "pytest>=7.3.0",
31
+ "ipython>=8.12.0",
32
+ "ruff>=0.17.6",
33
+ ]
34
+
35
+ [build-system]
36
+ requires = ["uv_build>=0.13.8,<0.14"]
37
+ build-backend = "uv_build"
38
+
39
+ [tool.uv.build-backend]
40
+ module-name = "mdsite"
41
+ module-root = ""
42
+
43
+ [tool.ruff]
44
+ target-version = "py311"
45
+
46
+ [tool.ruff.lint]
47
+ # pyflakes, pycodestyle, isort, pyupgrade, bugbear, flake8-datetimez
48
+ select = ["F", "E", "W", "I", "UP", "B", "DTZ"]
49
+
50
+ [tool.pytest.ini_options]
51
+ filterwarnings = ["error"]
@@ -1,68 +0,0 @@
1
- Metadata-Version: 2.1
2
- Name: markdown-site-utils
3
- Version: 0.2.2
4
- Summary: Some utilities for managing Markdown files with metadata.
5
- Home-page: https://github.com/smulloni/markdown_site_utils
6
- License: MIT
7
- Author: Jacob Smullyan
8
- Author-email: smulloni@smullyan.org
9
- Requires-Python: >=3.11,<4.0
10
- Classifier: License :: OSI Approved :: MIT License
11
- Classifier: Programming Language :: Python :: 3
12
- Classifier: Programming Language :: Python :: 3.11
13
- Requires-Dist: MarkupSafe (>=2.1.2,<3.0.0)
14
- Requires-Dist: PyYAML (>=6.0,<7.0)
15
- Requires-Dist: markdown2 (>=2.4.8,<3.0.0)
16
- Requires-Dist: toml (>=0.10.2,<0.11.0)
17
- Project-URL: Repository, https://github.com/smulloni/markdown_site_utils
18
- Description-Content-Type: text/markdown
19
-
20
- # Markdown Site Utils
21
-
22
- Some utilities for managing Markdown files with metadata.
23
-
24
- The notion is that a content-oriented website may be written as a
25
- hierarchical series of Markdown files (with an ".md" extension) underneath
26
- some data directory, e.g.:
27
-
28
- DATA_DIR/
29
- index.md
30
- foo.md
31
- bar.md
32
- subdir/
33
- index.md
34
- foo.md
35
- bar.md
36
-
37
- Each file may contain metadata, written in TOML in a section at
38
- the top, bounded by '+++' lines:
39
-
40
- +++
41
- title = "My Page Title"
42
- +++
43
-
44
- # Some Markdown
45
-
46
- YAML and JSON may also be used. YAML blocks should start and end with lines
47
- consisting of three dashes; JSON blocks should consist of a single JSON object
48
- with opening and closing braces on lines by themselves. The data block is optional
49
- but if present must begin on the first line of the file.
50
-
51
- To use the library, you get create an `mdsite.DB` object with the path to your
52
- data directory:
53
-
54
- mydb = mdsite.DB("/path/to/data/dir")
55
-
56
- Then call `get_data(path)` for the path into the directory you want, leaving
57
- out the `.md` filename suffix, and, if you are looking for an index file, leaving
58
- out `index.md`:
59
-
60
- data = mydb.get_data("/node/leaf")
61
-
62
- The above gets data for `$DATA_DIR/node/leaf.md`, or for
63
- `$DATA_DIR/node/leaf/index.md`, if that file exists instead.
64
-
65
- The library also supports hierarchical configuration, also written in TOML,
66
- YAML, or JSON, stored in files called `config.{toml,yaml,json}` depending on the
67
- config language employed.
68
-
@@ -1,48 +0,0 @@
1
- # Markdown Site Utils
2
-
3
- Some utilities for managing Markdown files with metadata.
4
-
5
- The notion is that a content-oriented website may be written as a
6
- hierarchical series of Markdown files (with an ".md" extension) underneath
7
- some data directory, e.g.:
8
-
9
- DATA_DIR/
10
- index.md
11
- foo.md
12
- bar.md
13
- subdir/
14
- index.md
15
- foo.md
16
- bar.md
17
-
18
- Each file may contain metadata, written in TOML in a section at
19
- the top, bounded by '+++' lines:
20
-
21
- +++
22
- title = "My Page Title"
23
- +++
24
-
25
- # Some Markdown
26
-
27
- YAML and JSON may also be used. YAML blocks should start and end with lines
28
- consisting of three dashes; JSON blocks should consist of a single JSON object
29
- with opening and closing braces on lines by themselves. The data block is optional
30
- but if present must begin on the first line of the file.
31
-
32
- To use the library, you get create an `mdsite.DB` object with the path to your
33
- data directory:
34
-
35
- mydb = mdsite.DB("/path/to/data/dir")
36
-
37
- Then call `get_data(path)` for the path into the directory you want, leaving
38
- out the `.md` filename suffix, and, if you are looking for an index file, leaving
39
- out `index.md`:
40
-
41
- data = mydb.get_data("/node/leaf")
42
-
43
- The above gets data for `$DATA_DIR/node/leaf.md`, or for
44
- `$DATA_DIR/node/leaf/index.md`, if that file exists instead.
45
-
46
- The library also supports hierarchical configuration, also written in TOML,
47
- YAML, or JSON, stored in files called `config.{toml,yaml,json}` depending on the
48
- config language employed.
@@ -1,3 +0,0 @@
1
- from mdsite.data import PathConflict, DB
2
-
3
- version = '0.2.2'
@@ -1,78 +0,0 @@
1
- import datetime
2
- import os
3
- import unittest
4
-
5
- from mdsite.data import DB, PathConflict
6
-
7
-
8
- class DBTests(unittest.TestCase):
9
- def setUp(self):
10
- self.data_dir = os.path.join(
11
- os.path.dirname(os.path.realpath(__file__)), "testdata"
12
- )
13
- self.db = DB(self.data_dir)
14
-
15
- def testParseTOML(self):
16
- result = self.db.get_data("toml")
17
- self.assertEqual(result["owner"]["name"], "Tom Preston-Werner")
18
- self.assertEqual(
19
- result["owner"]["dob"].isoformat(),
20
- datetime.datetime(
21
- 1979, 5, 27, 7, 32, tzinfo=datetime.timezone.utc
22
- ).isoformat(),
23
- )
24
-
25
- def testParseYAML(self):
26
- result = self.db.get_data("yaml")
27
- self.assertEqual(result["owner"]["name"], "YAML Guy")
28
- self.assertEqual(result["database"]["enabled"], True)
29
- self.assertEqual(result["database"]["connection_max"], 5000)
30
-
31
- def testParseJSON(self):
32
- result = self.db.get_data("json")
33
- self.assertEqual(result["title"], "Well, Well!")
34
-
35
- def testConflict(self):
36
- with self.assertRaises(PathConflict):
37
- self.db.get_data("conflict")
38
-
39
- def testConfig(self):
40
- config = self.db.get_config("/")
41
- self.assertEqual(config["template"], "base.tmpl")
42
- config = self.db.get_config("/nougat")
43
- self.assertEqual(config["template"], "dessert.tmpl")
44
-
45
- def testListing(self):
46
- data = self.db.get_data("/")
47
- self.assertEqual(
48
- data["listing"],
49
- (["conflict", "nougat"], ["conflict", "json", "nohead", "toml", "yaml"]),
50
- )
51
-
52
- def testRecursiveListing(self):
53
- listing = self.db.get_recursive_listing("/")
54
- self.assertEqual(
55
- listing,
56
- {
57
- "": (
58
- ["conflict", "nougat"],
59
- ["conflict", "json", "nohead", "toml", "yaml"],
60
- ),
61
- "conflict": ([], ["index"]),
62
- "nougat": ([], []),
63
- },
64
- )
65
-
66
- def testRecursiveData(self):
67
- all_data = self.db.get_recursive_data("/nougat")
68
- self.assertEqual(set(all_data), {"nougat"})
69
-
70
- def testNoDataHeader(self):
71
- data = self.db.get_data("nohead")
72
- self.assertTrue(data.get("content", ""))
73
- self.assertIn("This markdown file", data.get("content", ""))
74
-
75
-
76
-
77
- if __name__ == "__main__":
78
- unittest.main()
@@ -1,29 +0,0 @@
1
- [tool.poetry]
2
- name = "markdown-site-utils"
3
- version = "0.2.2"
4
- description = "Some utilities for managing Markdown files with metadata."
5
- authors = ["Jacob Smullyan <smulloni@smullyan.org>"]
6
- readme = "README.md"
7
- license = "MIT"
8
- repository = "https://github.com/smulloni/markdown_site_utils"
9
- packages = [{include = "mdsite"}]
10
- include = [
11
- {path="mdsite/testdata/*"},
12
- {path="mdsite/testdata/conflict/*"},
13
- ]
14
-
15
- [tool.poetry.dependencies]
16
- python = "^3.11"
17
- MarkupSafe = "^2.1.2"
18
- PyYAML = "^6.0"
19
- markdown2 = "^2.4.8"
20
- toml = "^0.10.2"
21
-
22
- [tool.poetry.group.dev.dependencies]
23
- pytest = "^7.3.0"
24
- ipython = "^8.12.0"
25
- black = "^23.3.0"
26
-
27
- [build-system]
28
- requires = ["poetry-core"]
29
- build-backend = "poetry.core.masonry.api"
@@ -1,34 +0,0 @@
1
- # -*- coding: utf-8 -*-
2
- from setuptools import setup
3
-
4
- packages = \
5
- ['mdsite']
6
-
7
- package_data = \
8
- {'': ['*'],
9
- 'mdsite': ['testdata/*', 'testdata/conflict/*', 'testdata/nougat/*']}
10
-
11
- install_requires = \
12
- ['MarkupSafe>=2.1.2,<3.0.0',
13
- 'PyYAML>=6.0,<7.0',
14
- 'markdown2>=2.4.8,<3.0.0',
15
- 'toml>=0.10.2,<0.11.0']
16
-
17
- setup_kwargs = {
18
- 'name': 'markdown-site-utils',
19
- 'version': '0.2.2',
20
- 'description': 'Some utilities for managing Markdown files with metadata.',
21
- 'long_description': '# Markdown Site Utils\n\nSome utilities for managing Markdown files with metadata.\n\nThe notion is that a content-oriented website may be written as a \nhierarchical series of Markdown files (with an ".md" extension) underneath\nsome data directory, e.g.:\n\n DATA_DIR/\n index.md\n foo.md\n bar.md\n subdir/\n index.md\n foo.md\n bar.md\n\nEach file may contain metadata, written in TOML in a section at\nthe top, bounded by \'+++\' lines:\n\n +++\n title = "My Page Title"\n +++\n\n # Some Markdown\n\nYAML and JSON may also be used. YAML blocks should start and end with lines\nconsisting of three dashes; JSON blocks should consist of a single JSON object\nwith opening and closing braces on lines by themselves. The data block is optional\nbut if present must begin on the first line of the file.\n\nTo use the library, you get create an `mdsite.DB` object with the path to your\ndata directory:\n\n mydb = mdsite.DB("/path/to/data/dir")\n\nThen call `get_data(path)` for the path into the directory you want, leaving\nout the `.md` filename suffix, and, if you are looking for an index file, leaving\nout `index.md`:\n\n data = mydb.get_data("/node/leaf")\n\nThe above gets data for `$DATA_DIR/node/leaf.md`, or for\n`$DATA_DIR/node/leaf/index.md`, if that file exists instead. \n\nThe library also supports hierarchical configuration, also written in TOML,\nYAML, or JSON, stored in files called `config.{toml,yaml,json}` depending on the\nconfig language employed.\n',
22
- 'author': 'Jacob Smullyan',
23
- 'author_email': 'smulloni@smullyan.org',
24
- 'maintainer': 'None',
25
- 'maintainer_email': 'None',
26
- 'url': 'https://github.com/smulloni/markdown_site_utils',
27
- 'packages': packages,
28
- 'package_data': package_data,
29
- 'install_requires': install_requires,
30
- 'python_requires': '>=3.11,<4.0',
31
- }
32
-
33
-
34
- setup(**setup_kwargs)