Skip to content

Instantly share code, notes, and snippets.

@Yuhtin
Created October 22, 2023 00:11
Show Gist options
  • Save Yuhtin/2458fb05c2cd79086c7ccdff70426ea7 to your computer and use it in GitHub Desktop.
Save Yuhtin/2458fb05c2cd79086c7ccdff70426ea7 to your computer and use it in GitHub Desktop.
Compress projects recursively respecting .gitignore
const fs = require('fs');
const path = require('path');
const { exec } = require('child_process');
const tarPath = 'C:\\Windows\\System32\\tar.exe';
const scriptDir = process.cwd();
const sourceDir = scriptDir;
const destDir = path.join(scriptDir, 'compressed');
if (!fs.existsSync(destDir)) {
fs.mkdirSync(destDir);
}
function compressItem(itemPath) {
if (itemPath === destDir) return;
const itemName = path.basename(itemPath);
const archiveName = path.join(destDir, `${itemName}.tar.gz`);
console.log(`Comprimindo ${itemName}`);
if (fs.existsSync(path.join(itemPath, '.gitignore'))) {
const gitignorePath = path.join(itemPath, '.gitignore');
const tarCommand = `"${tarPath}" --exclude-from="${gitignorePath}" -czf "${archiveName}" -C "${itemPath}" .`;
exec(tarCommand, (error) => {
if (error) {
console.error(`Erro ao compactar ${itemName}: ${error.message}`);
} else {
console.log(`${itemName} compactado com sucesso.`);
}
});
} else {
const tarCommand = `"${tarPath}" -czf "${archiveName}" -C "${itemPath}" .`;
exec(tarCommand, (error) => {
if (error) {
console.error(`Erro ao compactar ${itemName}: ${error.message}`);
} else {
console.log(`${itemName} compactado com sucesso.`);
}
});
}
}
function processItems(dir) {
fs.readdirSync(dir).forEach((item) => {
const itemPath = path.join(dir, item);
if (fs.statSync(itemPath).isDirectory()) {
compressItem(itemPath);
}
});
}
processItems(sourceDir);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment