Enhances path handling and file resolution #5

Merged
AlexKucera merged 36 commits from 1.3.0 into master 2025-09-25 16:47:12 +02:00
2 changed files with 110 additions and 18 deletions
Showing only changes of commit 497407e288 - Show all commits

No files matched your search

+1 -1
View File
@@ -124,7 +124,7 @@ export class PdfToImageConverter {
}
// Find the generated image file (may have different name than expected)
const fileDiscovery = await FileDiscovery.findGeneratedFile(outputDir, expectedOutputFileName);
const fileDiscovery = await FileDiscovery.findGeneratedFile(outputDir, expectedOutputFileName, this.plugin);
if (!fileDiscovery.found) {
return {
imagePath: '',
+109 -17
View File
@@ -3,8 +3,9 @@
* Handles filename pattern matching when pdf2img generates files with different names.
*/
import * as fs from 'fs/promises';
import * as path from 'path';
import { PathUtils } from '../../core/PathUtils';
import type { obsidianTypstPDFExport } from '../../../main';
export interface FileDiscoveryResult {
/** Path to the discovered file */
1
@@ -21,43 +22,68 @@ export class FileDiscovery {
* Handles cases where pdf2img sanitizes filenames differently than expected.
coderabbitai[bot] commented 2025-09-25 13:05:39 +02:00 (Migrated from github.com)
Review

⚠️ Potential issue | 🟠 Major

Don’t hard‑code .png when searching for generated previews

Both vault-adapter and FS fallbacks now throw away every candidate that doesn’t end in .png. As soon as we request JPEG output (which ImageOptimizer explicitly supports), candidates becomes empty and we report “file not found” even though a perfectly good .jpeg/.jpg file is sitting in the directory. That’s a regression for anyone relying on JPEG previews.

Please derive the allowed extensions from expectedFileName (and treat .jpeg/.jpg as interchangeable) before filtering, in both branches.

-			// Look for any PNG files that might match
-			const pngFiles = files.filter(f => f.endsWith('.png'));
-			if (pngFiles.length === 0) {
+			const expectedExt = (path.extname(expectedFileName) || '.png').toLowerCase();
+			const allowedExts = expectedExt === '.jpeg' ? ['.jpeg', '.jpg'] : [expectedExt];
+			const candidateFiles = files.filter(f => {
+				const lower = f.toLowerCase();
+				return allowedExts.some(ext => lower.endsWith(ext));
+			});
+			if (candidateFiles.length === 0) {
 				return {
 					filePath: '',
 					found: false,
-					error: `No PNG files found in output directory: ${outputDir}`
+					error: `No ${allowedExts.join('/')} files found in output directory: ${outputDir}`
 				};
 			}
 
 			// Try to find a file that matches the pattern (with or without exact name)
 			// pdf2img might sanitize filenames differently
-			const matchingFile = this.matchFilePattern(pngFiles, expectedFileName);
+			const matchingFile = this.matchFilePattern(candidateFiles, expectedFileName);
@@
-					error: `Generated image file not found: ${expectedOutputPath}. Available files: ${pngFiles.join(', ')}`
+					error: `Generated image file not found: ${expectedOutputPath}. Available files: ${candidateFiles.join(', ')}`
 				};
 			}

Apply the same adjustment inside findAlternativeFileFs.

-			const pngFiles = files.filter((f: string) => f.endsWith('.png'));
-			if (pngFiles.length === 0) {
+			const expectedExt = (path.extname(expectedFileName) || '.png').toLowerCase();
+			const allowedExts = expectedExt === '.jpeg' ? ['.jpeg', '.jpg'] : [expectedExt];
+			const candidateFiles = files.filter((f: string) => {
+				const lower = f.toLowerCase();
+				return allowedExts.some(ext => lower.endsWith(ext));
+			});
+			if (candidateFiles.length === 0) {
 				return {
 					filePath: '',
 					found: false,
-					error: `No PNG files found in output directory: ${outputDir}`
+					error: `No ${allowedExts.join('/')} files found in output directory: ${outputDir}`
 				};
 			}
@@
-			const matchingFile = this.matchFilePattern(pngFiles, expectedFileName);
+			const matchingFile = this.matchFilePattern(candidateFiles, expectedFileName);
@@
-					error: `Generated image file not found: ${expectedOutputPath}. Available files: ${pngFiles.join(', ')}`
+					error: `Generated image file not found: ${expectedOutputPath}. Available files: ${candidateFiles.join(', ')}`
 				};

Also applies to: 154-190

🤖 Prompt for AI Agents
In src/converters/pdf/FileDiscovery.ts around lines 88-123 (and similarly update
the logic in findAlternativeFileFs at lines ~154-190), the code currently
hard-codes filtering for ".png" files; change it to derive the allowed
extensions from expectedFileName (e.g., if expectedFileName ends with .jpg or
.jpeg treat both .jpg and .jpeg as allowed), build a set of allowed extensions
(include the explicit extension plus normalized jpeg variants), filter files by
those extensions instead of ".png", then use that filtered list for
matchFilePattern and subsequent checks; replicate the same extension-derivation
+ filtering change in the findAlternativeFileFs branch so JPEG output is
discovered correctly.

✅ Addressed in commits 24a169d to 2cdc9c3

_⚠️ Potential issue_ | _🟠 Major_ **Don’t hard‑code `.png` when searching for generated previews** Both vault-adapter and FS fallbacks now throw away every candidate that doesn’t end in `.png`. As soon as we request JPEG output (which `ImageOptimizer` explicitly supports), `candidates` becomes empty and we report “file not found” even though a perfectly good `.jpeg/.jpg` file is sitting in the directory. That’s a regression for anyone relying on JPEG previews. Please derive the allowed extensions from `expectedFileName` (and treat `.jpeg`/`.jpg` as interchangeable) before filtering, in both branches. ```diff - // Look for any PNG files that might match - const pngFiles = files.filter(f => f.endsWith('.png')); - if (pngFiles.length === 0) { + const expectedExt = (path.extname(expectedFileName) || '.png').toLowerCase(); + const allowedExts = expectedExt === '.jpeg' ? ['.jpeg', '.jpg'] : [expectedExt]; + const candidateFiles = files.filter(f => { + const lower = f.toLowerCase(); + return allowedExts.some(ext => lower.endsWith(ext)); + }); + if (candidateFiles.length === 0) { return { filePath: '', found: false, - error: `No PNG files found in output directory: ${outputDir}` + error: `No ${allowedExts.join('/')} files found in output directory: ${outputDir}` }; } // Try to find a file that matches the pattern (with or without exact name) // pdf2img might sanitize filenames differently - const matchingFile = this.matchFilePattern(pngFiles, expectedFileName); + const matchingFile = this.matchFilePattern(candidateFiles, expectedFileName); @@ - error: `Generated image file not found: ${expectedOutputPath}. Available files: ${pngFiles.join(', ')}` + error: `Generated image file not found: ${expectedOutputPath}. Available files: ${candidateFiles.join(', ')}` }; } ``` Apply the same adjustment inside `findAlternativeFileFs`. ```diff - const pngFiles = files.filter((f: string) => f.endsWith('.png')); - if (pngFiles.length === 0) { + const expectedExt = (path.extname(expectedFileName) || '.png').toLowerCase(); + const allowedExts = expectedExt === '.jpeg' ? ['.jpeg', '.jpg'] : [expectedExt]; + const candidateFiles = files.filter((f: string) => { + const lower = f.toLowerCase(); + return allowedExts.some(ext => lower.endsWith(ext)); + }); + if (candidateFiles.length === 0) { return { filePath: '', found: false, - error: `No PNG files found in output directory: ${outputDir}` + error: `No ${allowedExts.join('/')} files found in output directory: ${outputDir}` }; } @@ - const matchingFile = this.matchFilePattern(pngFiles, expectedFileName); + const matchingFile = this.matchFilePattern(candidateFiles, expectedFileName); @@ - error: `Generated image file not found: ${expectedOutputPath}. Available files: ${pngFiles.join(', ')}` + error: `Generated image file not found: ${expectedOutputPath}. Available files: ${candidateFiles.join(', ')}` }; ``` Also applies to: 154-190 <details> <summary>🤖 Prompt for AI Agents</summary> ``` In src/converters/pdf/FileDiscovery.ts around lines 88-123 (and similarly update the logic in findAlternativeFileFs at lines ~154-190), the code currently hard-codes filtering for ".png" files; change it to derive the allowed extensions from expectedFileName (e.g., if expectedFileName ends with .jpg or .jpeg treat both .jpg and .jpeg as allowed), build a set of allowed extensions (include the explicit extension plus normalized jpeg variants), filter files by those extensions instead of ".png", then use that filtered list for matchFilePattern and subsequent checks; replicate the same extension-derivation + filtering change in the findAlternativeFileFs branch so JPEG output is discovered correctly. ``` </details> <!-- fingerprinting:phantom:medusa:sabertoothed --> <!-- This is an auto-generated comment by CodeRabbit --> ✅ Addressed in commits 24a169d to 2cdc9c3
* @param outputDir Directory where files were generated
* @param expectedFileName Expected output filename
* @param plugin Plugin instance for PathUtils
* @returns Discovery result with actual file path
*/
public static async findGeneratedFile(
outputDir: string,
expectedFileName: string
expectedFileName: string,
plugin?: obsidianTypstPDFExport
): Promise<FileDiscoveryResult> {
const expectedOutputPath = path.join(outputDir, expectedFileName);
if (!plugin?.app) {
// Fallback to path for external tool output directories
const expectedOutputPath = path.join(outputDir, expectedFileName);
const fs = require('fs').promises;
try {
await fs.access(expectedOutputPath);
return {
filePath: expectedOutputPath,
found: true
};
} catch {
return await this.findAlternativeFileFs(outputDir, expectedFileName, expectedOutputPath);
}
}
const pathUtils = new PathUtils(plugin.app);
const expectedOutputPath = pathUtils.joinPath(outputDir, expectedFileName);
// Check if the expected output file exists first
try {
await fs.access(expectedOutputPath);
return {
filePath: expectedOutputPath,
found: true
};
if (await pathUtils.fileExists(expectedOutputPath)) {
return {
filePath: expectedOutputPath,
found: true
};
}
} catch {
// File not found with expected name, try to find alternatives
return await this.findAlternativeFile(outputDir, expectedFileName, expectedOutputPath);
// Continue to alternative search
}
// File not found with expected name, try to find alternatives
return await this.findAlternativeFile(outputDir, expectedFileName, expectedOutputPath, plugin);
}
/**
* Find alternative files when the expected filename doesn't match.
* Find alternative files when the expected filename doesn't match (using vault.adapter).
* @param outputDir Output directory to search
* @param expectedFileName Expected filename for pattern matching
* @param expectedOutputPath Full expected output path
* @param plugin Plugin instance for vault access
* @returns Discovery result with alternative file if found
*/
private static async findAlternativeFile(
outputDir: string,
expectedFileName: string,
expectedOutputPath: string
expectedOutputPath: string,
plugin: obsidianTypstPDFExport
): Promise<FileDiscoveryResult> {
try {
// Debug: List what files are actually in the output directory
const files = await fs.readdir(outputDir);
const dirList = await plugin.app.vault.adapter.list(outputDir);
const files = dirList.files.map(f => path.basename(f));
const pathUtils = new PathUtils(plugin.app);
// Look for any PNG files that might match
const pngFiles = files.filter(f => f.endsWith('.png'));
if (pngFiles.length === 0) {
@@ -67,14 +93,80 @@ export class FileDiscovery {
error: `No PNG files found in output directory: ${outputDir}`
};
}
// Try to find a file that matches the pattern (with or without exact name)
// pdf2img might sanitize filenames differently
const matchingFile = this.matchFilePattern(pngFiles, expectedFileName);
if (matchingFile) {
const actualOutputPath = pathUtils.joinPath(outputDir, matchingFile);
// Final check if we found an alternative file
if (await pathUtils.fileExists(actualOutputPath)) {
return {
filePath: actualOutputPath,
found: true
};
} else {
return {
filePath: '',
found: false,
error: `Alternative file not accessible: ${actualOutputPath}`
};
}
} else {
return {
filePath: '',
found: false,
coderabbitai[bot] commented 2025-09-25 16:51:33 +02:00 (Migrated from github.com)
Review

⚠️ Potential issue | 🟠 Major

Compute vault-relative path without path.relative; normalize separators

Using path.relative(base, outputDir) is fragile across platforms and separator styles. Use PathUtils.getVaultPath() and strip the prefix instead, ensuring forward slashes for adapter.list.

-			// Check if outputDir is inside the vault
-			const vaultPath = plugin.app.vault.adapter.basePath || '';
-			let isVaultRelative = false;
-			let vaultRelativeDir = outputDir;
-
-			if (vaultPath) {
-				// Compute relative path from vault root
-				const relativePath = path.relative(vaultPath, outputDir);
-				// Path is inside vault if it doesn't start with '..' or path separator
-				isVaultRelative = !relativePath.startsWith('..') && !path.isAbsolute(relativePath);
-				if (isVaultRelative) {
-					vaultRelativeDir = relativePath;
-				}
-			}
+			// Check if outputDir is inside the vault using PathUtils
+			const vaultPath = pathUtils.getVaultPath();
+			let isVaultRelative = false;
+			let vaultRelativeDir = outputDir;
+			if (outputDir.startsWith(vaultPath)) {
+				vaultRelativeDir = outputDir.substring(vaultPath.length).replace(/^[/\\]+/, '');
+				isVaultRelative = true;
+			}
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

			// Check if outputDir is inside the vault using PathUtils
			const vaultPath = pathUtils.getVaultPath();
			let isVaultRelative = false;
			let vaultRelativeDir = outputDir;
			if (outputDir.startsWith(vaultPath)) {
				vaultRelativeDir = outputDir.substring(vaultPath.length).replace(/^[/\\]+/, '');
				isVaultRelative = true;
			}
🤖 Prompt for AI Agents
In src/converters/pdf/FileDiscovery.ts around lines 87 to 99, replace the
path.relative-based vault detection with a prefix-strip approach: obtain the
vault root via PathUtils.getVaultPath(), normalize both vault root and outputDir
to use forward slashes and no trailing slash, check if outputDir starts with the
vault root + '/' to set isVaultRelative, and if so set vaultRelativeDir to the
substring after the vault root (ensuring it uses forward slashes) so
adapter.list receives a vault-relative path; otherwise keep vaultRelativeDir as
the original outputDir.
_⚠️ Potential issue_ | _🟠 Major_ **Compute vault-relative path without path.relative; normalize separators** Using `path.relative(base, outputDir)` is fragile across platforms and separator styles. Use `PathUtils.getVaultPath()` and strip the prefix instead, ensuring forward slashes for adapter.list. ```diff - // Check if outputDir is inside the vault - const vaultPath = plugin.app.vault.adapter.basePath || ''; - let isVaultRelative = false; - let vaultRelativeDir = outputDir; - - if (vaultPath) { - // Compute relative path from vault root - const relativePath = path.relative(vaultPath, outputDir); - // Path is inside vault if it doesn't start with '..' or path separator - isVaultRelative = !relativePath.startsWith('..') && !path.isAbsolute(relativePath); - if (isVaultRelative) { - vaultRelativeDir = relativePath; - } - } + // Check if outputDir is inside the vault using PathUtils + const vaultPath = pathUtils.getVaultPath(); + let isVaultRelative = false; + let vaultRelativeDir = outputDir; + if (outputDir.startsWith(vaultPath)) { + vaultRelativeDir = outputDir.substring(vaultPath.length).replace(/^[/\\]+/, ''); + isVaultRelative = true; + } ``` <!-- suggestion_start --> <details> <summary>📝 Committable suggestion</summary> > ‼️ **IMPORTANT** > Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements. ```suggestion // Check if outputDir is inside the vault using PathUtils const vaultPath = pathUtils.getVaultPath(); let isVaultRelative = false; let vaultRelativeDir = outputDir; if (outputDir.startsWith(vaultPath)) { vaultRelativeDir = outputDir.substring(vaultPath.length).replace(/^[/\\]+/, ''); isVaultRelative = true; } ``` </details> <!-- suggestion_end --> <details> <summary>🤖 Prompt for AI Agents</summary> ``` In src/converters/pdf/FileDiscovery.ts around lines 87 to 99, replace the path.relative-based vault detection with a prefix-strip approach: obtain the vault root via PathUtils.getVaultPath(), normalize both vault root and outputDir to use forward slashes and no trailing slash, check if outputDir starts with the vault root + '/' to set isVaultRelative, and if so set vaultRelativeDir to the substring after the vault root (ensuring it uses forward slashes) so adapter.list receives a vault-relative path; otherwise keep vaultRelativeDir as the original outputDir. ``` </details> <!-- fingerprinting:phantom:medusa:chinchilla --> <!-- This is an auto-generated comment by CodeRabbit -->
error: `Generated image file not found: ${expectedOutputPath}. Available files: ${pngFiles.join(', ')}`
};
}
} catch (listError: unknown) {
console.error(`Failed to list output directory:`, listError);
const errorMessage = listError instanceof Error ? listError.message : String(listError);
return {
filePath: '',
found: false,
error: `Failed to search output directory: ${errorMessage}`
};
}
}
/**
* Find alternative files when the expected filename doesn't match (fs fallback).
* @param outputDir Output directory to search
* @param expectedFileName Expected filename for pattern matching
* @param expectedOutputPath Full expected output path
* @returns Discovery result with alternative file if found
*/
private static async findAlternativeFileFs(
outputDir: string,
expectedFileName: string,
expectedOutputPath: string
): Promise<FileDiscoveryResult> {
try {
const fs = require('fs').promises;
// Debug: List what files are actually in the output directory
const files = await fs.readdir(outputDir);
// Look for any PNG files that might match
const pngFiles = files.filter((f: string) => f.endsWith('.png'));
if (pngFiles.length === 0) {
return {
filePath: '',
found: false,
error: `No PNG files found in output directory: ${outputDir}`
};
}
// Try to find a file that matches the pattern (with or without exact name)
// pdf2img might sanitize filenames differently
const matchingFile = this.matchFilePattern(pngFiles, expectedFileName);
if (matchingFile) {
const actualOutputPath = path.join(outputDir, matchingFile);
// Final check if we found an alternative file
try {
await fs.access(actualOutputPath);