Skip to content

Instantly share code, notes, and snippets.

@samitha9125
Created October 7, 2023 07:34
Show Gist options
  • Save samitha9125/6c94d501676af26b8eae87cd5f082eb8 to your computer and use it in GitHub Desktop.
Save samitha9125/6c94d501676af26b8eae87cd5f082eb8 to your computer and use it in GitHub Desktop.
Danger JS - File Size Check
/**
* This script serves as a mechanism to ensure that no files exceeding a size of 50MB are committed to the repository.
* It checks the size of each file that has been modified or created in the current git commit, and alerts the developer if any oversized files are found.
*
* Requirement:
* 1. **File Size Check**: Before committing files, it's crucial to ensure that file sizes are within reasonable limits to prevent bloating the repository.
*
* Note:
* - This script can be executed either locally or as part of a CI/CD pipeline.
* - When executed locally, it can be run with the `danger local` option or integrated with git hooks using tools such as Husky to perform checks when a developer executes a git commit.
* - When integrated into a CI/CD pipeline, it utilizes the `danger` library to report oversized files and fail the pipeline if necessary.
*/
import { fail, danger } from 'danger';
import fs from 'fs';
// Get the list of modified and created files from the git diff
const modifiedFiles = danger.git.modified_files || [];
const createdFiles = danger.git.created_files || [];
const allFiles = [...modifiedFiles, ...createdFiles];
const sizeLimit = 50 // In MBs
function generateFailMessage(file: string, fileSizeInMB: number): string {
return `🚨 ${file} is ${fileSizeInMB.toFixed(2)} MB and exceeds 50MB limit. Please reduce file size. 🚨`;
}
function checkForFileSize(file: string) {
if (fs.existsSync(file)) {
// Get file stats to retrieve its size
const stats = fs.statSync(file);
const fileSizeInBytes = stats.size;
const fileSizeInMB = fileSizeInBytes / (1024 * 1024); // Convert size to Megabytes (MB)
if (fileSizeInMB > 50) {
const failMessage = generateFailMessage(file, fileSizeInMB);
fail(failMessage);
process.exit(1);
}
}
}
// Iterate through all the files and check their sizes
allFiles.forEach(file => {
checkForFileSize(file);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment