eleventy-blog 0.1.1 → 0.2.1

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.
package/README.md CHANGED
@@ -1,10 +1,16 @@
1
1
  # eleventy-blog
2
2
 
3
3
  Command-line tool for [eleventy-plugin-blog](https://sielay.github.io/eleventy-plugin-blog/).
4
- Add the blog to an Eleventy site, write posts, publish drafts, tidy tags,
5
- and check the site before you deploy.
4
+ Start a blog, write posts, publish drafts, tidy tags, check the site
5
+ before you deploy, upgrade the plugin, and edit posts in a browser.
6
6
 
7
- You do not install it. Run it with `npx` in your site's folder:
7
+ You do not install it. Run it with `npx`. To start a new blog:
8
+
9
+ ```bash
10
+ npx eleventy-blog create my-blog
11
+ ```
12
+
13
+ To add the blog to an Eleventy site you have, run this in its folder:
8
14
 
9
15
  ```bash
10
16
  npx eleventy-blog init
@@ -16,6 +22,7 @@ It needs Node.js 18.3 or later, and Eleventy 3 installed in the site.
16
22
 
17
23
  Command | What it does
18
24
  ------- | ------------
25
+ `create <folder>` | Makes a new blog: Eleventy 3, the plugin, a layout, a stylesheet, and a first post. See [Start a new blog](#start-a-new-blog)
19
26
  `init` | Installs the plugin, adds it to your Eleventy config, and writes a first post if there is none
20
27
  `new "Title" [--tags a,b]` | Writes a draft post under your blog folder, named after the date and title
21
28
  `list [--drafts] [--json]` | Lists posts, newest first, with date, status, and title
@@ -24,6 +31,9 @@ Command | What it does
24
31
  `tag rename <old> <new>` | Renames a tag in every post, and tells you which redirect to add
25
32
  `studio [--open]` | Opens a visual editor for your posts in the browser, with a live preview. See [The studio](#the-studio)
26
33
  `check` | Builds the site into a temporary folder and reports problems: posts with no title, unreadable dates, tags spelled two ways, broken internal links, and missing images. Exits with code 1 on errors, so it can stop a deploy
34
+ `compare [commit]` | Builds a commit and your files, and lists pages that are gone, new, or changed. The default commit is `HEAD`. See [Compare builds](#compare-builds)
35
+ `update` | Upgrades the plugin, shows what changed, offers any fix your site needs, and lists the pages that changed. See [Upgrade the plugin](#upgrade-the-plugin)
36
+ `eject [page\|all]` | Copies a built-in page into your site so you can edit it. With no page, lists them
27
37
 
28
38
  `<post>` is a path, a file name, or part of the title. If it matches more
29
39
  than one post, the command lists them and changes nothing.
@@ -66,6 +76,61 @@ The editor is [Milkdown](https://milkdown.dev/). The choice and its
66
76
  test results are in the
67
77
  [editor trial](https://github.com/sielay/eleventy-plugin-blog/blob/master/docs/EDITOR-TRIAL.md).
68
78
 
79
+ ## Start a new blog
80
+
81
+ ```bash
82
+ npx eleventy-blog create my-blog --title "My blog" --url https://example.com --host vercel
83
+ ```
84
+
85
+ You get a site that builds as it is: the plugin's post list, tag pages,
86
+ and archive inside a simple layout, a home page with the newest posts, a
87
+ first post, and a `README.md` with the commands. Then:
88
+
89
+ ```bash
90
+ cd my-blog
91
+ npm start # the site, at http://localhost:8080
92
+ npm run studio # the editor
93
+ ```
94
+
95
+ Option | What it does
96
+ ------ | ------------
97
+ `--title <text>` | The site's name. The default comes from the folder name
98
+ `--url <address>` | Your site's address. Adds an Atom feed
99
+ `--host vercel\|netlify` | Adds `vercel.json` or `netlify.toml`, so the host builds the site
100
+ `--no-install` | Skips `npm install`
101
+
102
+ ## Upgrade the plugin
103
+
104
+ ```bash
105
+ npx eleventy-blog update
106
+ ```
107
+
108
+ 1. Shows the changelog between your version and the latest, with
109
+ breaking changes highlighted.
110
+ 2. Asks, then installs the new version with your package manager, as the
111
+ same kind of dependency.
112
+ 3. If a breaking change needs a fix in your site, shows the edit and
113
+ asks. For example, a site with its own `/blog/` page gets
114
+ `pages: false`, so the plugin keeps out of its way.
115
+ 4. Builds the site, and lists every page that is gone, new, or changed
116
+ since the old version.
117
+
118
+ `--to <version>` upgrades to a version other than the latest.
119
+
120
+ ## Compare builds
121
+
122
+ ```bash
123
+ npx eleventy-blog compare # your files against the last commit
124
+ npx eleventy-blog compare main # against another branch or commit
125
+ ```
126
+
127
+ It checks out the commit in a temporary folder, builds both, and lists
128
+ the pages by URL. A page under **Gone** breaks links to it, so add a
129
+ redirect if it moved. Whitespace-only changes do not count. `--json`
130
+ prints the lists for scripts. The commit builds with the packages
131
+ installed today; after an upgrade, `update` makes this comparison for
132
+ you.
133
+
69
134
  ## Changes are shown first
70
135
 
71
136
  Every command that changes files prints the change and asks before it
@@ -2,6 +2,7 @@
2
2
  const { parseArgs } = require("util");
3
3
 
4
4
  const COMMANDS = {
5
+ create: () => require("../lib/commands/create"),
5
6
  init: () => require("../lib/commands/init"),
6
7
  new: () => require("../lib/commands/new"),
7
8
  list: () => require("../lib/commands/list"),
@@ -9,6 +10,9 @@ const COMMANDS = {
9
10
  tag: () => require("../lib/commands/tag"),
10
11
  check: () => require("../lib/commands/check"),
11
12
  studio: () => require("../lib/commands/studio"),
13
+ compare: () => require("../lib/commands/compare"),
14
+ update: () => require("../lib/commands/update"),
15
+ eject: () => require("../lib/commands/eject"),
12
16
  };
13
17
 
14
18
  const HELP = `eleventy-blog: write and maintain an Eleventy blog
@@ -16,6 +20,7 @@ const HELP = `eleventy-blog: write and maintain an Eleventy blog
16
20
  Usage: eleventy-blog <command> [options]
17
21
 
18
22
  Commands:
23
+ create <folder> Start a new blog (--title, --url, --host vercel|netlify)
19
24
  init Add eleventy-plugin-blog to this site
20
25
  new "Title" [--tags a,b] Write a new draft post
21
26
  list [--drafts] [--json] List posts, newest first
@@ -24,6 +29,9 @@ Commands:
24
29
  tag rename <old> <new> Rename a tag in every post
25
30
  check Find problems before you deploy
26
31
  studio [--open] Edit posts in your browser, with a live preview
32
+ compare [commit] List pages that changed since a commit (default: HEAD)
33
+ update Upgrade the plugin, show what changed, and fix the site
34
+ eject [page|all] Copy a built-in page into your site to edit it
27
35
 
28
36
  Options:
29
37
  --cwd <folder> Run in another folder
@@ -52,6 +60,11 @@ async function main(argv) {
52
60
  images: { type: "string" },
53
61
  "images-url": { type: "string" },
54
62
  "no-preview": { type: "boolean" },
63
+ "no-install": { type: "boolean" },
64
+ host: { type: "string" },
65
+ url: { type: "string" },
66
+ title: { type: "string" },
67
+ to: { type: "string" },
55
68
  },
56
69
  });
57
70
  const [command, ...rest] = positionals;
package/lib/builds.js ADDED
@@ -0,0 +1,83 @@
1
+ const fs = require("fs");
2
+ const path = require("path");
3
+ const { spawnSync } = require("child_process");
4
+ const { glob } = require("tinyglobby");
5
+ const { findConfig, eleventyBin } = require("./site");
6
+ const { colour, plural } = require("./ui");
7
+
8
+ const TEXT = /\.(html?|xml|json|txt|css|js|mjs|svg|md|webmanifest)$/i;
9
+
10
+ /** Eleventy's error without stack traces or repeats. */
11
+ function shortError(text) {
12
+ const lines = String(text)
13
+ .split("\n")
14
+ .map((line) => line.replace(/^\[11ty\]\s?/, ""))
15
+ .filter((line) => line.trim() && !/^\s+at /.test(line) && !/Original error stack trace/.test(line));
16
+ return [...new Set(lines)].slice(0, 8).join("\n");
17
+ }
18
+
19
+ /**
20
+ * Build a site folder into `output` with the site's own Eleventy.
21
+ * @param {string} siteDir folder to build in
22
+ * @param {string} output folder to write to
23
+ * @param {string} [configName] config file name, relative to siteDir
24
+ * @param {string} [bin] Eleventy's command to use; by default the site's own
25
+ * @returns {string|null} null, or a short error
26
+ */
27
+ function buildSite(siteDir, output, configName, bin = eleventyBin(siteDir)) {
28
+ if (!bin) return "Eleventy is not installed in this site.";
29
+ const config = configName || (findConfig(siteDir) && path.basename(findConfig(siteDir)));
30
+ const result = spawnSync(process.execPath, [bin, "--quiet", `--output=${output}`, ...(config ? [`--config=${config}`] : [])], {
31
+ cwd: siteDir,
32
+ encoding: "utf8",
33
+ });
34
+ return result.status === 0 ? null : shortError(result.stderr || result.stdout || "The build failed.");
35
+ }
36
+
37
+ /** Text with runs of whitespace collapsed, so reformatting is not a change. */
38
+ const squash = (buffer) => buffer.toString("utf8").replace(/\s+/g, " ").trim();
39
+
40
+ function sameFile(a, b) {
41
+ const left = fs.readFileSync(a);
42
+ const right = fs.readFileSync(b);
43
+ if (left.equals(right)) return true;
44
+ return TEXT.test(a) && squash(left) === squash(right);
45
+ }
46
+
47
+ /** Page addresses, such as /blog/tag/x/ for blog/tag/x/index.html. */
48
+ const urlOf = (file) => `/${file.replace(/index\.html$/, "").split(path.sep).join("/")}`;
49
+
50
+ /** Compare two builds. Returns { removed, added, changed } as output paths. */
51
+ async function diffBuilds(before, after) {
52
+ const list = async (dir) => (await glob("**/*", { cwd: dir })).sort();
53
+ const old = await list(before);
54
+ const next = await list(after);
55
+ const nextSet = new Set(next);
56
+ const oldSet = new Set(old);
57
+ return {
58
+ removed: old.filter((file) => !nextSet.has(file)),
59
+ added: next.filter((file) => !oldSet.has(file)),
60
+ changed: old.filter((file) => nextSet.has(file) && !sameFile(path.join(before, file), path.join(after, file))),
61
+ };
62
+ }
63
+
64
+ /** Print a diff from diffBuilds. `since` names the earlier build. */
65
+ function printDiff(result, since) {
66
+ if (!result.removed.length && !result.added.length && !result.changed.length) {
67
+ console.log(colour.green(`No pages changed since ${since}.`));
68
+ return;
69
+ }
70
+ const section = (title, files, hint) => {
71
+ if (!files.length) return;
72
+ console.log(`\n${colour.bold(title)}${hint ? colour.dim(` ${hint}`) : ""}`);
73
+ for (const file of files) console.log(` ${urlOf(file)}`);
74
+ };
75
+ section("Gone", result.removed, "(links to these break; add a redirect if they moved)");
76
+ section("New", result.added);
77
+ section("Changed", result.changed);
78
+ console.log(
79
+ `\n${plural(result.removed.length, "page")} gone, ${result.added.length} new, ${result.changed.length} changed since ${since}. Whitespace-only changes are ignored.`
80
+ );
81
+ }
82
+
83
+ module.exports = { buildSite, shortError, diffBuilds, printDiff, urlOf };
@@ -0,0 +1,78 @@
1
+ const fs = require("fs");
2
+ const os = require("os");
3
+ const path = require("path");
4
+ const { spawnSync } = require("child_process");
5
+ const { findConfig, eleventyBin } = require("../site");
6
+ const { buildSite, diffBuilds, printDiff } = require("../builds");
7
+ const { colour } = require("../ui");
8
+
9
+ const git = (cwd, ...args) => spawnSync("git", args, { cwd, encoding: "utf8" });
10
+
11
+ module.exports = async function compare(args) {
12
+ const cwd = args.cwd;
13
+ const ref = args.positionals[0] || "HEAD";
14
+ const top = git(cwd, "rev-parse", "--show-toplevel");
15
+ if (top.status !== 0) {
16
+ console.error(colour.red("compare needs a Git repository: it builds an earlier commit next to your files."));
17
+ return 1;
18
+ }
19
+ if (git(cwd, "rev-parse", "--verify", "--quiet", `${ref}^{commit}`).status !== 0) {
20
+ console.error(colour.red(`No commit called "${ref}".`));
21
+ return 1;
22
+ }
23
+ const root = fs.realpathSync(top.stdout.trim());
24
+ const relative = path.relative(root, fs.realpathSync(cwd));
25
+ const configPath = findConfig(cwd);
26
+ const configName = configPath ? path.basename(configPath) : null;
27
+
28
+ const work = fs.mkdtempSync(path.join(os.tmpdir(), "eleventy-blog-compare-"));
29
+ const baseRoot = path.join(work, "base-src");
30
+ try {
31
+ const added = git(root, "worktree", "add", "--quiet", "--detach", baseRoot, ref);
32
+ if (added.status !== 0) {
33
+ console.error(colour.red(`Could not check out ${ref}: ${added.stderr.trim()}`));
34
+ return 1;
35
+ }
36
+ const baseSite = path.join(baseRoot, relative);
37
+ // The old commit builds with today's installed packages.
38
+ const manifest = (dir) => {
39
+ try {
40
+ return fs.readFileSync(path.join(dir, "package.json"), "utf8");
41
+ } catch {
42
+ return "";
43
+ }
44
+ };
45
+ const packagesChanged = manifest(baseSite) !== manifest(cwd);
46
+ // Use the site's installed packages for the old commit too.
47
+ for (const dir of new Set([path.join(cwd, "node_modules"), path.join(root, "node_modules")])) {
48
+ const target = path.join(baseRoot, path.relative(root, dir));
49
+ if (fs.existsSync(dir) && !fs.existsSync(target)) fs.symlinkSync(dir, target, "dir");
50
+ }
51
+
52
+ console.log(colour.dim(`Building ${ref}…`));
53
+ // Build the old commit with the Eleventy installed today.
54
+ const beforeError = buildSite(baseSite, path.join(work, "before"), configName, eleventyBin(cwd));
55
+ if (beforeError) {
56
+ console.error(colour.red(`The build of ${ref} failed:\n${beforeError}`));
57
+ if (packagesChanged) {
58
+ console.error("Your packages changed since then, and the old commit builds with today's packages. After an upgrade, `eleventy-blog update` compares the pages for you.");
59
+ }
60
+ return 1;
61
+ }
62
+ console.log(colour.dim("Building your files…"));
63
+ const afterError = buildSite(cwd, path.join(work, "after"), configName);
64
+ if (afterError) {
65
+ console.error(colour.red(`The build of your files failed:\n${afterError}`));
66
+ return 1;
67
+ }
68
+
69
+ const result = await diffBuilds(path.join(work, "before"), path.join(work, "after"));
70
+ if (args.json) console.log(JSON.stringify(result, null, 2));
71
+ else printDiff(result, ref);
72
+ return 0;
73
+ } finally {
74
+ git(root, "worktree", "remove", "--force", baseRoot);
75
+ fs.rmSync(work, { recursive: true, force: true });
76
+ }
77
+ };
78
+
@@ -0,0 +1,252 @@
1
+ const fs = require("fs");
2
+ const path = require("path");
3
+ const { spawnSync } = require("child_process");
4
+ const { colour, confirm } = require("../ui");
5
+ const { newPostText } = require("../frontmatter");
6
+
7
+ const shell = process.platform === "win32";
8
+ const OWN_VERSION = require("../../package.json").version;
9
+
10
+ /** Latest version of a package within a range, or the fallback when offline. */
11
+ function versionOf(spec, fallback) {
12
+ const result = spawnSync("npm", ["view", spec, "version", "--json"], { encoding: "utf8", shell });
13
+ if (result.status !== 0) return fallback;
14
+ try {
15
+ const value = JSON.parse(result.stdout);
16
+ return Array.isArray(value) ? value[value.length - 1] : value;
17
+ } catch {
18
+ return fallback;
19
+ }
20
+ }
21
+
22
+ const slugify = (text) =>
23
+ String(text)
24
+ .toLowerCase()
25
+ .replace(/[^a-z0-9]+/g, "-")
26
+ .replace(/^-|-$/g, "") || "my-blog";
27
+
28
+ const today = () => new Date().toISOString().slice(0, 10);
29
+
30
+ /**
31
+ * Every file of a new site, as { path: text }.
32
+ * @param {Object} options { name, title, url, host, versions }
33
+ */
34
+ function siteFiles({ name, title, url, host, versions }) {
35
+ const feed = url
36
+ ? ` feed: { url: ${JSON.stringify(url.replace(/\/+$/, ""))}, title: ${JSON.stringify(title)} },\n`
37
+ : ` // Add an Atom feed by setting your site's address:\n // feed: { url: "https://example.com", title: ${JSON.stringify(title)} },\n`;
38
+ const files = {
39
+ "package.json": `${JSON.stringify(
40
+ {
41
+ name,
42
+ private: true,
43
+ type: "module",
44
+ scripts: {
45
+ start: "eleventy --serve",
46
+ build: "eleventy",
47
+ studio: "eleventy-blog studio --open",
48
+ },
49
+ devDependencies: {
50
+ "@11ty/eleventy": `^${versions.eleventy}`,
51
+ "eleventy-blog": `^${versions.cli}`,
52
+ "eleventy-plugin-blog": `^${versions.plugin}`,
53
+ },
54
+ },
55
+ null,
56
+ 2
57
+ )}\n`,
58
+ "eleventy.config.js": `import blog from "eleventy-plugin-blog";
59
+
60
+ export default function (eleventyConfig) {
61
+ eleventyConfig.addPlugin(blog, {
62
+ layout: "base.njk",
63
+ blogPostTemplate: "post.njk",
64
+ ${feed} });
65
+
66
+ eleventyConfig.addPassthroughCopy("src/assets");
67
+ eleventyConfig.addPassthroughCopy("src/blog/images");
68
+ eleventyConfig.addGlobalData("site", { title: ${JSON.stringify(title)} });
69
+ }
70
+
71
+ export const config = {
72
+ dir: { input: "src" },
73
+ };
74
+ `,
75
+ "src/_includes/base.njk": `<!doctype html>
76
+ <html lang="en">
77
+ <head>
78
+ <meta charset="utf-8">
79
+ <meta name="viewport" content="width=device-width, initial-scale=1">
80
+ <title>{% if title %}{{ title }} · {% endif %}{{ site.title }}</title>
81
+ <link rel="stylesheet" href="/assets/style.css">
82
+ ${url ? ' <link rel="alternate" type="application/atom+xml" href="/blog/feed.xml" title="{{ site.title }}">\n' : ""}</head>
83
+ <body>
84
+ <header class="top">
85
+ <a class="brand" href="/">{{ site.title }}</a>
86
+ <nav>
87
+ <a href="/blog/">Posts</a>
88
+ <a href="/blog/tag/">Tags</a>
89
+ ${url ? ' <a href="/blog/feed.xml">Feed</a>\n' : ""} </nav>
90
+ </header>
91
+ <main>
92
+ {{ content | safe }}
93
+ </main>
94
+ </body>
95
+ </html>
96
+ `,
97
+ "src/_includes/post.njk": `---
98
+ layout: base.njk
99
+ ---
100
+ <article class="post">
101
+ <h1>{{ title }}</h1>
102
+ <p class="meta">
103
+ <time datetime="{{ page.date | blog_dateformat('YYYY-MM-DD') }}">{{ page.date | blog_dateformat('D MMMM YYYY') }}</time>
104
+ {%- for tag in tags %} · <a href="/blog/tag/{{ tag | blog_slug }}/">{{ tag }}</a>{% endfor %}
105
+ </p>
106
+ {{ content | safe }}
107
+ </article>
108
+ `,
109
+ "src/index.njk": `---
110
+ layout: base.njk
111
+ ---
112
+ <h1>{{ site.title }}</h1>
113
+ <p>Welcome. The newest posts are below; all of them are on the <a href="/blog/">posts page</a>.</p>
114
+ <ul class="blog-post-list">
115
+ {%- for post in collections.blog_flat | blog_top_n(5) %}
116
+ <li>
117
+ <time datetime="{{ post.date | blog_dateformat('YYYY-MM-DD') }}">{{ post.date | blog_dateformat('D MMMM YYYY') }}</time>
118
+ <a href="{{ post.url }}">{{ post.data.title }}</a>
119
+ </li>
120
+ {%- endfor %}
121
+ </ul>
122
+ `,
123
+ "src/assets/style.css": `:root {
124
+ --bg: #fbfaf7;
125
+ --fg: #1d1c1a;
126
+ --muted: #5f5b54;
127
+ --accent: #b4412f;
128
+ --line: #e2ddd3;
129
+ --code-bg: #f0ede6;
130
+ color-scheme: light dark;
131
+ }
132
+ @media (prefers-color-scheme: dark) {
133
+ :root { --bg: #161514; --fg: #ecebe8; --muted: #a8a39a; --accent: #f08a6e; --line: #34312c; --code-bg: #24221f; }
134
+ }
135
+ * { box-sizing: border-box; }
136
+ body { margin: 0; background: var(--bg); color: var(--fg); font: 18px/1.65 system-ui, -apple-system, "Segoe UI", sans-serif; }
137
+ a { color: var(--accent); }
138
+ main, .top { max-width: 42rem; margin: 0 auto; padding: 0 1rem; }
139
+ .top { display: flex; flex-wrap: wrap; gap: 0.5rem 1.5rem; justify-content: space-between; align-items: baseline; padding-top: 1.25rem; padding-bottom: 1.25rem; border-bottom: 1px solid var(--line); }
140
+ .brand { font-weight: 700; color: var(--fg); text-decoration: none; }
141
+ .top nav { display: flex; gap: 1rem; }
142
+ .top nav a { color: var(--muted); text-decoration: none; }
143
+ h1 { line-height: 1.2; }
144
+ img { max-width: 100%; height: auto; }
145
+ code { background: var(--code-bg); padding: 0.1em 0.3em; border-radius: 4px; }
146
+ pre { background: var(--code-bg); padding: 1rem; border-radius: 8px; overflow-x: auto; }
147
+ pre code { padding: 0; background: none; }
148
+ blockquote { margin-left: 0; padding-left: 1rem; border-left: 3px solid var(--line); color: var(--muted); }
149
+ .post .meta, .blog-post-list time { color: var(--muted); font-size: 0.9rem; }
150
+ .blog-post-list, .blog-tag-list { list-style: none; padding: 0; }
151
+ .blog-post-list li, .blog-tag-list li { padding: 0.5rem 0; border-bottom: 1px solid var(--line); }
152
+ .blog-post-list time { display: block; }
153
+ .blog-pager { display: flex; justify-content: space-between; gap: 1rem; margin: 1.5rem 0; color: var(--muted); }
154
+ `,
155
+ [`src/blog/${today()}-hello.md`]: newPostText({
156
+ title: "Hello",
157
+ date: today(),
158
+ tags: ["welcome"],
159
+ draft: false,
160
+ body: `
161
+ This is the first post. Edit it in the studio:
162
+
163
+ \`\`\`bash
164
+ npm run studio
165
+ \`\`\`
166
+
167
+ Or write a new one with \`npx eleventy-blog new "Title"\`.
168
+ `,
169
+ }),
170
+ ".gitignore": "node_modules/\n_site/\n.DS_Store\n",
171
+ "README.md": `# ${title}
172
+
173
+ A blog built with [Eleventy](https://www.11ty.dev/) and [eleventy-plugin-blog](https://sielay.github.io/eleventy-plugin-blog/).
174
+
175
+ | Command | What it does |
176
+ | --- | --- |
177
+ | \`npm start\` | Serves the site at http://localhost:8080 and rebuilds on save |
178
+ | \`npm run studio\` | Opens the visual editor for posts |
179
+ | \`npm run build\` | Builds the site into \`_site/\` |
180
+ | \`npx eleventy-blog new "Title"\` | Writes a new draft post |
181
+ | \`npx eleventy-blog check\` | Finds broken links and other problems before you deploy |
182
+ | \`npx eleventy-blog update\` | Upgrades the plugin |
183
+
184
+ Posts live in \`src/blog/\`. The plugin adds the post list, tag pages, archive${url ? ", and feed" : ""}.
185
+ `,
186
+ };
187
+ if (host === "vercel") {
188
+ files["vercel.json"] = `${JSON.stringify({ buildCommand: "npm run build", outputDirectory: "_site" }, null, 2)}\n`;
189
+ } else if (host === "netlify") {
190
+ files["netlify.toml"] = `[build]\n command = "npm run build"\n publish = "_site"\n`;
191
+ }
192
+ return files;
193
+ }
194
+
195
+ module.exports = async function create(args) {
196
+ const folder = args.positionals[0];
197
+ if (!folder) {
198
+ console.error(colour.red('Name the folder for the new site: npx eleventy-blog create my-blog'));
199
+ return 1;
200
+ }
201
+ const host = args.host || "none";
202
+ if (!["vercel", "netlify", "none"].includes(host)) {
203
+ console.error(colour.red("--host must be vercel, netlify, or none."));
204
+ return 1;
205
+ }
206
+ if (args.url && !/^https?:\/\//.test(args.url)) {
207
+ console.error(colour.red("--url must start with https:// or http://"));
208
+ return 1;
209
+ }
210
+ const dir = path.resolve(args.cwd, folder);
211
+ if (fs.existsSync(dir) && fs.readdirSync(dir).length) {
212
+ console.error(colour.red(`${folder} is not empty. Choose a new folder name.`));
213
+ return 1;
214
+ }
215
+
216
+ const name = slugify(path.basename(dir));
217
+ const title = args.title || path.basename(dir).replace(/[-_]+/g, " ").replace(/^\w/, (c) => c.toUpperCase());
218
+ const versions = {
219
+ eleventy: versionOf("@11ty/eleventy@^3", "3.1.2"),
220
+ plugin: versionOf("eleventy-plugin-blog", "0.5.0"),
221
+ cli: OWN_VERSION,
222
+ };
223
+ const files = siteFiles({ name, title, url: args.url, host, versions });
224
+
225
+ console.log(`A new blog in ${colour.bold(path.relative(args.cwd, dir) || ".")}:\n`);
226
+ for (const file of Object.keys(files)) console.log(` ${file}`);
227
+ console.log("");
228
+ if (!(await confirm("Create these files?", args))) return 0;
229
+ for (const [file, text] of Object.entries(files)) {
230
+ const target = path.join(dir, file);
231
+ fs.mkdirSync(path.dirname(target), { recursive: true });
232
+ fs.writeFileSync(target, text);
233
+ }
234
+
235
+ let installed = false;
236
+ if (!args["no-install"] && (await confirm("Install the packages with npm now?", args))) {
237
+ installed = spawnSync("npm", ["install"], { cwd: dir, stdio: "inherit", shell }).status === 0;
238
+ if (!installed) console.log(colour.yellow("npm install failed. Run it again in the new folder."));
239
+ }
240
+
241
+ const cd = path.relative(args.cwd, dir) || ".";
242
+ console.log(colour.green("\nYour blog is ready. Next:"));
243
+ console.log(` cd ${cd}`);
244
+ if (!installed) console.log(" npm install");
245
+ console.log(" npm start # the site, at http://localhost:8080");
246
+ console.log(" npm run studio # the editor");
247
+ if (!args.url) console.log(colour.dim("Add a feed later: set feed.url in eleventy.config.js."));
248
+ if (host === "none") console.log(colour.dim("To deploy, create the site with --host vercel or --host netlify, or point any static host at _site/."));
249
+ return 0;
250
+ };
251
+
252
+ Object.assign(module.exports, { siteFiles, slugify });
@@ -0,0 +1,93 @@
1
+ const fs = require("fs");
2
+ const path = require("path");
3
+ const YAML = require("yaml");
4
+ const { loadSite } = require("../site");
5
+ const { colour, confirm, printChange, printTable } = require("../ui");
6
+
7
+ /**
8
+ * The text of an ejected page: the plugin's data as front matter, then
9
+ * the template body.
10
+ */
11
+ function pageText(template) {
12
+ const data = YAML.stringify(template.data, { lineWidth: 0 });
13
+ return `---\n# Ejected from eleventy-plugin-blog. The plugin no longer changes this page.\n${data}---\n${template.body}`;
14
+ }
15
+
16
+ /** What `eject` can copy, with where each one goes. */
17
+ function ejectables(site) {
18
+ const pages = site.plugin.pages;
19
+ const options = (site.plugin.OPTIONS && site.plugin.OPTIONS.pageOptions) || {};
20
+ const list = pages.PAGE_NAMES.map((name) => {
21
+ const template = pages.pageTemplate(name, options);
22
+ return {
23
+ name,
24
+ file: path.join(site.input, pages.PAGE_FOLDER, `${name}.njk`),
25
+ text: template ? pageText(template) : null,
26
+ why: template ? null : "set feed.url in the plugin options first",
27
+ };
28
+ });
29
+ list.push({
30
+ name: "layout",
31
+ file: path.join(site.includes, pages.BASE_LAYOUT),
32
+ text: options.layout ? null : pages.BASE,
33
+ why: options.layout ? `the pages already use your layout, ${options.layout}` : null,
34
+ });
35
+ return list;
36
+ }
37
+
38
+ module.exports = async function eject(args) {
39
+ const site = await loadSite(args.cwd);
40
+ if (!site.plugin || !site.plugin.pages || !site.plugin.pages.pageTemplate) {
41
+ console.error(colour.red("This needs eleventy-plugin-blog 0.5.0 or later. Run `npx eleventy-blog update` first."));
42
+ return 1;
43
+ }
44
+ const list = ejectables(site);
45
+ const names = args.positionals;
46
+
47
+ if (!names.length) {
48
+ console.log("Pages you can copy into your site:\n");
49
+ printTable([
50
+ ["Page", "Status", "File"],
51
+ ...list.map((item) => [
52
+ item.name,
53
+ fs.existsSync(item.file) ? "yours" : item.text ? "built in" : item.name === "layout" ? "uses your layout" : "needs feed.url",
54
+ path.relative(args.cwd, item.file),
55
+ ]),
56
+ ]);
57
+ console.log(`\nRun ${colour.bold("npx eleventy-blog eject <page>")}, or ${colour.bold("eject all")}. After that, updates do not change the page.`);
58
+ return 0;
59
+ }
60
+
61
+ const wanted = names.includes("all") ? list.filter((item) => item.text && !fs.existsSync(item.file)) : [];
62
+ for (const name of names.filter((n) => n !== "all")) {
63
+ const item = list.find((entry) => entry.name === name);
64
+ if (!item) {
65
+ console.error(colour.red(`No page called "${name}". Pages: ${list.map((entry) => entry.name).join(", ")}`));
66
+ return 1;
67
+ }
68
+ if (fs.existsSync(item.file)) {
69
+ console.log(colour.dim(`${path.relative(args.cwd, item.file)} is already yours.`));
70
+ continue;
71
+ }
72
+ if (!item.text) {
73
+ console.log(colour.yellow(`Cannot copy ${name}: ${item.why}.`));
74
+ continue;
75
+ }
76
+ if (!wanted.includes(item)) wanted.push(item);
77
+ }
78
+ if (!wanted.length) {
79
+ console.log("Nothing to copy.");
80
+ return 0;
81
+ }
82
+
83
+ for (const item of wanted) printChange(`${path.relative(args.cwd, item.file)} (new)`, null, item.text);
84
+ if (!(await confirm(`Copy ${wanted.length === 1 ? "this page" : `these ${wanted.length} pages`} into your site?`, args))) return 0;
85
+ for (const item of wanted) {
86
+ fs.mkdirSync(path.dirname(item.file), { recursive: true });
87
+ fs.writeFileSync(item.file, item.text);
88
+ }
89
+ console.log(colour.green(`Copied ${wanted.map((item) => item.name).join(", ")}. Edit them as you like; the plugin now uses your files.`));
90
+ return 0;
91
+ };
92
+
93
+ module.exports.pageText = pageText;
@@ -25,8 +25,10 @@ async function buildUrlMap(site) {
25
25
  const previous = process.cwd();
26
26
  process.chdir(site.cwd);
27
27
  try {
28
+ // Serve mode, as for the preview, so drafts get their addresses too.
28
29
  const elev = new site.Eleventy(undefined, undefined, {
29
30
  quietMode: true,
31
+ runMode: "serve",
30
32
  ...(site.configPath ? { configPath: site.configPath } : {}),
31
33
  });
32
34
  const results = await elev.toJSON();
@@ -0,0 +1,193 @@
1
+ const fs = require("fs");
2
+ const os = require("os");
3
+ const path = require("path");
4
+ const { spawnSync } = require("child_process");
5
+ const { resolveFromSite, loadSite, findConfig } = require("../site");
6
+ const { buildSite, diffBuilds, printDiff } = require("../builds");
7
+ const { MIGRATIONS } = require("../migrations");
8
+ const { colour, confirm, printChange } = require("../ui");
9
+
10
+ const PLUGIN = "eleventy-plugin-blog";
11
+ const shell = process.platform === "win32";
12
+
13
+ /** Compare two versions such as 0.4.0 and 0.10.1. Pre-release tags sort first. */
14
+ function compareVersions(a, b) {
15
+ const parse = (v) => {
16
+ const [main, pre] = String(v).replace(/^v/, "").split("-");
17
+ return { parts: main.split(".").map(Number), pre };
18
+ };
19
+ const x = parse(a);
20
+ const y = parse(b);
21
+ for (let i = 0; i < 3; i++) {
22
+ const diff = (x.parts[i] || 0) - (y.parts[i] || 0);
23
+ if (diff) return Math.sign(diff);
24
+ }
25
+ if (x.pre && !y.pre) return -1;
26
+ if (!x.pre && y.pre) return 1;
27
+ return 0;
28
+ }
29
+
30
+ /**
31
+ * Changelog sections after `from`, up to and including `to`, newest first.
32
+ * @returns {{version: string, text: string}[]}
33
+ */
34
+ function changelogBetween(changelog, from, to) {
35
+ const sections = [];
36
+ const parts = String(changelog).split(/^## +/m).slice(1);
37
+ for (const part of parts) {
38
+ const version = part.split("\n")[0].trim().split(/\s/)[0];
39
+ if (!/^\d+\.\d+\.\d+/.test(version)) continue;
40
+ if (compareVersions(version, from) > 0 && compareVersions(version, to) <= 0) {
41
+ sections.push({ version, text: part.slice(part.indexOf("\n") + 1).replace(/^\s*\n/, "").trimEnd() });
42
+ }
43
+ }
44
+ return sections;
45
+ }
46
+
47
+ /** The plugin version installed in the site, or null. */
48
+ function installedVersion(cwd) {
49
+ const resolved = resolveFromSite(cwd, PLUGIN);
50
+ if (!resolved) return null;
51
+ let dir = path.dirname(resolved);
52
+ while (dir !== path.dirname(dir)) {
53
+ const manifest = path.join(dir, "package.json");
54
+ if (fs.existsSync(manifest)) {
55
+ const pkg = JSON.parse(fs.readFileSync(manifest, "utf8"));
56
+ if (pkg.name === PLUGIN) return pkg.version;
57
+ }
58
+ dir = path.dirname(dir);
59
+ }
60
+ return null;
61
+ }
62
+
63
+ function npm(cwd, args) {
64
+ return spawnSync("npm", args, { cwd, encoding: "utf8", shell });
65
+ }
66
+
67
+ function latestVersion(cwd) {
68
+ const result = npm(cwd, ["view", PLUGIN, "version"]);
69
+ return result.status === 0 ? result.stdout.trim() : null;
70
+ }
71
+
72
+ /** Download a version's package and read its changelog, without installing it. */
73
+ function fetchChangelog(version) {
74
+ const work = fs.mkdtempSync(path.join(os.tmpdir(), "eleventy-blog-update-"));
75
+ try {
76
+ const packed = npm(work, ["pack", `${PLUGIN}@${version}`, "--silent"]);
77
+ if (packed.status !== 0) return null;
78
+ const tarball = packed.stdout.trim().split("\n").pop();
79
+ const unpacked = spawnSync("tar", ["-xzf", tarball, "package/CHANGELOG.md"], { cwd: work });
80
+ if (unpacked.status !== 0) return null;
81
+ return fs.readFileSync(path.join(work, "package", "CHANGELOG.md"), "utf8");
82
+ } finally {
83
+ fs.rmSync(work, { recursive: true, force: true });
84
+ }
85
+ }
86
+
87
+ /** The install command for the site's package manager, keeping the dependency type. */
88
+ function installCommand(cwd, version) {
89
+ let pkg = {};
90
+ try {
91
+ pkg = JSON.parse(fs.readFileSync(path.join(cwd, "package.json"), "utf8"));
92
+ } catch {
93
+ // No package.json: npm creates one.
94
+ }
95
+ const dev = !(pkg.dependencies && pkg.dependencies[PLUGIN]);
96
+ const spec = `${PLUGIN}@^${version}`;
97
+ if (fs.existsSync(path.join(cwd, "pnpm-lock.yaml"))) return ["pnpm", ["add", ...(dev ? ["-D"] : []), spec]];
98
+ if (fs.existsSync(path.join(cwd, "yarn.lock"))) return ["yarn", ["add", ...(dev ? ["-D"] : []), spec]];
99
+ return ["npm", ["install", dev ? "--save-dev" : "--save", spec]];
100
+ }
101
+
102
+ module.exports = async function update(args) {
103
+ const cwd = args.cwd;
104
+ const current = installedVersion(cwd);
105
+ if (!current) {
106
+ console.error(colour.red(`${PLUGIN} is not installed here. Run \`npx eleventy-blog init\` to add it.`));
107
+ return 1;
108
+ }
109
+ const latest = args.to || latestVersion(cwd);
110
+ if (!latest) {
111
+ console.error(colour.red("Could not reach the npm registry to find the latest version."));
112
+ return 1;
113
+ }
114
+ if (compareVersions(latest, current) <= 0) {
115
+ console.log(colour.green(`${PLUGIN} ${current} is up to date.`));
116
+ return 0;
117
+ }
118
+
119
+ // 1. What changes.
120
+ console.log(`${colour.bold(PLUGIN)} ${current} → ${colour.green(latest)}\n`);
121
+ const changelog = fetchChangelog(latest);
122
+ const sections = changelog ? changelogBetween(changelog, current, latest) : [];
123
+ if (sections.length) {
124
+ for (const { version, text } of sections) {
125
+ console.log(colour.bold(version));
126
+ for (const line of text.split("\n")) {
127
+ console.log(/BREAKING/.test(line) ? colour.yellow(line) : line);
128
+ }
129
+ console.log("");
130
+ }
131
+ } else {
132
+ console.log(colour.dim(`See what changed: https://github.com/sielay/eleventy-plugin-blog/blob/master/CHANGELOG.md\n`));
133
+ }
134
+
135
+ // 2. Upgrade, with a build from before it to compare against.
136
+ const [tool, toolArgs] = installCommand(cwd, latest);
137
+ if (!(await confirm(`Run \`${tool} ${toolArgs.join(" ")}\`?`, args))) return 0;
138
+ const work = fs.mkdtempSync(path.join(os.tmpdir(), "eleventy-blog-update-"));
139
+ try {
140
+ return await upgrade({ args, cwd, current, latest, tool, toolArgs, work });
141
+ } finally {
142
+ fs.rmSync(work, { recursive: true, force: true });
143
+ }
144
+ };
145
+
146
+ async function upgrade({ args, cwd, current, latest, tool, toolArgs, work }) {
147
+ const before = path.join(work, "before");
148
+ const after = path.join(work, "after");
149
+ const beforeError = buildSite(cwd, before);
150
+ const installed = spawnSync(tool, toolArgs, { cwd, stdio: "inherit", shell });
151
+ if (installed.status !== 0) {
152
+ console.error(colour.red("The install failed. Nothing else was changed."));
153
+ return 1;
154
+ }
155
+
156
+ // 3. Changes the site needs, for each breaking version crossed.
157
+ let buildError = buildSite(cwd, after);
158
+ const due = MIGRATIONS.filter(
159
+ (m) => compareVersions(m.version, current) > 0 && compareVersions(m.version, latest) <= 0
160
+ );
161
+ if (due.length) {
162
+ const site = await loadSite(cwd).catch(() => ({ cwd, configPath: findConfig(cwd) }));
163
+ for (const migration of due) {
164
+ const change = migration.run({ site, buildError });
165
+ if (!change) continue;
166
+ console.log(`\n${colour.bold(`${migration.version}: ${migration.title}`)}\n${change.why}\n`);
167
+ printChange(path.relative(cwd, change.file), change.before, change.after);
168
+ if (await confirm("Apply this change?", args)) {
169
+ fs.writeFileSync(change.file, change.after);
170
+ fs.rmSync(after, { recursive: true, force: true });
171
+ buildError = buildSite(cwd, after);
172
+ }
173
+ }
174
+ }
175
+
176
+ // 4. Does it still build?
177
+ if (buildError) {
178
+ console.error(colour.red(`\nThe site does not build with ${latest}:\n${buildError}`));
179
+ console.error(`Go back with: ${tool} ${installCommand(cwd, current)[1].join(" ")}`);
180
+ return 1;
181
+ }
182
+ console.log(colour.green(`\nUpdated to ${latest}. The site builds.`));
183
+
184
+ // 5. Which pages changed?
185
+ if (beforeError) {
186
+ console.log(colour.dim(`The site did not build with ${current}, so there is nothing to compare with.`));
187
+ } else {
188
+ printDiff(await diffBuilds(before, after), current);
189
+ }
190
+ return 0;
191
+ }
192
+
193
+ Object.assign(module.exports, { compareVersions, changelogBetween, installCommand, installedVersion });
@@ -0,0 +1,63 @@
1
+ const fs = require("fs");
2
+
3
+ /**
4
+ * Changes `update` offers when a site crosses a version with a breaking
5
+ * change. Each one looks at the site after the upgrade and returns a file
6
+ * edit to show, or null when the site needs nothing.
7
+ *
8
+ * A migration gets { site, buildError } and returns
9
+ * { file, before, after, why } or null.
10
+ */
11
+
12
+ /** The name the config gives the plugin, such as `blog`. */
13
+ function pluginName(text) {
14
+ const match =
15
+ text.match(/import\s+(\w+)\s+from\s+["']eleventy-plugin-blog["']/) ||
16
+ text.match(/(?:const|let|var)\s+(\w+)\s*=\s*require\(\s*["']eleventy-plugin-blog["']\s*\)/);
17
+ return match ? match[1] : null;
18
+ }
19
+
20
+ /**
21
+ * Add `key: value` to the options of the config's addPlugin call.
22
+ * Returns the new text, or null when the call is not found.
23
+ */
24
+ function addPluginOption(text, key, value) {
25
+ const name = pluginName(text);
26
+ if (!name) return null;
27
+ const call = new RegExp(`addPlugin\\(\\s*${name}\\s*(\\)|,\\s*\\{)`);
28
+ const match = text.match(call);
29
+ if (!match) return null;
30
+ const at = match.index + match[0].length;
31
+ if (match[1] === ")") {
32
+ return `${text.slice(0, at - 1)}, { ${key}: ${value} })${text.slice(at)}`;
33
+ }
34
+ // Options object: put the new key first, matching the next line's indent.
35
+ const rest = text.slice(at);
36
+ const nextLine = rest.match(/^[ \t]*\n([ \t]*)/);
37
+ if (nextLine) return `${text.slice(0, at)}\n${nextLine[1]}${key}: ${value},${rest}`;
38
+ return `${text.slice(0, at)} ${key}: ${value},${rest}`;
39
+ }
40
+
41
+ const MIGRATIONS = [
42
+ {
43
+ version: "0.4.0",
44
+ title: "The plugin adds the blog pages itself",
45
+ run({ site, buildError }) {
46
+ // A site with its own pages at the same URLs now fails to build.
47
+ if (!buildError || !/DuplicatePermalink|Output conflict|multiple input files/i.test(buildError)) return null;
48
+ if (!site.configPath) return null;
49
+ const before = fs.readFileSync(site.configPath, "utf8");
50
+ if (/\bpages\s*:/.test(before)) return null;
51
+ const after = addPluginOption(before, "pages", "false");
52
+ if (!after) return null;
53
+ return {
54
+ file: site.configPath,
55
+ before,
56
+ after,
57
+ why: "Your site has its own blog pages at the URLs the plugin now uses. `pages: false` keeps yours.",
58
+ };
59
+ },
60
+ },
61
+ ];
62
+
63
+ module.exports = { MIGRATIONS, addPluginOption, pluginName };
package/lib/site.js CHANGED
@@ -116,10 +116,12 @@ async function loadSite(cwd, { configFile } = {}) {
116
116
  // ./src/posts from ./src/posts/**/*.md.
117
117
  const fixedPart = String(blogGlobs[0] || "").split(/[*{[]/)[0].replace(/\/+$/, "");
118
118
  const blogDir = fixedPart ? path.resolve(cwd, fixedPart) : path.join(input, "blog");
119
+ const includes = path.resolve(input, elev.directories.includes ? path.relative(elev.directories.input || ".", elev.directories.includes) : "_includes");
119
120
  return {
120
121
  cwd,
121
122
  configPath,
122
123
  input,
124
+ includes,
123
125
  blogDir,
124
126
  blogGlobs,
125
127
  blogSlug: (options && options.blogSlug) || "blog",
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "eleventy-blog",
3
- "version": "0.1.1",
3
+ "version": "0.2.1",
4
4
  "description": "Command-line tool and local editor for eleventy-plugin-blog: add the blog to a site, write and publish posts, tidy tags, check before you deploy, and edit in a browser",
5
5
  "bin": {
6
6
  "eleventy-blog": "bin/eleventy-blog.js"