Skip to content

Instantly share code, notes, and snippets.

@igniuss
Created January 31, 2024 12:33
Show Gist options
  • Save igniuss/b3a490fbc9e2771e974601ed34dddce5 to your computer and use it in GitHub Desktop.
Save igniuss/b3a490fbc9e2771e974601ed34dddce5 to your computer and use it in GitHub Desktop.
Cleans out empty folders & dangling meta files (Unity3D)
#!/usr/bin/env zx
/*
@ Use at your own risk -- Sean Lavaerts
HOW TO USE:
this uses zx (https://google.github.io/zx/getting-started)
essentially 'run javascript as a bash script'
but you could also just, run this as normal js under node/deno/what-ever you want,
you'd just need to hardcode the path.
usage:
```
$ cd projectfolder/Assets
$ ../my-script-location/script.mjs
<wait an eternity>
```
you can also add this to path, or manually run using `zx path-to-script`
essentially this iterates over all the files in a directory, and first deletes the empty folders,
followed by iterating over all the files *again* and deleting the dangling metas.
we detect dangling metas by removing the .meta part, and scanning the current filelist for the filename
this works because unity (thankfully!) does filename/foldername + .meta
so, this works for folders & files
*/
import 'zx/globals'
const fs = require('fs-extra');
const path = require('node:path');
async function deleteEmptyDirectories(dir) {
try {
// check if folder is empty
const files = await fs.promises.readdir(dir);
if (files.length == 0) {
console.log(`${dir} is empty! Deleting`)
fs.promises.rmdir(dir);
return;
}
for (const filename of files) {
// get full path
const fullPath = path.join(dir, filename);
const stat = await fs.promises.stat(fullPath);
if (stat.isDirectory()) {
await deleteEmptyDirectories(fullPath);
}
}
} catch (err) {
console.error(err);
}
}
async function deleteDanglingMeta(dir) {
try {
const files = await fs.promises.readdir(dir);
for (const filename of files) {
// get full path
const fullPath = path.join(dir, filename);
const stat = await fs.promises.stat(fullPath);
if (stat.isFile()) {
if(path.extname(filename) == '.meta') {
const original = path.parse(filename).name;
// dangling meta
if(files.includes(original) == false) {
await fs.promises.rm(fullPath);
console.log(`${fullPath} dangles! Deleting`)
}
}
} else if(stat.isDirectory()) {
await deleteDanglingMeta(fullPath);
}
}
} catch (err) {
console.error(err);
}
}
let folder = process.cwd();
console.log('Deleting empty directories');
await deleteEmptyDirectories(folder);
console.log('Deleting dangling meta files');
await deleteDanglingMeta(folder);
console.log(`Done ✨ go commit some things now :)`);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment