hypermarkdown 0.2.0__tar.gz → 0.3.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.
Files changed (33) hide show
  1. {hypermarkdown-0.2.0 → hypermarkdown-0.3.0}/CHANGELOG.md +30 -1
  2. {hypermarkdown-0.2.0 → hypermarkdown-0.3.0}/LICENSE +1 -1
  3. {hypermarkdown-0.2.0/src/hypermarkdown.egg-info → hypermarkdown-0.3.0}/PKG-INFO +26 -6
  4. {hypermarkdown-0.2.0 → hypermarkdown-0.3.0}/README.md +25 -5
  5. {hypermarkdown-0.2.0 → hypermarkdown-0.3.0}/src/hypermarkdown/__init__.py +1 -1
  6. {hypermarkdown-0.2.0 → hypermarkdown-0.3.0}/src/hypermarkdown/cli.py +38 -0
  7. hypermarkdown-0.3.0/src/hypermarkdown/config.py +318 -0
  8. {hypermarkdown-0.2.0 → hypermarkdown-0.3.0/src/hypermarkdown.egg-info}/PKG-INFO +26 -6
  9. hypermarkdown-0.2.0/src/hypermarkdown/config.py +0 -110
  10. {hypermarkdown-0.2.0 → hypermarkdown-0.3.0}/MANIFEST.in +0 -0
  11. {hypermarkdown-0.2.0 → hypermarkdown-0.3.0}/pyproject.toml +0 -0
  12. {hypermarkdown-0.2.0 → hypermarkdown-0.3.0}/setup.cfg +0 -0
  13. {hypermarkdown-0.2.0 → hypermarkdown-0.3.0}/src/hypermarkdown/diagram.py +0 -0
  14. {hypermarkdown-0.2.0 → hypermarkdown-0.3.0}/src/hypermarkdown/embed.py +0 -0
  15. {hypermarkdown-0.2.0 → hypermarkdown-0.3.0}/src/hypermarkdown/frontmatter.py +0 -0
  16. {hypermarkdown-0.2.0 → hypermarkdown-0.3.0}/src/hypermarkdown/graph.py +0 -0
  17. {hypermarkdown-0.2.0 → hypermarkdown-0.3.0}/src/hypermarkdown/imports.py +0 -0
  18. {hypermarkdown-0.2.0 → hypermarkdown-0.3.0}/src/hypermarkdown/lint/__init__.py +0 -0
  19. {hypermarkdown-0.2.0 → hypermarkdown-0.3.0}/src/hypermarkdown/lint/report.py +0 -0
  20. {hypermarkdown-0.2.0 → hypermarkdown-0.3.0}/src/hypermarkdown/lint/rules.py +0 -0
  21. {hypermarkdown-0.2.0 → hypermarkdown-0.3.0}/src/hypermarkdown/mkdocs_plugin.py +0 -0
  22. {hypermarkdown-0.2.0 → hypermarkdown-0.3.0}/src/hypermarkdown/model.py +0 -0
  23. {hypermarkdown-0.2.0 → hypermarkdown-0.3.0}/src/hypermarkdown/parse.py +0 -0
  24. {hypermarkdown-0.2.0 → hypermarkdown-0.3.0}/src/hypermarkdown/render/__init__.py +0 -0
  25. {hypermarkdown-0.2.0 → hypermarkdown-0.3.0}/src/hypermarkdown/render/flat.py +0 -0
  26. {hypermarkdown-0.2.0 → hypermarkdown-0.3.0}/src/hypermarkdown/resolve.py +0 -0
  27. {hypermarkdown-0.2.0 → hypermarkdown-0.3.0}/src/hypermarkdown/scan.py +0 -0
  28. {hypermarkdown-0.2.0 → hypermarkdown-0.3.0}/src/hypermarkdown/urls.py +0 -0
  29. {hypermarkdown-0.2.0 → hypermarkdown-0.3.0}/src/hypermarkdown.egg-info/SOURCES.txt +0 -0
  30. {hypermarkdown-0.2.0 → hypermarkdown-0.3.0}/src/hypermarkdown.egg-info/dependency_links.txt +0 -0
  31. {hypermarkdown-0.2.0 → hypermarkdown-0.3.0}/src/hypermarkdown.egg-info/entry_points.txt +0 -0
  32. {hypermarkdown-0.2.0 → hypermarkdown-0.3.0}/src/hypermarkdown.egg-info/requires.txt +0 -0
  33. {hypermarkdown-0.2.0 → hypermarkdown-0.3.0}/src/hypermarkdown.egg-info/top_level.txt +0 -0
@@ -13,6 +13,34 @@ only for the Python API.
13
13
 
14
14
  ## [Unreleased]
15
15
 
16
+ ## [0.3.0] — 2026-09-14
17
+
18
+ ### Added
19
+ - **`hmd init`** — create `.hmd/config.toml` at a project root, with every
20
+ setting written at its default and commented. A blank file, or one with the
21
+ defaults commented out, teaches nothing that no file at all does not; the
22
+ written file is where an author finds out which keys exist. `--wiki` names
23
+ the namespace root, and the command creates that directory too, because
24
+ `load()` rejects a `wiki` setting pointing at nothing — writing the config
25
+ and stopping there would leave a project whose next command fails about a
26
+ directory nobody asked for. A missing project directory is created; an
27
+ existing config is never replaced without `--force`. Initialising inside an
28
+ existing project succeeds and says so on stderr, since the nearer marker wins
29
+ and that silently changes where cards resolve.
30
+ - **`[namespace]` in the written config** — `name` and `provider`. A project's
31
+ own namespace is otherwise unnamed, and naming it is what lets another
32
+ project bind to it and address a card as `name:card`. `--name` defaults to
33
+ the project directory's own name and is *repaired* into that address form
34
+ when it has to be (`My Notes` → `My-Notes`); a `--name` passed explicitly is
35
+ validated and refused instead, because a name somebody typed is a request
36
+ and answering a different one is worse than an error. `provider` is `folder`
37
+ — a local tree — and no other value is accepted yet.
38
+
39
+ **Nothing reads either key.** The specification pins the MVP to exactly two
40
+ settings, `wiki` and `[discovery]`, and requires the rest of the file to be
41
+ ignored; `init` writing a section is not the resolver reading one. The
42
+ section exists so binding has somewhere to land when it is implemented.
43
+
16
44
  ## [0.2.0] — 2026-08-10
17
45
 
18
46
  **The distribution is renamed.** `pip install hypermarkdown` replaces
@@ -215,7 +243,8 @@ Deliberate, and tracked per proposal under `doc/proposals/HMD-NNNN/STATUS.md`:
215
243
  Both specifications — the format and the site — are still `drafted`. Expect the
216
244
  format to move before `1.0`.
217
245
 
218
- [Unreleased]: https://github.com/ewiger/hypermarkdown/compare/v0.2.0...HEAD
246
+ [Unreleased]: https://github.com/ewiger/hypermarkdown/compare/v0.3.0...HEAD
247
+ [0.3.0]: https://github.com/ewiger/hypermarkdown/compare/v0.2.0...v0.3.0
219
248
  [0.2.0]: https://github.com/ewiger/hypermarkdown/compare/v0.1.1...v0.2.0
220
249
  [0.1.1]: https://github.com/ewiger/hypermarkdown/compare/v0.1.0...v0.1.1
221
250
  [0.1.0]: https://github.com/ewiger/hypermarkdown/releases/tag/v0.1.0
@@ -1,6 +1,6 @@
1
1
  MIT License
2
2
 
3
- Copyright (c) 2026 Yauhen Yakimovich
3
+ Copyright (c) 2026 HyperMarkDown Contributors — see https://github.com/ewiger/hypermarkdown/blob/main/CONTRIBUTORS.md for full attribution.
4
4
 
5
5
  Permission is hereby granted, free of charge, to any person obtaining a copy
6
6
  of this software and associated documentation files (the "Software"), to deal
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: hypermarkdown
3
- Version: 0.2.0
3
+ Version: 0.3.0
4
4
  Summary: A strict, machine-checkable markdown dialect for project knowledge bases.
5
5
  Author: Yauhen Yakimovich
6
6
  License-Expression: MIT
@@ -45,7 +45,7 @@ Dynamic: license-file
45
45
  **The Python implementation, and the `hmd` command**
46
46
 
47
47
  [![PyPI](https://img.shields.io/pypi/v/hypermarkdown.svg)](https://pypi.org/project/hypermarkdown/)
48
- [![Python versions](https://img.shields.io/pypi/pyversions/hypermarkdown.svg)](https://pypi.org/project/hypermarkdown/)
48
+ [![Python versions](https://img.shields.io/pypi/pyversions/hypermarkdown?color=blue&label=python)](https://pypi.org/project/hypermarkdown/)
49
49
  [![CI](https://github.com/ewiger/hypermarkdown/actions/workflows/ci.yml/badge.svg)](https://github.com/ewiger/hypermarkdown/actions/workflows/ci.yml)
50
50
  [![Documentation](https://img.shields.io/badge/docs-hypermarkdown.org-ffb300)](https://hypermarkdown.org/)
51
51
  [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://github.com/ewiger/hypermarkdown/blob/main/tools/hmd/LICENSE)
@@ -147,16 +147,36 @@ Every other key is yours, and nothing will inspect it.
147
147
 
148
148
  | Command | What it does |
149
149
  | --- | --- |
150
+ | `hmd init` | Write `.hmd/config.toml` and create the namespace root it names |
150
151
  | `hmd lint` | Parse, resolve, and report — `HMD001`–`HMD017`, text or JSON |
151
152
  | `hmd render` | Expand embeds and rewrite links, to flat markdown or HTML |
152
153
  | `hmd graph` | Dump the resolved link graph as JSON |
153
154
  | `hmd info` | Show the resolved root and discovery policy |
154
155
  | `hmd --version` | Print the installed version |
155
156
 
156
- Each takes `--root` to override the namespace root, which otherwise comes from
157
- the `wiki` setting in `.hmd/config.toml` (defaulting to `doc/wiki`). A `.hmd/`
158
- directory doubles as the project root marker, so any subtree can be
159
- self-contained.
157
+ Every command but `init` takes `--root` to override the namespace root, which
158
+ otherwise comes from the `wiki` setting in `.hmd/config.toml` (defaulting to
159
+ `doc/wiki`). A `.hmd/` directory doubles as the project root marker, so any
160
+ subtree can be self-contained.
161
+
162
+ ```bash
163
+ hmd init # here; the namespace is named after the directory
164
+ hmd init path/to/project --wiki notes --name shared
165
+ ```
166
+
167
+ `init` writes every setting at its default rather than leaving them implicit —
168
+ the file is where you find out which keys exist. It creates the wiki root
169
+ alongside the config, since a `wiki` setting pointing at nothing is an error
170
+ every later command reports. It refuses to replace a config it did not write;
171
+ `--force` overrides that.
172
+
173
+ The `[namespace]` section names this tree so another project can bind to it and
174
+ address a card as `name:card`. `--name` defaults to the project directory's own
175
+ name, repaired into that address form if it has to be — a folder called
176
+ `My Notes` becomes `My-Notes`. A `--name` you pass is validated instead of
177
+ repaired, because a name you typed is a request rather than a guess. Nothing
178
+ reads either key yet: binding is specified and not implemented, so the section
179
+ records intent.
160
180
 
161
181
  `hmd render --to markdown` is **one-way** on purpose. Flattening a card erases
162
182
  the embed boundary and the provenance of every link, which is right for
@@ -7,7 +7,7 @@
7
7
  **The Python implementation, and the `hmd` command**
8
8
 
9
9
  [![PyPI](https://img.shields.io/pypi/v/hypermarkdown.svg)](https://pypi.org/project/hypermarkdown/)
10
- [![Python versions](https://img.shields.io/pypi/pyversions/hypermarkdown.svg)](https://pypi.org/project/hypermarkdown/)
10
+ [![Python versions](https://img.shields.io/pypi/pyversions/hypermarkdown?color=blue&label=python)](https://pypi.org/project/hypermarkdown/)
11
11
  [![CI](https://github.com/ewiger/hypermarkdown/actions/workflows/ci.yml/badge.svg)](https://github.com/ewiger/hypermarkdown/actions/workflows/ci.yml)
12
12
  [![Documentation](https://img.shields.io/badge/docs-hypermarkdown.org-ffb300)](https://hypermarkdown.org/)
13
13
  [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://github.com/ewiger/hypermarkdown/blob/main/tools/hmd/LICENSE)
@@ -109,16 +109,36 @@ Every other key is yours, and nothing will inspect it.
109
109
 
110
110
  | Command | What it does |
111
111
  | --- | --- |
112
+ | `hmd init` | Write `.hmd/config.toml` and create the namespace root it names |
112
113
  | `hmd lint` | Parse, resolve, and report — `HMD001`–`HMD017`, text or JSON |
113
114
  | `hmd render` | Expand embeds and rewrite links, to flat markdown or HTML |
114
115
  | `hmd graph` | Dump the resolved link graph as JSON |
115
116
  | `hmd info` | Show the resolved root and discovery policy |
116
117
  | `hmd --version` | Print the installed version |
117
118
 
118
- Each takes `--root` to override the namespace root, which otherwise comes from
119
- the `wiki` setting in `.hmd/config.toml` (defaulting to `doc/wiki`). A `.hmd/`
120
- directory doubles as the project root marker, so any subtree can be
121
- self-contained.
119
+ Every command but `init` takes `--root` to override the namespace root, which
120
+ otherwise comes from the `wiki` setting in `.hmd/config.toml` (defaulting to
121
+ `doc/wiki`). A `.hmd/` directory doubles as the project root marker, so any
122
+ subtree can be self-contained.
123
+
124
+ ```bash
125
+ hmd init # here; the namespace is named after the directory
126
+ hmd init path/to/project --wiki notes --name shared
127
+ ```
128
+
129
+ `init` writes every setting at its default rather than leaving them implicit —
130
+ the file is where you find out which keys exist. It creates the wiki root
131
+ alongside the config, since a `wiki` setting pointing at nothing is an error
132
+ every later command reports. It refuses to replace a config it did not write;
133
+ `--force` overrides that.
134
+
135
+ The `[namespace]` section names this tree so another project can bind to it and
136
+ address a card as `name:card`. `--name` defaults to the project directory's own
137
+ name, repaired into that address form if it has to be — a folder called
138
+ `My Notes` becomes `My-Notes`. A `--name` you pass is validated instead of
139
+ repaired, because a name you typed is a request rather than a guess. Nothing
140
+ reads either key yet: binding is specified and not implemented, so the section
141
+ records intent.
122
142
 
123
143
  `hmd render --to markdown` is **one-way** on purpose. Flattening a card erases
124
144
  the embed boundary and the provenance of every link, which is right for
@@ -15,7 +15,7 @@ from .config import Config, ConfigError
15
15
  from .model import Diagnostic, Document, Link, Span
16
16
  from .resolve import Outcome, Resolution, Workspace
17
17
 
18
- __version__ = "0.2.0"
18
+ __version__ = "0.3.0"
19
19
 
20
20
  __all__ = [
21
21
  "Config",
@@ -90,6 +90,44 @@ def _selected(workspace: Workspace, paths: list[Path] | None) -> list[Path] | No
90
90
  return sorted(set(selected))
91
91
 
92
92
 
93
+ @app.command()
94
+ def init(
95
+ path: Optional[Path] = typer.Argument(None, help="Project root to initialise (default: the working directory)."),
96
+ wiki: str = typer.Option(config_mod.DEFAULT_WIKI, "--wiki", help="Namespace root, relative to the project root."),
97
+ name: Optional[str] = typer.Option(None, "--name", help="Namespace name (default: the project directory's name)."),
98
+ force: bool = typer.Option(False, "--force", help="Replace an existing .hmd/config.toml."),
99
+ ) -> None:
100
+ """Create `.hmd/config.toml` and the namespace root it names."""
101
+ try:
102
+ result = config_mod.init(path, wiki=wiki, name=name, force=force)
103
+ except config_mod.ConfigError as exc:
104
+ typer.echo(f"hmd: {exc}", err=True)
105
+ raise typer.Exit(EXIT_USAGE)
106
+
107
+ def note(target: Path) -> str:
108
+ if target in result.created:
109
+ return " (created)"
110
+ if target == result.config and result.overwritten:
111
+ return " (replaced)"
112
+ return " (already there)"
113
+
114
+ typer.echo(f"project: {result.project}{note(result.project)}")
115
+ typer.echo(f"config: {result.config}{note(result.config)}")
116
+ typer.echo(f"wiki: {result.wiki}{note(result.wiki)}")
117
+ typer.echo(
118
+ f"namespace: {result.name} ({result.provider})"
119
+ f"{' — from the directory name' if result.derived_name else ''}"
120
+ )
121
+
122
+ if result.enclosing is not None:
123
+ typer.echo(
124
+ f"hmd: note: {result.enclosing} is already a project root, and the nearer "
125
+ f"marker wins — cards under {result.project} now resolve against the new root.",
126
+ err=True,
127
+ )
128
+ raise typer.Exit(EXIT_OK)
129
+
130
+
93
131
  @app.command()
94
132
  def lint(
95
133
  paths: Optional[list[Path]] = typer.Argument(None, help="Files or directories; default is the whole tree."),
@@ -0,0 +1,318 @@
1
+ """Root discovery and `.hmd/config.toml` (HMD-0001 §4, §5.3)."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import re
6
+ import tomllib
7
+ from dataclasses import dataclass
8
+ from pathlib import Path, PurePosixPath, PureWindowsPath
9
+
10
+ MARKER_DIR = ".hmd"
11
+ CONFIG_NAME = "config.toml"
12
+ DEFAULT_WIKI = "doc/wiki"
13
+ DEFAULT_MODE = "both"
14
+ VALID_MODES = frozenset({"both", "recursive"})
15
+
16
+ #: The provider kinds a namespace name can be bound to. Only a local directory
17
+ #: is implementable today; a remote provider is reserved and unbuilt, which is
18
+ #: why the key is written at all — the distinction is the thing it records.
19
+ DEFAULT_PROVIDER = "folder"
20
+ VALID_PROVIDERS = frozenset({"folder"})
21
+
22
+ #: A namespace name has to survive `name:card`, the address form another
23
+ #: project uses to reach into a bound namespace. Everything that would make
24
+ #: that ambiguous is out: the wikilink punctuation `[]|#^`, the separator `:`,
25
+ #: the path separators, and whitespace.
26
+ NAME_PATTERN = re.compile(r"\A[A-Za-z0-9][A-Za-z0-9._-]*\Z")
27
+
28
+ #: What `hmd init` writes. Every setting is stated at its default rather than
29
+ #: left implicit: the file is the one place an author learns which keys exist,
30
+ #: and a commented-out default teaches nothing a blank file does not.
31
+ CONFIG_TEMPLATE = """\
32
+ # HyperMarkdown project configuration.
33
+ #
34
+ # This directory doubles as the project root marker — `hmd` finds a project by
35
+ # walking up from the working directory looking for `.hmd/`, falling back to
36
+ # `.git/`. Only the settings below are read; every other key is ignored, so the
37
+ # file is safe to extend.
38
+
39
+ # The namespace root, relative to this project root. Every `.hmd` card beneath
40
+ # it is a page, and links resolve within it. Nothing outside it is checked.
41
+ wiki = "{wiki}"
42
+
43
+ [namespace]
44
+ # This tree's own name. A project's own namespace is otherwise unnamed — there
45
+ # is nothing to tell it apart from until a second tree is in play — and naming
46
+ # it is what lets another project bind to it and address a card as `name:card`.
47
+ # Nothing reads this yet: binding is specified but not implemented, so today
48
+ # the key records the intent rather than doing anything.
49
+ name = "{name}"
50
+
51
+ # What provides the tree behind that name. "folder" is a local directory, this
52
+ # one. A remote provider is reserved and not implemented.
53
+ provider = "{provider}"
54
+
55
+ [discovery]
56
+ # Whether a bare [[link]] the spine walk missed falls back to a sweep of the
57
+ # whole namespace. A card overrides this in either direction with `use`.
58
+ autodiscovery = {autodiscovery}
59
+
60
+ # How that sweep searches once it runs: "both" covers the whole namespace,
61
+ # "recursive" only the source card's own subtree. Not settable per card.
62
+ mode = "{mode}"
63
+ """
64
+
65
+
66
+ @dataclass(frozen=True)
67
+ class Config:
68
+ """Resolved project configuration."""
69
+
70
+ root: Path # the namespace root, absolute
71
+ autodiscovery: bool = True
72
+ mode: str = DEFAULT_MODE
73
+ source: Path | None = None # the config file actually read, if any
74
+
75
+
76
+ @dataclass(frozen=True)
77
+ class InitResult:
78
+ """What `init` found and what it had to make."""
79
+
80
+ project: Path # the project root, absolute
81
+ config: Path # the config file, written either way
82
+ wiki: Path # the namespace root the config names, absolute
83
+ created: frozenset[Path] # of the three above, the ones that did not exist
84
+ name: str = "" # the namespace name written, derived or given
85
+ provider: str = DEFAULT_PROVIDER # what backs that name
86
+ derived_name: bool = False # the name came from the directory, not the caller
87
+ overwritten: bool = False # an existing config replaced under `force`
88
+ enclosing: Path | None = None # an ancestor project this one now nests inside
89
+
90
+
91
+ class ConfigError(Exception):
92
+ """An unusable root or config file — exit code 2, not a lint finding."""
93
+
94
+
95
+ def find_project_root(start: Path) -> Path | None:
96
+ """Nearest ancestor holding `.hmd/`, else nearest holding `.git`."""
97
+ start = start.resolve()
98
+ candidates = [start, *start.parents] if start.is_dir() else list(start.parents)
99
+ for parent in candidates:
100
+ if (parent / MARKER_DIR).is_dir():
101
+ return parent
102
+ for parent in candidates:
103
+ if (parent / ".git").exists():
104
+ return parent
105
+ return None
106
+
107
+
108
+ def load(root_override: Path | None = None, start: Path | None = None) -> Config:
109
+ """Resolve the namespace root and discovery policy.
110
+
111
+ Absent `.hmd/config.toml` entirely, the root is `doc/wiki`, autodiscovery is
112
+ on, and the mode is `both` — a tree with no configuration behaves the way a
113
+ new author expects.
114
+ """
115
+ if root_override is not None:
116
+ root = root_override.resolve()
117
+ if not root.is_dir():
118
+ raise ConfigError(f"root is not a directory: {root}")
119
+ project = find_project_root(root) or root
120
+ data, source = _read(project)
121
+ return Config(
122
+ root=root,
123
+ autodiscovery=_autodiscovery(data),
124
+ mode=_mode(data),
125
+ source=source,
126
+ )
127
+
128
+ start = (start or Path.cwd()).resolve()
129
+ project = find_project_root(start)
130
+ if project is None:
131
+ raise ConfigError(
132
+ f"no project root above {start}: expected a .hmd/ or .git directory. "
133
+ f"Pass --root to name the namespace root directly."
134
+ )
135
+
136
+ data, source = _read(project)
137
+ wiki = data.get("wiki", DEFAULT_WIKI)
138
+ if not isinstance(wiki, str):
139
+ raise ConfigError(f"`wiki` must be a string in {source}")
140
+
141
+ root = (project / wiki).resolve()
142
+ if not root.is_dir():
143
+ raise ConfigError(f"namespace root does not exist: {root}")
144
+
145
+ return Config(root=root, autodiscovery=_autodiscovery(data), mode=_mode(data), source=source)
146
+
147
+
148
+ def init(
149
+ project: Path | None = None,
150
+ wiki: str = DEFAULT_WIKI,
151
+ name: str | None = None,
152
+ provider: str = DEFAULT_PROVIDER,
153
+ force: bool = False,
154
+ ) -> InitResult:
155
+ """Write `.hmd/config.toml` under `project` and make the root it names.
156
+
157
+ `project` defaults to the working directory and `name` to that directory's
158
+ own name, so a bare `init` is a complete answer: the common case is a
159
+ project you are standing in, whose namespace should be called what the
160
+ folder is already called.
161
+
162
+ The namespace root is created alongside the config on purpose. `load`
163
+ refuses a `wiki` setting that points at nothing, so writing the file and
164
+ stopping there would leave a project whose very next command fails with a
165
+ message about a directory the author never asked for.
166
+
167
+ Refuses to replace an existing config unless `force`; overwriting one is
168
+ discarding settings somebody chose, and a marker directory already there is
169
+ the ordinary way to discover a project has been initialised before.
170
+ """
171
+ project = (project or Path.cwd()).expanduser()
172
+ if project.exists() and not project.is_dir():
173
+ raise ConfigError(f"project root is not a directory: {project}")
174
+
175
+ setting = _wiki_setting(wiki)
176
+ namespace = _namespace_name(project) if name is None else _checked_name(name)
177
+ if provider not in VALID_PROVIDERS:
178
+ raise ConfigError(f"provider must be one of {sorted(VALID_PROVIDERS)}, got {provider!r}")
179
+ enclosing = _enclosing_project(project)
180
+
181
+ marker = project / MARKER_DIR
182
+ config_path = marker / CONFIG_NAME
183
+ wiki_path = project / setting
184
+
185
+ # Everything that can fail is checked before anything is written. The
186
+ # command touches three paths, and a run that creates the marker and then
187
+ # trips over the wiki root leaves a project half-made — with a config file
188
+ # claiming a root that is not there, which is the one state `load` cannot
189
+ # explain to whoever finds it.
190
+ overwritten = config_path.is_file()
191
+ if overwritten and not force:
192
+ raise ConfigError(f"already initialised: {config_path} exists. Pass --force to replace it.")
193
+ if marker.exists() and not marker.is_dir():
194
+ raise ConfigError(f"{marker} exists and is not a directory")
195
+ if wiki_path.exists() and not wiki_path.is_dir():
196
+ raise ConfigError(f"wiki root exists and is not a directory: {wiki_path}")
197
+
198
+ created = frozenset(path for path in (project, config_path, wiki_path) if not path.exists())
199
+
200
+ try:
201
+ marker.mkdir(parents=True, exist_ok=True)
202
+ config_path.write_text(
203
+ CONFIG_TEMPLATE.format(
204
+ wiki=setting,
205
+ name=namespace,
206
+ provider=provider,
207
+ autodiscovery="true",
208
+ mode=DEFAULT_MODE,
209
+ ),
210
+ encoding="utf-8",
211
+ )
212
+ wiki_path.mkdir(parents=True, exist_ok=True)
213
+ except OSError as exc:
214
+ raise ConfigError(f"cannot initialise {project}: {exc}") from exc
215
+
216
+ return InitResult(
217
+ project=project.resolve(),
218
+ config=config_path.resolve(),
219
+ wiki=wiki_path.resolve(),
220
+ created=frozenset(path.resolve() for path in created),
221
+ name=namespace,
222
+ provider=provider,
223
+ derived_name=name is None,
224
+ overwritten=overwritten,
225
+ enclosing=enclosing,
226
+ )
227
+
228
+
229
+ def _wiki_setting(value: str) -> str:
230
+ """Normalise a `--wiki` argument into a TOML-safe relative path.
231
+
232
+ Rejected rather than escaped: absolute paths, `..` escapes, and the two
233
+ characters a TOML basic string would need escaping. A wiki root outside the
234
+ project it is configured from is not a narrower project, it is a config file
235
+ filed somewhere it does not describe.
236
+ """
237
+ text = value.strip().replace("\\", "/")
238
+ if not text:
239
+ raise ConfigError("wiki must name a directory relative to the project root")
240
+ if PurePosixPath(text).is_absolute() or PureWindowsPath(text).is_absolute():
241
+ raise ConfigError(f"wiki must be relative to the project root, got {value!r}")
242
+ if ".." in PurePosixPath(text).parts:
243
+ raise ConfigError(f"wiki must stay inside the project root, got {value!r}")
244
+ if '"' in text or any(ord(char) < 0x20 for char in text):
245
+ raise ConfigError(f"wiki contains characters a TOML string cannot hold: {value!r}")
246
+ return PurePosixPath(text).as_posix()
247
+
248
+
249
+ def _namespace_name(project: Path) -> str:
250
+ """Derive a namespace name from the project directory's own name.
251
+
252
+ Derivation is lenient where validation is strict, and the asymmetry is the
253
+ point. A folder called `My Notes` is not the author asking for anything, so
254
+ rewriting it to `My-Notes` is helpful; a `--name` of `My Notes` *is* a
255
+ request, and quietly returning something else would be answering a question
256
+ nobody asked. So this repairs, `_checked_name` refuses.
257
+ """
258
+ raw = project.resolve().name
259
+ slug = re.sub(r"[^A-Za-z0-9._-]+", "-", raw).strip("-._")
260
+ if not NAME_PATTERN.match(slug):
261
+ raise ConfigError(
262
+ f"cannot derive a namespace name from {raw!r}. Pass --name to give the project one."
263
+ )
264
+ return slug
265
+
266
+
267
+ def _checked_name(value: str) -> str:
268
+ """Validate a namespace name the caller asked for, never repair it."""
269
+ name = value.strip()
270
+ if not NAME_PATTERN.match(name):
271
+ raise ConfigError(
272
+ f"namespace name must start with a letter or digit and hold only "
273
+ f"letters, digits, dot, dash, or underscore, got {value!r}"
274
+ )
275
+ return name
276
+
277
+
278
+ def _enclosing_project(project: Path) -> Path | None:
279
+ """The nearest ancestor already carrying a `.hmd/`, if any.
280
+
281
+ Only the marker counts, not the `.git` fallback — every repository would
282
+ answer to that one, and nesting inside a repository is the normal case.
283
+ """
284
+ start = project.resolve()
285
+ for parent in start.parents:
286
+ if (parent / MARKER_DIR).is_dir():
287
+ return parent
288
+ return None
289
+
290
+
291
+ def _read(project: Path) -> tuple[dict, Path | None]:
292
+ path = project / MARKER_DIR / CONFIG_NAME
293
+ if not path.is_file():
294
+ return {}, None
295
+ try:
296
+ with path.open("rb") as handle:
297
+ return tomllib.load(handle), path
298
+ except (OSError, tomllib.TOMLDecodeError) as exc:
299
+ raise ConfigError(f"cannot read {path}: {exc}") from exc
300
+
301
+
302
+ def _discovery(data: dict) -> dict:
303
+ section = data.get("discovery", {})
304
+ return section if isinstance(section, dict) else {}
305
+
306
+
307
+ def _autodiscovery(data: dict) -> bool:
308
+ value = _discovery(data).get("autodiscovery", True)
309
+ if not isinstance(value, bool):
310
+ raise ConfigError("[discovery] autodiscovery must be a boolean")
311
+ return value
312
+
313
+
314
+ def _mode(data: dict) -> str:
315
+ value = _discovery(data).get("mode", DEFAULT_MODE)
316
+ if value not in VALID_MODES:
317
+ raise ConfigError(f"[discovery] mode must be one of {sorted(VALID_MODES)}, got {value!r}")
318
+ return value
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: hypermarkdown
3
- Version: 0.2.0
3
+ Version: 0.3.0
4
4
  Summary: A strict, machine-checkable markdown dialect for project knowledge bases.
5
5
  Author: Yauhen Yakimovich
6
6
  License-Expression: MIT
@@ -45,7 +45,7 @@ Dynamic: license-file
45
45
  **The Python implementation, and the `hmd` command**
46
46
 
47
47
  [![PyPI](https://img.shields.io/pypi/v/hypermarkdown.svg)](https://pypi.org/project/hypermarkdown/)
48
- [![Python versions](https://img.shields.io/pypi/pyversions/hypermarkdown.svg)](https://pypi.org/project/hypermarkdown/)
48
+ [![Python versions](https://img.shields.io/pypi/pyversions/hypermarkdown?color=blue&label=python)](https://pypi.org/project/hypermarkdown/)
49
49
  [![CI](https://github.com/ewiger/hypermarkdown/actions/workflows/ci.yml/badge.svg)](https://github.com/ewiger/hypermarkdown/actions/workflows/ci.yml)
50
50
  [![Documentation](https://img.shields.io/badge/docs-hypermarkdown.org-ffb300)](https://hypermarkdown.org/)
51
51
  [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://github.com/ewiger/hypermarkdown/blob/main/tools/hmd/LICENSE)
@@ -147,16 +147,36 @@ Every other key is yours, and nothing will inspect it.
147
147
 
148
148
  | Command | What it does |
149
149
  | --- | --- |
150
+ | `hmd init` | Write `.hmd/config.toml` and create the namespace root it names |
150
151
  | `hmd lint` | Parse, resolve, and report — `HMD001`–`HMD017`, text or JSON |
151
152
  | `hmd render` | Expand embeds and rewrite links, to flat markdown or HTML |
152
153
  | `hmd graph` | Dump the resolved link graph as JSON |
153
154
  | `hmd info` | Show the resolved root and discovery policy |
154
155
  | `hmd --version` | Print the installed version |
155
156
 
156
- Each takes `--root` to override the namespace root, which otherwise comes from
157
- the `wiki` setting in `.hmd/config.toml` (defaulting to `doc/wiki`). A `.hmd/`
158
- directory doubles as the project root marker, so any subtree can be
159
- self-contained.
157
+ Every command but `init` takes `--root` to override the namespace root, which
158
+ otherwise comes from the `wiki` setting in `.hmd/config.toml` (defaulting to
159
+ `doc/wiki`). A `.hmd/` directory doubles as the project root marker, so any
160
+ subtree can be self-contained.
161
+
162
+ ```bash
163
+ hmd init # here; the namespace is named after the directory
164
+ hmd init path/to/project --wiki notes --name shared
165
+ ```
166
+
167
+ `init` writes every setting at its default rather than leaving them implicit —
168
+ the file is where you find out which keys exist. It creates the wiki root
169
+ alongside the config, since a `wiki` setting pointing at nothing is an error
170
+ every later command reports. It refuses to replace a config it did not write;
171
+ `--force` overrides that.
172
+
173
+ The `[namespace]` section names this tree so another project can bind to it and
174
+ address a card as `name:card`. `--name` defaults to the project directory's own
175
+ name, repaired into that address form if it has to be — a folder called
176
+ `My Notes` becomes `My-Notes`. A `--name` you pass is validated instead of
177
+ repaired, because a name you typed is a request rather than a guess. Nothing
178
+ reads either key yet: binding is specified and not implemented, so the section
179
+ records intent.
160
180
 
161
181
  `hmd render --to markdown` is **one-way** on purpose. Flattening a card erases
162
182
  the embed boundary and the provenance of every link, which is right for
@@ -1,110 +0,0 @@
1
- """Root discovery and `.hmd/config.toml` (HMD-0001 §4, §5.3)."""
2
-
3
- from __future__ import annotations
4
-
5
- import tomllib
6
- from dataclasses import dataclass
7
- from pathlib import Path
8
-
9
- MARKER_DIR = ".hmd"
10
- CONFIG_NAME = "config.toml"
11
- DEFAULT_WIKI = "doc/wiki"
12
- DEFAULT_MODE = "both"
13
- VALID_MODES = frozenset({"both", "recursive"})
14
-
15
-
16
- @dataclass(frozen=True)
17
- class Config:
18
- """Resolved project configuration."""
19
-
20
- root: Path # the namespace root, absolute
21
- autodiscovery: bool = True
22
- mode: str = DEFAULT_MODE
23
- source: Path | None = None # the config file actually read, if any
24
-
25
-
26
- class ConfigError(Exception):
27
- """An unusable root or config file — exit code 2, not a lint finding."""
28
-
29
-
30
- def find_project_root(start: Path) -> Path | None:
31
- """Nearest ancestor holding `.hmd/`, else nearest holding `.git`."""
32
- start = start.resolve()
33
- candidates = [start, *start.parents] if start.is_dir() else list(start.parents)
34
- for parent in candidates:
35
- if (parent / MARKER_DIR).is_dir():
36
- return parent
37
- for parent in candidates:
38
- if (parent / ".git").exists():
39
- return parent
40
- return None
41
-
42
-
43
- def load(root_override: Path | None = None, start: Path | None = None) -> Config:
44
- """Resolve the namespace root and discovery policy.
45
-
46
- Absent `.hmd/config.toml` entirely, the root is `doc/wiki`, autodiscovery is
47
- on, and the mode is `both` — a tree with no configuration behaves the way a
48
- new author expects.
49
- """
50
- if root_override is not None:
51
- root = root_override.resolve()
52
- if not root.is_dir():
53
- raise ConfigError(f"root is not a directory: {root}")
54
- project = find_project_root(root) or root
55
- data, source = _read(project)
56
- return Config(
57
- root=root,
58
- autodiscovery=_autodiscovery(data),
59
- mode=_mode(data),
60
- source=source,
61
- )
62
-
63
- start = (start or Path.cwd()).resolve()
64
- project = find_project_root(start)
65
- if project is None:
66
- raise ConfigError(
67
- f"no project root above {start}: expected a .hmd/ or .git directory. "
68
- f"Pass --root to name the namespace root directly."
69
- )
70
-
71
- data, source = _read(project)
72
- wiki = data.get("wiki", DEFAULT_WIKI)
73
- if not isinstance(wiki, str):
74
- raise ConfigError(f"`wiki` must be a string in {source}")
75
-
76
- root = (project / wiki).resolve()
77
- if not root.is_dir():
78
- raise ConfigError(f"namespace root does not exist: {root}")
79
-
80
- return Config(root=root, autodiscovery=_autodiscovery(data), mode=_mode(data), source=source)
81
-
82
-
83
- def _read(project: Path) -> tuple[dict, Path | None]:
84
- path = project / MARKER_DIR / CONFIG_NAME
85
- if not path.is_file():
86
- return {}, None
87
- try:
88
- with path.open("rb") as handle:
89
- return tomllib.load(handle), path
90
- except (OSError, tomllib.TOMLDecodeError) as exc:
91
- raise ConfigError(f"cannot read {path}: {exc}") from exc
92
-
93
-
94
- def _discovery(data: dict) -> dict:
95
- section = data.get("discovery", {})
96
- return section if isinstance(section, dict) else {}
97
-
98
-
99
- def _autodiscovery(data: dict) -> bool:
100
- value = _discovery(data).get("autodiscovery", True)
101
- if not isinstance(value, bool):
102
- raise ConfigError("[discovery] autodiscovery must be a boolean")
103
- return value
104
-
105
-
106
- def _mode(data: dict) -> str:
107
- value = _discovery(data).get("mode", DEFAULT_MODE)
108
- if value not in VALID_MODES:
109
- raise ConfigError(f"[discovery] mode must be one of {sorted(VALID_MODES)}, got {value!r}")
110
- return value
File without changes
File without changes