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/cli.py
ADDED
|
@@ -0,0 +1,1479 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import argparse
|
|
4
|
+
import os
|
|
5
|
+
import posixpath
|
|
6
|
+
import re
|
|
7
|
+
import shutil
|
|
8
|
+
import sys
|
|
9
|
+
import time
|
|
10
|
+
import unicodedata
|
|
11
|
+
from collections import Counter
|
|
12
|
+
from collections.abc import Callable, Mapping, Sequence
|
|
13
|
+
from datetime import UTC, datetime
|
|
14
|
+
from pathlib import Path, PurePosixPath
|
|
15
|
+
from typing import TextIO
|
|
16
|
+
|
|
17
|
+
import httpx
|
|
18
|
+
|
|
19
|
+
from wpsync import __version__
|
|
20
|
+
from wpsync.config import (
|
|
21
|
+
Configuration,
|
|
22
|
+
ConfigurationError,
|
|
23
|
+
ConfigurationStore,
|
|
24
|
+
Profile,
|
|
25
|
+
canonical_local_root,
|
|
26
|
+
default_password_env,
|
|
27
|
+
validate_environment_name,
|
|
28
|
+
validate_profile_name,
|
|
29
|
+
)
|
|
30
|
+
from wpsync.documents import (
|
|
31
|
+
CONTENT_DIR,
|
|
32
|
+
TRASH_DIR,
|
|
33
|
+
Document,
|
|
34
|
+
DocumentError,
|
|
35
|
+
LocalDocument,
|
|
36
|
+
display_path,
|
|
37
|
+
format_date,
|
|
38
|
+
scan_documents,
|
|
39
|
+
scan_trash,
|
|
40
|
+
write_document,
|
|
41
|
+
)
|
|
42
|
+
from wpsync.editors import Editor, EditorError, editor_command, launch
|
|
43
|
+
from wpsync.posts import Post, PostStatus, PostSummary, RemoteState
|
|
44
|
+
from wpsync.pull import Puller
|
|
45
|
+
from wpsync.push import Pusher
|
|
46
|
+
from wpsync.state import (
|
|
47
|
+
PostRecord,
|
|
48
|
+
StateError,
|
|
49
|
+
follow_moves,
|
|
50
|
+
read_media,
|
|
51
|
+
read_records,
|
|
52
|
+
)
|
|
53
|
+
from wpsync.sync import Action, DiffEntry, Outcome, SelectionError, compare, select
|
|
54
|
+
from wpsync.trash import TrashError, delete_post, restore_post
|
|
55
|
+
from wpsync.wordpress.client import WordPressClient, WordPressError, discover_api_root
|
|
56
|
+
from wpsync.wordpress.remote import WordPressRemote
|
|
57
|
+
|
|
58
|
+
COMMANDS = (
|
|
59
|
+
"init",
|
|
60
|
+
"map",
|
|
61
|
+
"remove",
|
|
62
|
+
"root",
|
|
63
|
+
"profile",
|
|
64
|
+
"profiles",
|
|
65
|
+
"editor",
|
|
66
|
+
"create",
|
|
67
|
+
"ls",
|
|
68
|
+
"show",
|
|
69
|
+
"open",
|
|
70
|
+
"diff",
|
|
71
|
+
"pull",
|
|
72
|
+
"push",
|
|
73
|
+
"delete",
|
|
74
|
+
"trash",
|
|
75
|
+
"restore",
|
|
76
|
+
)
|
|
77
|
+
PROFILE_AWARE_COMMANDS = frozenset(
|
|
78
|
+
{
|
|
79
|
+
"map",
|
|
80
|
+
"remove",
|
|
81
|
+
"root",
|
|
82
|
+
"profile",
|
|
83
|
+
"create",
|
|
84
|
+
"ls",
|
|
85
|
+
"show",
|
|
86
|
+
"open",
|
|
87
|
+
"diff",
|
|
88
|
+
"pull",
|
|
89
|
+
"push",
|
|
90
|
+
"delete",
|
|
91
|
+
"trash",
|
|
92
|
+
"restore",
|
|
93
|
+
}
|
|
94
|
+
)
|
|
95
|
+
TIMESTAMP_FORMAT = "%Y-%m-%d-%H%M"
|
|
96
|
+
NO_POSTS = "No posts here yet. Run wpsync pull, or add Markdown files under content/."
|
|
97
|
+
RESET = "\033[0m"
|
|
98
|
+
MARKER_COLORS = {
|
|
99
|
+
"+": "\033[38;5;82m",
|
|
100
|
+
"~": "\033[33m",
|
|
101
|
+
"-": "\033[31m",
|
|
102
|
+
"?": "\033[35m",
|
|
103
|
+
"x": "\033[90m",
|
|
104
|
+
"l": "\033[38;5;51m",
|
|
105
|
+
"r": "\033[38;5;30m",
|
|
106
|
+
}
|
|
107
|
+
DIRECTORY_COLOR = "\033[38;5;75m"
|
|
108
|
+
LEGEND = (
|
|
109
|
+
("+ l", "local only; push creates the post"),
|
|
110
|
+
("~ ", "on both sides; push updates the post"),
|
|
111
|
+
(" r", "on WordPress only; push keeps it"),
|
|
112
|
+
("- r", "on WordPress only; push -p deletes it"),
|
|
113
|
+
(" x ", "private; push skips it"),
|
|
114
|
+
("l", "local only"),
|
|
115
|
+
("r", "on WordPress only"),
|
|
116
|
+
(" ", "blank side column: on both sides"),
|
|
117
|
+
("?", "conflict; push asks first, or cannot send it"),
|
|
118
|
+
("=", "unchanged"),
|
|
119
|
+
("x", "private"),
|
|
120
|
+
("/", "folder"),
|
|
121
|
+
)
|
|
122
|
+
HIDDEN_HINTS = {Action.PRIVATE: ("private", "-x"), Action.KEPT: ("remote-only", "-a")}
|
|
123
|
+
LS_LEGEND = (
|
|
124
|
+
("*", "Public: push publishes it (blank means private)"),
|
|
125
|
+
("*Jan 1, 2029", "Public: scheduled; the blog shows it from that date"),
|
|
126
|
+
)
|
|
127
|
+
|
|
128
|
+
|
|
129
|
+
class _Session:
|
|
130
|
+
"""The process context a command runs in."""
|
|
131
|
+
|
|
132
|
+
def __init__(
|
|
133
|
+
self,
|
|
134
|
+
store: ConfigurationStore,
|
|
135
|
+
stdin: TextIO,
|
|
136
|
+
stdout: TextIO,
|
|
137
|
+
progress: TextIO,
|
|
138
|
+
environ: Mapping[str, str],
|
|
139
|
+
transport: httpx.BaseTransport | None,
|
|
140
|
+
launch: Callable[[list[str]], None],
|
|
141
|
+
) -> None:
|
|
142
|
+
self.store = store
|
|
143
|
+
self.stdin = stdin
|
|
144
|
+
self.stdout = stdout
|
|
145
|
+
self.progress = progress
|
|
146
|
+
"""Where status lines, file lines, and the progress bar go: stderr."""
|
|
147
|
+
self.environ = environ
|
|
148
|
+
self.transport = transport
|
|
149
|
+
self.launch = launch
|
|
150
|
+
|
|
151
|
+
def ask(self, prompt: str) -> str:
|
|
152
|
+
print(prompt, end="", file=self.stdout, flush=True)
|
|
153
|
+
return self.stdin.readline().strip()
|
|
154
|
+
|
|
155
|
+
def confirm(self, prompt: str, *, default: bool) -> bool:
|
|
156
|
+
"""Ask a yes/no question. End of input counts as No."""
|
|
157
|
+
while True:
|
|
158
|
+
print(prompt, end="", file=self.stdout, flush=True)
|
|
159
|
+
answer = self.stdin.readline()
|
|
160
|
+
if answer == "":
|
|
161
|
+
print(file=self.stdout)
|
|
162
|
+
return False
|
|
163
|
+
normalized = answer.strip().lower()
|
|
164
|
+
if normalized in {"y", "yes"}:
|
|
165
|
+
return True
|
|
166
|
+
if normalized in {"n", "no"}:
|
|
167
|
+
return False
|
|
168
|
+
if normalized == "":
|
|
169
|
+
return default
|
|
170
|
+
print("Please answer yes or no.", file=self.stdout)
|
|
171
|
+
|
|
172
|
+
def status(self, text: str) -> None:
|
|
173
|
+
print(text, file=self.progress, flush=True)
|
|
174
|
+
|
|
175
|
+
def password(self, profile: Profile) -> str:
|
|
176
|
+
password = self.environ.get(profile.password_env)
|
|
177
|
+
if not password:
|
|
178
|
+
raise ConfigurationError(f"{profile.password_env} is not set")
|
|
179
|
+
return password
|
|
180
|
+
|
|
181
|
+
|
|
182
|
+
def _resolve_command(value: str) -> str:
|
|
183
|
+
if value in COMMANDS:
|
|
184
|
+
return value
|
|
185
|
+
matches = [command for command in COMMANDS if command.startswith(value)]
|
|
186
|
+
if not matches:
|
|
187
|
+
raise ConfigurationError(f"unknown command '{value}'")
|
|
188
|
+
if len(matches) > 1:
|
|
189
|
+
raise ConfigurationError(f"ambiguous command '{value}': {', '.join(matches)}")
|
|
190
|
+
return matches[0]
|
|
191
|
+
|
|
192
|
+
|
|
193
|
+
def _could_be_command(value: str) -> bool:
|
|
194
|
+
return any(command.startswith(value) for command in COMMANDS)
|
|
195
|
+
|
|
196
|
+
|
|
197
|
+
def _resolve_invocation(arguments: list[str]) -> tuple[list[str], str | None]:
|
|
198
|
+
"""Expand command prefixes and split off a leading profile override."""
|
|
199
|
+
if not arguments or arguments[0].startswith("-"):
|
|
200
|
+
return arguments, None
|
|
201
|
+
first = arguments[0]
|
|
202
|
+
if (
|
|
203
|
+
first not in COMMANDS
|
|
204
|
+
and len(arguments) > 1
|
|
205
|
+
and not arguments[1].startswith("-")
|
|
206
|
+
and _could_be_command(arguments[1])
|
|
207
|
+
):
|
|
208
|
+
command = _resolve_command(arguments[1])
|
|
209
|
+
if command not in PROFILE_AWARE_COMMANDS:
|
|
210
|
+
raise ConfigurationError(
|
|
211
|
+
f"profile prefix '{first}' cannot be used with '{command}'"
|
|
212
|
+
)
|
|
213
|
+
return [command, *arguments[2:]], validate_profile_name(first)
|
|
214
|
+
return [_resolve_command(first), *arguments[1:]], None
|
|
215
|
+
|
|
216
|
+
|
|
217
|
+
def _profile_argument(parser: argparse.ArgumentParser) -> None:
|
|
218
|
+
parser.add_argument(
|
|
219
|
+
"profile_name",
|
|
220
|
+
nargs="?",
|
|
221
|
+
metavar="PROFILE",
|
|
222
|
+
help="profile; inferred from the current directory when omitted",
|
|
223
|
+
)
|
|
224
|
+
|
|
225
|
+
|
|
226
|
+
def build_parser() -> argparse.ArgumentParser:
|
|
227
|
+
parser = argparse.ArgumentParser(
|
|
228
|
+
prog="wpsync",
|
|
229
|
+
description=(
|
|
230
|
+
"Manage WordPress posts as local Markdown files. Run commands inside "
|
|
231
|
+
"a mapped profile folder, or prefix a command with a profile name. "
|
|
232
|
+
"Commands may be shortened to any unique prefix."
|
|
233
|
+
),
|
|
234
|
+
)
|
|
235
|
+
parser.add_argument("-v", "--version", action="version", version=__version__)
|
|
236
|
+
parser.add_argument(
|
|
237
|
+
"--legend", action="store_true", help="show diff and ls symbols and exit"
|
|
238
|
+
)
|
|
239
|
+
subparsers = parser.add_subparsers(dest="command")
|
|
240
|
+
|
|
241
|
+
init = subparsers.add_parser(
|
|
242
|
+
"init",
|
|
243
|
+
help="create a profile that maps a local folder to a blog",
|
|
244
|
+
description=(
|
|
245
|
+
"Create a profile for a WordPress site without signing in. Without "
|
|
246
|
+
"--local-root, offer the current directory. Pull next."
|
|
247
|
+
),
|
|
248
|
+
)
|
|
249
|
+
init.add_argument("profile_name", metavar="PROFILE", help="new profile name")
|
|
250
|
+
init.add_argument(
|
|
251
|
+
"--site", required=True, help="blog address, such as https://example.com"
|
|
252
|
+
)
|
|
253
|
+
init.add_argument(
|
|
254
|
+
"-u", "--username", help="WordPress username; prompted when omitted"
|
|
255
|
+
)
|
|
256
|
+
init.add_argument(
|
|
257
|
+
"--password-env",
|
|
258
|
+
metavar="NAME",
|
|
259
|
+
help="password environment variable (default: PROFILE_WP_PASSWORD)",
|
|
260
|
+
)
|
|
261
|
+
init.add_argument("--local-root", metavar="PATH", help="local folder for this blog")
|
|
262
|
+
|
|
263
|
+
map_parser = subparsers.add_parser(
|
|
264
|
+
"map",
|
|
265
|
+
help="move a profile's local folder",
|
|
266
|
+
usage="wpsync map [PROFILE] [--local-root PATH]\n wpsync PROFILE map",
|
|
267
|
+
description=(
|
|
268
|
+
"Point a profile at a different local folder after a [y/N] "
|
|
269
|
+
"confirmation. A different blog needs its own profile."
|
|
270
|
+
),
|
|
271
|
+
)
|
|
272
|
+
_profile_argument(map_parser)
|
|
273
|
+
map_parser.add_argument(
|
|
274
|
+
"--local-root",
|
|
275
|
+
metavar="PATH",
|
|
276
|
+
help="new local folder; defaults to the current directory",
|
|
277
|
+
)
|
|
278
|
+
|
|
279
|
+
remove = subparsers.add_parser(
|
|
280
|
+
"remove",
|
|
281
|
+
help="remove a profile",
|
|
282
|
+
usage="wpsync remove [PROFILE]\n wpsync PROFILE remove",
|
|
283
|
+
description="Remove the profile only; local files and the blog stay unchanged.",
|
|
284
|
+
)
|
|
285
|
+
_profile_argument(remove)
|
|
286
|
+
|
|
287
|
+
root = subparsers.add_parser(
|
|
288
|
+
"root",
|
|
289
|
+
help="print a profile's local folder",
|
|
290
|
+
usage="wpsync root [PROFILE]\n wpsync PROFILE root",
|
|
291
|
+
description=(
|
|
292
|
+
'Print only the local folder, suitable for cd "$(wpsync root PROFILE)".'
|
|
293
|
+
),
|
|
294
|
+
)
|
|
295
|
+
_profile_argument(root)
|
|
296
|
+
|
|
297
|
+
profile = subparsers.add_parser(
|
|
298
|
+
"profile",
|
|
299
|
+
help="show the current or named profile",
|
|
300
|
+
usage=(
|
|
301
|
+
"wpsync profile [PROFILE] [--details]\n"
|
|
302
|
+
" wpsync PROFILE profile [--details]"
|
|
303
|
+
),
|
|
304
|
+
)
|
|
305
|
+
_profile_argument(profile)
|
|
306
|
+
profile.add_argument(
|
|
307
|
+
"--details",
|
|
308
|
+
action="store_true",
|
|
309
|
+
help="show the site, account, and local folder",
|
|
310
|
+
)
|
|
311
|
+
|
|
312
|
+
subparsers.add_parser(
|
|
313
|
+
"profiles",
|
|
314
|
+
help="list profiles",
|
|
315
|
+
description="List profiles; * marks the one containing this directory.",
|
|
316
|
+
)
|
|
317
|
+
|
|
318
|
+
editor = subparsers.add_parser(
|
|
319
|
+
"editor",
|
|
320
|
+
help="choose the editor that open uses",
|
|
321
|
+
usage="wpsync editor [obsidian|vscode]",
|
|
322
|
+
description=(
|
|
323
|
+
"Choose the Markdown editor that open uses, saved in "
|
|
324
|
+
"~/.wpsync/config.json. Asks when no editor is named."
|
|
325
|
+
),
|
|
326
|
+
)
|
|
327
|
+
editor.add_argument(
|
|
328
|
+
"name",
|
|
329
|
+
nargs="?",
|
|
330
|
+
choices=list(Editor),
|
|
331
|
+
metavar="obsidian|vscode",
|
|
332
|
+
help="the editor",
|
|
333
|
+
)
|
|
334
|
+
|
|
335
|
+
create = subparsers.add_parser(
|
|
336
|
+
"create",
|
|
337
|
+
help="start a new post file",
|
|
338
|
+
usage=(
|
|
339
|
+
"wpsync create [FILE] [-t TITLE] [-s SLUG] [-o]\n"
|
|
340
|
+
" wpsync PROFILE create [FILE] [-t TITLE] [-s SLUG] [-o]"
|
|
341
|
+
),
|
|
342
|
+
description=(
|
|
343
|
+
"Start a private post under content/. Set its status to public when push "
|
|
344
|
+
"should publish it. A post may stay untitled."
|
|
345
|
+
),
|
|
346
|
+
)
|
|
347
|
+
create.add_argument(
|
|
348
|
+
"file",
|
|
349
|
+
nargs="?",
|
|
350
|
+
metavar="FILE",
|
|
351
|
+
help=(
|
|
352
|
+
'a title, such as "Working with AI", or a slug, such as '
|
|
353
|
+
"working-with-ai; makes the title, slug, and file name under content/. "
|
|
354
|
+
"Without it, an untitled post named from the date and time"
|
|
355
|
+
),
|
|
356
|
+
)
|
|
357
|
+
create.add_argument("-t", "--title", default="", help="a different title")
|
|
358
|
+
create.add_argument(
|
|
359
|
+
"-o", "--open", action="store_true", help="open the new file in your editor"
|
|
360
|
+
)
|
|
361
|
+
create.add_argument(
|
|
362
|
+
"-s", "--slug", help="a different slug, the post's address on the blog"
|
|
363
|
+
)
|
|
364
|
+
|
|
365
|
+
ls = subparsers.add_parser(
|
|
366
|
+
"ls",
|
|
367
|
+
help="list local posts and how many issues each has",
|
|
368
|
+
usage="wpsync ls [-l]\n wpsync PROFILE ls [-l]",
|
|
369
|
+
description=(
|
|
370
|
+
"List the post files in this profile without contacting the blog. On a "
|
|
371
|
+
"terminal, lines are cut to fit instead of wrapping."
|
|
372
|
+
),
|
|
373
|
+
)
|
|
374
|
+
ls.add_argument(
|
|
375
|
+
"-l",
|
|
376
|
+
"--long",
|
|
377
|
+
action="store_true",
|
|
378
|
+
help="show each post's file and URL on their own lines",
|
|
379
|
+
)
|
|
380
|
+
|
|
381
|
+
show = subparsers.add_parser(
|
|
382
|
+
"show",
|
|
383
|
+
help="show one post's details and issues",
|
|
384
|
+
usage="wpsync show ID|SLUG\n wpsync PROFILE show ID|SLUG",
|
|
385
|
+
description=(
|
|
386
|
+
"Show a post's details and what is wrong with it, without contacting "
|
|
387
|
+
"the blog. A title or file also selects a post."
|
|
388
|
+
),
|
|
389
|
+
)
|
|
390
|
+
show.add_argument("post", metavar="ID|SLUG", help="the post")
|
|
391
|
+
|
|
392
|
+
open_parser = subparsers.add_parser(
|
|
393
|
+
"open",
|
|
394
|
+
help="open a post file in your editor",
|
|
395
|
+
usage="wpsync open [ID|SLUG]\n wpsync PROFILE open [ID|SLUG]",
|
|
396
|
+
description=(
|
|
397
|
+
"Open a post's file in the editor chosen with wpsync editor, asking "
|
|
398
|
+
"first if none is chosen. A title or file also selects the post."
|
|
399
|
+
),
|
|
400
|
+
)
|
|
401
|
+
open_parser.add_argument(
|
|
402
|
+
"post",
|
|
403
|
+
nargs="?",
|
|
404
|
+
metavar="ID|SLUG",
|
|
405
|
+
help="the post; the one edited last when omitted",
|
|
406
|
+
)
|
|
407
|
+
|
|
408
|
+
diff = subparsers.add_parser(
|
|
409
|
+
"diff",
|
|
410
|
+
help="show what push would change",
|
|
411
|
+
usage=(
|
|
412
|
+
"wpsync diff [ID|SLUG] [-a] [-x] [-p]\n"
|
|
413
|
+
" wpsync PROFILE diff [ID|SLUG] [-a] [-x] [-p]"
|
|
414
|
+
),
|
|
415
|
+
description=(
|
|
416
|
+
"Show local changes and anything that would stop a push. Contacts the "
|
|
417
|
+
"blog only for changed, new, or, with -p, deleted posts. A title or file "
|
|
418
|
+
"also selects a post."
|
|
419
|
+
),
|
|
420
|
+
)
|
|
421
|
+
diff.add_argument(
|
|
422
|
+
"post", nargs="?", metavar="ID|SLUG", help="one post; all when omitted"
|
|
423
|
+
)
|
|
424
|
+
diff.add_argument(
|
|
425
|
+
"-a", "--all", action="store_true", help="show every post, unchanged too"
|
|
426
|
+
)
|
|
427
|
+
diff.add_argument(
|
|
428
|
+
"-x",
|
|
429
|
+
"--excluded",
|
|
430
|
+
action="store_true",
|
|
431
|
+
help="also show private posts, which push skips",
|
|
432
|
+
)
|
|
433
|
+
diff.add_argument(
|
|
434
|
+
"-p",
|
|
435
|
+
"--prune",
|
|
436
|
+
action="store_true",
|
|
437
|
+
help="show what push -p would delete from the blog",
|
|
438
|
+
)
|
|
439
|
+
|
|
440
|
+
push = subparsers.add_parser(
|
|
441
|
+
"push",
|
|
442
|
+
help="send local posts to the blog",
|
|
443
|
+
usage=(
|
|
444
|
+
"wpsync push [ID|SLUG] [-p] [-y]\n"
|
|
445
|
+
" wpsync PROFILE push [ID|SLUG] [-p] [-y]"
|
|
446
|
+
),
|
|
447
|
+
description=(
|
|
448
|
+
"Create and update posts on the blog from changed local files. Publishes "
|
|
449
|
+
"public posts and never sends private ones, except to turn a published "
|
|
450
|
+
"post that became private into a draft. Deletes nothing unless -p is "
|
|
451
|
+
"given. A title or file also selects a post; select a deleted file's "
|
|
452
|
+
"post by its ID."
|
|
453
|
+
),
|
|
454
|
+
)
|
|
455
|
+
push.add_argument(
|
|
456
|
+
"post", nargs="?", metavar="ID|SLUG", help="one post; all when omitted"
|
|
457
|
+
)
|
|
458
|
+
push.add_argument(
|
|
459
|
+
"-p",
|
|
460
|
+
"--prune",
|
|
461
|
+
action="store_true",
|
|
462
|
+
help="delete posts whose files were deleted, keeping them in .trash/",
|
|
463
|
+
)
|
|
464
|
+
push.add_argument(
|
|
465
|
+
"-y", "--yes", action="store_true", help="answer yes to every question"
|
|
466
|
+
)
|
|
467
|
+
|
|
468
|
+
delete = subparsers.add_parser(
|
|
469
|
+
"delete",
|
|
470
|
+
help="delete a post from the blog, keeping it in .trash/",
|
|
471
|
+
usage="wpsync delete ID|SLUG [-y]\n wpsync PROFILE delete ID|SLUG [-y]",
|
|
472
|
+
description=(
|
|
473
|
+
"Delete a post from the blog for good, with the library images no other "
|
|
474
|
+
"post or page uses, and move its file and images into the profile "
|
|
475
|
+
"folder's .trash/, keeping their paths. Asks first. A title or file "
|
|
476
|
+
"also selects the post."
|
|
477
|
+
),
|
|
478
|
+
)
|
|
479
|
+
delete.add_argument("post", metavar="ID|SLUG", help="the post")
|
|
480
|
+
delete.add_argument(
|
|
481
|
+
"-y", "--yes", action="store_true", help="delete without asking"
|
|
482
|
+
)
|
|
483
|
+
|
|
484
|
+
subparsers.add_parser(
|
|
485
|
+
"trash",
|
|
486
|
+
help="list the posts in .trash/",
|
|
487
|
+
usage="wpsync trash\n wpsync PROFILE trash",
|
|
488
|
+
description="List deleted posts kept in .trash/, without contacting the blog.",
|
|
489
|
+
)
|
|
490
|
+
|
|
491
|
+
restore = subparsers.add_parser(
|
|
492
|
+
"restore",
|
|
493
|
+
help="bring a post back from .trash/",
|
|
494
|
+
usage="wpsync restore ID|SLUG\n wpsync PROFILE restore ID|SLUG",
|
|
495
|
+
description=(
|
|
496
|
+
"Move a post and its images from .trash/ back where they were, as a new "
|
|
497
|
+
"post: the next push creates it on the blog. A title or file also "
|
|
498
|
+
"selects the post."
|
|
499
|
+
),
|
|
500
|
+
)
|
|
501
|
+
restore.add_argument("post", metavar="ID|SLUG", help="the post")
|
|
502
|
+
|
|
503
|
+
pull = subparsers.add_parser(
|
|
504
|
+
"pull",
|
|
505
|
+
help="bring posts from the blog into local files",
|
|
506
|
+
usage="wpsync pull [ID|SLUG] [-y]\n wpsync PROFILE pull [ID|SLUG] [-y]",
|
|
507
|
+
description=(
|
|
508
|
+
"Create and update local post files from the blog and download their "
|
|
509
|
+
"images. Local edits are never overwritten without asking. A file also "
|
|
510
|
+
"selects a post."
|
|
511
|
+
),
|
|
512
|
+
)
|
|
513
|
+
pull.add_argument(
|
|
514
|
+
"post", nargs="?", metavar="ID|SLUG", help="one post; all when omitted"
|
|
515
|
+
)
|
|
516
|
+
pull.add_argument(
|
|
517
|
+
"-y", "--yes", action="store_true", help="answer yes to every question"
|
|
518
|
+
)
|
|
519
|
+
return parser
|
|
520
|
+
|
|
521
|
+
|
|
522
|
+
def _resolve_profile(
|
|
523
|
+
arguments: argparse.Namespace, configuration: Configuration
|
|
524
|
+
) -> tuple[str, Profile]:
|
|
525
|
+
prefix = arguments.profile_prefix
|
|
526
|
+
positional = getattr(arguments, "profile_name", None)
|
|
527
|
+
if prefix is not None and positional is not None:
|
|
528
|
+
raise ConfigurationError(
|
|
529
|
+
"profile was specified both before the command and as an argument"
|
|
530
|
+
)
|
|
531
|
+
name = prefix or positional
|
|
532
|
+
if name is None:
|
|
533
|
+
active = configuration.profile_for_path(Path.cwd().resolve())
|
|
534
|
+
if active is None:
|
|
535
|
+
raise ConfigurationError(
|
|
536
|
+
"current directory is not inside a mapped profile; prefix the "
|
|
537
|
+
"command with a profile (wpsync PROFILE COMMAND)"
|
|
538
|
+
)
|
|
539
|
+
return active
|
|
540
|
+
name = validate_profile_name(name)
|
|
541
|
+
if name not in configuration.profiles:
|
|
542
|
+
raise ConfigurationError(f"profile '{name}' does not exist")
|
|
543
|
+
return name, configuration.profiles[name]
|
|
544
|
+
|
|
545
|
+
|
|
546
|
+
def _normalize_site(site: str) -> str:
|
|
547
|
+
site = site.strip()
|
|
548
|
+
if "://" not in site:
|
|
549
|
+
site = f"https://{site}"
|
|
550
|
+
url = httpx.URL(site)
|
|
551
|
+
if url.scheme not in {"http", "https"} or not url.host:
|
|
552
|
+
raise ConfigurationError(f"'{site}' is not an http or https address")
|
|
553
|
+
return site
|
|
554
|
+
|
|
555
|
+
|
|
556
|
+
def _sign_in(client: WordPressClient, profile: Profile) -> list[str]:
|
|
557
|
+
"""Check the account can sync, and describe what limits it."""
|
|
558
|
+
user = client.current_user()
|
|
559
|
+
capabilities = user.get("capabilities", {})
|
|
560
|
+
if not capabilities.get("edit_posts"):
|
|
561
|
+
raise WordPressError(
|
|
562
|
+
f"'{profile.username}' cannot edit posts on {profile.site}"
|
|
563
|
+
)
|
|
564
|
+
roles = ", ".join(user.get("roles", [])) or "no role"
|
|
565
|
+
lines = [f"Signed in to {profile.site} as '{profile.username}' ({roles})."]
|
|
566
|
+
if not capabilities.get("edit_others_posts"):
|
|
567
|
+
lines.append(
|
|
568
|
+
"Note: this account can edit only its own posts, so posts by other "
|
|
569
|
+
"authors are not pulled."
|
|
570
|
+
)
|
|
571
|
+
if not capabilities.get("unfiltered_html"):
|
|
572
|
+
lines.append(
|
|
573
|
+
"Note: this account lacks unfiltered_html, so WordPress removes "
|
|
574
|
+
"markup such as iframes and scripts from saved posts."
|
|
575
|
+
)
|
|
576
|
+
return lines
|
|
577
|
+
|
|
578
|
+
|
|
579
|
+
def _init(arguments: argparse.Namespace, session: _Session) -> str:
|
|
580
|
+
name = validate_profile_name(arguments.profile_name)
|
|
581
|
+
configuration = session.store.load()
|
|
582
|
+
if name in configuration.profiles:
|
|
583
|
+
raise ConfigurationError(f"profile '{name}' already exists")
|
|
584
|
+
site = _normalize_site(arguments.site)
|
|
585
|
+
api_root = discover_api_root(site, session.transport)
|
|
586
|
+
password_env = (
|
|
587
|
+
validate_environment_name(arguments.password_env)
|
|
588
|
+
if arguments.password_env
|
|
589
|
+
else default_password_env(name)
|
|
590
|
+
)
|
|
591
|
+
username = arguments.username or session.ask("WordPress username: ")
|
|
592
|
+
if not username:
|
|
593
|
+
raise ConfigurationError("a WordPress username is required")
|
|
594
|
+
if arguments.local_root is not None:
|
|
595
|
+
local_root = canonical_local_root(arguments.local_root)
|
|
596
|
+
else:
|
|
597
|
+
current = canonical_local_root(Path.cwd())
|
|
598
|
+
if session.confirm(
|
|
599
|
+
f"Map current directory '{current}' to {site}? [Y/n] ", default=True
|
|
600
|
+
):
|
|
601
|
+
local_root = current
|
|
602
|
+
else:
|
|
603
|
+
supplied = session.ask("What local folder should be mapped instead? ")
|
|
604
|
+
if not supplied:
|
|
605
|
+
raise ConfigurationError("a local folder is required; use --local-root")
|
|
606
|
+
local_root = canonical_local_root(supplied)
|
|
607
|
+
configuration.check_root(name, local_root)
|
|
608
|
+
configuration.add(name, Profile(site, api_root, username, password_env, local_root))
|
|
609
|
+
session.store.save(configuration)
|
|
610
|
+
step = "run wpsync pull"
|
|
611
|
+
if not session.environ.get(password_env):
|
|
612
|
+
step = f"set {password_env} to an Application Password, then {step}"
|
|
613
|
+
return f"Created profile '{name}': '{local_root}' maps to {site}.\nNext: {step}."
|
|
614
|
+
|
|
615
|
+
|
|
616
|
+
def _map(arguments: argparse.Namespace, session: _Session) -> str:
|
|
617
|
+
configuration = session.store.load()
|
|
618
|
+
name, profile = _resolve_profile(arguments, configuration)
|
|
619
|
+
local_root = canonical_local_root(arguments.local_root or Path.cwd())
|
|
620
|
+
if local_root == profile.local_root:
|
|
621
|
+
return f"Profile '{name}' already uses '{local_root}'."
|
|
622
|
+
configuration.remap(name, local_root)
|
|
623
|
+
prompt = (
|
|
624
|
+
f"Change profile '{name}' local folder from '{profile.local_root}' "
|
|
625
|
+
f"to '{local_root}'? [y/N] "
|
|
626
|
+
)
|
|
627
|
+
if not session.confirm(prompt, default=False):
|
|
628
|
+
return f"Profile '{name}' is unchanged."
|
|
629
|
+
session.store.save(configuration)
|
|
630
|
+
return f"Mapped '{local_root}' to {profile.site}."
|
|
631
|
+
|
|
632
|
+
|
|
633
|
+
def _remove(arguments: argparse.Namespace, session: _Session) -> str:
|
|
634
|
+
configuration = session.store.load()
|
|
635
|
+
name, _ = _resolve_profile(arguments, configuration)
|
|
636
|
+
del configuration.profiles[name]
|
|
637
|
+
session.store.save(configuration)
|
|
638
|
+
return f"Removed profile '{name}'. Local files and the blog are unchanged."
|
|
639
|
+
|
|
640
|
+
|
|
641
|
+
def _root(arguments: argparse.Namespace, session: _Session) -> str:
|
|
642
|
+
_, profile = _resolve_profile(arguments, session.store.load())
|
|
643
|
+
return os.fspath(profile.local_root)
|
|
644
|
+
|
|
645
|
+
|
|
646
|
+
def _profile(arguments: argparse.Namespace, session: _Session) -> str:
|
|
647
|
+
configuration = session.store.load()
|
|
648
|
+
if arguments.profile_prefix is None and arguments.profile_name is None:
|
|
649
|
+
active = configuration.profile_for_path(Path.cwd().resolve())
|
|
650
|
+
if active is None:
|
|
651
|
+
return "No active profile. Use wpsync PROFILE COMMAND."
|
|
652
|
+
name, profile = active
|
|
653
|
+
else:
|
|
654
|
+
name, profile = _resolve_profile(arguments, configuration)
|
|
655
|
+
if not arguments.details:
|
|
656
|
+
return name
|
|
657
|
+
return "\n".join(
|
|
658
|
+
(
|
|
659
|
+
f"Profile '{name}':",
|
|
660
|
+
f" Site: {profile.site}",
|
|
661
|
+
f" REST API: {profile.api_root}",
|
|
662
|
+
f" Username: {profile.username}",
|
|
663
|
+
f" Password env: {profile.password_env}",
|
|
664
|
+
f" Local root: {profile.local_root}",
|
|
665
|
+
)
|
|
666
|
+
)
|
|
667
|
+
|
|
668
|
+
|
|
669
|
+
def _profiles(arguments: argparse.Namespace, session: _Session) -> str:
|
|
670
|
+
configuration = session.store.load()
|
|
671
|
+
if not configuration.profiles:
|
|
672
|
+
return "No profiles configured."
|
|
673
|
+
active = configuration.profile_for_path(Path.cwd().resolve())
|
|
674
|
+
active_name = active[0] if active else None
|
|
675
|
+
return "\n".join(
|
|
676
|
+
f"{'*' if name == active_name else ' '} {name}"
|
|
677
|
+
for name in sorted(configuration.profiles)
|
|
678
|
+
)
|
|
679
|
+
|
|
680
|
+
|
|
681
|
+
def _use_color(stream: TextIO, environ: Mapping[str, str]) -> bool:
|
|
682
|
+
if "NO_COLOR" in environ:
|
|
683
|
+
return False
|
|
684
|
+
is_terminal = getattr(stream, "isatty", None)
|
|
685
|
+
return bool(is_terminal and is_terminal())
|
|
686
|
+
|
|
687
|
+
|
|
688
|
+
def _paint(text: str, color: bool) -> str:
|
|
689
|
+
if not color:
|
|
690
|
+
return text
|
|
691
|
+
return "".join(
|
|
692
|
+
f"{MARKER_COLORS[char]}{char}{RESET}" if char in MARKER_COLORS else char
|
|
693
|
+
for char in text
|
|
694
|
+
)
|
|
695
|
+
|
|
696
|
+
|
|
697
|
+
def _legend(session: _Session) -> str:
|
|
698
|
+
color = _use_color(session.stdout, session.environ)
|
|
699
|
+
lines = ["Diff legend:"]
|
|
700
|
+
for marker, meaning in LEGEND:
|
|
701
|
+
if marker == "/":
|
|
702
|
+
shown = f"{DIRECTORY_COLOR}/{RESET}" if color else marker
|
|
703
|
+
else:
|
|
704
|
+
shown = _paint(marker, color)
|
|
705
|
+
lines.append(f" {shown} {meaning}")
|
|
706
|
+
lines.append("ls legend:")
|
|
707
|
+
width = max(len(marker) for marker, _ in LS_LEGEND)
|
|
708
|
+
lines.extend(f" {marker:<{width}} {meaning}" for marker, meaning in LS_LEGEND)
|
|
709
|
+
return "\n".join(lines)
|
|
710
|
+
|
|
711
|
+
|
|
712
|
+
class _LazyRemote:
|
|
713
|
+
"""Connects to the blog only if a command turns out to need it."""
|
|
714
|
+
|
|
715
|
+
def __init__(self, profile: Profile, session: _Session) -> None:
|
|
716
|
+
self.profile = profile
|
|
717
|
+
self.session = session
|
|
718
|
+
self.client: WordPressClient | None = None
|
|
719
|
+
|
|
720
|
+
def connect(self) -> WordPressClient:
|
|
721
|
+
if self.client is None:
|
|
722
|
+
self.session.status(f"Connecting to {self.profile.site}...")
|
|
723
|
+
self.client = WordPressClient(
|
|
724
|
+
self.profile.api_root,
|
|
725
|
+
self.profile.username,
|
|
726
|
+
self.session.password(self.profile),
|
|
727
|
+
self.session.transport,
|
|
728
|
+
)
|
|
729
|
+
return self.client
|
|
730
|
+
|
|
731
|
+
def post_states(self, ids: list[str]) -> dict[str, RemoteState]:
|
|
732
|
+
return self.connect().post_states(ids)
|
|
733
|
+
|
|
734
|
+
def post_summaries(self) -> list[PostSummary]:
|
|
735
|
+
return self.connect().post_summaries()
|
|
736
|
+
|
|
737
|
+
def close(self) -> None:
|
|
738
|
+
if self.client is not None:
|
|
739
|
+
self.client.http.close()
|
|
740
|
+
|
|
741
|
+
|
|
742
|
+
def _profile_name(arguments: argparse.Namespace, session: _Session) -> str:
|
|
743
|
+
return _resolve_profile(arguments, session.store.load())[0]
|
|
744
|
+
|
|
745
|
+
|
|
746
|
+
def _profile_root(
|
|
747
|
+
arguments: argparse.Namespace, session: _Session
|
|
748
|
+
) -> tuple[Profile, Path]:
|
|
749
|
+
_, profile = _resolve_profile(arguments, session.store.load())
|
|
750
|
+
base = profile.local_root if arguments.profile_prefix else Path.cwd().resolve()
|
|
751
|
+
return profile, base
|
|
752
|
+
|
|
753
|
+
|
|
754
|
+
def _create(arguments: argparse.Namespace, session: _Session) -> str:
|
|
755
|
+
profile, _ = _profile_root(arguments, session)
|
|
756
|
+
root = profile.local_root
|
|
757
|
+
title, slug = arguments.title, arguments.slug or ""
|
|
758
|
+
if arguments.file is None:
|
|
759
|
+
relative = _timestamp_file(root, datetime.now())
|
|
760
|
+
else:
|
|
761
|
+
relative, named_title, named_slug = _named_post(arguments.file)
|
|
762
|
+
title, slug = title or named_title, slug or named_slug
|
|
763
|
+
if slug:
|
|
764
|
+
users = [
|
|
765
|
+
item.path
|
|
766
|
+
for item in scan_documents(root)
|
|
767
|
+
if item.document.post.slug == slug
|
|
768
|
+
]
|
|
769
|
+
if users:
|
|
770
|
+
raise SelectionError(f"slug '{slug}' is used by {users[0]}")
|
|
771
|
+
path = root / relative
|
|
772
|
+
if path.exists():
|
|
773
|
+
raise SelectionError(f"{relative} already exists")
|
|
774
|
+
write_document(path, Document(None, Post(title=title, slug=slug)))
|
|
775
|
+
created = f"Created {relative} (private; set status: public to publish it)."
|
|
776
|
+
if arguments.open:
|
|
777
|
+
return f"{created}\n{_open_file(session, root, relative)}"
|
|
778
|
+
return created
|
|
779
|
+
|
|
780
|
+
|
|
781
|
+
def _timestamp_file(root: Path, now: datetime) -> PurePosixPath:
|
|
782
|
+
"""A free file name under the posts folder from the current time."""
|
|
783
|
+
stem = now.strftime(TIMESTAMP_FORMAT)
|
|
784
|
+
for name in (stem, *(f"{stem}-{n}" for n in range(2, 100))):
|
|
785
|
+
relative = PurePosixPath(CONTENT_DIR, f"{name}.md")
|
|
786
|
+
if not (root / relative).exists():
|
|
787
|
+
return relative
|
|
788
|
+
raise SelectionError(f"too many posts named {stem} in {CONTENT_DIR}/")
|
|
789
|
+
|
|
790
|
+
|
|
791
|
+
def _named_post(name: str) -> tuple[PurePosixPath, str, str]:
|
|
792
|
+
"""A new post's file, title, and slug from the name given to create.
|
|
793
|
+
|
|
794
|
+
A name already in slug form is the file name and slug, and its words make the
|
|
795
|
+
title; any other name is the title, and its slug names the file.
|
|
796
|
+
"""
|
|
797
|
+
folder, _, last = name.removesuffix(".md").rpartition("/")
|
|
798
|
+
slug = _slugify(last)
|
|
799
|
+
title = last.replace("-", " ").capitalize() if slug == last else last
|
|
800
|
+
if not slug or ".." in folder.split("/") or folder.startswith("/"):
|
|
801
|
+
raise SelectionError(f"'{name}' does not make a file name")
|
|
802
|
+
return PurePosixPath(CONTENT_DIR, folder, f"{slug}.md"), title, slug
|
|
803
|
+
|
|
804
|
+
|
|
805
|
+
def _slugify(text: str) -> str:
|
|
806
|
+
"""Lowercase words joined by hyphens, accents dropped, as blogs make slugs."""
|
|
807
|
+
decomposed = unicodedata.normalize("NFKD", text)
|
|
808
|
+
plain = "".join(c for c in decomposed if not unicodedata.combining(c))
|
|
809
|
+
return re.sub(r"\W+", "-", plain.casefold()).strip("-")
|
|
810
|
+
|
|
811
|
+
|
|
812
|
+
def _ls(arguments: argparse.Namespace, session: _Session) -> str:
|
|
813
|
+
profile, _ = _profile_root(arguments, session)
|
|
814
|
+
documents = scan_documents(profile.local_root)
|
|
815
|
+
if not documents:
|
|
816
|
+
return NO_POSTS
|
|
817
|
+
|
|
818
|
+
def order(item): # noqa: ANN001, ANN202
|
|
819
|
+
post_id = item.document.post_id
|
|
820
|
+
return (post_id is None, int(post_id) if post_id else 0, str(item.path))
|
|
821
|
+
|
|
822
|
+
records = read_records(profile.local_root, profile.api_root)
|
|
823
|
+
heading = "Title" if arguments.long else "Title (file)"
|
|
824
|
+
now = datetime.now(UTC)
|
|
825
|
+
rows = [("ID", "Public", "Issues", heading)]
|
|
826
|
+
details: list[list[str]] = [[]]
|
|
827
|
+
for item in sorted(documents, key=order):
|
|
828
|
+
post = item.document.post
|
|
829
|
+
post_id = item.document.post_id or "-"
|
|
830
|
+
record = records.get(post_id)
|
|
831
|
+
public = _public(post, now)
|
|
832
|
+
title = post.title or "(no title)"
|
|
833
|
+
missing = record.missing_files if record else ()
|
|
834
|
+
issues = str(len(missing)) if missing else "-"
|
|
835
|
+
if arguments.long:
|
|
836
|
+
rows.append((post_id, public, issues, title))
|
|
837
|
+
details.append([str(item.path), *([record.url] if record else [])])
|
|
838
|
+
else:
|
|
839
|
+
name = PurePosixPath(item.path).relative_to(CONTENT_DIR)
|
|
840
|
+
rows.append((post_id, public, issues, f"{title} ({name})"))
|
|
841
|
+
details.append([])
|
|
842
|
+
widths = [max(len(row[i]) for row in rows) for i in range(3)]
|
|
843
|
+
indent = " " * (sum(widths) + 6)
|
|
844
|
+
lines = []
|
|
845
|
+
for (post_id, public, issues, title), extra in zip(rows, details, strict=True):
|
|
846
|
+
lines.append(
|
|
847
|
+
f"{post_id:>{widths[0]}} {public:<{widths[1]}} "
|
|
848
|
+
f"{issues:<{widths[2]}} {title}"
|
|
849
|
+
)
|
|
850
|
+
lines.extend(indent + line for line in extra)
|
|
851
|
+
is_terminal = getattr(session.stdout, "isatty", None)
|
|
852
|
+
if is_terminal and is_terminal():
|
|
853
|
+
columns = shutil.get_terminal_size().columns
|
|
854
|
+
lines = [_fit(line, columns) for line in lines]
|
|
855
|
+
return "\n".join(lines)
|
|
856
|
+
|
|
857
|
+
|
|
858
|
+
def _public(post: Post, now: datetime) -> str:
|
|
859
|
+
"""The Public column: a mark, before the date for a post not yet shown."""
|
|
860
|
+
if post.status is not PostStatus.PUBLIC:
|
|
861
|
+
return ""
|
|
862
|
+
if post.date is None or post.date <= now:
|
|
863
|
+
return "*"
|
|
864
|
+
return f"*{post.date:%b} {post.date.day}, {post.date.year}"
|
|
865
|
+
|
|
866
|
+
|
|
867
|
+
def _cells(character: str) -> int:
|
|
868
|
+
"""How many terminal columns a character takes."""
|
|
869
|
+
if unicodedata.category(character) in ("Mn", "Me"):
|
|
870
|
+
return 0
|
|
871
|
+
return 2 if unicodedata.east_asian_width(character) in ("W", "F") else 1
|
|
872
|
+
|
|
873
|
+
|
|
874
|
+
def _fit(line: str, columns: int) -> str:
|
|
875
|
+
"""Cut a line to the terminal's width, so that it does not wrap."""
|
|
876
|
+
if sum(map(_cells, line)) <= columns:
|
|
877
|
+
return line
|
|
878
|
+
kept, used = [], 0
|
|
879
|
+
for character in line:
|
|
880
|
+
used += _cells(character)
|
|
881
|
+
if used > columns - 1:
|
|
882
|
+
break
|
|
883
|
+
kept.append(character)
|
|
884
|
+
return "".join(kept) + "…"
|
|
885
|
+
|
|
886
|
+
|
|
887
|
+
def _one_post(
|
|
888
|
+
arguments: argparse.Namespace, session: _Session
|
|
889
|
+
) -> tuple[Profile, LocalDocument, dict[str, PostRecord]]:
|
|
890
|
+
"""The profile, the file of the post a command names, and the records."""
|
|
891
|
+
profile, base = _profile_root(arguments, session)
|
|
892
|
+
root = profile.local_root
|
|
893
|
+
records = read_records(root, profile.api_root)
|
|
894
|
+
selection = select(
|
|
895
|
+
arguments.post, scan_documents(root), records, root=root, base=base
|
|
896
|
+
)
|
|
897
|
+
if not selection.documents:
|
|
898
|
+
raise SelectionError(f"post {arguments.post} has no local file")
|
|
899
|
+
return profile, selection.documents[0], records
|
|
900
|
+
|
|
901
|
+
|
|
902
|
+
def _show(arguments: argparse.Namespace, session: _Session) -> str:
|
|
903
|
+
_, item, records = _one_post(arguments, session)
|
|
904
|
+
post = item.document.post
|
|
905
|
+
post_id = item.document.post_id
|
|
906
|
+
record = records.get(post_id) if post_id else None
|
|
907
|
+
missing = record.missing_files if record else ()
|
|
908
|
+
fields = (
|
|
909
|
+
("ID", post_id or "-"),
|
|
910
|
+
("Title", post.title or "(no title)"),
|
|
911
|
+
("Slug", post.slug or "-"),
|
|
912
|
+
("Status", post.status.value),
|
|
913
|
+
("Date", format_date(post.date) if post.date else "-"),
|
|
914
|
+
("Categories", ", ".join(post.categories) or "-"),
|
|
915
|
+
("Tags", ", ".join(post.tags) or "-"),
|
|
916
|
+
("File", str(item.path)),
|
|
917
|
+
("URL", record.url if record else "-"),
|
|
918
|
+
("Issues", str(len(missing)) if missing else "-"),
|
|
919
|
+
)
|
|
920
|
+
lines = [f"{name + ':':<12}{value}" for name, value in fields]
|
|
921
|
+
lines.extend(f" missing file: {url}" for url in missing)
|
|
922
|
+
return "\n".join(lines)
|
|
923
|
+
|
|
924
|
+
|
|
925
|
+
def _diff(arguments: argparse.Namespace, session: _Session) -> str:
|
|
926
|
+
profile, base = _profile_root(arguments, session)
|
|
927
|
+
root = profile.local_root
|
|
928
|
+
selection = select(
|
|
929
|
+
arguments.post,
|
|
930
|
+
scan_documents(root),
|
|
931
|
+
read_records(root, profile.api_root),
|
|
932
|
+
root=root,
|
|
933
|
+
base=base,
|
|
934
|
+
)
|
|
935
|
+
session.status(
|
|
936
|
+
f"Checking differences for profile '{_profile_name(arguments, session)}'..."
|
|
937
|
+
)
|
|
938
|
+
session.status("Comparing local and remote posts...")
|
|
939
|
+
remote = _LazyRemote(profile, session)
|
|
940
|
+
try:
|
|
941
|
+
result = compare(
|
|
942
|
+
selection,
|
|
943
|
+
remote,
|
|
944
|
+
root=root,
|
|
945
|
+
media=read_media(root, profile.api_root),
|
|
946
|
+
prune=arguments.prune,
|
|
947
|
+
)
|
|
948
|
+
finally:
|
|
949
|
+
remote.close()
|
|
950
|
+
if not result.entries:
|
|
951
|
+
return NO_POSTS
|
|
952
|
+
color = _use_color(session.stdout, session.environ)
|
|
953
|
+
shown, hidden = [], Counter()
|
|
954
|
+
for entry in result.entries:
|
|
955
|
+
visible = (
|
|
956
|
+
arguments.all
|
|
957
|
+
or entry.action not in (Action.UNCHANGED, Action.PRIVATE, Action.KEPT)
|
|
958
|
+
or (entry.action is Action.PRIVATE and arguments.excluded)
|
|
959
|
+
)
|
|
960
|
+
if visible:
|
|
961
|
+
shown.append(entry)
|
|
962
|
+
elif entry.action in HIDDEN_HINTS:
|
|
963
|
+
hidden[entry.action] += 1
|
|
964
|
+
lines = _diff_tree(shown, color)
|
|
965
|
+
if not shown:
|
|
966
|
+
lines.append("No local changes.")
|
|
967
|
+
if hidden:
|
|
968
|
+
counts = [
|
|
969
|
+
f"{hidden[action]} {name} (try using {flag})"
|
|
970
|
+
for action, (name, flag) in HIDDEN_HINTS.items()
|
|
971
|
+
if hidden[action]
|
|
972
|
+
]
|
|
973
|
+
lines.append(f"Not shown: {', '.join(counts)}")
|
|
974
|
+
lines.extend(f"Note: {note}" for note in result.notes)
|
|
975
|
+
return "\n".join(lines)
|
|
976
|
+
|
|
977
|
+
|
|
978
|
+
def _diff_tree(entries: list[DiffEntry], color: bool) -> list[str]:
|
|
979
|
+
"""HLSync's diff layout: status slots, then folders before files, indented."""
|
|
980
|
+
|
|
981
|
+
def order(entry: DiffEntry) -> list[tuple[int, str]]:
|
|
982
|
+
*folders, name = PurePosixPath(display_path(entry.path)).parts
|
|
983
|
+
return [(0, folder) for folder in folders] + [(1, name)]
|
|
984
|
+
|
|
985
|
+
lines: list[str] = []
|
|
986
|
+
opened: tuple[str, ...] = ()
|
|
987
|
+
for entry in sorted(entries, key=order):
|
|
988
|
+
*folders, name = PurePosixPath(display_path(entry.path)).parts
|
|
989
|
+
common = 0
|
|
990
|
+
while common < min(len(opened), len(folders)) and (
|
|
991
|
+
opened[common] == folders[common]
|
|
992
|
+
):
|
|
993
|
+
common += 1
|
|
994
|
+
for depth in range(common, len(folders)):
|
|
995
|
+
folder = f"{folders[depth]}/"
|
|
996
|
+
if color:
|
|
997
|
+
folder = f"{DIRECTORY_COLOR}{folder}{RESET}"
|
|
998
|
+
lines.append(f" {' ' * depth}{folder}")
|
|
999
|
+
opened = tuple(folders)
|
|
1000
|
+
lines.append(
|
|
1001
|
+
_status_line(entry.action, entry.presence, name, len(folders), color)
|
|
1002
|
+
)
|
|
1003
|
+
# An image goes under the post that shows it, as the post refers to it.
|
|
1004
|
+
for image in entry.images:
|
|
1005
|
+
source = posixpath.relpath(image.path, entry.path.parent)
|
|
1006
|
+
presence = "l" if image.action is Action.NEW else ""
|
|
1007
|
+
lines.append(
|
|
1008
|
+
_status_line(image.action, presence, source, len(folders) + 1, color)
|
|
1009
|
+
)
|
|
1010
|
+
return lines
|
|
1011
|
+
|
|
1012
|
+
|
|
1013
|
+
def _status_line(
|
|
1014
|
+
entry_action: Action, entry_presence: str, name: str, depth: int, color: bool
|
|
1015
|
+
) -> str:
|
|
1016
|
+
"""Action, exclusion, and presence slots, as HLSync shows them."""
|
|
1017
|
+
private = entry_action is Action.PRIVATE
|
|
1018
|
+
action = " " if private else entry_action.value
|
|
1019
|
+
exclusion = "x" if private else " "
|
|
1020
|
+
presence = entry_presence or " "
|
|
1021
|
+
status = f"{action}{exclusion} {presence}"
|
|
1022
|
+
if not color:
|
|
1023
|
+
return f"{status} {' ' * depth}{name}"
|
|
1024
|
+
style = MARKER_COLORS.get(action) or MARKER_COLORS.get(presence)
|
|
1025
|
+
painted = f"{style}{name}{RESET}" if style else name
|
|
1026
|
+
return f"{_paint(status, color)} {' ' * depth}{painted}"
|
|
1027
|
+
|
|
1028
|
+
|
|
1029
|
+
def _pull_target(
|
|
1030
|
+
selector: str | None, documents: list[LocalDocument], root: Path, base: Path
|
|
1031
|
+
) -> tuple[list[str] | None, str | None]:
|
|
1032
|
+
"""The post IDs or slug a pull selector names; a slug may be remote only."""
|
|
1033
|
+
if selector is None:
|
|
1034
|
+
return None, None
|
|
1035
|
+
if selector.isdigit():
|
|
1036
|
+
return [selector], None
|
|
1037
|
+
if "/" in selector or selector.endswith(".md"):
|
|
1038
|
+
chosen = select(selector, documents, {}, root=root, base=base).documents
|
|
1039
|
+
post_id = chosen[0].document.post_id
|
|
1040
|
+
if post_id is None:
|
|
1041
|
+
raise SelectionError(
|
|
1042
|
+
f"{selector} is not linked to a post yet; push it first"
|
|
1043
|
+
)
|
|
1044
|
+
return [post_id], None
|
|
1045
|
+
local = [d for d in documents if d.document.post.slug == selector]
|
|
1046
|
+
if local and local[0].document.post_id:
|
|
1047
|
+
return [local[0].document.post_id], None
|
|
1048
|
+
return None, selector
|
|
1049
|
+
|
|
1050
|
+
|
|
1051
|
+
def _open(arguments: argparse.Namespace, session: _Session) -> str:
|
|
1052
|
+
if arguments.post is not None:
|
|
1053
|
+
profile, item, _ = _one_post(arguments, session)
|
|
1054
|
+
return _open_file(session, profile.local_root, PurePosixPath(item.path))
|
|
1055
|
+
# Without a name, the post edited last: the one just created when -o was
|
|
1056
|
+
# forgotten, or the one being worked on.
|
|
1057
|
+
profile, _ = _profile_root(arguments, session)
|
|
1058
|
+
root = profile.local_root
|
|
1059
|
+
documents = scan_documents(root)
|
|
1060
|
+
if not documents:
|
|
1061
|
+
raise SelectionError(NO_POSTS)
|
|
1062
|
+
latest = max(documents, key=lambda item: (root / item.path).stat().st_mtime)
|
|
1063
|
+
return _open_file(session, root, PurePosixPath(latest.path))
|
|
1064
|
+
|
|
1065
|
+
|
|
1066
|
+
def _open_file(session: _Session, root: Path, relative: PurePosixPath) -> str:
|
|
1067
|
+
configuration = session.store.load()
|
|
1068
|
+
editor = configuration.editor
|
|
1069
|
+
if editor is None:
|
|
1070
|
+
editor = _ask_editor(session)
|
|
1071
|
+
configuration.editor = editor
|
|
1072
|
+
session.store.save(configuration)
|
|
1073
|
+
session.launch(editor_command(editor, root, root / relative))
|
|
1074
|
+
return f"Opened {relative} in {editor.label}."
|
|
1075
|
+
|
|
1076
|
+
|
|
1077
|
+
def _delete(arguments: argparse.Namespace, session: _Session) -> str:
|
|
1078
|
+
profile, item, records = _one_post(arguments, session)
|
|
1079
|
+
root = profile.local_root
|
|
1080
|
+
path = PurePosixPath(item.path)
|
|
1081
|
+
post_id = item.document.post_id
|
|
1082
|
+
record = records.get(post_id) if post_id else None
|
|
1083
|
+
if post_id is not None and record is None:
|
|
1084
|
+
raise SelectionError(
|
|
1085
|
+
f"{path} has id {post_id} but was never synced here; pull it first"
|
|
1086
|
+
)
|
|
1087
|
+
confirm = _confirmer(session, arguments.yes)
|
|
1088
|
+
declined = "Nothing deleted." + (
|
|
1089
|
+
"" if arguments.yes else " Rerun with --yes to delete it."
|
|
1090
|
+
)
|
|
1091
|
+
if record is None:
|
|
1092
|
+
if not confirm(f"{path} is not on WordPress. Move it to {TRASH_DIR}/?"):
|
|
1093
|
+
return declined
|
|
1094
|
+
deleted = delete_post(
|
|
1095
|
+
root, profile.api_root, None, None, path, item.document, on_disk=True
|
|
1096
|
+
)
|
|
1097
|
+
return f"Moved {path} to {deleted.trashed}."
|
|
1098
|
+
post_id = record.post_id
|
|
1099
|
+
lazy = _LazyRemote(profile, session)
|
|
1100
|
+
remote: WordPressRemote | None = None
|
|
1101
|
+
try:
|
|
1102
|
+
state = lazy.post_states([post_id]).get(post_id)
|
|
1103
|
+
title = item.document.post.title
|
|
1104
|
+
question = (
|
|
1105
|
+
f"Delete #{post_id} {title!r} from WordPress for good, with its "
|
|
1106
|
+
f"comments? The file moves to {TRASH_DIR}/."
|
|
1107
|
+
)
|
|
1108
|
+
if state is None:
|
|
1109
|
+
question = (
|
|
1110
|
+
f"#{post_id} is already gone from WordPress. "
|
|
1111
|
+
f"Move {path} to {TRASH_DIR}/?"
|
|
1112
|
+
)
|
|
1113
|
+
elif state.fingerprint != record.remote_fingerprint:
|
|
1114
|
+
question = (
|
|
1115
|
+
f"#{post_id} changed on WordPress since the last sync. {question}"
|
|
1116
|
+
)
|
|
1117
|
+
if not confirm(question):
|
|
1118
|
+
return declined
|
|
1119
|
+
if state is not None:
|
|
1120
|
+
remote = WordPressRemote(lazy.connect(), session.transport)
|
|
1121
|
+
deleted = delete_post(
|
|
1122
|
+
root, profile.api_root, remote, post_id, path, item.document, on_disk=True
|
|
1123
|
+
)
|
|
1124
|
+
finally:
|
|
1125
|
+
if remote is not None:
|
|
1126
|
+
remote.close()
|
|
1127
|
+
lazy.close()
|
|
1128
|
+
moved = f"moved {path} to {deleted.trashed}"
|
|
1129
|
+
if remote is None:
|
|
1130
|
+
return f"#{post_id} was already gone from WordPress; {moved}."
|
|
1131
|
+
images = ""
|
|
1132
|
+
if deleted.media:
|
|
1133
|
+
count = len(deleted.media)
|
|
1134
|
+
images = f", with {count} image{'s' * (count != 1)}"
|
|
1135
|
+
return f"Deleted #{post_id} from WordPress{images}; {moved}."
|
|
1136
|
+
|
|
1137
|
+
|
|
1138
|
+
def _trash(arguments: argparse.Namespace, session: _Session) -> str:
|
|
1139
|
+
profile, _ = _profile_root(arguments, session)
|
|
1140
|
+
items = scan_trash(profile.local_root)
|
|
1141
|
+
if not items:
|
|
1142
|
+
return "The trash is empty."
|
|
1143
|
+
width = max(len("ID"), *(len(item.document.post_id or "-") for item in items))
|
|
1144
|
+
lines = [f"{'ID':>{width}} Title (restores to)"]
|
|
1145
|
+
for item in items:
|
|
1146
|
+
post = item.document.post
|
|
1147
|
+
original = PurePosixPath(item.path).relative_to(TRASH_DIR)
|
|
1148
|
+
lines.append(
|
|
1149
|
+
f"{item.document.post_id or '-':>{width}} "
|
|
1150
|
+
f"{post.title or '(no title)'} ({original})"
|
|
1151
|
+
)
|
|
1152
|
+
return "\n".join(lines)
|
|
1153
|
+
|
|
1154
|
+
|
|
1155
|
+
def _restore(arguments: argparse.Namespace, session: _Session) -> str:
|
|
1156
|
+
profile, base = _profile_root(arguments, session)
|
|
1157
|
+
root = profile.local_root
|
|
1158
|
+
selection = select(arguments.post, scan_trash(root), {}, root=root, base=base)
|
|
1159
|
+
if not selection.documents:
|
|
1160
|
+
raise SelectionError(f"post {arguments.post} is not in the trash")
|
|
1161
|
+
item = selection.documents[0]
|
|
1162
|
+
original = restore_post(root, item)
|
|
1163
|
+
if item.document.post_id and item.document.post.status is PostStatus.PUBLIC:
|
|
1164
|
+
return f"Restored {original}; push puts it back on the blog."
|
|
1165
|
+
return f"Restored {original}."
|
|
1166
|
+
|
|
1167
|
+
|
|
1168
|
+
def _editor(arguments: argparse.Namespace, session: _Session) -> str:
|
|
1169
|
+
editor = Editor(arguments.name) if arguments.name else _ask_editor(session)
|
|
1170
|
+
configuration = session.store.load()
|
|
1171
|
+
configuration.editor = editor
|
|
1172
|
+
session.store.save(configuration)
|
|
1173
|
+
return f"wpsync open now uses {editor.label}."
|
|
1174
|
+
|
|
1175
|
+
|
|
1176
|
+
def _ask_editor(session: _Session) -> Editor:
|
|
1177
|
+
if not getattr(session.stdin, "isatty", lambda: False)():
|
|
1178
|
+
raise EditorError("no editor chosen; run wpsync editor obsidian|vscode")
|
|
1179
|
+
editors = list(Editor)
|
|
1180
|
+
print("Open posts with:", file=session.stdout)
|
|
1181
|
+
for number, editor in enumerate(editors, 1):
|
|
1182
|
+
print(f" {number}) {editor.label}", file=session.stdout)
|
|
1183
|
+
other = len(editors) + 1
|
|
1184
|
+
print(f" {other}) Other", file=session.stdout)
|
|
1185
|
+
while True:
|
|
1186
|
+
answer = session.ask(f"Choose 1-{other}: ")
|
|
1187
|
+
if not answer:
|
|
1188
|
+
raise EditorError("no editor chosen")
|
|
1189
|
+
if answer == str(other):
|
|
1190
|
+
raise EditorError("only Obsidian and VS Code are supported for now")
|
|
1191
|
+
if answer.isdigit() and 1 <= int(answer) < other:
|
|
1192
|
+
return editors[int(answer) - 1]
|
|
1193
|
+
|
|
1194
|
+
|
|
1195
|
+
def _confirmer(session: _Session, yes: bool) -> Callable[[str], bool]:
|
|
1196
|
+
def confirm(question: str) -> bool:
|
|
1197
|
+
# Without a terminal nobody can answer, so the question counts as No.
|
|
1198
|
+
if yes:
|
|
1199
|
+
return True
|
|
1200
|
+
interactive = getattr(session.stdin, "isatty", lambda: False)()
|
|
1201
|
+
return interactive and session.confirm(f"{question} [y/N] ", default=False)
|
|
1202
|
+
|
|
1203
|
+
return confirm
|
|
1204
|
+
|
|
1205
|
+
|
|
1206
|
+
class _Progress:
|
|
1207
|
+
"""Push and pull's file lines, with HLSync's progress bar on a terminal."""
|
|
1208
|
+
|
|
1209
|
+
def __init__(self, session: _Session) -> None:
|
|
1210
|
+
self.output = session.progress
|
|
1211
|
+
self.color = _use_color(self.output, session.environ)
|
|
1212
|
+
isatty = getattr(self.output, "isatty", lambda: False)
|
|
1213
|
+
self.terminal = isatty() and session.environ.get("TERM") != "dumb"
|
|
1214
|
+
self.total = 0
|
|
1215
|
+
self.done = 0
|
|
1216
|
+
self.failed = 0
|
|
1217
|
+
self.unit = ""
|
|
1218
|
+
self.visible = False
|
|
1219
|
+
self.last_draw = 0.0
|
|
1220
|
+
|
|
1221
|
+
def start(self, total: int, unit: str) -> None:
|
|
1222
|
+
self.total, self.unit = total, unit
|
|
1223
|
+
self.draw(force=True)
|
|
1224
|
+
|
|
1225
|
+
def step(self) -> None:
|
|
1226
|
+
self.done += 1
|
|
1227
|
+
self.draw()
|
|
1228
|
+
|
|
1229
|
+
def report(self, outcome: Outcome, *, step: bool = False) -> None:
|
|
1230
|
+
self.clear()
|
|
1231
|
+
if outcome.failure:
|
|
1232
|
+
self.failed += 1
|
|
1233
|
+
line = f"failed {display_path(outcome.path)}: {outcome.failure}"
|
|
1234
|
+
line = f"{MARKER_COLORS['-']}{line}{RESET}" if self.color else line
|
|
1235
|
+
else:
|
|
1236
|
+
marker = outcome.action.value
|
|
1237
|
+
style = MARKER_COLORS.get(marker) if self.color else None
|
|
1238
|
+
line = f"{marker} {display_path(outcome.path)}"
|
|
1239
|
+
line = f"{style}{line}{RESET}" if style else line
|
|
1240
|
+
print(f" {line}", file=self.output, flush=True)
|
|
1241
|
+
self.done += step
|
|
1242
|
+
self.draw(force=True)
|
|
1243
|
+
|
|
1244
|
+
def clear(self) -> None:
|
|
1245
|
+
if self.visible:
|
|
1246
|
+
print("\r\033[2K", end="", file=self.output, flush=True)
|
|
1247
|
+
self.visible = False
|
|
1248
|
+
|
|
1249
|
+
def draw(self, *, force: bool = False) -> None:
|
|
1250
|
+
if not self.terminal or not self.total:
|
|
1251
|
+
return
|
|
1252
|
+
now = time.monotonic()
|
|
1253
|
+
if not force and now - self.last_draw < 0.1:
|
|
1254
|
+
return
|
|
1255
|
+
self.last_draw = now
|
|
1256
|
+
filled = min(16, self.done * 16 // self.total)
|
|
1257
|
+
bar = "#" * filled + "-" * (16 - filled)
|
|
1258
|
+
line = f" [{bar}] {self.done}/{self.total} {self.unit}"
|
|
1259
|
+
if self.failed:
|
|
1260
|
+
line += f" · {self.failed} failed"
|
|
1261
|
+
width = max(1, shutil.get_terminal_size().columns - 1)
|
|
1262
|
+
print(f"\r\033[2K{line[:width]}", end="", file=self.output, flush=True)
|
|
1263
|
+
self.visible = True
|
|
1264
|
+
|
|
1265
|
+
def finish(self) -> None:
|
|
1266
|
+
"""Leave the final bar on screen, on its own line."""
|
|
1267
|
+
if self.visible:
|
|
1268
|
+
self.draw(force=True)
|
|
1269
|
+
print(file=self.output, flush=True)
|
|
1270
|
+
self.visible = False
|
|
1271
|
+
|
|
1272
|
+
def asking(self, confirm: Callable[[str], bool]) -> Callable[[str], bool]:
|
|
1273
|
+
"""A question, with the bar out of its way."""
|
|
1274
|
+
|
|
1275
|
+
def ask(question: str) -> bool:
|
|
1276
|
+
self.clear()
|
|
1277
|
+
answer = confirm(question)
|
|
1278
|
+
self.draw(force=True)
|
|
1279
|
+
return answer
|
|
1280
|
+
|
|
1281
|
+
return ask
|
|
1282
|
+
|
|
1283
|
+
|
|
1284
|
+
def _pull(arguments: argparse.Namespace, session: _Session) -> str:
|
|
1285
|
+
profile, base = _profile_root(arguments, session)
|
|
1286
|
+
root = profile.local_root
|
|
1287
|
+
yes = arguments.yes
|
|
1288
|
+
documents = scan_documents(root)
|
|
1289
|
+
ids, slug = _pull_target(arguments.post, documents, root, base)
|
|
1290
|
+
records = _follow_files(profile, documents)
|
|
1291
|
+
|
|
1292
|
+
session.status(
|
|
1293
|
+
f"Preparing pull for profile '{_profile_name(arguments, session)}'..."
|
|
1294
|
+
)
|
|
1295
|
+
session.status(f"Connecting to {profile.site}...")
|
|
1296
|
+
client = WordPressClient(
|
|
1297
|
+
profile.api_root, profile.username, session.password(profile), session.transport
|
|
1298
|
+
)
|
|
1299
|
+
remote = WordPressRemote(client, session.transport)
|
|
1300
|
+
progress = _Progress(session)
|
|
1301
|
+
|
|
1302
|
+
def started(total: int) -> None:
|
|
1303
|
+
session.status("Comparing local and remote posts...")
|
|
1304
|
+
if total:
|
|
1305
|
+
session.status("Pulling changes...")
|
|
1306
|
+
progress.start(total, "posts")
|
|
1307
|
+
|
|
1308
|
+
try:
|
|
1309
|
+
account = _sign_in(client, profile)
|
|
1310
|
+
# Until something is pulled, say who signed in and what limits the account.
|
|
1311
|
+
if not records:
|
|
1312
|
+
session.status("\n".join(account))
|
|
1313
|
+
session.status("Reading posts from WordPress...")
|
|
1314
|
+
puller = Puller(
|
|
1315
|
+
root,
|
|
1316
|
+
profile.api_root,
|
|
1317
|
+
remote,
|
|
1318
|
+
documents,
|
|
1319
|
+
records,
|
|
1320
|
+
read_media(root, profile.api_root),
|
|
1321
|
+
progress.asking(_confirmer(session, yes)),
|
|
1322
|
+
progress.report,
|
|
1323
|
+
started,
|
|
1324
|
+
progress.step,
|
|
1325
|
+
)
|
|
1326
|
+
result = puller.pull(ids=ids, slug=slug)
|
|
1327
|
+
finally:
|
|
1328
|
+
progress.finish()
|
|
1329
|
+
remote.close()
|
|
1330
|
+
client.http.close()
|
|
1331
|
+
summary = result.summary()
|
|
1332
|
+
if result.declined and not yes:
|
|
1333
|
+
summary += " Rerun with --yes to accept the skipped changes."
|
|
1334
|
+
return summary
|
|
1335
|
+
|
|
1336
|
+
|
|
1337
|
+
def _follow_files(
|
|
1338
|
+
profile: Profile, documents: list[LocalDocument]
|
|
1339
|
+
) -> dict[str, PostRecord]:
|
|
1340
|
+
"""The post records, with each path following its file if it moved."""
|
|
1341
|
+
root = profile.local_root
|
|
1342
|
+
paths = {
|
|
1343
|
+
item.document.post_id: PurePosixPath(item.path)
|
|
1344
|
+
for item in documents
|
|
1345
|
+
if item.document.post_id is not None
|
|
1346
|
+
}
|
|
1347
|
+
return follow_moves(
|
|
1348
|
+
root, profile.api_root, read_records(root, profile.api_root), paths
|
|
1349
|
+
)
|
|
1350
|
+
|
|
1351
|
+
|
|
1352
|
+
def _push(arguments: argparse.Namespace, session: _Session) -> str:
|
|
1353
|
+
profile, base = _profile_root(arguments, session)
|
|
1354
|
+
root = profile.local_root
|
|
1355
|
+
documents = scan_documents(root)
|
|
1356
|
+
records = _follow_files(profile, documents)
|
|
1357
|
+
selection = select(arguments.post, documents, records, root=root, base=base)
|
|
1358
|
+
lazy = _LazyRemote(profile, session)
|
|
1359
|
+
opened: list[WordPressRemote] = []
|
|
1360
|
+
|
|
1361
|
+
def connect() -> WordPressRemote:
|
|
1362
|
+
client = lazy.connect()
|
|
1363
|
+
account = _sign_in(client, profile)
|
|
1364
|
+
# Until something is synced, say who signed in and what limits the account.
|
|
1365
|
+
if not records:
|
|
1366
|
+
session.status("\n".join(account))
|
|
1367
|
+
opened.append(WordPressRemote(client, session.transport))
|
|
1368
|
+
return opened[0]
|
|
1369
|
+
|
|
1370
|
+
session.status(
|
|
1371
|
+
f"Preparing push for profile '{_profile_name(arguments, session)}'..."
|
|
1372
|
+
)
|
|
1373
|
+
session.status("Comparing local and remote posts...")
|
|
1374
|
+
media = read_media(root, profile.api_root)
|
|
1375
|
+
progress = _Progress(session)
|
|
1376
|
+
try:
|
|
1377
|
+
plan = compare(selection, lazy, root=root, media=media, prune=arguments.prune)
|
|
1378
|
+
for note in plan.notes:
|
|
1379
|
+
session.status(f"Note: {note}")
|
|
1380
|
+
sending = [entry for entry in plan.entries if entry.step is not None]
|
|
1381
|
+
images = {image.path for entry in sending for image in entry.images}
|
|
1382
|
+
if sending:
|
|
1383
|
+
posts = f"{len(sending)} post{'s' * (len(sending) != 1)}"
|
|
1384
|
+
uploads = (
|
|
1385
|
+
f" · {len(images)} image{'s' * (len(images) != 1)}" if images else ""
|
|
1386
|
+
)
|
|
1387
|
+
session.status(f"Sending: {posts}{uploads}.")
|
|
1388
|
+
session.status("Pushing changes...")
|
|
1389
|
+
progress.start(len(sending) + len(images), "sent")
|
|
1390
|
+
pusher = Pusher(
|
|
1391
|
+
root,
|
|
1392
|
+
profile.api_root,
|
|
1393
|
+
connect,
|
|
1394
|
+
records,
|
|
1395
|
+
media,
|
|
1396
|
+
progress.asking(_confirmer(session, arguments.yes)),
|
|
1397
|
+
lambda outcome: progress.report(outcome, step=True),
|
|
1398
|
+
)
|
|
1399
|
+
result = pusher.push(plan.entries)
|
|
1400
|
+
finally:
|
|
1401
|
+
progress.finish()
|
|
1402
|
+
for remote in opened:
|
|
1403
|
+
remote.close()
|
|
1404
|
+
lazy.close()
|
|
1405
|
+
summary = result.summary()
|
|
1406
|
+
if result.declined and not arguments.yes:
|
|
1407
|
+
summary += " Rerun with --yes to accept the skipped changes."
|
|
1408
|
+
return "\n".join([summary, *(f"Note: {note}" for note in result.notes)])
|
|
1409
|
+
|
|
1410
|
+
|
|
1411
|
+
HANDLERS = {
|
|
1412
|
+
"init": _init,
|
|
1413
|
+
"map": _map,
|
|
1414
|
+
"remove": _remove,
|
|
1415
|
+
"root": _root,
|
|
1416
|
+
"profile": _profile,
|
|
1417
|
+
"profiles": _profiles,
|
|
1418
|
+
"editor": _editor,
|
|
1419
|
+
"create": _create,
|
|
1420
|
+
"ls": _ls,
|
|
1421
|
+
"show": _show,
|
|
1422
|
+
"open": _open,
|
|
1423
|
+
"diff": _diff,
|
|
1424
|
+
"pull": _pull,
|
|
1425
|
+
"push": _push,
|
|
1426
|
+
"delete": _delete,
|
|
1427
|
+
"trash": _trash,
|
|
1428
|
+
"restore": _restore,
|
|
1429
|
+
}
|
|
1430
|
+
|
|
1431
|
+
|
|
1432
|
+
def run(
|
|
1433
|
+
argv: Sequence[str] | None = None,
|
|
1434
|
+
*,
|
|
1435
|
+
store: ConfigurationStore | None = None,
|
|
1436
|
+
stdin: TextIO = sys.stdin,
|
|
1437
|
+
stdout: TextIO = sys.stdout,
|
|
1438
|
+
stderr: TextIO = sys.stderr,
|
|
1439
|
+
environ: Mapping[str, str] = os.environ,
|
|
1440
|
+
transport: httpx.BaseTransport | None = None,
|
|
1441
|
+
launch: Callable[[list[str]], None] = launch,
|
|
1442
|
+
) -> int:
|
|
1443
|
+
parser = build_parser()
|
|
1444
|
+
raw_arguments = list(sys.argv[1:] if argv is None else argv)
|
|
1445
|
+
try:
|
|
1446
|
+
raw_arguments, profile_prefix = _resolve_invocation(raw_arguments)
|
|
1447
|
+
except ConfigurationError as error:
|
|
1448
|
+
parser.error(str(error))
|
|
1449
|
+
arguments = parser.parse_args(raw_arguments)
|
|
1450
|
+
arguments.profile_prefix = profile_prefix
|
|
1451
|
+
session = _Session(
|
|
1452
|
+
store or ConfigurationStore(), stdin, stdout, stderr, environ, transport, launch
|
|
1453
|
+
)
|
|
1454
|
+
if arguments.legend:
|
|
1455
|
+
if arguments.command is not None:
|
|
1456
|
+
parser.error("--legend cannot be combined with a command")
|
|
1457
|
+
print(_legend(session), file=stdout)
|
|
1458
|
+
return 0
|
|
1459
|
+
if arguments.command is None:
|
|
1460
|
+
parser.error("a command is required")
|
|
1461
|
+
try:
|
|
1462
|
+
message = HANDLERS[arguments.command](arguments, session)
|
|
1463
|
+
except (
|
|
1464
|
+
ConfigurationError,
|
|
1465
|
+
DocumentError,
|
|
1466
|
+
EditorError,
|
|
1467
|
+
SelectionError,
|
|
1468
|
+
StateError,
|
|
1469
|
+
TrashError,
|
|
1470
|
+
WordPressError,
|
|
1471
|
+
) as error:
|
|
1472
|
+
print(f"wpsync: error: {error}", file=stderr)
|
|
1473
|
+
return 1
|
|
1474
|
+
print(message, file=stdout)
|
|
1475
|
+
return 0
|
|
1476
|
+
|
|
1477
|
+
|
|
1478
|
+
def main(argv: Sequence[str] | None = None) -> int:
|
|
1479
|
+
return run(argv)
|