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

feat: Add zip method #68

Merged
merged 13 commits into from
Mar 19, 2024
Merged
Show file tree
Hide file tree
Changes from 8 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
2 changes: 1 addition & 1 deletion .husky/pre-commit
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
#!/usr/bin/env sh
. "$(dirname -- "$0")/_/husky.sh"

npm run test:lint
npm run lint
2 changes: 1 addition & 1 deletion .husky/pre-push
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
#!/usr/bin/env sh
. "$(dirname -- "$0")/_/husky.sh"

npm run test:unit
npm run test
9 changes: 9 additions & 0 deletions src/error.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
export function errCode(obj: unknown): string | number {
if (typeof obj !== 'object' || obj === null || !('code' in obj)) {
return '';
}
if (typeof obj.code === 'number' || typeof obj.code === 'string') {
return obj.code;
}
return '';
}
2 changes: 2 additions & 0 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
import * as npm from './npm';
import * as utils from './utils';
import * as preExec from './preExec';
import { zip } from './zip';
import {
getAbsolutePath,
shouldRecordVideo,
Expand All @@ -25,6 +26,7 @@ export {
npm,
utils,
preExec,
zip,

// Exporting all to keep compatibility with previous API
getAbsolutePath,
Expand Down
117 changes: 117 additions & 0 deletions src/zip.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,117 @@
import fs from 'fs';
import path from 'path';
import { execSync } from 'child_process';
import { platform } from 'os';
import { errCode } from './error';

function validate(workspace: string, source: string, dest: string) {
if (!source.trim()) {
throw new Error('The source path cannot be empty');
}
if (!dest.trim()) {
throw new Error('The destination file cannot be empty');
}

// Verify the source folder exists and is not a file.
try {
const stats = fs.statSync(source);
if (!stats.isDirectory()) {
throw new Error('Invalid source folder: the source must be a directory');
}
} catch (err) {
if (errCode(err) === 'ENOENT') {
throw new Error('Invalid source folder: not exist');
}
}

if (path.isAbsolute(source)) {
throw new Error('Invalid source folder: absolute path is not supported');
}
if (isFolderOutside(source, workspace)) {
throw new Error(
'Invalid source folder: the source path is outside of the user workspace',
);
}
if (!dest.endsWith('.zip')) {
throw new Error('Invalid zip filename: Only .zip file is permitted');
}
}

/**
* Checks if a folder is outside of a specified folder.
*
* Contextual note: Ordinarily, a folder cannot be considered outside of itself.
* However, in scenarios where the targetFolder equals the specifiedFolder,
* it implies an attempt to archive the entire workspace.
* Such actions are prohibited, thus leading to a return value of true.
*
* @param {string} targetFolder The path to the target folder.
* @param {string} specifiedFolder The path to the specified folder.
* @returns {boolean} Returns true if the target folder is outside of the specified folder, false otherwise.
*/
export function isFolderOutside(
targetFolder: string,
specifiedFolder: string,
): boolean {
// Resolve absolute paths.
const absoluteTargetFolder = path.resolve(targetFolder);
const absoluteSpecifiedFolder = path.resolve(specifiedFolder);

// Ensure the specified folder path ends with a path separator to avoid partial matches.
const specifiedFolderWithTrailingSlash = absoluteSpecifiedFolder.endsWith(
path.sep,
)
? absoluteSpecifiedFolder
: `${absoluteSpecifiedFolder}${path.sep}`;

// Check if the target folder is outside of the specified folder.
return !absoluteTargetFolder.startsWith(specifiedFolderWithTrailingSlash);
}

/**
* Generates a platform-specific command string for compressing files into a zip archive.
*
* On macOS, it constructs a shell command using the `zip` utility with options to
* recursively zip the content, preserve symlinks, and operate quietly.
*
* On Windows, it constructs a PowerShell command using `Compress-Archive` with options to
* specify the source and destination paths directly, and the `-Force` option to overwrite
* any existing destination file.
*
* For other operating systems, throw an error to indicates an unsupported platform.
*
* @param source The path of the directory or file to be compressed.
* @param dest The path where the output zip file should be saved, including the file name.
* @returns A string containing the command to execute, or an empty string if the platform is not supported.
*/
function getCommand(source: string, dest: string): string {
const osPlatform = platform();

switch (osPlatform) {
case 'darwin':
return `zip -ryq "${dest}" "${source}"`;
case 'win32':
return `Compress-Archive -Path ${source} -DestinationPath ${dest} -Force`;
default:
// Throw an error if the operating system is not supported
throw new Error(`Unsupported operating system: ${osPlatform}`);
}
}

/**
* Compresses the specified source into a zip file at the destination path.
*
* @param workspace The user workspace directory.
* @param source The path of the directory or file to be compressed.
* @param dest The path where the output zip file should be saved.
*/
export function zip(workspace: string, source: string, dest: string) {
try {
validate(workspace, source, dest);
execSync(getCommand(source, dest));
} catch (error) {
console.error(
`Zip file creation failed for destination: "${dest}", source: "${source}". Error: ${error}.`,
);
Comment on lines +110 to +112
Copy link
Contributor

Choose a reason for hiding this comment

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

One thing I'm hung up on is whether or not its better to let whoever is invoking the function to print the error. Printing to console is a user facing behaviour and having a low level utility function do that seems more surprising than just throwing the error.

Copy link
Contributor

Choose a reason for hiding this comment

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

Oops, added this comment, but forgot to submit the review. Fine to disregard, but still wanted to bring it up.

Copy link
Contributor Author

Choose a reason for hiding this comment

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

I agree that an error thrown by a low-level function may be unexpected. However, given that the zipping behavior is determined by user settings in the sauce configuration, such an error could be understandable and helpful.
It allows users to debug and modify their configuration as necessary. This is different from generating JUnit or Sauce reports, where a failure could be misinterpreted as a test failure, as those operations are not directly controlled by the user.

Choose a reason for hiding this comment

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

@tianfeng92 Mike is talking about removing this log line and instead throwing the error all the way back to the caller (the runner in that case). The caller (runner) is then the one to handle (i.e. log) the error.

Choose a reason for hiding this comment

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

Oops, added this comment, but forgot to submit the review. Fine to disregard, but still wanted to bring it up.

Now that you bring this up, I'd personally prefer that approach. Generally I'm in favor of keeping user facing messaging out of low level libs. Having user facing messages in low level libs, prevents the lib from being used more broadly and robs the caller of controlling what the user should see.

Copy link
Contributor Author

Choose a reason for hiding this comment

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

Make sense. Let me draft a PR to address it.

}
}
25 changes: 25 additions & 0 deletions tests/unit/src/zip.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
import path from 'path';
import { isFolderOutside } from '../../../src/zip';

describe('isFolderOutside', () => {
const baseFolder = path.resolve('path/to/base');
const insideFolder = path.resolve('path/to/base/inside');
const outsideFolder = path.resolve('path/to/outside');

test('should return false for a folder inside the specified folder', () => {
expect(isFolderOutside(insideFolder, baseFolder)).toBeFalsy();
});

test('should return true for a folder outside the specified folder', () => {
expect(isFolderOutside(outsideFolder, baseFolder)).toBeTruthy();
});

test('should handle relative paths correctly', () => {
const relativeOutside = '../outside';
expect(isFolderOutside(relativeOutside, baseFolder)).toBeTruthy();
});

test('should return true for the same folder', () => {
expect(isFolderOutside(baseFolder, baseFolder)).toBeTruthy();
});
});
Loading