Skip to content

Instantly share code, notes, and snippets.

@Explosion-Scratch
Created September 23, 2023 17:30
Show Gist options
  • Save Explosion-Scratch/d915138e3c6268fa2b76013c0557d9b9 to your computer and use it in GitHub Desktop.
Save Explosion-Scratch/d915138e3c6268fa2b76013c0557d9b9 to your computer and use it in GitHub Desktop.
import fs from 'fs';
import { exec, execSync } from 'child_process';
import { join } from 'path';
import path from 'path';
const args = process.argv.slice(2);
if (!process.env.SUDO_UID) {
console.log('Re-run as sudo');
process.exit(1);
}
const fileIconPath = fileIconExists();
if (!fileIconPath) {
console.log('Installing fileicon from npm...');
execSync('npm install -g fileicon');
}
if (!fileIconExists()) {
console.error('fileicon not found');
process.exit(1);
}
if (!args.length) {
console.error('No arguments provided');
process.exit(1);
}
const apps = fs.readdirSync('/Applications');
const icons = fs.readdirSync(args[0])
const maxNameLength = apps.reduce((maxLength, app) => {
const appName = path.basename(app).replace('.app', '');
const nameLength = appName.length;
return Math.max(maxLength, nameLength);
}, 0);
const promises = apps.map(async (app) => {
const icon = icons.find((i) => strip(i) === strip(app));
if (icon) {
try {
await exec(`${JSON.stringify(fileIconPath)} rm ${JSON.stringify(join('/Applications', app))}`);
const output = await exec(`${JSON.stringify(fileIconPath)} set ${JSON.stringify(join('/Applications', app))} ${JSON.stringify(join(args[0], icon))}`);
const appName = app.replace('.app', '');
const fileName = icon.replace(/^.*[\\/]/, '');
console.log(`✅ ${appName.padEnd(maxNameLength + 5, ' ')} — Set to ${fileName}`);
} catch (e) {
console.error(`🛑 Error setting icon for ${app}:`, e);
process.exit(1);
}
}
});
try {
await Promise.all(promises);
} catch (e) {
console.error('Error executing promises:', e);
process.exit(1);
}
function strip(str) {
return str.replace('.app', '').replace('.icns', '').toLowerCase().trim();
}
function fileIconExists() {
try {
return execSync(`which fileicon`).toString().trim();
} catch (e) {
return false;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment