From 4c8b47c5cc8381c39ee7e0de9b40291734b470e3 Mon Sep 17 00:00:00 2001 From: Himanshu Mishra Date: Wed, 20 Jan 2021 17:43:04 +0100 Subject: [PATCH] backend: (GitLab) URL Reader uses content-disposition header for filename --- .../src/reading/GitlabUrlReader.test.ts | 12 +++++++++ .../src/reading/GitlabUrlReader.ts | 26 ++++++++++++++++--- 2 files changed, 35 insertions(+), 3 deletions(-) diff --git a/packages/backend-common/src/reading/GitlabUrlReader.test.ts b/packages/backend-common/src/reading/GitlabUrlReader.test.ts index 2e66794397..c0736f769d 100644 --- a/packages/backend-common/src/reading/GitlabUrlReader.test.ts +++ b/packages/backend-common/src/reading/GitlabUrlReader.test.ts @@ -176,6 +176,10 @@ describe('GitlabUrlReader', () => { res( ctx.status(200), ctx.set('Content-Type', 'application/zip'), + ctx.set( + 'content-disposition', + 'attachment; filename="mock-main-sha123abc.zip"', + ), ctx.body(archiveBuffer), ), ), @@ -225,6 +229,10 @@ describe('GitlabUrlReader', () => { res( ctx.status(200), ctx.set('Content-Type', 'application/zip'), + ctx.set( + 'content-disposition', + 'attachment; filename="mock-main-sha123abc.zip"', + ), ctx.body(archiveBuffer), ), ), @@ -254,6 +262,10 @@ describe('GitlabUrlReader', () => { res( ctx.status(200), ctx.set('Content-Type', 'application/zip'), + ctx.set( + 'content-disposition', + 'attachment; filename="mock-main-sha123abc.zip"', + ), ctx.body(archiveBuffer), ), ), diff --git a/packages/backend-common/src/reading/GitlabUrlReader.ts b/packages/backend-common/src/reading/GitlabUrlReader.ts index 72db901ac1..24fc640784 100644 --- a/packages/backend-common/src/reading/GitlabUrlReader.ts +++ b/packages/backend-common/src/reading/GitlabUrlReader.ts @@ -140,9 +140,29 @@ export class GitlabUrlReader implements UrlReader { throw new Error(message); } - const path = filepath - ? `${repoName}-${branch}-${commitSha}/${filepath}/` - : ''; + // Get the filename of archive from the header of the response + const contentDispositionHeader = archiveGitLabResponse.headers.get( + 'content-disposition', + ) as string; + if (!contentDispositionHeader) { + throw new Error( + `Failed to read tree from ${url}. ` + + 'GitLab API response for downloading archive does not contain content-disposition header ', + ); + } + const fileNameRegEx = new RegExp( + /^attachment; filename="(?.*).zip"$/, + ); + const archiveFileName = contentDispositionHeader.match(fileNameRegEx) + ?.groups?.fileName; + if (!archiveFileName) { + throw new Error( + `Failed to read tree from ${url}. GitLab API response for downloading archive has an unexpected ` + + `format of content-disposition header ${contentDispositionHeader} `, + ); + } + + const path = filepath ? `${archiveFileName}/${filepath}/` : ''; return await this.treeResponseFactory.fromZipArchive({ stream: (archiveGitLabResponse.body as unknown) as Readable,