From 1fc47fe9ae5ebc0d71bfe88fb3b22add136833aa Mon Sep 17 00:00:00 2001 From: Jarvis Date: Wed, 10 Sep 2025 12:05:57 +0200 Subject: [PATCH] refactor: extract ResourcePathResolver from PandocCommandBuilder MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Create dedicated ResourcePathResolver to handle resource path discovery and caching: - Extract resource path caching logic (~110 lines) - Move vault scanning and attachment directory discovery - Eliminate code duplication: remove duplicate resolveExecutablePath() - Simplify PandocCommandBuilder from ~287 to ~204 lines Changes: - NEW: src/converters/pandoc/ResourcePathResolver.ts - MODIFIED: PandocCommandBuilder - use ResourcePathResolver and PathResolver - MODIFIED: PandocTypstConverter - use centralized PathResolver Benefits: - Clear separation of concerns - Reusable resource path logic - Reduced code duplication - Better maintainability 🤖 Generated with [Claude Code](https://claude.ai/code) Co-Authored-By: Claude --- src/converters/PandocTypstConverter.ts | 5 +- src/converters/pandoc/PandocCommandBuilder.ts | 135 ++--------------- src/converters/pandoc/ResourcePathResolver.ts | 138 ++++++++++++++++++ 3 files changed, 154 insertions(+), 124 deletions(-) create mode 100644 src/converters/pandoc/ResourcePathResolver.ts diff --git a/src/converters/PandocTypstConverter.ts b/src/converters/PandocTypstConverter.ts index b94a4bb..0b7ee87 100644 --- a/src/converters/PandocTypstConverter.ts +++ b/src/converters/PandocTypstConverter.ts @@ -14,12 +14,14 @@ import type { obsidianTypstPDFExportSettings } from '../core/settings'; import { TempDirectoryManager } from '../core/TempDirectoryManager'; import { PandocCommandBuilder } from './pandoc/PandocCommandBuilder'; +import { PathResolver } from '../plugin/PathResolver'; export class PandocTypstConverter { private tempDir: string | null = null; private cleanupHandlers: (() => void)[] = []; private plugin: any; // Will be properly typed when we refactor the main plugin class private commandBuilder: PandocCommandBuilder; + private pathResolver: PathResolver; /** * Create a new PandocTypstConverter instance @@ -34,6 +36,7 @@ export class PandocTypstConverter { ) { this.plugin = plugin; this.commandBuilder = new PandocCommandBuilder(plugin); + this.pathResolver = new PathResolver(plugin); // Set up cleanup handlers for process termination this.setupCleanup(); } @@ -272,7 +275,7 @@ export class PandocTypstConverter { */ private async executePandoc(args: string[], progressCallback?: ProgressCallback): Promise { return new Promise((resolve) => { - const pandocPath = this.commandBuilder.resolveExecutablePath(this.pandocOptions.pandocPath, 'pandoc'); + const pandocPath = this.pathResolver.resolveExecutablePath(this.pandocOptions.pandocPath, 'pandoc'); const timeout = this.pandocOptions.timeout || 60000; // Log the exact command being executed for debugging diff --git a/src/converters/pandoc/PandocCommandBuilder.ts b/src/converters/pandoc/PandocCommandBuilder.ts index 425136c..99f51b5 100644 --- a/src/converters/pandoc/PandocCommandBuilder.ts +++ b/src/converters/pandoc/PandocCommandBuilder.ts @@ -4,24 +4,22 @@ */ import * as path from 'path'; -import { promises as fsPromises } from 'fs'; -import { spawnSync } from 'child_process'; import { PandocOptions } from '../converterTypes'; import { TypstVariableMapper } from './TypstVariableMapper'; +import { ResourcePathResolver } from './ResourcePathResolver'; +import { PathResolver } from '../../plugin/PathResolver'; export class PandocCommandBuilder { private plugin: any; private variableMapper: TypstVariableMapper; - - // Cache for directory scanning optimization - private resourcePathCache: string[] = []; - private resourcePathCacheTimestamp: number = 0; - private resourcePathCacheVaultPath: string = ''; - private readonly CACHE_EXPIRY_MS = 5 * 60 * 1000; // 5 minutes + private resourcePathResolver: ResourcePathResolver; + private pathResolver: PathResolver; constructor(plugin: any) { this.plugin = plugin; this.variableMapper = new TypstVariableMapper(plugin); + this.resourcePathResolver = new ResourcePathResolver(); + this.pathResolver = new PathResolver(plugin); } /** @@ -40,7 +38,7 @@ export class PandocCommandBuilder { args.push('--from', 'markdown-smart'); // Set PDF engine to Typst (use configured path if available) - const typstPath = this.resolveExecutablePath(pandocOptions.typstPath, 'typst'); + const typstPath = this.pathResolver.resolveExecutablePath(pandocOptions.typstPath, 'typst'); args.push(`--pdf-engine=${typstPath}`); // Enable standalone mode (required for PDF output) @@ -80,90 +78,15 @@ export class PandocCommandBuilder { return; } - const fs = require('fs'); + // Get all resource paths from the resolver + const resourcePaths = await this.resourcePathResolver.getResourcePaths(pandocOptions.vaultBasePath); - // Add vault root as primary resource path - args.push('--resource-path', pandocOptions.vaultBasePath); - - // Add common attachment directories as additional resource paths - const commonAttachmentPaths = [ - path.join(pandocOptions.vaultBasePath, 'attachments'), - path.join(pandocOptions.vaultBasePath, 'assets'), - path.join(pandocOptions.vaultBasePath, 'files'), - path.join(pandocOptions.vaultBasePath, 'images'), - path.join(pandocOptions.vaultBasePath, '.attachments') - ]; - - // Check if these directories exist and add them - for (const attachPath of commonAttachmentPaths) { - if (fs.existsSync(attachPath)) { - args.push('--resource-path', attachPath); - } - } - - // Also scan for note-specific attachment folders (Obsidian often creates these) - // Use cache to avoid scanning entire vault on every export - const now = Date.now(); - const cacheIsValid = this.resourcePathCacheVaultPath === pandocOptions.vaultBasePath && - (now - this.resourcePathCacheTimestamp) < this.CACHE_EXPIRY_MS && - this.resourcePathCache.length > 0; - - if (cacheIsValid) { - // Use cached resource paths - for (const cachedPath of this.resourcePathCache) { - args.push('--resource-path', cachedPath); - } - } else { - // Cache is invalid or expired, perform fresh scan - await this.scanAndCacheResourcePaths(args, pandocOptions, fs, now); + // Add each path to the pandoc arguments + for (const resourcePath of resourcePaths) { + args.push('--resource-path', resourcePath); } } - /** - * Scan vault for additional resource paths and cache results - */ - private async scanAndCacheResourcePaths(args: string[], pandocOptions: PandocOptions, fs: any, now: number): Promise { - const foundResourcePaths: string[] = []; - - try { - const vaultContents = fs.readdirSync(pandocOptions.vaultBasePath); - for (const item of vaultContents) { - const itemPath = path.join(pandocOptions.vaultBasePath!, item); - - let stat; - try { - stat = await fsPromises.stat(itemPath); - } catch (error) { - // File might have been deleted between readdirSync and statSync - console.warn(`Export: Unable to stat ${itemPath}:`, (error as Error).message); - continue; - } - - if (stat.isDirectory() && !item.startsWith('.') && !item.startsWith('_')) { - // Check if this directory contains images - try { - const dirContents = fs.readdirSync(itemPath); - const hasImages = dirContents.some((file: string) => - /\.(png|jpg|jpeg|gif|svg|webp|bmp|ico|tiff)$/i.test(file) - ); - if (hasImages) { - foundResourcePaths.push(itemPath); - args.push('--resource-path', itemPath); - } - } catch (e) { - // Ignore directories we can't read - } - } - } - - // Update cache with fresh results - this.resourcePathCache = foundResourcePaths; - this.resourcePathCacheTimestamp = now; - this.resourcePathCacheVaultPath = pandocOptions.vaultBasePath!; - } catch (e) { - console.warn('Could not scan vault for attachment directories:', e); - } - } /** * Add template configuration to pandoc arguments @@ -251,38 +174,4 @@ export class PandocCommandBuilder { }); } - /** - * Resolve an executable path, handling empty settings by falling back to system search - */ - resolveExecutablePath(userPath: string | undefined, defaultName: string): string { - // If user provided a path and it's not empty, use it - if (userPath && userPath.trim() !== '') { - return userPath; - } - - // Try to find the executable using which command - try { - const augmentedEnv = { - ...process.env, - PATH: `/opt/homebrew/bin:/usr/local/bin:/usr/bin:/bin:${process.env.PATH || ''}` - }; - - const result = spawnSync('which', [defaultName], { - encoding: 'utf8', - env: augmentedEnv - }); - - if (result.status === 0 && result.stdout) { - const foundPath = result.stdout.trim(); - if (foundPath) { - return foundPath; - } - } - } catch { - // Ignore errors from which command - } - - // Fall back to the default name (will be found via PATH if available) - return defaultName; - } } \ No newline at end of file diff --git a/src/converters/pandoc/ResourcePathResolver.ts b/src/converters/pandoc/ResourcePathResolver.ts new file mode 100644 index 0000000..d2126a8 --- /dev/null +++ b/src/converters/pandoc/ResourcePathResolver.ts @@ -0,0 +1,138 @@ +import * as path from 'path'; +import { promises as fsPromises } from 'fs'; + +/** + * Handles resource path resolution and caching for Pandoc conversions. + * Discovers and caches attachment directories to help Pandoc find embedded resources. + */ +export class ResourcePathResolver { + private resourcePathCache: string[] = []; + private resourcePathCacheTimestamp: number = 0; + private resourcePathCacheVaultPath: string = ''; + private readonly CACHE_EXPIRY_MS = 5 * 60 * 1000; // 5 minutes + + /** + * Get all resource paths for the given vault, using cache when possible + * @param vaultBasePath The base path of the vault + * @returns Array of resource paths for Pandoc to search + */ + async getResourcePaths(vaultBasePath: string): Promise { + if (!vaultBasePath) { + return []; + } + + const fs = require('fs'); + const resourcePaths: string[] = []; + + // Add vault root as primary resource path + resourcePaths.push(vaultBasePath); + + // Add common attachment directories + const commonPaths = this.getCommonAttachmentPaths(vaultBasePath); + for (const attachPath of commonPaths) { + if (fs.existsSync(attachPath)) { + resourcePaths.push(attachPath); + } + } + + // Add cached or freshly scanned resource paths + const now = Date.now(); + if (this.isCacheValid(vaultBasePath, now)) { + // Use cached resource paths + resourcePaths.push(...this.resourcePathCache); + } else { + // Cache is invalid or expired, perform fresh scan + const scannedPaths = await this.scanForResourcePaths(vaultBasePath, fs, now); + resourcePaths.push(...scannedPaths); + } + + return resourcePaths; + } + + /** + * Get common attachment directory paths that Obsidian users typically use + * @param vaultBasePath The base path of the vault + * @returns Array of common attachment directory paths + */ + private getCommonAttachmentPaths(vaultBasePath: string): string[] { + return [ + path.join(vaultBasePath, 'attachments'), + path.join(vaultBasePath, 'assets'), + path.join(vaultBasePath, 'files'), + path.join(vaultBasePath, 'images'), + path.join(vaultBasePath, '.attachments') + ]; + } + + /** + * Check if the resource path cache is still valid + * @param vaultBasePath The vault path to check against + * @param now Current timestamp + * @returns True if cache is valid and can be used + */ + private isCacheValid(vaultBasePath: string, now: number): boolean { + return this.resourcePathCacheVaultPath === vaultBasePath && + (now - this.resourcePathCacheTimestamp) < this.CACHE_EXPIRY_MS && + this.resourcePathCache.length > 0; + } + + /** + * Scan the vault for directories containing images and cache the results + * @param vaultBasePath The base path of the vault + * @param fs File system module + * @param now Current timestamp + * @returns Array of resource paths found during scan + */ + private async scanForResourcePaths(vaultBasePath: string, fs: any, now: number): Promise { + const foundResourcePaths: string[] = []; + + try { + const vaultContents = fs.readdirSync(vaultBasePath); + for (const item of vaultContents) { + const itemPath = path.join(vaultBasePath, item); + + let stat; + try { + stat = await fsPromises.stat(itemPath); + } catch (error) { + // File might have been deleted between readdirSync and statSync + console.warn(`Export: Unable to stat ${itemPath}:`, (error as Error).message); + continue; + } + + if (stat.isDirectory() && !item.startsWith('.') && !item.startsWith('_')) { + // Check if this directory contains images + try { + const dirContents = fs.readdirSync(itemPath); + const hasImages = dirContents.some((file: string) => + /\.(png|jpg|jpeg|gif|svg|webp|bmp|ico|tiff)$/i.test(file) + ); + if (hasImages) { + foundResourcePaths.push(itemPath); + } + } catch (e) { + // Ignore directories we can't read + } + } + } + + // Update cache with fresh results + this.resourcePathCache = foundResourcePaths; + this.resourcePathCacheTimestamp = now; + this.resourcePathCacheVaultPath = vaultBasePath; + } catch (e) { + console.warn('Could not scan vault for attachment directories:', e); + } + + return foundResourcePaths; + } + + /** + * Clear the resource path cache + */ + clearCache(): void { + this.resourcePathCache = []; + this.resourcePathCacheTimestamp = 0; + this.resourcePathCacheVaultPath = ''; + } +} \ No newline at end of file