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
Showing only changes of commit 5598e0e538 - Show all commits
+87
View File
@@ -0,0 +1,87 @@
// ABOUTME: Centralized path utilities for safe Obsidian API operations
coderabbitai[bot] commented 2025-09-25 13:05:40 +02:00 (Migrated from github.com)
Review

⚠️ Potential issue | 🟠 Major

Windows absolute paths are not detected in fileExists

The heuristic path.includes('/') && !path.startsWith('.') misses Windows absolute paths (e.g., C:\foo\bar). Use path.isAbsolute instead.

Apply this diff:

-		// For paths outside vault, use fs fallback (needed for external file processing)
-		if (path.includes('/') && !path.startsWith('.')) {
-			try {
-				const fs = require('fs').promises;
-				await fs.access(path);
-				return true;
-			} catch {
-				return false;
-			}
-		}
+		// For paths outside vault, use fs fallback (needed for external file processing)
+		try {
+			const nodePath = require('path') as typeof import('path');
+			if (nodePath.isAbsolute(path)) {
+				const fs = require('fs').promises as typeof import('fs').promises;
+				await fs.access(path);
+				return true;
+			}
+		} catch {
+			// ignore
+		}
📝 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.

        // For paths outside vault, use fs fallback (needed for external file processing)
        try {
            const nodePath = require('path') as typeof import('path');
            if (nodePath.isAbsolute(path)) {
                const fs = require('fs').promises as typeof import('fs').promises;
                await fs.access(path);
                return true;
            }
        } catch {
            // ignore
        }

        return false;
🤖 Prompt for AI Agents
In src/core/PathUtils.ts around lines 108-119, the current heuristic using
path.includes('/') && !path.startsWith('.') misses Windows absolute paths;
replace that check with a proper absolute-path test using Node's
path.isAbsolute. Import or require the Node path module without shadowing the
function parameter (e.g., const nodePath = require('path') or import * as
nodePath from 'path') and use nodePath.isAbsolute(path) in the conditional so
both Unix and Windows absolute paths are detected; keep the existing
fs.promises.access fallback and preserve the try/catch behavior.

✅ Addressed in commit ff8e9f9

_⚠️ Potential issue_ | _🟠 Major_ **Windows absolute paths are not detected in fileExists** The heuristic `path.includes('/') && !path.startsWith('.')` misses Windows absolute paths (e.g., C:\foo\bar). Use path.isAbsolute instead. Apply this diff: ```diff - // For paths outside vault, use fs fallback (needed for external file processing) - if (path.includes('/') && !path.startsWith('.')) { - try { - const fs = require('fs').promises; - await fs.access(path); - return true; - } catch { - return false; - } - } + // For paths outside vault, use fs fallback (needed for external file processing) + try { + const nodePath = require('path') as typeof import('path'); + if (nodePath.isAbsolute(path)) { + const fs = require('fs').promises as typeof import('fs').promises; + await fs.access(path); + return true; + } + } catch { + // ignore + } ``` <!-- 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 // For paths outside vault, use fs fallback (needed for external file processing) try { const nodePath = require('path') as typeof import('path'); if (nodePath.isAbsolute(path)) { const fs = require('fs').promises as typeof import('fs').promises; await fs.access(path); return true; } } catch { // ignore } return false; ``` </details> <!-- suggestion_end --> <details> <summary>🤖 Prompt for AI Agents</summary> ``` In src/core/PathUtils.ts around lines 108-119, the current heuristic using path.includes('/') && !path.startsWith('.') misses Windows absolute paths; replace that check with a proper absolute-path test using Node's path.isAbsolute. Import or require the Node path module without shadowing the function parameter (e.g., const nodePath = require('path') or import * as nodePath from 'path') and use nodePath.isAbsolute(path) in the conditional so both Unix and Windows absolute paths are detected; keep the existing fs.promises.access fallback and preserve the try/catch behavior. ``` </details> <!-- fingerprinting:phantom:medusa:chinchilla --> <!-- This is an auto-generated reply by CodeRabbit --> ✅ Addressed in commit ff8e9f9 <!-- This is an auto-generated comment by CodeRabbit -->
AlexKucera commented 2025-09-25 16:27:04 +02:00 (Migrated from github.com)
Review

@coderabbitai we are trying to stay away from using path and sticking to Obsidian API calls.

@coderabbitai we are trying to stay away from using path and sticking to Obsidian API calls.
coderabbitai[bot] commented 2025-09-25 16:27:33 +02:00 (Migrated from github.com)
Review

@AlexKucera I understand your preference to stick with Obsidian APIs. Here's an alternative approach that improves Windows absolute path detection without using the Node.js path module:

// For paths outside vault, use fs fallback (needed for external file processing)
const isAbsolutePath = path.startsWith('/') || // Unix absolute
    /^[a-zA-Z]:[/\\]/.test(path) || // Windows drive letter (C:\ or C:/)
    path.startsWith('\\\\'); // Windows UNC path (\\server\share)

if (isAbsolutePath) {
    try {
        const fs = require('fs').promises;
        await fs.access(path);
        return true;
    } catch {
        return false;
    }
}

This pattern-based approach detects:

  • Unix absolute paths starting with /
  • Windows drive letter paths like C:\ or C:/
  • Windows UNC paths like \\server\share

This keeps the code aligned with your goal of avoiding Node.js path utilities while fixing the Windows compatibility issue.


✏️ Learnings added
Learnt from: AlexKucera
PR: AlexKucera/obsidian-typst-pdf-export#5
File: src/core/PathUtils.ts:108-119
Timestamp: 2025-09-25T14:27:31.819Z
Learning: The obsidian-typst-pdf-export plugin prefers to avoid Node.js built-in modules like 'path' and instead stick to Obsidian API calls for path operations.

Note: Learnings are effective only in the context of similar code segments. To apply general coding guidelines, please configure review instructions. You can manage existing learnings in the app.

@AlexKucera I understand your preference to stick with Obsidian APIs. Here's an alternative approach that improves Windows absolute path detection without using the Node.js path module: ```typescript // For paths outside vault, use fs fallback (needed for external file processing) const isAbsolutePath = path.startsWith('/') || // Unix absolute /^[a-zA-Z]:[/\\]/.test(path) || // Windows drive letter (C:\ or C:/) path.startsWith('\\\\'); // Windows UNC path (\\server\share) if (isAbsolutePath) { try { const fs = require('fs').promises; await fs.access(path); return true; } catch { return false; } } ``` This pattern-based approach detects: - Unix absolute paths starting with `/` - Windows drive letter paths like `C:\` or `C:/` - Windows UNC paths like `\\server\share` This keeps the code aligned with your goal of avoiding Node.js path utilities while fixing the Windows compatibility issue. --- <details> <summary>✏️ Learnings added</summary> ``` Learnt from: AlexKucera PR: AlexKucera/obsidian-typst-pdf-export#5 File: src/core/PathUtils.ts:108-119 Timestamp: 2025-09-25T14:27:31.819Z Learning: The obsidian-typst-pdf-export plugin prefers to avoid Node.js built-in modules like 'path' and instead stick to Obsidian API calls for path operations. ``` > Note: Learnings are effective only in the context of similar code segments. To apply general coding guidelines, please configure [review instructions](https://docs.coderabbit.ai/guides/review-instructions). You can manage existing learnings in the [app](https://app.coderabbit.ai/learnings). </details> <!-- This is an auto-generated reply by CodeRabbit -->
// ABOUTME: Handles vault paths, plugin directories, and file operations
import { FileSystemAdapter, normalizePath, Notice } from 'obsidian';
import type { App, PluginManifest } from 'obsidian';
export class PathUtils {
constructor(private app: App) {}
/**
* Get vault base path safely with FileSystemAdapter check
*/
getVaultPath(): string {
const adapter = this.app.vault.adapter;
if (!(adapter instanceof FileSystemAdapter)) {
new Notice('This plugin requires desktop Obsidian');
throw new Error('FileSystemAdapter not available - desktop Obsidian required');
}
return adapter.getBasePath();
}
/**
* Get plugin directory path
*/
getPluginDir(pluginManifest: PluginManifest): string {
return normalizePath(pluginManifest.dir || '');
}
/**
* Join path segments with normalizePath
*/
joinPath(...segments: string[]): string {
// Filter out empty segments
const filtered = segments.filter(s => s);
const joined = filtered.join('/');
return normalizePath(joined);
}
/**
* Ensure directory exists, create if necessary
*/
async ensureDir(path: string): Promise<void> {
const normalizedPath = normalizePath(path);
try {
const exists = await this.app.vault.adapter.exists(normalizedPath);
if (!exists) {
await this.app.vault.adapter.mkdir(normalizedPath);
}
} catch (error) {
new Notice(`Failed to create directory: ${normalizedPath}`);
throw error;
}
}
/**
* Clean up directory contents (files only, like current TempDirectoryManager)
*/
async cleanupDir(path: string): Promise<boolean> {
const normalizedPath = normalizePath(path);
try {
const exists = await this.app.vault.adapter.exists(normalizedPath);
if (exists && this.app.vault.adapter instanceof FileSystemAdapter) {
const list = await this.app.vault.adapter.list(normalizedPath);
// Remove only files, not subdirectories (matching current pattern)
for (const file of list.files) {
await this.app.vault.adapter.remove(file);
}
}
return true;
} catch (error) {
console.warn(`Failed to cleanup directory ${normalizedPath}:`, error);
return false;
}
}
/**
* Check if file or directory exists
*/
async fileExists(path: string): Promise<boolean> {
const normalizedPath = normalizePath(path);
try {
return await this.app.vault.adapter.exists(normalizedPath);
} catch {
return false;
}
}
}