wpsync 1.2.1__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.
Potentially problematic release.
This version of wpsync might be problematic. Click here for more details.
- wpsync/__init__.py +3 -0
- wpsync/__main__.py +3 -0
- wpsync/cli.py +740 -0
- wpsync/config.py +173 -0
- wpsync/documents.py +258 -0
- wpsync/markup/__init__.py +0 -0
- wpsync/markup/dom.py +313 -0
- wpsync/markup/markdown.py +526 -0
- wpsync/media.py +92 -0
- wpsync/posts.py +76 -0
- wpsync/pull.py +324 -0
- wpsync/state.py +177 -0
- wpsync/storage.py +28 -0
- wpsync/sync.py +260 -0
- wpsync/wordpress/__init__.py +0 -0
- wpsync/wordpress/autop.py +114 -0
- wpsync/wordpress/client.py +208 -0
- wpsync/wordpress/content.py +565 -0
- wpsync/wordpress/remote.py +100 -0
- wpsync-1.2.1.dist-info/METADATA +312 -0
- wpsync-1.2.1.dist-info/RECORD +24 -0
- wpsync-1.2.1.dist-info/WHEEL +4 -0
- wpsync-1.2.1.dist-info/entry_points.txt +2 -0
- wpsync-1.2.1.dist-info/licenses/LICENSE +61 -0
wpsync/cli.py
ADDED
|
@@ -0,0 +1,740 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import argparse
|
|
4
|
+
import os
|
|
5
|
+
import sys
|
|
6
|
+
from collections import Counter
|
|
7
|
+
from collections.abc import Mapping, Sequence
|
|
8
|
+
from pathlib import Path
|
|
9
|
+
from typing import TextIO
|
|
10
|
+
|
|
11
|
+
import httpx
|
|
12
|
+
|
|
13
|
+
from wpsync import __version__
|
|
14
|
+
from wpsync.config import (
|
|
15
|
+
Configuration,
|
|
16
|
+
ConfigurationError,
|
|
17
|
+
ConfigurationStore,
|
|
18
|
+
Profile,
|
|
19
|
+
canonical_local_root,
|
|
20
|
+
default_password_env,
|
|
21
|
+
validate_environment_name,
|
|
22
|
+
validate_profile_name,
|
|
23
|
+
)
|
|
24
|
+
from wpsync.documents import DocumentError, LocalDocument, scan_documents
|
|
25
|
+
from wpsync.posts import PostStatus, PostSummary, RemoteState
|
|
26
|
+
from wpsync.pull import Puller
|
|
27
|
+
from wpsync.state import StateError, read_media, read_records
|
|
28
|
+
from wpsync.sync import Action, DiffEntry, SelectionError, compare, select
|
|
29
|
+
from wpsync.wordpress.client import WordPressClient, WordPressError, discover_api_root
|
|
30
|
+
from wpsync.wordpress.remote import WordPressRemote
|
|
31
|
+
|
|
32
|
+
COMMANDS = (
|
|
33
|
+
"create",
|
|
34
|
+
"connect",
|
|
35
|
+
"map",
|
|
36
|
+
"remove",
|
|
37
|
+
"root",
|
|
38
|
+
"profile",
|
|
39
|
+
"profiles",
|
|
40
|
+
"ls",
|
|
41
|
+
"diff",
|
|
42
|
+
"pull",
|
|
43
|
+
)
|
|
44
|
+
PROFILE_AWARE_COMMANDS = frozenset(
|
|
45
|
+
{"connect", "map", "remove", "root", "profile", "ls", "diff", "pull"}
|
|
46
|
+
)
|
|
47
|
+
RESET = "\033[0m"
|
|
48
|
+
MARKER_COLORS = {
|
|
49
|
+
"+": "\033[38;5;82m",
|
|
50
|
+
"~": "\033[33m",
|
|
51
|
+
"-": "\033[31m",
|
|
52
|
+
"?": "\033[35m",
|
|
53
|
+
"l": "\033[38;5;51m",
|
|
54
|
+
"r": "\033[38;5;30m",
|
|
55
|
+
}
|
|
56
|
+
LEGEND = (
|
|
57
|
+
("+ l", "new local post; push creates it, or links it to the post it matches"),
|
|
58
|
+
("~ l", "changed locally; push updates the post"),
|
|
59
|
+
("- l", "deleted locally; WordPress keeps the post"),
|
|
60
|
+
("? ", "conflict or ambiguous match; push stops and asks"),
|
|
61
|
+
("= ", "unchanged (shown with -a)"),
|
|
62
|
+
)
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
class _Session:
|
|
66
|
+
"""The process context a command runs in."""
|
|
67
|
+
|
|
68
|
+
def __init__(
|
|
69
|
+
self,
|
|
70
|
+
store: ConfigurationStore,
|
|
71
|
+
stdin: TextIO,
|
|
72
|
+
stdout: TextIO,
|
|
73
|
+
environ: Mapping[str, str],
|
|
74
|
+
transport: httpx.BaseTransport | None,
|
|
75
|
+
) -> None:
|
|
76
|
+
self.store = store
|
|
77
|
+
self.stdin = stdin
|
|
78
|
+
self.stdout = stdout
|
|
79
|
+
self.environ = environ
|
|
80
|
+
self.transport = transport
|
|
81
|
+
|
|
82
|
+
def ask(self, prompt: str) -> str:
|
|
83
|
+
print(prompt, end="", file=self.stdout, flush=True)
|
|
84
|
+
return self.stdin.readline().strip()
|
|
85
|
+
|
|
86
|
+
def confirm(self, prompt: str, *, default: bool) -> bool:
|
|
87
|
+
"""Ask a yes/no question. End of input counts as No."""
|
|
88
|
+
while True:
|
|
89
|
+
print(prompt, end="", file=self.stdout, flush=True)
|
|
90
|
+
answer = self.stdin.readline()
|
|
91
|
+
if answer == "":
|
|
92
|
+
print(file=self.stdout)
|
|
93
|
+
return False
|
|
94
|
+
normalized = answer.strip().lower()
|
|
95
|
+
if normalized in {"y", "yes"}:
|
|
96
|
+
return True
|
|
97
|
+
if normalized in {"n", "no"}:
|
|
98
|
+
return False
|
|
99
|
+
if normalized == "":
|
|
100
|
+
return default
|
|
101
|
+
print("Please answer yes or no.", file=self.stdout)
|
|
102
|
+
|
|
103
|
+
def password(self, profile: Profile) -> str:
|
|
104
|
+
password = self.environ.get(profile.password_env)
|
|
105
|
+
if not password:
|
|
106
|
+
raise ConfigurationError(
|
|
107
|
+
f"set {profile.password_env} to an Application Password for "
|
|
108
|
+
f"'{profile.username}' on {profile.site} (create one in WordPress "
|
|
109
|
+
"under Users > Profile > Application Passwords)"
|
|
110
|
+
)
|
|
111
|
+
return password
|
|
112
|
+
|
|
113
|
+
|
|
114
|
+
def _resolve_command(value: str) -> str:
|
|
115
|
+
if value in COMMANDS:
|
|
116
|
+
return value
|
|
117
|
+
matches = [command for command in COMMANDS if command.startswith(value)]
|
|
118
|
+
if not matches:
|
|
119
|
+
raise ConfigurationError(f"unknown command '{value}'")
|
|
120
|
+
if len(matches) > 1:
|
|
121
|
+
raise ConfigurationError(f"ambiguous command '{value}': {', '.join(matches)}")
|
|
122
|
+
return matches[0]
|
|
123
|
+
|
|
124
|
+
|
|
125
|
+
def _could_be_command(value: str) -> bool:
|
|
126
|
+
return any(command.startswith(value) for command in COMMANDS)
|
|
127
|
+
|
|
128
|
+
|
|
129
|
+
def _resolve_invocation(arguments: list[str]) -> tuple[list[str], str | None]:
|
|
130
|
+
"""Expand command prefixes and split off a leading profile override."""
|
|
131
|
+
if not arguments or arguments[0].startswith("-"):
|
|
132
|
+
return arguments, None
|
|
133
|
+
first = arguments[0]
|
|
134
|
+
if (
|
|
135
|
+
first not in COMMANDS
|
|
136
|
+
and len(arguments) > 1
|
|
137
|
+
and not arguments[1].startswith("-")
|
|
138
|
+
and _could_be_command(arguments[1])
|
|
139
|
+
):
|
|
140
|
+
command = _resolve_command(arguments[1])
|
|
141
|
+
if command not in PROFILE_AWARE_COMMANDS:
|
|
142
|
+
raise ConfigurationError(
|
|
143
|
+
f"profile prefix '{first}' cannot be used with '{command}'"
|
|
144
|
+
)
|
|
145
|
+
return [command, *arguments[2:]], validate_profile_name(first)
|
|
146
|
+
return [_resolve_command(first), *arguments[1:]], None
|
|
147
|
+
|
|
148
|
+
|
|
149
|
+
def _profile_argument(parser: argparse.ArgumentParser) -> None:
|
|
150
|
+
parser.add_argument(
|
|
151
|
+
"profile_name",
|
|
152
|
+
nargs="?",
|
|
153
|
+
metavar="PROFILE",
|
|
154
|
+
help="profile; inferred from the current directory when omitted",
|
|
155
|
+
)
|
|
156
|
+
|
|
157
|
+
|
|
158
|
+
def build_parser() -> argparse.ArgumentParser:
|
|
159
|
+
parser = argparse.ArgumentParser(
|
|
160
|
+
prog="wpsync",
|
|
161
|
+
description=(
|
|
162
|
+
"Manage WordPress posts as local Markdown files. Run commands inside "
|
|
163
|
+
"a mapped profile folder, or prefix a command with a profile name. "
|
|
164
|
+
"Commands may be shortened to any unique prefix."
|
|
165
|
+
),
|
|
166
|
+
)
|
|
167
|
+
parser.add_argument("-v", "--version", action="version", version=__version__)
|
|
168
|
+
parser.add_argument(
|
|
169
|
+
"--legend", action="store_true", help="show diff symbols and exit"
|
|
170
|
+
)
|
|
171
|
+
subparsers = parser.add_subparsers(dest="command")
|
|
172
|
+
|
|
173
|
+
create = subparsers.add_parser(
|
|
174
|
+
"create",
|
|
175
|
+
help="create a profile that maps a local folder to a blog",
|
|
176
|
+
description=(
|
|
177
|
+
"Create a profile, verify the Application Password from its "
|
|
178
|
+
"environment variable, and list the blog's posts. Without "
|
|
179
|
+
"--local-root, offer the current directory."
|
|
180
|
+
),
|
|
181
|
+
)
|
|
182
|
+
create.add_argument("profile_name", metavar="PROFILE", help="new profile name")
|
|
183
|
+
create.add_argument(
|
|
184
|
+
"--site", required=True, help="blog address, such as https://example.com"
|
|
185
|
+
)
|
|
186
|
+
create.add_argument("--username", help="WordPress username; prompted when omitted")
|
|
187
|
+
create.add_argument(
|
|
188
|
+
"--password-env",
|
|
189
|
+
metavar="NAME",
|
|
190
|
+
help="password environment variable (default: PROFILE_WP_PASSWORD)",
|
|
191
|
+
)
|
|
192
|
+
create.add_argument(
|
|
193
|
+
"--local-root", metavar="PATH", help="local folder for this blog"
|
|
194
|
+
)
|
|
195
|
+
|
|
196
|
+
connect = subparsers.add_parser(
|
|
197
|
+
"connect",
|
|
198
|
+
help="verify a profile's credentials and list the blog's posts",
|
|
199
|
+
usage="wpsync connect [PROFILE]\n wpsync PROFILE connect",
|
|
200
|
+
)
|
|
201
|
+
_profile_argument(connect)
|
|
202
|
+
|
|
203
|
+
map_parser = subparsers.add_parser(
|
|
204
|
+
"map",
|
|
205
|
+
help="move a profile's local folder",
|
|
206
|
+
usage="wpsync map [PROFILE] [--local-root PATH]\n wpsync PROFILE map",
|
|
207
|
+
description=(
|
|
208
|
+
"Point a profile at a different local folder after a [y/N] "
|
|
209
|
+
"confirmation. A different blog needs its own profile."
|
|
210
|
+
),
|
|
211
|
+
)
|
|
212
|
+
_profile_argument(map_parser)
|
|
213
|
+
map_parser.add_argument(
|
|
214
|
+
"--local-root",
|
|
215
|
+
metavar="PATH",
|
|
216
|
+
help="new local folder; defaults to the current directory",
|
|
217
|
+
)
|
|
218
|
+
|
|
219
|
+
remove = subparsers.add_parser(
|
|
220
|
+
"remove",
|
|
221
|
+
help="remove a profile",
|
|
222
|
+
usage="wpsync remove [PROFILE]\n wpsync PROFILE remove",
|
|
223
|
+
description="Remove the profile only; local files and the blog stay unchanged.",
|
|
224
|
+
)
|
|
225
|
+
_profile_argument(remove)
|
|
226
|
+
|
|
227
|
+
root = subparsers.add_parser(
|
|
228
|
+
"root",
|
|
229
|
+
help="print a profile's local folder",
|
|
230
|
+
usage="wpsync root [PROFILE]\n wpsync PROFILE root",
|
|
231
|
+
description=(
|
|
232
|
+
'Print only the local folder, suitable for cd "$(wpsync root PROFILE)".'
|
|
233
|
+
),
|
|
234
|
+
)
|
|
235
|
+
_profile_argument(root)
|
|
236
|
+
|
|
237
|
+
profile = subparsers.add_parser(
|
|
238
|
+
"profile",
|
|
239
|
+
help="show the current or named profile",
|
|
240
|
+
usage=(
|
|
241
|
+
"wpsync profile [PROFILE] [--details]\n"
|
|
242
|
+
" wpsync PROFILE profile [--details]"
|
|
243
|
+
),
|
|
244
|
+
)
|
|
245
|
+
_profile_argument(profile)
|
|
246
|
+
profile.add_argument(
|
|
247
|
+
"--details",
|
|
248
|
+
action="store_true",
|
|
249
|
+
help="show the site, account, and local folder",
|
|
250
|
+
)
|
|
251
|
+
|
|
252
|
+
subparsers.add_parser(
|
|
253
|
+
"profiles",
|
|
254
|
+
help="list profiles",
|
|
255
|
+
description="List profiles; * marks the one containing this directory.",
|
|
256
|
+
)
|
|
257
|
+
|
|
258
|
+
subparsers.add_parser(
|
|
259
|
+
"ls",
|
|
260
|
+
help="list local posts with their IDs and slugs",
|
|
261
|
+
usage="wpsync ls\n wpsync PROFILE ls",
|
|
262
|
+
description="List the post files in this profile without contacting the blog.",
|
|
263
|
+
)
|
|
264
|
+
|
|
265
|
+
diff = subparsers.add_parser(
|
|
266
|
+
"diff",
|
|
267
|
+
help="show what push would change",
|
|
268
|
+
usage="wpsync diff [POST] [-a]\n wpsync PROFILE diff [POST] [-a]",
|
|
269
|
+
description=(
|
|
270
|
+
"Show local changes and anything that would stop a push. Contacts the "
|
|
271
|
+
"blog only for changed or new posts. POST is a post ID, slug, or file."
|
|
272
|
+
),
|
|
273
|
+
)
|
|
274
|
+
diff.add_argument(
|
|
275
|
+
"post", nargs="?", metavar="POST", help="one post; all when omitted"
|
|
276
|
+
)
|
|
277
|
+
diff.add_argument(
|
|
278
|
+
"-a", "--all", action="store_true", help="also show unchanged posts"
|
|
279
|
+
)
|
|
280
|
+
|
|
281
|
+
pull = subparsers.add_parser(
|
|
282
|
+
"pull",
|
|
283
|
+
help="bring posts from the blog into local files",
|
|
284
|
+
usage="wpsync pull [POST] [-y]\n wpsync PROFILE pull [POST] [-y]",
|
|
285
|
+
description=(
|
|
286
|
+
"Create and update local post files from the blog and download their "
|
|
287
|
+
"images. Local edits are never overwritten without asking. POST is a "
|
|
288
|
+
"post ID, slug, or file."
|
|
289
|
+
),
|
|
290
|
+
)
|
|
291
|
+
pull.add_argument(
|
|
292
|
+
"post", nargs="?", metavar="POST", help="one post; all when omitted"
|
|
293
|
+
)
|
|
294
|
+
pull.add_argument(
|
|
295
|
+
"-y", "--yes", action="store_true", help="answer yes to every question"
|
|
296
|
+
)
|
|
297
|
+
return parser
|
|
298
|
+
|
|
299
|
+
|
|
300
|
+
def _resolve_profile(
|
|
301
|
+
arguments: argparse.Namespace, configuration: Configuration
|
|
302
|
+
) -> tuple[str, Profile]:
|
|
303
|
+
prefix = arguments.profile_prefix
|
|
304
|
+
positional = getattr(arguments, "profile_name", None)
|
|
305
|
+
if prefix is not None and positional is not None:
|
|
306
|
+
raise ConfigurationError(
|
|
307
|
+
"profile was specified both before the command and as an argument"
|
|
308
|
+
)
|
|
309
|
+
name = prefix or positional
|
|
310
|
+
if name is None:
|
|
311
|
+
active = configuration.profile_for_path(Path.cwd().resolve())
|
|
312
|
+
if active is None:
|
|
313
|
+
raise ConfigurationError(
|
|
314
|
+
"current directory is not inside a mapped profile; prefix the "
|
|
315
|
+
"command with a profile (wpsync PROFILE COMMAND)"
|
|
316
|
+
)
|
|
317
|
+
return active
|
|
318
|
+
name = validate_profile_name(name)
|
|
319
|
+
if name not in configuration.profiles:
|
|
320
|
+
raise ConfigurationError(f"profile '{name}' does not exist")
|
|
321
|
+
return name, configuration.profiles[name]
|
|
322
|
+
|
|
323
|
+
|
|
324
|
+
def _normalize_site(site: str) -> str:
|
|
325
|
+
site = site.strip()
|
|
326
|
+
if "://" not in site:
|
|
327
|
+
site = f"https://{site}"
|
|
328
|
+
url = httpx.URL(site)
|
|
329
|
+
if url.scheme not in {"http", "https"} or not url.host:
|
|
330
|
+
raise ConfigurationError(f"'{site}' is not an http or https address")
|
|
331
|
+
return site
|
|
332
|
+
|
|
333
|
+
|
|
334
|
+
def _connection_report(profile: Profile, session: _Session) -> str:
|
|
335
|
+
with WordPressClient(
|
|
336
|
+
profile.api_root, profile.username, session.password(profile), session.transport
|
|
337
|
+
) as client:
|
|
338
|
+
user = client.current_user()
|
|
339
|
+
capabilities = user.get("capabilities", {})
|
|
340
|
+
if not capabilities.get("edit_posts"):
|
|
341
|
+
raise WordPressError(
|
|
342
|
+
f"'{profile.username}' cannot edit posts on {profile.site}"
|
|
343
|
+
)
|
|
344
|
+
posts = client.post_summaries()
|
|
345
|
+
roles = ", ".join(user.get("roles", [])) or "no role"
|
|
346
|
+
lines = [f"Connected to {profile.site} as '{profile.username}' ({roles})."]
|
|
347
|
+
if not capabilities.get("unfiltered_html"):
|
|
348
|
+
lines.append(
|
|
349
|
+
"Note: this account lacks unfiltered_html, so WordPress removes "
|
|
350
|
+
"markup such as iframes and scripts from saved posts."
|
|
351
|
+
)
|
|
352
|
+
lines.append(_post_listing(posts))
|
|
353
|
+
return "\n".join(lines)
|
|
354
|
+
|
|
355
|
+
|
|
356
|
+
def _post_listing(posts: list[PostSummary]) -> str:
|
|
357
|
+
if not posts:
|
|
358
|
+
return "The blog has no posts."
|
|
359
|
+
counts = Counter(post.status for post in posts)
|
|
360
|
+
breakdown = ", ".join(
|
|
361
|
+
f"{counts[status]} {status}" for status in PostStatus if counts[status]
|
|
362
|
+
)
|
|
363
|
+
noun = "post" if len(posts) == 1 else "posts"
|
|
364
|
+
lines = [f"{len(posts)} {noun}: {breakdown}", ""]
|
|
365
|
+
id_width = max(len(post.id) for post in posts)
|
|
366
|
+
status_width = max(len(post.status) for post in posts)
|
|
367
|
+
for post in sorted(posts, key=lambda post: (post.date, int(post.id)), reverse=True):
|
|
368
|
+
lines.append(
|
|
369
|
+
f" {post.id:>{id_width}} {post.status:<{status_width}} "
|
|
370
|
+
f"{post.date:%Y-%m-%d} {post.title or '(no title)'}"
|
|
371
|
+
)
|
|
372
|
+
return "\n".join(lines)
|
|
373
|
+
|
|
374
|
+
|
|
375
|
+
def _create(arguments: argparse.Namespace, session: _Session) -> str:
|
|
376
|
+
name = validate_profile_name(arguments.profile_name)
|
|
377
|
+
configuration = session.store.load()
|
|
378
|
+
if name in configuration.profiles:
|
|
379
|
+
raise ConfigurationError(f"profile '{name}' already exists")
|
|
380
|
+
site = _normalize_site(arguments.site)
|
|
381
|
+
password_env = (
|
|
382
|
+
validate_environment_name(arguments.password_env)
|
|
383
|
+
if arguments.password_env
|
|
384
|
+
else default_password_env(name)
|
|
385
|
+
)
|
|
386
|
+
if not session.environ.get(password_env):
|
|
387
|
+
raise ConfigurationError(
|
|
388
|
+
f"set {password_env} to an Application Password for {site} (create "
|
|
389
|
+
"one in WordPress under Users > Profile > Application Passwords), "
|
|
390
|
+
"then run create again"
|
|
391
|
+
)
|
|
392
|
+
username = arguments.username or session.ask("WordPress username: ")
|
|
393
|
+
if not username:
|
|
394
|
+
raise ConfigurationError("a WordPress username is required")
|
|
395
|
+
if arguments.local_root is not None:
|
|
396
|
+
local_root = canonical_local_root(arguments.local_root)
|
|
397
|
+
else:
|
|
398
|
+
current = canonical_local_root(Path.cwd())
|
|
399
|
+
if session.confirm(
|
|
400
|
+
f"Map current directory '{current}' to {site}? [Y/n] ", default=True
|
|
401
|
+
):
|
|
402
|
+
local_root = current
|
|
403
|
+
else:
|
|
404
|
+
supplied = session.ask("What local folder should be mapped instead? ")
|
|
405
|
+
if not supplied:
|
|
406
|
+
raise ConfigurationError("a local folder is required; use --local-root")
|
|
407
|
+
local_root = canonical_local_root(supplied)
|
|
408
|
+
configuration.check_root(name, local_root)
|
|
409
|
+
profile = Profile(
|
|
410
|
+
site=site,
|
|
411
|
+
api_root=discover_api_root(site, session.transport),
|
|
412
|
+
username=username,
|
|
413
|
+
password_env=password_env,
|
|
414
|
+
local_root=local_root,
|
|
415
|
+
)
|
|
416
|
+
configuration.add(name, profile)
|
|
417
|
+
report = _connection_report(profile, session)
|
|
418
|
+
session.store.save(configuration)
|
|
419
|
+
return f"Created profile '{name}'.\nMapped '{local_root}' to {site}.\n{report}"
|
|
420
|
+
|
|
421
|
+
|
|
422
|
+
def _connect(arguments: argparse.Namespace, session: _Session) -> str:
|
|
423
|
+
_, profile = _resolve_profile(arguments, session.store.load())
|
|
424
|
+
return _connection_report(profile, session)
|
|
425
|
+
|
|
426
|
+
|
|
427
|
+
def _map(arguments: argparse.Namespace, session: _Session) -> str:
|
|
428
|
+
configuration = session.store.load()
|
|
429
|
+
name, profile = _resolve_profile(arguments, configuration)
|
|
430
|
+
local_root = canonical_local_root(arguments.local_root or Path.cwd())
|
|
431
|
+
if local_root == profile.local_root:
|
|
432
|
+
return f"Profile '{name}' already uses '{local_root}'."
|
|
433
|
+
configuration.remap(name, local_root)
|
|
434
|
+
prompt = (
|
|
435
|
+
f"Change profile '{name}' local folder from '{profile.local_root}' "
|
|
436
|
+
f"to '{local_root}'? [y/N] "
|
|
437
|
+
)
|
|
438
|
+
if not session.confirm(prompt, default=False):
|
|
439
|
+
return f"Profile '{name}' is unchanged."
|
|
440
|
+
session.store.save(configuration)
|
|
441
|
+
return f"Mapped '{local_root}' to {profile.site}."
|
|
442
|
+
|
|
443
|
+
|
|
444
|
+
def _remove(arguments: argparse.Namespace, session: _Session) -> str:
|
|
445
|
+
configuration = session.store.load()
|
|
446
|
+
name, _ = _resolve_profile(arguments, configuration)
|
|
447
|
+
del configuration.profiles[name]
|
|
448
|
+
session.store.save(configuration)
|
|
449
|
+
return f"Removed profile '{name}'. Local files and the blog are unchanged."
|
|
450
|
+
|
|
451
|
+
|
|
452
|
+
def _root(arguments: argparse.Namespace, session: _Session) -> str:
|
|
453
|
+
_, profile = _resolve_profile(arguments, session.store.load())
|
|
454
|
+
return os.fspath(profile.local_root)
|
|
455
|
+
|
|
456
|
+
|
|
457
|
+
def _profile(arguments: argparse.Namespace, session: _Session) -> str:
|
|
458
|
+
configuration = session.store.load()
|
|
459
|
+
if arguments.profile_prefix is None and arguments.profile_name is None:
|
|
460
|
+
active = configuration.profile_for_path(Path.cwd().resolve())
|
|
461
|
+
if active is None:
|
|
462
|
+
return "No active profile. Use wpsync PROFILE COMMAND."
|
|
463
|
+
name, profile = active
|
|
464
|
+
else:
|
|
465
|
+
name, profile = _resolve_profile(arguments, configuration)
|
|
466
|
+
if not arguments.details:
|
|
467
|
+
return name
|
|
468
|
+
return "\n".join(
|
|
469
|
+
(
|
|
470
|
+
f"Profile '{name}':",
|
|
471
|
+
f" Site: {profile.site}",
|
|
472
|
+
f" REST API: {profile.api_root}",
|
|
473
|
+
f" Username: {profile.username}",
|
|
474
|
+
f" Password env: {profile.password_env}",
|
|
475
|
+
f" Local root: {profile.local_root}",
|
|
476
|
+
)
|
|
477
|
+
)
|
|
478
|
+
|
|
479
|
+
|
|
480
|
+
def _profiles(arguments: argparse.Namespace, session: _Session) -> str:
|
|
481
|
+
configuration = session.store.load()
|
|
482
|
+
if not configuration.profiles:
|
|
483
|
+
return "No profiles configured."
|
|
484
|
+
active = configuration.profile_for_path(Path.cwd().resolve())
|
|
485
|
+
active_name = active[0] if active else None
|
|
486
|
+
return "\n".join(
|
|
487
|
+
f"{'*' if name == active_name else ' '} {name}"
|
|
488
|
+
for name in sorted(configuration.profiles)
|
|
489
|
+
)
|
|
490
|
+
|
|
491
|
+
|
|
492
|
+
def _use_color(stream: TextIO, environ: Mapping[str, str]) -> bool:
|
|
493
|
+
if "NO_COLOR" in environ:
|
|
494
|
+
return False
|
|
495
|
+
is_terminal = getattr(stream, "isatty", None)
|
|
496
|
+
return bool(is_terminal and is_terminal())
|
|
497
|
+
|
|
498
|
+
|
|
499
|
+
def _paint(text: str, color: bool) -> str:
|
|
500
|
+
if not color:
|
|
501
|
+
return text
|
|
502
|
+
return "".join(
|
|
503
|
+
f"{MARKER_COLORS[char]}{char}{RESET}" if char in MARKER_COLORS else char
|
|
504
|
+
for char in text
|
|
505
|
+
)
|
|
506
|
+
|
|
507
|
+
|
|
508
|
+
def _legend(session: _Session) -> str:
|
|
509
|
+
color = _use_color(session.stdout, session.environ)
|
|
510
|
+
lines = ["Diff legend:"]
|
|
511
|
+
lines.extend(f" {_paint(marker, color)} {meaning}" for marker, meaning in LEGEND)
|
|
512
|
+
return "\n".join(lines)
|
|
513
|
+
|
|
514
|
+
|
|
515
|
+
class _LazyRemote:
|
|
516
|
+
"""Connects to the blog only if a command turns out to need it."""
|
|
517
|
+
|
|
518
|
+
def __init__(self, profile: Profile, session: _Session) -> None:
|
|
519
|
+
self.profile = profile
|
|
520
|
+
self.session = session
|
|
521
|
+
self.client: WordPressClient | None = None
|
|
522
|
+
|
|
523
|
+
def _connect(self) -> WordPressClient:
|
|
524
|
+
if self.client is None:
|
|
525
|
+
self.client = WordPressClient(
|
|
526
|
+
self.profile.api_root,
|
|
527
|
+
self.profile.username,
|
|
528
|
+
self.session.password(self.profile),
|
|
529
|
+
self.session.transport,
|
|
530
|
+
)
|
|
531
|
+
return self.client
|
|
532
|
+
|
|
533
|
+
def post_states(self, ids: list[str]) -> dict[str, RemoteState]:
|
|
534
|
+
return self._connect().post_states(ids)
|
|
535
|
+
|
|
536
|
+
def post_summaries(self) -> list[PostSummary]:
|
|
537
|
+
return self._connect().post_summaries()
|
|
538
|
+
|
|
539
|
+
def close(self) -> None:
|
|
540
|
+
if self.client is not None:
|
|
541
|
+
self.client.http.close()
|
|
542
|
+
|
|
543
|
+
|
|
544
|
+
def _profile_root(
|
|
545
|
+
arguments: argparse.Namespace, session: _Session
|
|
546
|
+
) -> tuple[Profile, Path]:
|
|
547
|
+
_, profile = _resolve_profile(arguments, session.store.load())
|
|
548
|
+
base = profile.local_root if arguments.profile_prefix else Path.cwd().resolve()
|
|
549
|
+
return profile, base
|
|
550
|
+
|
|
551
|
+
|
|
552
|
+
def _ls(arguments: argparse.Namespace, session: _Session) -> str:
|
|
553
|
+
profile, _ = _profile_root(arguments, session)
|
|
554
|
+
documents = scan_documents(profile.local_root)
|
|
555
|
+
if not documents:
|
|
556
|
+
return "No posts. Run wpsync pull, or add Markdown files under posts/."
|
|
557
|
+
|
|
558
|
+
def order(item): # noqa: ANN001, ANN202
|
|
559
|
+
post_id = item.document.post_id
|
|
560
|
+
return (post_id is None, int(post_id) if post_id else 0, str(item.path))
|
|
561
|
+
|
|
562
|
+
rows = [
|
|
563
|
+
(
|
|
564
|
+
item.document.post_id or "-",
|
|
565
|
+
item.document.post.slug or "-",
|
|
566
|
+
item.document.post.title or "(no title)",
|
|
567
|
+
str(item.path),
|
|
568
|
+
)
|
|
569
|
+
for item in sorted(documents, key=order)
|
|
570
|
+
]
|
|
571
|
+
widths = [
|
|
572
|
+
max(len(row[i]) for row in rows + [("ID", "Slug", "Title", "")])
|
|
573
|
+
for i in range(3)
|
|
574
|
+
]
|
|
575
|
+
header = f"{'ID':>{widths[0]}} {'Slug':<{widths[1]}} {'Title':<{widths[2]}} File"
|
|
576
|
+
lines = [header]
|
|
577
|
+
lines.extend(
|
|
578
|
+
f"{post_id:>{widths[0]}} {slug:<{widths[1]}} {title:<{widths[2]}} {path}"
|
|
579
|
+
for post_id, slug, title, path in rows
|
|
580
|
+
)
|
|
581
|
+
return "\n".join(lines)
|
|
582
|
+
|
|
583
|
+
|
|
584
|
+
def _diff(arguments: argparse.Namespace, session: _Session) -> str:
|
|
585
|
+
profile, base = _profile_root(arguments, session)
|
|
586
|
+
root = profile.local_root
|
|
587
|
+
selection = select(
|
|
588
|
+
arguments.post,
|
|
589
|
+
scan_documents(root),
|
|
590
|
+
read_records(root, profile.api_root),
|
|
591
|
+
root=root,
|
|
592
|
+
base=base,
|
|
593
|
+
)
|
|
594
|
+
remote = _LazyRemote(profile, session)
|
|
595
|
+
try:
|
|
596
|
+
result = compare(selection, remote)
|
|
597
|
+
finally:
|
|
598
|
+
remote.close()
|
|
599
|
+
color = _use_color(session.stdout, session.environ)
|
|
600
|
+
shown = [
|
|
601
|
+
e for e in result.entries if arguments.all or e.action is not Action.UNCHANGED
|
|
602
|
+
]
|
|
603
|
+
hidden = len(result.entries) - len(shown)
|
|
604
|
+
width = max((len(e.post_id or "-") for e in shown), default=1)
|
|
605
|
+
lines = [_entry_line(entry, color, width) for entry in shown]
|
|
606
|
+
if not shown:
|
|
607
|
+
lines.append("No local changes.")
|
|
608
|
+
if hidden:
|
|
609
|
+
lines.append(f"Not shown: {hidden} unchanged (-a to show)")
|
|
610
|
+
lines.extend(f"Note: {note}" for note in result.notes)
|
|
611
|
+
return "\n".join(lines)
|
|
612
|
+
|
|
613
|
+
|
|
614
|
+
def _entry_line(entry: DiffEntry, color: bool, width: int = 1) -> str:
|
|
615
|
+
marker = _paint(f"{entry.action} {entry.side or ' '}", color)
|
|
616
|
+
detail = f" {entry.detail}" if entry.detail else ""
|
|
617
|
+
return f"{marker} {entry.post_id or '-':>{width}} {entry.path}{detail}"
|
|
618
|
+
|
|
619
|
+
|
|
620
|
+
def _pull_target(
|
|
621
|
+
selector: str | None, documents: list[LocalDocument], root: Path, base: Path
|
|
622
|
+
) -> tuple[list[str] | None, str | None]:
|
|
623
|
+
"""The post IDs or slug a pull selector names; a slug may be remote only."""
|
|
624
|
+
if selector is None:
|
|
625
|
+
return None, None
|
|
626
|
+
if selector.isdigit():
|
|
627
|
+
return [selector], None
|
|
628
|
+
if "/" in selector or selector.endswith(".md"):
|
|
629
|
+
chosen = select(selector, documents, {}, root=root, base=base).documents
|
|
630
|
+
post_id = chosen[0].document.post_id
|
|
631
|
+
if post_id is None:
|
|
632
|
+
raise SelectionError(
|
|
633
|
+
f"{selector} is not linked to a post yet; push it first"
|
|
634
|
+
)
|
|
635
|
+
return [post_id], None
|
|
636
|
+
local = [d for d in documents if d.document.post.slug == selector]
|
|
637
|
+
if local and local[0].document.post_id:
|
|
638
|
+
return [local[0].document.post_id], None
|
|
639
|
+
return None, selector
|
|
640
|
+
|
|
641
|
+
|
|
642
|
+
def _pull(arguments: argparse.Namespace, session: _Session) -> str:
|
|
643
|
+
profile, base = _profile_root(arguments, session)
|
|
644
|
+
root = profile.local_root
|
|
645
|
+
documents = scan_documents(root)
|
|
646
|
+
ids, slug = _pull_target(arguments.post, documents, root, base)
|
|
647
|
+
color = _use_color(session.stdout, session.environ)
|
|
648
|
+
|
|
649
|
+
def confirm(question: str) -> bool:
|
|
650
|
+
# Without a terminal nobody can answer, so the question counts as No.
|
|
651
|
+
if arguments.yes:
|
|
652
|
+
return True
|
|
653
|
+
interactive = getattr(session.stdin, "isatty", lambda: False)()
|
|
654
|
+
return interactive and session.confirm(f"{question} [y/N] ", default=False)
|
|
655
|
+
|
|
656
|
+
def report(entry: DiffEntry) -> None:
|
|
657
|
+
print(_entry_line(entry, color), file=session.stdout, flush=True)
|
|
658
|
+
|
|
659
|
+
client = WordPressClient(
|
|
660
|
+
profile.api_root, profile.username, session.password(profile), session.transport
|
|
661
|
+
)
|
|
662
|
+
remote = WordPressRemote(client, session.transport)
|
|
663
|
+
try:
|
|
664
|
+
puller = Puller(
|
|
665
|
+
root,
|
|
666
|
+
profile.api_root,
|
|
667
|
+
remote,
|
|
668
|
+
documents,
|
|
669
|
+
read_records(root, profile.api_root),
|
|
670
|
+
read_media(root, profile.api_root),
|
|
671
|
+
confirm,
|
|
672
|
+
report,
|
|
673
|
+
)
|
|
674
|
+
result = puller.pull(ids=ids, slug=slug)
|
|
675
|
+
finally:
|
|
676
|
+
remote.close()
|
|
677
|
+
client.http.close()
|
|
678
|
+
summary = result.summary()
|
|
679
|
+
if result.skipped and not arguments.yes:
|
|
680
|
+
summary += " Rerun with --yes to accept the skipped changes."
|
|
681
|
+
return summary
|
|
682
|
+
|
|
683
|
+
|
|
684
|
+
HANDLERS = {
|
|
685
|
+
"create": _create,
|
|
686
|
+
"connect": _connect,
|
|
687
|
+
"map": _map,
|
|
688
|
+
"remove": _remove,
|
|
689
|
+
"root": _root,
|
|
690
|
+
"profile": _profile,
|
|
691
|
+
"profiles": _profiles,
|
|
692
|
+
"ls": _ls,
|
|
693
|
+
"diff": _diff,
|
|
694
|
+
"pull": _pull,
|
|
695
|
+
}
|
|
696
|
+
|
|
697
|
+
|
|
698
|
+
def run(
|
|
699
|
+
argv: Sequence[str] | None = None,
|
|
700
|
+
*,
|
|
701
|
+
store: ConfigurationStore | None = None,
|
|
702
|
+
stdin: TextIO = sys.stdin,
|
|
703
|
+
stdout: TextIO = sys.stdout,
|
|
704
|
+
stderr: TextIO = sys.stderr,
|
|
705
|
+
environ: Mapping[str, str] = os.environ,
|
|
706
|
+
transport: httpx.BaseTransport | None = None,
|
|
707
|
+
) -> int:
|
|
708
|
+
parser = build_parser()
|
|
709
|
+
raw_arguments = list(sys.argv[1:] if argv is None else argv)
|
|
710
|
+
try:
|
|
711
|
+
raw_arguments, profile_prefix = _resolve_invocation(raw_arguments)
|
|
712
|
+
except ConfigurationError as error:
|
|
713
|
+
parser.error(str(error))
|
|
714
|
+
arguments = parser.parse_args(raw_arguments)
|
|
715
|
+
arguments.profile_prefix = profile_prefix
|
|
716
|
+
session = _Session(store or ConfigurationStore(), stdin, stdout, environ, transport)
|
|
717
|
+
if arguments.legend:
|
|
718
|
+
if arguments.command is not None:
|
|
719
|
+
parser.error("--legend cannot be combined with a command")
|
|
720
|
+
print(_legend(session), file=stdout)
|
|
721
|
+
return 0
|
|
722
|
+
if arguments.command is None:
|
|
723
|
+
parser.error("a command is required")
|
|
724
|
+
try:
|
|
725
|
+
message = HANDLERS[arguments.command](arguments, session)
|
|
726
|
+
except (
|
|
727
|
+
ConfigurationError,
|
|
728
|
+
DocumentError,
|
|
729
|
+
SelectionError,
|
|
730
|
+
StateError,
|
|
731
|
+
WordPressError,
|
|
732
|
+
) as error:
|
|
733
|
+
print(f"wpsync: error: {error}", file=stderr)
|
|
734
|
+
return 1
|
|
735
|
+
print(message, file=stdout)
|
|
736
|
+
return 0
|
|
737
|
+
|
|
738
|
+
|
|
739
|
+
def main(argv: Sequence[str] | None = None) -> int:
|
|
740
|
+
return run(argv)
|