Skip to content

Commit

Permalink
fix: check real path for included file in case of symlink
Browse files Browse the repository at this point in the history
  • Loading branch information
martyanovandrey committed Nov 15, 2024
1 parent ae8ad21 commit 7096441
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 9 deletions.
24 changes: 16 additions & 8 deletions src/transform/plugins/includes/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,13 @@ import {bold} from 'chalk';
import Token from 'markdown-it/lib/token';

import {StateCore} from '../../typings';
import {GetFileTokensOpts, getFileTokens, getFullIncludePath, isFileExists} from '../../utilsFS';
import {
GetFileTokensOpts,
getFileTokens,
getFullIncludePath,
getRealPath,
isFileExists,
} from '../../utilsFS';
import {findBlockTokens} from '../../utils';
import {MarkdownItPluginCb, MarkdownItPluginOpts} from '../typings';

Expand Down Expand Up @@ -44,20 +50,22 @@ function unfoldIncludes(md: MarkdownItIncluded, state: StateCore, path: string,

const fullIncludePath = getFullIncludePath(includePath, root, path);

let pathname = fullIncludePath;
let hash = '';
const hashIndex = fullIncludePath.lastIndexOf('#');
if (hashIndex > -1 && !isFileExists(pathname)) {
pathname = fullIncludePath.slice(0, hashIndex);
hash = fullIncludePath.slice(hashIndex + 1);
}
// Check the real path of the file in case of a symlink
let pathname = getRealPath(fullIncludePath);

if (!pathname.startsWith(root)) {
i++;

continue;
}

let hash = '';
const hashIndex = fullIncludePath.lastIndexOf('#');
if (hashIndex > -1 && !isFileExists(pathname)) {
pathname = fullIncludePath.slice(0, hashIndex);
hash = fullIncludePath.slice(hashIndex + 1);
}

// Check the existed included store and extract it
const included = md.included?.[pathname];

Expand Down
10 changes: 9 additions & 1 deletion src/transform/utilsFS.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import type {Dictionary} from 'lodash';

import {readFileSync, statSync} from 'fs';
import {readFileSync, realpathSync, statSync} from 'fs';
import escapeRegExp from 'lodash/escapeRegExp';
import {join, parse, relative, resolve, sep} from 'path';

Expand Down Expand Up @@ -168,3 +168,11 @@ export function getRelativePath(path: string, toPath: string) {
const parentPath = pathDirs.join(sep);
return relative(parentPath, toPath);
}

export function getRealPath(symlinkPath: string): string {
try {
return realpathSync(symlinkPath);
} catch (err) {
return symlinkPath;
}
}

0 comments on commit 7096441

Please sign in to comment.