wpsync 1.17.2__py3-none-any.whl
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.
- wpsync/__init__.py +3 -0
- wpsync/__main__.py +3 -0
- wpsync/cli.py +1479 -0
- wpsync/config.py +178 -0
- wpsync/documents.py +294 -0
- wpsync/editors.py +68 -0
- wpsync/markup/__init__.py +0 -0
- wpsync/markup/dom.py +371 -0
- wpsync/markup/markdown.py +526 -0
- wpsync/media.py +161 -0
- wpsync/posts.py +78 -0
- wpsync/pull.py +400 -0
- wpsync/push.py +288 -0
- wpsync/state.py +219 -0
- wpsync/storage.py +28 -0
- wpsync/sync.py +501 -0
- wpsync/trash.py +132 -0
- wpsync/wordpress/__init__.py +0 -0
- wpsync/wordpress/autop.py +114 -0
- wpsync/wordpress/client.py +233 -0
- wpsync/wordpress/content.py +602 -0
- wpsync/wordpress/remote.py +264 -0
- wpsync-1.17.2.dist-info/METADATA +148 -0
- wpsync-1.17.2.dist-info/RECORD +27 -0
- wpsync-1.17.2.dist-info/WHEEL +4 -0
- wpsync-1.17.2.dist-info/entry_points.txt +2 -0
- wpsync-1.17.2.dist-info/licenses/LICENSE +61 -0
wpsync/config.py
ADDED
|
@@ -0,0 +1,178 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import json
|
|
4
|
+
import os
|
|
5
|
+
import re
|
|
6
|
+
from dataclasses import dataclass, field, replace
|
|
7
|
+
from pathlib import Path
|
|
8
|
+
from typing import Any
|
|
9
|
+
|
|
10
|
+
from wpsync.editors import Editor
|
|
11
|
+
from wpsync.storage import write_text_atomic
|
|
12
|
+
|
|
13
|
+
CONFIG_VERSION = 1
|
|
14
|
+
PROFILE_NAME_PATTERN = re.compile(r"^[A-Za-z0-9][A-Za-z0-9._-]*$")
|
|
15
|
+
ENVIRONMENT_NAME_PATTERN = re.compile(r"^[A-Za-z_][A-Za-z0-9_]*$")
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
class ConfigurationError(ValueError):
|
|
19
|
+
"""Raised when configuration is invalid or cannot be decoded."""
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
def validate_profile_name(name: str) -> str:
|
|
23
|
+
if not PROFILE_NAME_PATTERN.fullmatch(name):
|
|
24
|
+
raise ConfigurationError(
|
|
25
|
+
"profile name must start with a letter or digit and contain "
|
|
26
|
+
"only letters, digits, '.', '_', or '-'"
|
|
27
|
+
)
|
|
28
|
+
return name
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
def validate_environment_name(name: str) -> str:
|
|
32
|
+
if not ENVIRONMENT_NAME_PATTERN.fullmatch(name):
|
|
33
|
+
raise ConfigurationError(f"'{name}' is not a valid environment-variable name")
|
|
34
|
+
return name
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
def default_password_env(profile_name: str) -> str:
|
|
38
|
+
stem = re.sub(r"[^A-Za-z0-9]", "_", profile_name).upper()
|
|
39
|
+
name = f"{stem}_WP_PASSWORD"
|
|
40
|
+
if not ENVIRONMENT_NAME_PATTERN.fullmatch(name):
|
|
41
|
+
raise ConfigurationError(
|
|
42
|
+
f"profile '{profile_name}' has no valid default password variable; "
|
|
43
|
+
"choose one with --password-env"
|
|
44
|
+
)
|
|
45
|
+
return name
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
def canonical_local_root(directory: str | Path) -> Path:
|
|
49
|
+
candidate = Path(directory).expanduser()
|
|
50
|
+
try:
|
|
51
|
+
resolved = candidate.resolve(strict=True)
|
|
52
|
+
except OSError as error:
|
|
53
|
+
raise ConfigurationError(f"local root does not exist: {candidate}") from error
|
|
54
|
+
if not resolved.is_dir():
|
|
55
|
+
raise ConfigurationError(f"local root is not a directory: {candidate}")
|
|
56
|
+
if resolved.parent == resolved:
|
|
57
|
+
raise ConfigurationError("local root cannot be the filesystem root")
|
|
58
|
+
return resolved
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
def _paths_overlap(first: Path, second: Path) -> bool:
|
|
62
|
+
return first == second or first in second.parents or second in first.parents
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
def _required_string(document: dict[str, Any], key: str, profile: str) -> str:
|
|
66
|
+
value = document.get(key)
|
|
67
|
+
if not isinstance(value, str) or not value.strip():
|
|
68
|
+
raise ConfigurationError(
|
|
69
|
+
f"profile '{profile}' {key} must be a non-empty string"
|
|
70
|
+
)
|
|
71
|
+
return value
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
@dataclass(frozen=True)
|
|
75
|
+
class Profile:
|
|
76
|
+
site: str
|
|
77
|
+
api_root: str
|
|
78
|
+
username: str
|
|
79
|
+
password_env: str
|
|
80
|
+
local_root: Path
|
|
81
|
+
|
|
82
|
+
def to_document(self) -> dict[str, str]:
|
|
83
|
+
return {
|
|
84
|
+
"site": self.site,
|
|
85
|
+
"api_root": self.api_root,
|
|
86
|
+
"username": self.username,
|
|
87
|
+
"password_env": self.password_env,
|
|
88
|
+
"local_root": os.fspath(self.local_root),
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
@classmethod
|
|
92
|
+
def from_document(cls, name: str, document: Any) -> Profile:
|
|
93
|
+
if not isinstance(document, dict):
|
|
94
|
+
raise ConfigurationError(f"profile '{name}' must be an object")
|
|
95
|
+
local_root = Path(_required_string(document, "local_root", name))
|
|
96
|
+
if not local_root.is_absolute():
|
|
97
|
+
raise ConfigurationError(f"profile '{name}' local_root must be absolute")
|
|
98
|
+
return cls(
|
|
99
|
+
site=_required_string(document, "site", name),
|
|
100
|
+
api_root=_required_string(document, "api_root", name),
|
|
101
|
+
username=_required_string(document, "username", name),
|
|
102
|
+
password_env=validate_environment_name(
|
|
103
|
+
_required_string(document, "password_env", name)
|
|
104
|
+
),
|
|
105
|
+
local_root=local_root,
|
|
106
|
+
)
|
|
107
|
+
|
|
108
|
+
|
|
109
|
+
@dataclass
|
|
110
|
+
class Configuration:
|
|
111
|
+
profiles: dict[str, Profile] = field(default_factory=dict)
|
|
112
|
+
editor: Editor | None = None
|
|
113
|
+
|
|
114
|
+
def add(self, name: str, profile: Profile) -> None:
|
|
115
|
+
if name in self.profiles:
|
|
116
|
+
raise ConfigurationError(f"profile '{name}' already exists")
|
|
117
|
+
self.check_root(name, profile.local_root)
|
|
118
|
+
self.profiles[name] = profile
|
|
119
|
+
|
|
120
|
+
def remap(self, name: str, local_root: Path) -> Profile:
|
|
121
|
+
self.check_root(name, local_root)
|
|
122
|
+
self.profiles[name] = replace(self.profiles[name], local_root=local_root)
|
|
123
|
+
return self.profiles[name]
|
|
124
|
+
|
|
125
|
+
def check_root(self, name: str, root: Path) -> None:
|
|
126
|
+
for other_name, other in self.profiles.items():
|
|
127
|
+
if other_name != name and _paths_overlap(root, other.local_root):
|
|
128
|
+
raise ConfigurationError(
|
|
129
|
+
f"local root '{root}' overlaps profile '{other_name}' "
|
|
130
|
+
f"at '{other.local_root}'"
|
|
131
|
+
)
|
|
132
|
+
|
|
133
|
+
def profile_for_path(self, path: Path) -> tuple[str, Profile] | None:
|
|
134
|
+
for name, profile in self.profiles.items():
|
|
135
|
+
if path == profile.local_root or profile.local_root in path.parents:
|
|
136
|
+
return name, profile
|
|
137
|
+
return None
|
|
138
|
+
|
|
139
|
+
|
|
140
|
+
class ConfigurationStore:
|
|
141
|
+
def __init__(self, path: Path | None = None) -> None:
|
|
142
|
+
self.path = path or Path.home() / ".wpsync" / "config.json"
|
|
143
|
+
|
|
144
|
+
def load(self) -> Configuration:
|
|
145
|
+
if not self.path.exists():
|
|
146
|
+
return Configuration()
|
|
147
|
+
try:
|
|
148
|
+
document = json.loads(self.path.read_text(encoding="utf-8"))
|
|
149
|
+
except (OSError, json.JSONDecodeError) as error:
|
|
150
|
+
raise ConfigurationError(f"cannot read {self.path}: {error}") from error
|
|
151
|
+
if not isinstance(document, dict) or document.get("version") != CONFIG_VERSION:
|
|
152
|
+
raise ConfigurationError(
|
|
153
|
+
f"{self.path} is not a version {CONFIG_VERSION} wpsync configuration"
|
|
154
|
+
)
|
|
155
|
+
profiles = document.get("profiles", {})
|
|
156
|
+
if not isinstance(profiles, dict):
|
|
157
|
+
raise ConfigurationError(f"{self.path}: profiles must be an object")
|
|
158
|
+
editor = document.get("editor")
|
|
159
|
+
if editor is not None and editor not in set(Editor):
|
|
160
|
+
raise ConfigurationError(f"{self.path}: unknown editor {editor!r}")
|
|
161
|
+
configuration = Configuration(editor=Editor(editor) if editor else None)
|
|
162
|
+
for name, profile in profiles.items():
|
|
163
|
+
configuration.add(
|
|
164
|
+
validate_profile_name(name), Profile.from_document(name, profile)
|
|
165
|
+
)
|
|
166
|
+
return configuration
|
|
167
|
+
|
|
168
|
+
def save(self, configuration: Configuration) -> None:
|
|
169
|
+
document: dict[str, Any] = {"version": CONFIG_VERSION}
|
|
170
|
+
if configuration.editor is not None:
|
|
171
|
+
document["editor"] = configuration.editor.value
|
|
172
|
+
document["profiles"] = {
|
|
173
|
+
name: profile.to_document()
|
|
174
|
+
for name, profile in sorted(configuration.profiles.items())
|
|
175
|
+
}
|
|
176
|
+
self.path.parent.mkdir(mode=0o700, parents=True, exist_ok=True)
|
|
177
|
+
payload = json.dumps(document, indent=2) + "\n"
|
|
178
|
+
write_text_atomic(self.path, payload, mode=0o600)
|
wpsync/documents.py
ADDED
|
@@ -0,0 +1,294 @@
|
|
|
1
|
+
"""Local post files: Markdown with YAML frontmatter.
|
|
2
|
+
|
|
3
|
+
WPSync owns the synchronized fields and rewrites them canonically. Any other
|
|
4
|
+
frontmatter entry is kept byte for byte, including its comments, and is never
|
|
5
|
+
sent to the blog.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
import hashlib
|
|
11
|
+
import json
|
|
12
|
+
import os
|
|
13
|
+
from dataclasses import dataclass
|
|
14
|
+
from datetime import UTC, datetime
|
|
15
|
+
from pathlib import Path, PurePosixPath
|
|
16
|
+
|
|
17
|
+
import yaml
|
|
18
|
+
from yaml.nodes import MappingNode, Node, ScalarNode, SequenceNode
|
|
19
|
+
|
|
20
|
+
from wpsync.posts import Post, PostStatus
|
|
21
|
+
from wpsync.storage import write_text_atomic
|
|
22
|
+
|
|
23
|
+
CONTENT_DIR = "content"
|
|
24
|
+
TRASH_DIR = ".trash"
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
def display_path(path: str | PurePosixPath) -> str:
|
|
28
|
+
"""A path as output shows it: under content/, which goes without saying."""
|
|
29
|
+
path = PurePosixPath(path)
|
|
30
|
+
if path.parts[:1] == (CONTENT_DIR,):
|
|
31
|
+
path = path.relative_to(CONTENT_DIR)
|
|
32
|
+
return str(path)
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
FENCE = "---"
|
|
36
|
+
FIELDS = ("id", "title", "slug", "date", "status", "categories", "tags")
|
|
37
|
+
EXAMPLE_HEADER = "---\ntitle: My post\nstatus: public\n---"
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
class DocumentError(ValueError):
|
|
41
|
+
"""Raised when a post file cannot be read as a WPSync document."""
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
@dataclass(frozen=True)
|
|
45
|
+
class Document:
|
|
46
|
+
post_id: str | None
|
|
47
|
+
post: Post
|
|
48
|
+
extra: tuple[tuple[str, str], ...] = ()
|
|
49
|
+
"""Unsynchronized frontmatter entries as (key, original text)."""
|
|
50
|
+
|
|
51
|
+
@property
|
|
52
|
+
def extra_keys(self) -> tuple[str, ...]:
|
|
53
|
+
return tuple(key for key, _ in self.extra)
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
@dataclass(frozen=True)
|
|
57
|
+
class LocalDocument:
|
|
58
|
+
path: Path
|
|
59
|
+
"""Relative to the profile's local root."""
|
|
60
|
+
document: Document
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
def _scalar(node: Node, key: str) -> str:
|
|
64
|
+
if not isinstance(node, ScalarNode):
|
|
65
|
+
raise DocumentError(f"'{key}' must be a single value")
|
|
66
|
+
return node.value
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
def _terms(node: Node, key: str) -> tuple[str, ...]:
|
|
70
|
+
if isinstance(node, ScalarNode) and node.value == "":
|
|
71
|
+
return ()
|
|
72
|
+
if not isinstance(node, SequenceNode):
|
|
73
|
+
raise DocumentError(f"'{key}' must be a list, such as {key}: [One, Two]")
|
|
74
|
+
names = [_scalar(item, key).strip() for item in node.value]
|
|
75
|
+
if not all(names):
|
|
76
|
+
raise DocumentError(f"'{key}' cannot contain empty names")
|
|
77
|
+
return tuple(sorted(set(names)))
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
def _date(value: str) -> datetime | None:
|
|
81
|
+
if value == "":
|
|
82
|
+
return None
|
|
83
|
+
try:
|
|
84
|
+
parsed = datetime.fromisoformat(value)
|
|
85
|
+
except ValueError as error:
|
|
86
|
+
raise DocumentError(
|
|
87
|
+
f"date '{value}' is not a date, such as 2026-10-01 or 2026-10-01 09:30"
|
|
88
|
+
) from error
|
|
89
|
+
# A date without a time zone is in this computer's; a missing time is 00:00.
|
|
90
|
+
return parsed if parsed.tzinfo is not None else parsed.astimezone()
|
|
91
|
+
|
|
92
|
+
|
|
93
|
+
def format_date(date: datetime) -> str:
|
|
94
|
+
"""A date in this computer's time zone, in its shortest exact form."""
|
|
95
|
+
local = date.astimezone()
|
|
96
|
+
if local.replace(tzinfo=None).astimezone() != date:
|
|
97
|
+
# A time the clocks pass twice keeps its offset to say which one.
|
|
98
|
+
return local.isoformat(sep=" ")
|
|
99
|
+
if local.microsecond:
|
|
100
|
+
return local.replace(tzinfo=None).isoformat(sep=" ")
|
|
101
|
+
if local.second:
|
|
102
|
+
return f"{local:%Y-%m-%d %H:%M:%S}"
|
|
103
|
+
if local.hour or local.minute:
|
|
104
|
+
return f"{local:%Y-%m-%d %H:%M}"
|
|
105
|
+
return f"{local:%Y-%m-%d}"
|
|
106
|
+
|
|
107
|
+
|
|
108
|
+
def _status(value: str) -> PostStatus:
|
|
109
|
+
if value == "":
|
|
110
|
+
return PostStatus.PRIVATE
|
|
111
|
+
try:
|
|
112
|
+
return PostStatus(value)
|
|
113
|
+
except ValueError as error:
|
|
114
|
+
choices = ", ".join(status.value for status in PostStatus)
|
|
115
|
+
raise DocumentError(f"status '{value}' must be one of: {choices}") from error
|
|
116
|
+
|
|
117
|
+
|
|
118
|
+
def _line_end(text: str, index: int) -> int:
|
|
119
|
+
if index > 0 and text[index - 1] == "\n":
|
|
120
|
+
return index
|
|
121
|
+
newline = text.find("\n", index)
|
|
122
|
+
return len(text) if newline == -1 else newline + 1
|
|
123
|
+
|
|
124
|
+
|
|
125
|
+
def _split(text: str) -> tuple[str, str]:
|
|
126
|
+
lines = text.split("\n")
|
|
127
|
+
if lines[0] != FENCE:
|
|
128
|
+
raise DocumentError(
|
|
129
|
+
f"missing frontmatter; start the file with a header such as:\n"
|
|
130
|
+
f"{EXAMPLE_HEADER}"
|
|
131
|
+
)
|
|
132
|
+
for index, line in enumerate(lines[1:], start=1):
|
|
133
|
+
if line in (FENCE, "..."):
|
|
134
|
+
return "\n".join(lines[1:index]) + "\n", "\n".join(lines[index + 1 :])
|
|
135
|
+
raise DocumentError("frontmatter is not closed with a '---' line")
|
|
136
|
+
|
|
137
|
+
|
|
138
|
+
def parse_document(text: str) -> Document:
|
|
139
|
+
text = text.removeprefix("").replace("\r\n", "\n")
|
|
140
|
+
header, body = _split(text)
|
|
141
|
+
try:
|
|
142
|
+
root = yaml.compose(header, Loader=yaml.BaseLoader)
|
|
143
|
+
except yaml.YAMLError as error:
|
|
144
|
+
raise DocumentError(f"frontmatter is not valid YAML: {error}") from error
|
|
145
|
+
if root is None:
|
|
146
|
+
entries = []
|
|
147
|
+
elif isinstance(root, MappingNode):
|
|
148
|
+
entries = root.value
|
|
149
|
+
else:
|
|
150
|
+
raise DocumentError("frontmatter must be a set of 'key: value' lines")
|
|
151
|
+
values: dict[str, Node] = {}
|
|
152
|
+
extra: list[tuple[str, str]] = []
|
|
153
|
+
seen: set[str] = set()
|
|
154
|
+
start = 0
|
|
155
|
+
for index, (key_node, value_node) in enumerate(entries):
|
|
156
|
+
key = _scalar(key_node, "frontmatter key")
|
|
157
|
+
last = index == len(entries) - 1
|
|
158
|
+
end = len(header) if last else _line_end(header, value_node.end_mark.index)
|
|
159
|
+
if key in seen:
|
|
160
|
+
raise DocumentError(f"'{key}' appears more than once")
|
|
161
|
+
seen.add(key)
|
|
162
|
+
if key in FIELDS:
|
|
163
|
+
values[key] = value_node
|
|
164
|
+
else:
|
|
165
|
+
extra.append((key, header[start:end]))
|
|
166
|
+
start = end
|
|
167
|
+
post_id = _scalar(values["id"], "id").strip() if "id" in values else ""
|
|
168
|
+
post = Post(
|
|
169
|
+
title=_scalar(values["title"], "title") if "title" in values else "",
|
|
170
|
+
slug=_scalar(values["slug"], "slug").strip() if "slug" in values else "",
|
|
171
|
+
date=_date(_scalar(values["date"], "date").strip())
|
|
172
|
+
if "date" in values
|
|
173
|
+
else None,
|
|
174
|
+
status=_status(_scalar(values["status"], "status").strip())
|
|
175
|
+
if "status" in values
|
|
176
|
+
else PostStatus.PRIVATE,
|
|
177
|
+
categories=_terms(values["categories"], "categories")
|
|
178
|
+
if "categories" in values
|
|
179
|
+
else (),
|
|
180
|
+
tags=_terms(values["tags"], "tags") if "tags" in values else (),
|
|
181
|
+
body=body.strip("\n"),
|
|
182
|
+
)
|
|
183
|
+
return Document(post_id or None, post, tuple(extra))
|
|
184
|
+
|
|
185
|
+
|
|
186
|
+
def _yaml_value(key: str, value: object) -> str:
|
|
187
|
+
return yaml.safe_dump(
|
|
188
|
+
{key: value}, allow_unicode=True, sort_keys=False, width=1_000_000
|
|
189
|
+
)
|
|
190
|
+
|
|
191
|
+
|
|
192
|
+
def serialize_document(document: Document) -> str:
|
|
193
|
+
post = document.post
|
|
194
|
+
lines = []
|
|
195
|
+
if document.post_id is not None:
|
|
196
|
+
if document.post_id.isdigit():
|
|
197
|
+
lines.append(f"id: {document.post_id}\n")
|
|
198
|
+
else:
|
|
199
|
+
lines.append(_yaml_value("id", document.post_id))
|
|
200
|
+
lines.append(_yaml_value("title", post.title))
|
|
201
|
+
if post.slug:
|
|
202
|
+
lines.append(_yaml_value("slug", post.slug))
|
|
203
|
+
if post.date is not None:
|
|
204
|
+
lines.append(f"date: {format_date(post.date)}\n")
|
|
205
|
+
lines.append(f"status: {post.status}\n")
|
|
206
|
+
lines.append(_yaml_value("categories", list(post.categories)))
|
|
207
|
+
lines.append(_yaml_value("tags", list(post.tags)))
|
|
208
|
+
for _, text in document.extra:
|
|
209
|
+
lines.append(text if text.endswith("\n") else text + "\n")
|
|
210
|
+
header = "".join(lines)
|
|
211
|
+
body = f"\n{post.body}\n" if post.body else ""
|
|
212
|
+
return f"{FENCE}\n{header}{FENCE}\n{body}"
|
|
213
|
+
|
|
214
|
+
|
|
215
|
+
def _load(path: Path) -> Document:
|
|
216
|
+
try:
|
|
217
|
+
text = path.read_text(encoding="utf-8")
|
|
218
|
+
except (OSError, UnicodeDecodeError) as error:
|
|
219
|
+
raise DocumentError(f"cannot read: {error}") from error
|
|
220
|
+
return parse_document(text)
|
|
221
|
+
|
|
222
|
+
|
|
223
|
+
def write_document(path: Path, document: Document) -> None:
|
|
224
|
+
write_text_atomic(path, serialize_document(document), mode=0o644)
|
|
225
|
+
|
|
226
|
+
|
|
227
|
+
def _post_files(posts_dir: Path) -> list[Path]:
|
|
228
|
+
files = []
|
|
229
|
+
for directory, subdirectories, names in os.walk(posts_dir):
|
|
230
|
+
subdirectories[:] = [
|
|
231
|
+
name for name in subdirectories if not name.startswith(".")
|
|
232
|
+
]
|
|
233
|
+
files.extend(
|
|
234
|
+
Path(directory, name)
|
|
235
|
+
for name in names
|
|
236
|
+
if name.endswith(".md") and not name.startswith(".")
|
|
237
|
+
)
|
|
238
|
+
return sorted(files)
|
|
239
|
+
|
|
240
|
+
|
|
241
|
+
def _read_folder(root: Path, folder: str) -> tuple[list[LocalDocument], list[str]]:
|
|
242
|
+
documents: list[LocalDocument] = []
|
|
243
|
+
problems: list[str] = []
|
|
244
|
+
for path in _post_files(root / folder):
|
|
245
|
+
relative = path.relative_to(root)
|
|
246
|
+
try:
|
|
247
|
+
documents.append(LocalDocument(relative, _load(path)))
|
|
248
|
+
except DocumentError as error:
|
|
249
|
+
problems.append(f"{relative}: {error}")
|
|
250
|
+
return documents, problems
|
|
251
|
+
|
|
252
|
+
|
|
253
|
+
def scan_trash(root: Path) -> list[LocalDocument]:
|
|
254
|
+
"""Read the post files in the profile folder's trash."""
|
|
255
|
+
documents, problems = _read_folder(root, TRASH_DIR)
|
|
256
|
+
if problems:
|
|
257
|
+
raise DocumentError("\n".join(problems))
|
|
258
|
+
return documents
|
|
259
|
+
|
|
260
|
+
|
|
261
|
+
def scan_documents(root: Path) -> list[LocalDocument]:
|
|
262
|
+
"""Read every post file under the root, reporting all problems together."""
|
|
263
|
+
documents, problems = _read_folder(root, CONTENT_DIR)
|
|
264
|
+
users: dict[str, list[Path]] = {}
|
|
265
|
+
for item in documents:
|
|
266
|
+
if item.document.post_id is not None:
|
|
267
|
+
users.setdefault(item.document.post_id, []).append(item.path)
|
|
268
|
+
for post_id, paths in sorted(users.items()):
|
|
269
|
+
if len(paths) > 1:
|
|
270
|
+
listed = ", ".join(str(path) for path in paths)
|
|
271
|
+
problems.append(
|
|
272
|
+
f"post id {post_id} is used by more than one file: {listed}"
|
|
273
|
+
)
|
|
274
|
+
if problems:
|
|
275
|
+
raise DocumentError("\n".join(problems))
|
|
276
|
+
return documents
|
|
277
|
+
|
|
278
|
+
|
|
279
|
+
def body_checksum(post: Post) -> str:
|
|
280
|
+
return hashlib.sha256(post.body.encode()).hexdigest()
|
|
281
|
+
|
|
282
|
+
|
|
283
|
+
def fields_checksum(post: Post) -> str:
|
|
284
|
+
"""One checksum over every synchronized header field."""
|
|
285
|
+
fields = {
|
|
286
|
+
"title": post.title,
|
|
287
|
+
"slug": post.slug,
|
|
288
|
+
"date": post.date.astimezone(UTC).isoformat() if post.date else None,
|
|
289
|
+
"status": post.status.value,
|
|
290
|
+
"categories": list(post.categories),
|
|
291
|
+
"tags": list(post.tags),
|
|
292
|
+
}
|
|
293
|
+
encoded = json.dumps(fields, sort_keys=True, ensure_ascii=False)
|
|
294
|
+
return hashlib.sha256(encoded.encode()).hexdigest()
|
wpsync/editors.py
ADDED
|
@@ -0,0 +1,68 @@
|
|
|
1
|
+
"""Opening post files in the user's Markdown editor."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import shutil
|
|
6
|
+
import subprocess
|
|
7
|
+
import sys
|
|
8
|
+
from enum import StrEnum
|
|
9
|
+
from pathlib import Path
|
|
10
|
+
from urllib.parse import quote
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
class EditorError(Exception):
|
|
14
|
+
"""No editor is chosen, or the chosen one cannot open the file."""
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
class Editor(StrEnum):
|
|
18
|
+
OBSIDIAN = "obsidian"
|
|
19
|
+
VSCODE = "vscode"
|
|
20
|
+
|
|
21
|
+
@property
|
|
22
|
+
def label(self) -> str:
|
|
23
|
+
return {Editor.OBSIDIAN: "Obsidian", Editor.VSCODE: "VS Code"}[self]
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
URL_OPENER = {"darwin": ["open"], "win32": ["cmd", "/c", "start", ""]}.get(
|
|
27
|
+
sys.platform, ["xdg-open"]
|
|
28
|
+
)
|
|
29
|
+
# macOS apps that open the same arguments when their command is not installed.
|
|
30
|
+
MAC_APPS = {"code": "Visual Studio Code"}
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
def editor_command(editor: Editor, root: Path, file: Path) -> list[str]:
|
|
34
|
+
"""The command that opens a post file of the profile folder in an editor."""
|
|
35
|
+
if editor is Editor.VSCODE:
|
|
36
|
+
# With the folder as its workspace, VS Code reuses one window per blog.
|
|
37
|
+
return ["code", str(root), str(file)]
|
|
38
|
+
if not any((folder / ".obsidian").is_dir() for folder in file.parents):
|
|
39
|
+
raise EditorError(
|
|
40
|
+
f"{file} is not in an Obsidian vault; open {root} as a vault in "
|
|
41
|
+
"Obsidian first"
|
|
42
|
+
)
|
|
43
|
+
return [*URL_OPENER, "obsidian://open?path=" + quote(str(file), safe="")]
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
def launch(command: list[str]) -> None:
|
|
47
|
+
program, *arguments = command
|
|
48
|
+
# which() also finds Windows .cmd files, such as VS Code's code.cmd.
|
|
49
|
+
executable = shutil.which(program)
|
|
50
|
+
if executable is not None:
|
|
51
|
+
_run([executable, *arguments], f"'{program}'")
|
|
52
|
+
elif sys.platform == "darwin" and program in MAC_APPS:
|
|
53
|
+
app = MAC_APPS[program]
|
|
54
|
+
_run(
|
|
55
|
+
["open", "-a", app, *arguments],
|
|
56
|
+
f"'{program}' is not on your PATH, and opening {app}",
|
|
57
|
+
)
|
|
58
|
+
else:
|
|
59
|
+
raise EditorError(f"'{program}' is not on your PATH")
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
def _run(command: list[str], name: str) -> None:
|
|
63
|
+
try:
|
|
64
|
+
subprocess.run(command, check=True)
|
|
65
|
+
except subprocess.CalledProcessError as error:
|
|
66
|
+
raise EditorError(
|
|
67
|
+
f"{name} failed with exit status {error.returncode}"
|
|
68
|
+
) from error
|
|
File without changes
|