Enhances path handling and file resolution #5
No files matched your search
@@ -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: '',
|
||||
|
||||
@@ -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 */
|
||||
@@ -21,43 +22,68 @@ export class FileDiscovery {
|
||||
* Handles cases where pdf2img sanitizes filenames differently than expected.
|
||||
|
|
||||
* @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,
|
||||
|
⚠️ Potential issue | 🟠 Major Compute vault-relative path without path.relative; normalize separators Using 📝 Committable suggestion
🤖 Prompt for AI Agents_⚠️ 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);
|
||||
|
||||
Reference in new issue
Block a user
⚠️ Potential issue | 🟠 Major
Don’t hard‑code
.pngwhen searching for generated previewsBoth vault-adapter and FS fallbacks now throw away every candidate that doesn’t end in
.png. As soon as we request JPEG output (whichImageOptimizerexplicitly supports),candidatesbecomes empty and we report “file not found” even though a perfectly good.jpeg/.jpgfile 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/.jpgas interchangeable) before filtering, in both branches.Apply the same adjustment inside
findAlternativeFileFs.Also applies to: 154-190
🤖 Prompt for AI Agents
✅ Addressed in commits
24a169dto2cdc9c3