ficgen 0.1.0__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.
- ficgen/__init__.py +77 -0
- ficgen/__main__.py +8 -0
- ficgen/cli.py +499 -0
- ficgen/generator.py +265 -0
- ficgen/importer.py +290 -0
- ficgen/kdlMeta.py +203 -0
- ficgen/markdownExt.py +241 -0
- ficgen/models.py +245 -0
- ficgen/parser.py +598 -0
- ficgen/py.typed +0 -0
- ficgen/scaffolder.py +168 -0
- ficgen/stamper.py +301 -0
- ficgen/static/style.css +1220 -0
- ficgen/t.py +51 -0
- ficgen/templates/_chapter_nav.html +33 -0
- ficgen/templates/_meta_block.html +90 -0
- ficgen/templates/_story_card.html +76 -0
- ficgen/templates/base.html +78 -0
- ficgen/templates/browse_detail.html +28 -0
- ficgen/templates/browse_index.html +34 -0
- ficgen/templates/feed.xml +31 -0
- ficgen/templates/index.html +30 -0
- ficgen/templates/story_all.html +116 -0
- ficgen/templates/story_chapter.html +64 -0
- ficgen/templates/story_single.html +55 -0
- ficgen/templates/story_toc.html +79 -0
- ficgen-0.1.0.dist-info/METADATA +368 -0
- ficgen-0.1.0.dist-info/RECORD +32 -0
- ficgen-0.1.0.dist-info/WHEEL +5 -0
- ficgen-0.1.0.dist-info/entry_points.txt +2 -0
- ficgen-0.1.0.dist-info/licenses/LICENSE +21 -0
- ficgen-0.1.0.dist-info/top_level.txt +1 -0
ficgen/__init__.py
ADDED
|
@@ -0,0 +1,77 @@
|
|
|
1
|
+
"""Static site generator for a personal fiction archive."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from .cli import buildArchive as buildArchive, main as main
|
|
6
|
+
from .generator import BuildResult as BuildResult, generateSite as generateSite
|
|
7
|
+
from .importer import (
|
|
8
|
+
ImportOptions as ImportOptions,
|
|
9
|
+
ImportResult as ImportResult,
|
|
10
|
+
htmlToMarkdown as htmlToMarkdown,
|
|
11
|
+
importFromSource as importFromSource,
|
|
12
|
+
writeImportedWork as writeImportedWork,
|
|
13
|
+
)
|
|
14
|
+
from .kdlMeta import (
|
|
15
|
+
StoryParseError as StoryParseError,
|
|
16
|
+
parseKdlDocument as parseKdlDocument,
|
|
17
|
+
)
|
|
18
|
+
from .markdownExt import MarkdownRenderer as MarkdownRenderer
|
|
19
|
+
from .models import (
|
|
20
|
+
Archive as Archive,
|
|
21
|
+
Chapter as Chapter,
|
|
22
|
+
FeedEntry as FeedEntry,
|
|
23
|
+
SiteConfig as SiteConfig,
|
|
24
|
+
Story as Story,
|
|
25
|
+
TaxonomyBucket as TaxonomyBucket,
|
|
26
|
+
TaxonomyItem as TaxonomyItem,
|
|
27
|
+
slugify as slugify,
|
|
28
|
+
)
|
|
29
|
+
from .parser import (
|
|
30
|
+
loadArchive as loadArchive,
|
|
31
|
+
parseMarkdownDocument as parseMarkdownDocument,
|
|
32
|
+
)
|
|
33
|
+
from .scaffolder import (
|
|
34
|
+
InitOptions as InitOptions,
|
|
35
|
+
InitResult as InitResult,
|
|
36
|
+
initStory as initStory,
|
|
37
|
+
)
|
|
38
|
+
from .stamper import (
|
|
39
|
+
StampEntry as StampEntry,
|
|
40
|
+
StampResult as StampResult,
|
|
41
|
+
stampDocumentText as stampDocumentText,
|
|
42
|
+
stampFile as stampFile,
|
|
43
|
+
stampStories as stampStories,
|
|
44
|
+
)
|
|
45
|
+
|
|
46
|
+
__all__ = [
|
|
47
|
+
"Archive",
|
|
48
|
+
"BuildResult",
|
|
49
|
+
"Chapter",
|
|
50
|
+
"FeedEntry",
|
|
51
|
+
"ImportOptions",
|
|
52
|
+
"ImportResult",
|
|
53
|
+
"InitOptions",
|
|
54
|
+
"InitResult",
|
|
55
|
+
"MarkdownRenderer",
|
|
56
|
+
"SiteConfig",
|
|
57
|
+
"StampEntry",
|
|
58
|
+
"StampResult",
|
|
59
|
+
"Story",
|
|
60
|
+
"StoryParseError",
|
|
61
|
+
"TaxonomyBucket",
|
|
62
|
+
"TaxonomyItem",
|
|
63
|
+
"buildArchive",
|
|
64
|
+
"generateSite",
|
|
65
|
+
"htmlToMarkdown",
|
|
66
|
+
"importFromSource",
|
|
67
|
+
"initStory",
|
|
68
|
+
"loadArchive",
|
|
69
|
+
"main",
|
|
70
|
+
"parseKdlDocument",
|
|
71
|
+
"parseMarkdownDocument",
|
|
72
|
+
"slugify",
|
|
73
|
+
"stampDocumentText",
|
|
74
|
+
"stampFile",
|
|
75
|
+
"stampStories",
|
|
76
|
+
"writeImportedWork",
|
|
77
|
+
]
|
ficgen/__main__.py
ADDED
ficgen/cli.py
ADDED
|
@@ -0,0 +1,499 @@
|
|
|
1
|
+
"""Command-line interface for building the fiction archive and stamping dates."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import argparse
|
|
6
|
+
import logging
|
|
7
|
+
import sys
|
|
8
|
+
from pathlib import Path
|
|
9
|
+
|
|
10
|
+
import ao3fetch
|
|
11
|
+
import kdl
|
|
12
|
+
|
|
13
|
+
from . import t
|
|
14
|
+
from .generator import BuildResult, generateSite
|
|
15
|
+
from .importer import ImportOptions, importFromSource
|
|
16
|
+
from .kdlMeta import StoryParseError, getBoolField, getStringField, parseKdlDocument
|
|
17
|
+
from .models import SiteConfig
|
|
18
|
+
from .parser import loadArchive
|
|
19
|
+
from .scaffolder import InitOptions, initStory
|
|
20
|
+
from .stamper import StampResult, defaultTodayDate, stampStories
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
def _loadKdlConfig(configPath: Path) -> kdl.Document:
|
|
24
|
+
"""Read an optional KDL site configuration file."""
|
|
25
|
+
try:
|
|
26
|
+
rawText = configPath.read_text(encoding="utf-8")
|
|
27
|
+
except OSError as exc:
|
|
28
|
+
msg = f"Failed to read config file {configPath}: {exc}"
|
|
29
|
+
raise StoryParseError(msg) from exc
|
|
30
|
+
return parseKdlDocument(rawText, sourceDesc=str(configPath))
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
def _resolveDefaultPaths() -> tuple[Path, Path]:
|
|
34
|
+
"""Resolve default stories/ and output directories from cwd or package layout."""
|
|
35
|
+
cwd = Path.cwd()
|
|
36
|
+
if (cwd / "stories").is_dir():
|
|
37
|
+
return (cwd / "stories", cwd)
|
|
38
|
+
parent = cwd.parent
|
|
39
|
+
if (parent / "stories").is_dir():
|
|
40
|
+
return (parent / "stories", parent)
|
|
41
|
+
return (cwd / "stories", cwd)
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
def _buildArgParser() -> argparse.ArgumentParser:
|
|
45
|
+
"""Create the CLI argument parser for building the site."""
|
|
46
|
+
defaultStories, defaultOutput = _resolveDefaultPaths()
|
|
47
|
+
parser = argparse.ArgumentParser(
|
|
48
|
+
prog="ficgen",
|
|
49
|
+
description="Build a static HTML fiction archive from Markdown story documents.",
|
|
50
|
+
epilog=(
|
|
51
|
+
"Subcommands:\n"
|
|
52
|
+
+ " ficgen [build] [options] Build the static HTML archive (default)\n"
|
|
53
|
+
+ " ficgen new TITLE [options] Initialize a new story directory (alias: init)\n"
|
|
54
|
+
+ " ficgen import SOURCE [options] Import stories from AO3-compatible archives or EPUBs\n"
|
|
55
|
+
+ " ficgen stamp [options] Stamp date into undated story/chapter KDL metadata blocks"
|
|
56
|
+
),
|
|
57
|
+
formatter_class=argparse.RawDescriptionHelpFormatter,
|
|
58
|
+
)
|
|
59
|
+
parser.add_argument(
|
|
60
|
+
"--stories",
|
|
61
|
+
type=Path,
|
|
62
|
+
default=defaultStories,
|
|
63
|
+
help=f"Directory containing story folders (default: {defaultStories})",
|
|
64
|
+
)
|
|
65
|
+
parser.add_argument(
|
|
66
|
+
"--output",
|
|
67
|
+
type=Path,
|
|
68
|
+
default=defaultOutput,
|
|
69
|
+
help=f"Output directory for generated HTML/CSS/feed (default: {defaultOutput})",
|
|
70
|
+
)
|
|
71
|
+
parser.add_argument(
|
|
72
|
+
"--config",
|
|
73
|
+
type=Path,
|
|
74
|
+
default=None,
|
|
75
|
+
help="Optional KDL configuration file (auto-loads site.kdl if present).",
|
|
76
|
+
)
|
|
77
|
+
parser.add_argument(
|
|
78
|
+
"--title",
|
|
79
|
+
type=str,
|
|
80
|
+
default=None,
|
|
81
|
+
help="Archive title (overrides config file).",
|
|
82
|
+
)
|
|
83
|
+
parser.add_argument(
|
|
84
|
+
"--subtitle",
|
|
85
|
+
type=str,
|
|
86
|
+
default=None,
|
|
87
|
+
help="Archive subtitle shown on the index page.",
|
|
88
|
+
)
|
|
89
|
+
parser.add_argument(
|
|
90
|
+
"--author",
|
|
91
|
+
type=str,
|
|
92
|
+
default=None,
|
|
93
|
+
help="Default author name for stories and Atom feed.",
|
|
94
|
+
)
|
|
95
|
+
parser.add_argument(
|
|
96
|
+
"--base-url",
|
|
97
|
+
type=str,
|
|
98
|
+
default=None,
|
|
99
|
+
help="Canonical base URL for the Atom feed (e.g. https://example.com/fic/).",
|
|
100
|
+
)
|
|
101
|
+
parser.add_argument(
|
|
102
|
+
"--drafts",
|
|
103
|
+
action="store_true",
|
|
104
|
+
default=False,
|
|
105
|
+
help="Include unpublished (published false) stories and chapters.",
|
|
106
|
+
)
|
|
107
|
+
return parser
|
|
108
|
+
|
|
109
|
+
|
|
110
|
+
def _stampArgParser() -> argparse.ArgumentParser:
|
|
111
|
+
"""Create the CLI argument parser for the `stamp` subcommand."""
|
|
112
|
+
defaultStories, _ = _resolveDefaultPaths()
|
|
113
|
+
parser = argparse.ArgumentParser(
|
|
114
|
+
prog="ficgen stamp",
|
|
115
|
+
description='Stamp `date "YYYY-MM-DD"` into KDL metadata blocks of undated story and chapter files.',
|
|
116
|
+
)
|
|
117
|
+
parser.add_argument(
|
|
118
|
+
"targets",
|
|
119
|
+
nargs="*",
|
|
120
|
+
type=Path,
|
|
121
|
+
help="Optional file paths, story directories, or story slugs to stamp (defaults to all stories).",
|
|
122
|
+
)
|
|
123
|
+
parser.add_argument(
|
|
124
|
+
"--stories",
|
|
125
|
+
type=Path,
|
|
126
|
+
default=defaultStories,
|
|
127
|
+
help=f"Directory containing story folders (default: {defaultStories})",
|
|
128
|
+
)
|
|
129
|
+
parser.add_argument(
|
|
130
|
+
"--date",
|
|
131
|
+
type=str,
|
|
132
|
+
default=None,
|
|
133
|
+
help="ISO-8601 date to stamp (default: today's date, YYYY-MM-DD).",
|
|
134
|
+
)
|
|
135
|
+
parser.add_argument(
|
|
136
|
+
"--force",
|
|
137
|
+
action="store_true",
|
|
138
|
+
default=False,
|
|
139
|
+
help="Overwrite existing date values.",
|
|
140
|
+
)
|
|
141
|
+
parser.add_argument(
|
|
142
|
+
"--drafts",
|
|
143
|
+
action="store_true",
|
|
144
|
+
default=False,
|
|
145
|
+
help="Also stamp files marked published false.",
|
|
146
|
+
)
|
|
147
|
+
parser.add_argument(
|
|
148
|
+
"-n",
|
|
149
|
+
"--dry-run",
|
|
150
|
+
action="store_true",
|
|
151
|
+
default=False,
|
|
152
|
+
help="Show which files would be stamped without modifying them.",
|
|
153
|
+
)
|
|
154
|
+
return parser
|
|
155
|
+
|
|
156
|
+
|
|
157
|
+
def _newArgParser() -> argparse.ArgumentParser:
|
|
158
|
+
"""Create the CLI argument parser for the `new` / `init` subcommand."""
|
|
159
|
+
defaultStories, _ = _resolveDefaultPaths()
|
|
160
|
+
parser = argparse.ArgumentParser(
|
|
161
|
+
prog="ficgen new",
|
|
162
|
+
description="Initialize a new story directory with KDL metadata and starter Markdown files.",
|
|
163
|
+
)
|
|
164
|
+
parser.add_argument(
|
|
165
|
+
"title",
|
|
166
|
+
type=str,
|
|
167
|
+
help="Title of the new story.",
|
|
168
|
+
)
|
|
169
|
+
parser.add_argument(
|
|
170
|
+
"--slug",
|
|
171
|
+
type=str,
|
|
172
|
+
default="",
|
|
173
|
+
help="Directory / URL slug (default: slugified from title).",
|
|
174
|
+
)
|
|
175
|
+
parser.add_argument(
|
|
176
|
+
"-m",
|
|
177
|
+
"--multi",
|
|
178
|
+
action="store_true",
|
|
179
|
+
default=False,
|
|
180
|
+
help="Create a multi-chapter story (story.kdl + ch1.md) instead of a one-shot index.md.",
|
|
181
|
+
)
|
|
182
|
+
parser.add_argument(
|
|
183
|
+
"--chapters",
|
|
184
|
+
type=int,
|
|
185
|
+
default=1,
|
|
186
|
+
help="Number of starter chapter files to create (implies --multi if > 1).",
|
|
187
|
+
)
|
|
188
|
+
parser.add_argument(
|
|
189
|
+
"--published",
|
|
190
|
+
action="store_true",
|
|
191
|
+
default=False,
|
|
192
|
+
help="Mark starter file(s) as published (default creates them as `published false` drafts).",
|
|
193
|
+
)
|
|
194
|
+
parser.add_argument(
|
|
195
|
+
"--date",
|
|
196
|
+
type=str,
|
|
197
|
+
default="",
|
|
198
|
+
help="Optional ISO-8601 publication date (YYYY-MM-DD).",
|
|
199
|
+
)
|
|
200
|
+
parser.add_argument(
|
|
201
|
+
"--fandom",
|
|
202
|
+
action="append",
|
|
203
|
+
default=[],
|
|
204
|
+
help="Fandom tag (repeatable).",
|
|
205
|
+
)
|
|
206
|
+
parser.add_argument(
|
|
207
|
+
"--category",
|
|
208
|
+
action="append",
|
|
209
|
+
default=[],
|
|
210
|
+
help="Relationship category such as F/F (repeatable).",
|
|
211
|
+
)
|
|
212
|
+
parser.add_argument(
|
|
213
|
+
"--relationship",
|
|
214
|
+
action="append",
|
|
215
|
+
default=[],
|
|
216
|
+
help="Relationship / ship tag (repeatable).",
|
|
217
|
+
)
|
|
218
|
+
parser.add_argument(
|
|
219
|
+
"--character",
|
|
220
|
+
action="append",
|
|
221
|
+
default=[],
|
|
222
|
+
help="Character tag (repeatable).",
|
|
223
|
+
)
|
|
224
|
+
parser.add_argument(
|
|
225
|
+
"--tag",
|
|
226
|
+
action="append",
|
|
227
|
+
default=[],
|
|
228
|
+
help="Additional freeform tag (repeatable).",
|
|
229
|
+
)
|
|
230
|
+
parser.add_argument(
|
|
231
|
+
"--stories",
|
|
232
|
+
type=Path,
|
|
233
|
+
default=defaultStories,
|
|
234
|
+
help=f"Directory containing story folders (default: {defaultStories})",
|
|
235
|
+
)
|
|
236
|
+
return parser
|
|
237
|
+
|
|
238
|
+
|
|
239
|
+
def _importArgParser() -> argparse.ArgumentParser:
|
|
240
|
+
"""Create the CLI argument parser for the `import` subcommand."""
|
|
241
|
+
defaultStories, _ = _resolveDefaultPaths()
|
|
242
|
+
parser = argparse.ArgumentParser(
|
|
243
|
+
prog="ficgen import",
|
|
244
|
+
description="Import one or more works from AO3, AO3-compatible archives, or downloaded AO3 EPUBs.",
|
|
245
|
+
)
|
|
246
|
+
parser.add_argument(
|
|
247
|
+
"sources",
|
|
248
|
+
nargs="+",
|
|
249
|
+
type=str,
|
|
250
|
+
help="AO3/mirror work URL(s), numeric work ID(s), or local .epub file path(s).",
|
|
251
|
+
)
|
|
252
|
+
parser.add_argument(
|
|
253
|
+
"--archive",
|
|
254
|
+
type=str,
|
|
255
|
+
default=ao3fetch.DEFAULT_BASE_URL,
|
|
256
|
+
help=f"Archive base URL for bare numeric work IDs (default: {ao3fetch.DEFAULT_BASE_URL}).",
|
|
257
|
+
)
|
|
258
|
+
parser.add_argument(
|
|
259
|
+
"--slug",
|
|
260
|
+
type=str,
|
|
261
|
+
default="",
|
|
262
|
+
help="Custom story directory/URL slug (only valid when importing a single work).",
|
|
263
|
+
)
|
|
264
|
+
parser.add_argument(
|
|
265
|
+
"--stories",
|
|
266
|
+
type=Path,
|
|
267
|
+
default=defaultStories,
|
|
268
|
+
help=f"Destination stories directory (default: {defaultStories})",
|
|
269
|
+
)
|
|
270
|
+
parser.add_argument(
|
|
271
|
+
"--draft",
|
|
272
|
+
action="store_true",
|
|
273
|
+
default=False,
|
|
274
|
+
help="Mark imported story/chapters as `published false`.",
|
|
275
|
+
)
|
|
276
|
+
parser.add_argument(
|
|
277
|
+
"--force",
|
|
278
|
+
action="store_true",
|
|
279
|
+
default=False,
|
|
280
|
+
help="Overwrite existing story directory if it already exists.",
|
|
281
|
+
)
|
|
282
|
+
parser.add_argument(
|
|
283
|
+
"--cookie",
|
|
284
|
+
type=str,
|
|
285
|
+
default="",
|
|
286
|
+
help="Optional Cookie header value (e.g. session cookie for restricted works).",
|
|
287
|
+
)
|
|
288
|
+
return parser
|
|
289
|
+
|
|
290
|
+
|
|
291
|
+
def buildConfigFromArgs(argv: t.Sequence[str] | None = None) -> SiteConfig:
|
|
292
|
+
"""Parse CLI arguments and optional KDL site config into a SiteConfig."""
|
|
293
|
+
parser = _buildArgParser()
|
|
294
|
+
args = parser.parse_args(argv)
|
|
295
|
+
|
|
296
|
+
storiesDir: Path = args.stories
|
|
297
|
+
outputDir: Path = args.output
|
|
298
|
+
configPath: Path | None = args.config
|
|
299
|
+
if configPath is None:
|
|
300
|
+
candidate = storiesDir.parent / "site.kdl"
|
|
301
|
+
if candidate.is_file():
|
|
302
|
+
configPath = candidate
|
|
303
|
+
|
|
304
|
+
configDoc = kdl.Document()
|
|
305
|
+
configSource = "<config>"
|
|
306
|
+
if configPath is not None:
|
|
307
|
+
configDoc = _loadKdlConfig(configPath)
|
|
308
|
+
configSource = str(configPath)
|
|
309
|
+
|
|
310
|
+
def _strOpt(cliVal: str | None, kdlKey: str, fallback: str) -> str:
|
|
311
|
+
if cliVal is not None:
|
|
312
|
+
return cliVal
|
|
313
|
+
kdlVal = getStringField(configDoc, kdlKey, sourceDesc=configSource)
|
|
314
|
+
return kdlVal or fallback
|
|
315
|
+
|
|
316
|
+
kdlDrafts = getBoolField(configDoc, "include-drafts", default=False, sourceDesc=configSource)
|
|
317
|
+
includeDrafts = bool(args.drafts) or kdlDrafts
|
|
318
|
+
|
|
319
|
+
return SiteConfig(
|
|
320
|
+
storiesDir=storiesDir,
|
|
321
|
+
outputDir=outputDir,
|
|
322
|
+
title=_strOpt(args.title, "title", "Fiction Archive"),
|
|
323
|
+
subtitle=_strOpt(args.subtitle, "subtitle", ""),
|
|
324
|
+
author=_strOpt(args.author, "author", ""),
|
|
325
|
+
baseUrl=_strOpt(args.base_url, "base-url", "https://example.com/"),
|
|
326
|
+
includeDrafts=includeDrafts,
|
|
327
|
+
)
|
|
328
|
+
|
|
329
|
+
|
|
330
|
+
def buildArchive(config: SiteConfig) -> BuildResult:
|
|
331
|
+
"""Load stories from disk and generate the static archive."""
|
|
332
|
+
archive = loadArchive(config)
|
|
333
|
+
return generateSite(archive)
|
|
334
|
+
|
|
335
|
+
|
|
336
|
+
def _printStampSummary(result: StampResult) -> None:
|
|
337
|
+
"""Print per-file actions and a concise summary for `ficgen stamp`."""
|
|
338
|
+
for entry in result.entries:
|
|
339
|
+
match entry.action:
|
|
340
|
+
case "stamped":
|
|
341
|
+
print(f"Stamped {entry.dateValue}: {entry.path}")
|
|
342
|
+
case "would_stamp":
|
|
343
|
+
print(f"Would stamp {entry.dateValue}: {entry.path}")
|
|
344
|
+
case "skipped_existing":
|
|
345
|
+
print(f"Skipped (already dated): {entry.path}")
|
|
346
|
+
case "skipped_draft":
|
|
347
|
+
print(f"Skipped (draft): {entry.path}")
|
|
348
|
+
|
|
349
|
+
verb = "Would stamp" if result.dryRun else "Stamped"
|
|
350
|
+
print(
|
|
351
|
+
f"{verb} {result.stampedCount} file(s)"
|
|
352
|
+
+ f" ({result.skippedExistingCount} already dated, {result.skippedDraftCount} draft(s) skipped).",
|
|
353
|
+
)
|
|
354
|
+
|
|
355
|
+
|
|
356
|
+
def _runStamp(argv: t.Sequence[str]) -> int:
|
|
357
|
+
"""Execute the `ficgen stamp` subcommand."""
|
|
358
|
+
parser = _stampArgParser()
|
|
359
|
+
args = parser.parse_args(argv)
|
|
360
|
+
dateValue: str = args.date if args.date is not None else defaultTodayDate()
|
|
361
|
+
result = stampStories(
|
|
362
|
+
storiesDir=args.stories,
|
|
363
|
+
dateValue=dateValue,
|
|
364
|
+
targets=args.targets,
|
|
365
|
+
force=bool(args.force),
|
|
366
|
+
includeDrafts=bool(args.drafts),
|
|
367
|
+
dryRun=bool(args.dry_run),
|
|
368
|
+
)
|
|
369
|
+
_printStampSummary(result)
|
|
370
|
+
return 0
|
|
371
|
+
|
|
372
|
+
|
|
373
|
+
def _runNew(argv: t.Sequence[str]) -> int:
|
|
374
|
+
"""Execute the `ficgen new` / `ficgen init` subcommand."""
|
|
375
|
+
parser = _newArgParser()
|
|
376
|
+
args = parser.parse_args(argv)
|
|
377
|
+
options = InitOptions(
|
|
378
|
+
storiesDir=args.stories,
|
|
379
|
+
title=args.title,
|
|
380
|
+
slug=args.slug,
|
|
381
|
+
multiChapter=bool(args.multi),
|
|
382
|
+
chapterCount=int(args.chapters),
|
|
383
|
+
published=bool(args.published),
|
|
384
|
+
dateValue=args.date,
|
|
385
|
+
fandoms=tuple(args.fandom),
|
|
386
|
+
categories=tuple(args.category),
|
|
387
|
+
relationships=tuple(args.relationship),
|
|
388
|
+
characters=tuple(args.character),
|
|
389
|
+
tags=tuple(args.tag),
|
|
390
|
+
)
|
|
391
|
+
result = initStory(options)
|
|
392
|
+
print(f"Initialized story '{options.title.strip()}' in {result.storyDir}:")
|
|
393
|
+
for createdPath in result.createdFiles:
|
|
394
|
+
print(f" {createdPath}")
|
|
395
|
+
return 0
|
|
396
|
+
|
|
397
|
+
|
|
398
|
+
def _makeCookieFetcher(baseFetcher: ao3fetch.Fetcher, extraCookie: str) -> ao3fetch.Fetcher:
|
|
399
|
+
"""Return a fetcher that appends an extra Cookie header to every request."""
|
|
400
|
+
|
|
401
|
+
def _wrapped(url: str, headers: t.Mapping[str, str] | None = None) -> ao3fetch.FetchResponse:
|
|
402
|
+
merged = dict(headers) if headers else {}
|
|
403
|
+
existing = merged.get("Cookie", "").strip()
|
|
404
|
+
merged["Cookie"] = f"{existing} {extraCookie}".strip() if existing else extraCookie
|
|
405
|
+
return baseFetcher(url, merged)
|
|
406
|
+
|
|
407
|
+
return _wrapped
|
|
408
|
+
|
|
409
|
+
|
|
410
|
+
def _runImport(argv: t.Sequence[str]) -> int:
|
|
411
|
+
"""Execute the `ficgen import` subcommand."""
|
|
412
|
+
parser = _importArgParser()
|
|
413
|
+
args = parser.parse_args(argv)
|
|
414
|
+
if args.slug and len(args.sources) > 1:
|
|
415
|
+
msg = "--slug can only be used when importing a single work."
|
|
416
|
+
raise StoryParseError(msg)
|
|
417
|
+
|
|
418
|
+
logger = logging.getLogger("ficgen.importer")
|
|
419
|
+
previousFetcher = ao3fetch.getFetcher()
|
|
420
|
+
installedCustom = False
|
|
421
|
+
if previousFetcher is ao3fetch.defaultFetch or args.cookie:
|
|
422
|
+
base: ao3fetch.Fetcher = previousFetcher
|
|
423
|
+
if args.cookie:
|
|
424
|
+
base = _makeCookieFetcher(base, args.cookie)
|
|
425
|
+
|
|
426
|
+
def _logRetry(event: ao3fetch.RetryEvent) -> None:
|
|
427
|
+
statusDesc = f"HTTP {event.response.status}" if event.response is not None else str(event.error)
|
|
428
|
+
logger.warning(
|
|
429
|
+
"Retry %d in %.1fs after %s",
|
|
430
|
+
event.attempt,
|
|
431
|
+
event.delaySeconds,
|
|
432
|
+
statusDesc,
|
|
433
|
+
)
|
|
434
|
+
|
|
435
|
+
ao3fetch.setFetcher(ao3fetch.withCache(ao3fetch.withRetry(base, onRetry=_logRetry)))
|
|
436
|
+
installedCustom = True
|
|
437
|
+
|
|
438
|
+
try:
|
|
439
|
+
for source in args.sources:
|
|
440
|
+
options = ImportOptions(
|
|
441
|
+
storiesDir=args.stories,
|
|
442
|
+
archiveUrl=args.archive,
|
|
443
|
+
slug=args.slug,
|
|
444
|
+
asDraft=bool(args.draft),
|
|
445
|
+
force=bool(args.force),
|
|
446
|
+
)
|
|
447
|
+
result = importFromSource(source, options)
|
|
448
|
+
chapterNote = f" ({result.chapterCount} chapters)" if result.chapterCount > 1 else ""
|
|
449
|
+
print(f"Imported '{result.title}'{chapterNote} -> {result.storyDir}")
|
|
450
|
+
for createdPath in result.createdFiles:
|
|
451
|
+
print(f" {createdPath}")
|
|
452
|
+
finally:
|
|
453
|
+
if installedCustom:
|
|
454
|
+
if previousFetcher is ao3fetch.defaultFetch:
|
|
455
|
+
ao3fetch.resetFetcher()
|
|
456
|
+
else:
|
|
457
|
+
ao3fetch.setFetcher(previousFetcher)
|
|
458
|
+
|
|
459
|
+
return 0
|
|
460
|
+
|
|
461
|
+
|
|
462
|
+
def _configureLogging() -> None:
|
|
463
|
+
"""Attach a stderr warning handler to the ficgen logger if none is configured."""
|
|
464
|
+
pkgLogger = logging.getLogger("ficgen")
|
|
465
|
+
if not pkgLogger.handlers:
|
|
466
|
+
handler = logging.StreamHandler(sys.stderr)
|
|
467
|
+
handler.setFormatter(logging.Formatter("%(levelname)s: %(message)s"))
|
|
468
|
+
pkgLogger.addHandler(handler)
|
|
469
|
+
if pkgLogger.level == logging.NOTSET:
|
|
470
|
+
pkgLogger.setLevel(logging.WARNING)
|
|
471
|
+
|
|
472
|
+
|
|
473
|
+
def main(argv: t.Sequence[str] | None = None) -> int:
|
|
474
|
+
"""Entry point for the ficgen CLI."""
|
|
475
|
+
_configureLogging()
|
|
476
|
+
rawArgs = list(sys.argv[1:] if argv is None else argv)
|
|
477
|
+
try:
|
|
478
|
+
if rawArgs and rawArgs[0] == "stamp":
|
|
479
|
+
return _runStamp(rawArgs[1:])
|
|
480
|
+
if rawArgs and rawArgs[0] in {"new", "init"}:
|
|
481
|
+
return _runNew(rawArgs[1:])
|
|
482
|
+
if rawArgs and rawArgs[0] == "import":
|
|
483
|
+
return _runImport(rawArgs[1:])
|
|
484
|
+
buildArgs = rawArgs[1:] if rawArgs and rawArgs[0] == "build" else rawArgs
|
|
485
|
+
config = buildConfigFromArgs(buildArgs)
|
|
486
|
+
result = buildArchive(config)
|
|
487
|
+
except StoryParseError as exc:
|
|
488
|
+
print(f"Error: {exc}", file=sys.stderr)
|
|
489
|
+
return 1
|
|
490
|
+
|
|
491
|
+
draftNote = " (including drafts)" if config.includeDrafts else ""
|
|
492
|
+
print(
|
|
493
|
+
f"Built {result.storyCount} stories"
|
|
494
|
+
+ f" ({result.chapterPageCount} chapter pages,"
|
|
495
|
+
+ f" {result.taxonomyPageCount} tag pages,"
|
|
496
|
+
+ f" {result.feedEntryCount} feed entries){draftNote}"
|
|
497
|
+
+ f" -> {result.outputDir}",
|
|
498
|
+
)
|
|
499
|
+
return 0
|