@chriswiegman/hugo-tools 0.1.2 → 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/src/pick-image.js CHANGED
@@ -1,80 +1,141 @@
1
1
  #!/usr/bin/env node
2
2
  'use strict';
3
3
 
4
- // Lists images in the configured images directory for the current year/month
5
- // and copies the selected path to the clipboard.
4
+ // Moves an image into assets/images/<year>/<month>/ and inserts a reference
5
+ // into a Hugo content file — appending to the frontmatter images: array when
6
+ // present, or appending a markdown image tag to the body otherwise.
6
7
 
7
8
  const fs = require('fs');
8
9
  const path = require('path');
9
- const readline = require('readline');
10
10
  const { execSync, execFileSync } = require('child_process');
11
11
  const config = require('./config');
12
12
 
13
- config.requireHugoSite();
14
-
15
13
  const IMAGE_EXTS = new Set(['.jpg', '.jpeg', '.png', '.webp', '.gif']);
16
14
 
17
- const now = new Date();
18
- const year = now.getFullYear().toString();
19
- const month = String(now.getMonth() + 1).padStart(2, '0');
20
- const imageDir = path.join(process.cwd(), config.imagesDir, year, month);
21
- const imagePath = `/${config.imagesDir}/${year}/${month}`;
15
+ function urlFromImagesDir(imagesDir, year, month, filename) {
16
+ const urlBase = imagesDir.replace(/^assets\//, '');
22
17
 
23
- if (!fs.existsSync(imageDir)) {
24
- console.error(`No image directory found at ${imageDir}`);
25
- process.exit(1);
18
+ return `/${urlBase}/${year}/${month}/${filename}`;
26
19
  }
27
20
 
28
- const files = fs.readdirSync(imageDir)
29
- .filter(f => IMAGE_EXTS.has(path.extname(f).toLowerCase()))
30
- .sort();
31
-
32
- if (files.length === 0) {
33
- console.error(`No images found in ${imageDir}`);
34
- process.exit(1);
21
+ function appendMarkdown(content, urlPath) {
22
+ return `${content.trimEnd()}\n\n![](${urlPath})\n`;
35
23
  }
36
24
 
37
- console.log(`\nImages in ${imagePath}/:\n`);
38
- files.forEach((f, i) => console.log(` ${i + 1}) ${f}`));
39
- console.log('');
25
+ function insertImage(content, urlPath) {
26
+ const fmEnd = content.indexOf('\n---', 4);
27
+
28
+ if (!content.startsWith('---\n') || fmEnd === -1) {
29
+ return appendMarkdown(content, urlPath);
30
+ }
31
+
32
+ const frontmatter = content.slice(4, fmEnd);
33
+
34
+ if (!/^images:/m.test(frontmatter)) {
35
+ return appendMarkdown(content, urlPath);
36
+ }
37
+
38
+ return content.replace(
39
+ /^(images:)((?:\n {2}-[^\n]*)*)/m,
40
+ (_, key, block) => {
41
+ const existing = block.split('\n').filter((line) => /^ {2}- \S/.test(line));
42
+
43
+ return [key, ...existing, ` - ${urlPath}`].join('\n');
44
+ },
45
+ );
46
+ }
40
47
 
41
48
  function copyToClipboard(text) {
42
- const platform = process.platform;
43
- if (platform === 'darwin') {
44
- execSync(`echo ${JSON.stringify(text)} | pbcopy`);
45
- return;
46
- }
47
- if (platform === 'win32') {
48
- execFileSync('clip', { input: text });
49
- return;
50
- }
51
- // Linux: try common clipboard tools in order
52
- const tools = [
53
- ['xclip', ['-selection', 'clipboard']],
54
- ['xsel', ['--clipboard', '--input']],
55
- ['wl-copy', []],
56
- ];
57
- for (const [cmd, args] of tools) {
58
- try {
59
- execFileSync(cmd, args, { input: text });
60
- return;
61
- } catch {
62
- // try next
63
- }
64
- }
65
- console.log('(clipboard unavailable — copy the path above manually)');
49
+ const platform = process.platform;
50
+
51
+ if (platform === 'darwin') {
52
+ execSync(`echo ${JSON.stringify(text)} | pbcopy`);
53
+ return;
54
+ }
55
+
56
+ if (platform === 'win32') {
57
+ execFileSync('clip', { input: text });
58
+ return;
59
+ }
60
+
61
+ const tools = [
62
+ ['xclip', ['-selection', 'clipboard']],
63
+ ['xsel', ['--clipboard', '--input']],
64
+ ['wl-copy', []],
65
+ ];
66
+
67
+ for (const [cmd, args] of tools) {
68
+ try {
69
+ execFileSync(cmd, args, { input: text });
70
+ return;
71
+ } catch {
72
+ // try next
73
+ }
74
+ }
75
+ console.log('(clipboard unavailable — copy the path above manually)');
76
+ }
77
+
78
+ if (require.main === module) {
79
+ config.requireHugoSite();
80
+
81
+ const args = process.argv.slice(2);
82
+
83
+ if (args.length === 0) {
84
+ console.error('Usage: pick-image <image-file> [content-file]');
85
+ process.exit(1);
86
+ }
87
+
88
+ const imageFile = path.resolve(args[0]);
89
+ const contentFile = args[1] ? path.resolve(args[1]) : null;
90
+
91
+ if (!fs.existsSync(imageFile)) {
92
+ console.error(`Image not found: ${imageFile}`);
93
+ process.exit(1);
94
+ }
95
+
96
+ const ext = path.extname(imageFile).toLowerCase();
97
+
98
+ if (!IMAGE_EXTS.has(ext)) {
99
+ console.error(`Unsupported image format: ${ext}`);
100
+ process.exit(1);
101
+ }
102
+
103
+ const now = new Date();
104
+ const year = now.getFullYear().toString();
105
+ const month = String(now.getMonth() + 1).padStart(2, '0');
106
+ const filename = path.basename(imageFile);
107
+ const destDir = path.join(process.cwd(), config.imagesDir, year, month);
108
+ const destFile = path.join(destDir, filename);
109
+ const urlPath = urlFromImagesDir(config.imagesDir, year, month, filename);
110
+
111
+ fs.mkdirSync(destDir, { recursive: true });
112
+
113
+ if (path.resolve(imageFile) !== path.resolve(destFile)) {
114
+ if (fs.existsSync(destFile)) {
115
+ console.error(`File already exists at destination: ${destFile}`);
116
+ process.exit(1);
117
+ }
118
+
119
+ fs.renameSync(imageFile, destFile);
120
+ console.log(`Moved to: ${destFile}`);
121
+ }
122
+
123
+ if (!contentFile) {
124
+ copyToClipboard(urlPath);
125
+ console.log(`Path copied to clipboard: ${urlPath}`);
126
+ process.exit(0);
127
+ }
128
+
129
+ if (!fs.existsSync(contentFile)) {
130
+ console.error(`Content file not found: ${contentFile}`);
131
+ process.exit(1);
132
+ }
133
+
134
+ const original = fs.readFileSync(contentFile, 'utf8');
135
+ const updated = insertImage(original, urlPath);
136
+
137
+ fs.writeFileSync(contentFile, updated);
138
+ console.log(`Updated: ${path.relative(process.cwd(), contentFile)}`);
66
139
  }
67
140
 
68
- const rl = readline.createInterface({ input: process.stdin, output: process.stdout });
69
- rl.question(`Select image (1-${files.length}): `, answer => {
70
- rl.close();
71
- const choice = parseInt(answer, 10);
72
- if (choice >= 1 && choice <= files.length) {
73
- const result = `${imagePath}/${files[choice - 1]}`;
74
- copyToClipboard(result);
75
- console.log(`\nCopied to clipboard: ${result}`);
76
- } else {
77
- console.error('Invalid selection');
78
- process.exit(1);
79
- }
80
- });
141
+ module.exports = { urlFromImagesDir, appendMarkdown, insertImage };
@@ -0,0 +1,121 @@
1
+ import assert from 'node:assert/strict';
2
+ import { test } from 'node:test';
3
+ import { createRequire } from 'node:module';
4
+
5
+ const require = createRequire(import.meta.url);
6
+ const { urlFromImagesDir, appendMarkdown, insertImage } = require('./pick-image.js');
7
+
8
+ // ---------------------------------------------------------------------------
9
+ // urlFromImagesDir
10
+ // ---------------------------------------------------------------------------
11
+
12
+ test('urlFromImagesDir: strips assets/ prefix', () => {
13
+ assert.equal(urlFromImagesDir('assets/images', '2026', '05', 'photo.jpg'), '/images/2026/05/photo.jpg');
14
+ });
15
+
16
+ test('urlFromImagesDir: preserves dir without assets/ prefix', () => {
17
+ assert.equal(urlFromImagesDir('images', '2026', '05', 'photo.jpg'), '/images/2026/05/photo.jpg');
18
+ });
19
+
20
+ test('urlFromImagesDir: preserves custom directory name', () => {
21
+ assert.equal(urlFromImagesDir('assets/media', '2026', '05', 'photo.jpg'), '/media/2026/05/photo.jpg');
22
+ });
23
+
24
+ // ---------------------------------------------------------------------------
25
+ // appendMarkdown
26
+ // ---------------------------------------------------------------------------
27
+
28
+ test('appendMarkdown: appends image tag with blank line separator', () => {
29
+ const result = appendMarkdown('Body text.\n', '/images/2026/05/photo.jpg');
30
+
31
+ assert.equal(result, 'Body text.\n\n![](/images/2026/05/photo.jpg)\n');
32
+ });
33
+
34
+ test('appendMarkdown: trims trailing whitespace before appending', () => {
35
+ const result = appendMarkdown('Body text.\n\n\n', '/images/2026/05/photo.jpg');
36
+
37
+ assert.equal(result, 'Body text.\n\n![](/images/2026/05/photo.jpg)\n');
38
+ });
39
+
40
+ test('appendMarkdown: works when content has no trailing newline', () => {
41
+ const result = appendMarkdown('Body text.', '/images/2026/05/photo.jpg');
42
+
43
+ assert.equal(result, 'Body text.\n\n![](/images/2026/05/photo.jpg)\n');
44
+ });
45
+
46
+ // ---------------------------------------------------------------------------
47
+ // insertImage — no frontmatter or no images: field → markdown fallback
48
+ // ---------------------------------------------------------------------------
49
+
50
+ test('insertImage: appends markdown when no frontmatter', () => {
51
+ const content = 'Just a plain body.\n';
52
+ const result = insertImage(content, '/images/2026/05/photo.jpg');
53
+
54
+ assert.ok(result.includes('![](/images/2026/05/photo.jpg)'));
55
+ assert.ok(result.includes('Just a plain body.'));
56
+ });
57
+
58
+ test('insertImage: appends markdown when frontmatter has no images: field', () => {
59
+ const content = '---\ntitle: "My Post"\n---\nBody text.\n';
60
+ const result = insertImage(content, '/images/2026/05/photo.jpg');
61
+
62
+ assert.ok(result.includes('![](/images/2026/05/photo.jpg)'));
63
+ assert.ok(result.includes('Body text.'));
64
+ });
65
+
66
+ // ---------------------------------------------------------------------------
67
+ // insertImage — frontmatter images: array manipulation
68
+ // ---------------------------------------------------------------------------
69
+
70
+ test('insertImage: replaces placeholder ( -) with real path', () => {
71
+ const content = '---\ntitle: "My Post"\nimages:\n -\n---\nBody.\n';
72
+ const result = insertImage(content, '/images/2026/05/photo.jpg');
73
+
74
+ assert.ok(result.includes(' - /images/2026/05/photo.jpg'));
75
+ assert.ok(!result.includes('\n -\n'));
76
+ assert.ok(!result.includes('![]('));
77
+ });
78
+
79
+ test('insertImage: appends to existing single-item images array', () => {
80
+ const content = '---\ntitle: "My Post"\nimages:\n - /images/2026/01/old.jpg\n---\nBody.\n';
81
+ const result = insertImage(content, '/images/2026/05/new.jpg');
82
+
83
+ assert.ok(result.includes(' - /images/2026/01/old.jpg'));
84
+ assert.ok(result.includes(' - /images/2026/05/new.jpg'));
85
+ assert.ok(!result.includes('![]('));
86
+ });
87
+
88
+ test('insertImage: appends to existing multi-item images array', () => {
89
+ const content = '---\nimages:\n - /images/2026/01/a.jpg\n - /images/2026/02/b.jpg\n---\n';
90
+ const result = insertImage(content, '/images/2026/05/c.jpg');
91
+ const lines = result.split('\n');
92
+ const imgLines = lines.filter((l) => l.startsWith(' - '));
93
+
94
+ assert.equal(imgLines.length, 3);
95
+ assert.equal(imgLines[2], ' - /images/2026/05/c.jpg');
96
+ });
97
+
98
+ test('insertImage: does not duplicate existing items', () => {
99
+ const content = '---\nimages:\n - /images/2026/01/a.jpg\n---\n';
100
+ const result = insertImage(content, '/images/2026/05/b.jpg');
101
+ const count = (result.match(/ {2}- \/images/g) || []).length;
102
+
103
+ assert.equal(count, 2);
104
+ });
105
+
106
+ test('insertImage: leaves other frontmatter fields untouched', () => {
107
+ const content = '---\ntitle: "My Post"\nimages:\n -\ncategories:\n - Tech\ntags:\n - go\n---\nBody.\n';
108
+ const result = insertImage(content, '/images/2026/05/photo.jpg');
109
+
110
+ assert.ok(result.includes('title: "My Post"'));
111
+ assert.ok(result.includes('categories:\n - Tech'));
112
+ assert.ok(result.includes('tags:\n - go'));
113
+ assert.ok(result.includes('Body.'));
114
+ });
115
+
116
+ test('insertImage: body content is preserved when updating frontmatter', () => {
117
+ const content = '---\ntitle: "My Post"\nimages:\n -\n---\nThis is the body.\n';
118
+ const result = insertImage(content, '/images/2026/05/photo.jpg');
119
+
120
+ assert.ok(result.includes('This is the body.'));
121
+ });