Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Replace relative paths with absolute #111

Closed
wants to merge 5 commits into from
Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
33 changes: 32 additions & 1 deletion index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,9 @@ export interface Options {
// declare some constants so we don't have magic integers without explanation
const DTSLEN = '.d.ts'.length;

// used to find relative paths to replace with their absolute
const relativePathsRegex = /(?:from\s+|import\s+|require\()['"]((?:\.|\.\.)\/[^'"]*)['"]/g;

const filenameToMid: (filename: string) => string = (function () {
if (pathUtil.sep === '/') {
return function (filename: string) {
Expand Down Expand Up @@ -134,6 +137,24 @@ function processTree(sourceFile: ts.SourceFile, replacer: (node: ts.Node) => str
return code;
}

function getAbsolutePath(base: string, relative: string): string {
var stack = base.split("/"),
parts = relative.split("/");
stack.pop(); // remove current file name (or empty string)
// (omit if "base" is the current folder without trailing slash)
for (var i = 0; i < parts.length; i++) {
if (parts[i] == ".")
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The if and else clauses here don't follow the code style guidelines here.

continue;
if (parts[i] == "..")
stack.pop();
else
stack.push(parts[i]);
}
// remove empty elements from the array to avoid ending /
stack = stack.filter(function(e) { return e });
return stack.join("/");
}

/**
* Load and parse a TSConfig File
* @param options The dts-generator options to load config into
Expand Down Expand Up @@ -497,7 +518,17 @@ export default function generate(options: Options): Promise<void> {
}
});

output.write(content.replace(nonEmptyLineStart, '$&' + indent));
let match = null;
let resultContent: string = content;
while ((match = relativePathsRegex.exec(content)) != null) {
let relativePath = match[1];
let absolutePath = getAbsolutePath(resolvedModuleId, match[1]);
// replace relative paths with absolute
resultContent = resultContent.replace(`'${relativePath}'`, `'${absolutePath}'`);
resultContent = resultContent.replace(`"${relativePath}"`, `"${absolutePath}"`);
}

output.write(resultContent.replace(nonEmptyLineStart, '$&' + indent));
output.write(eol + '}' + eol);
}
else {
Expand Down