Skip to content

Commit

Permalink
initial commit 0.1.0
Browse files Browse the repository at this point in the history
  • Loading branch information
tbillington committed Jan 27, 2020
0 parents commit 30bd6db
Show file tree
Hide file tree
Showing 6 changed files with 353 additions and 0 deletions.
3 changes: 3 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
/target
**/*.rs.bk
/test_dir
61 changes: 61 additions & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

26 changes: 26 additions & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
[package]
name = "kondo"
version = "0.1.0"
authors = ["Trent Billington <[email protected]>"]
description = """
kondo is a filesystem cleaning tool that recursively searches directories
for known project structures and determines how much space you could save by
deleting the unnecessary files.
"""
documentation = "https://github.com/tbillington/kondo"
homepage = "https://github.com/tbillington/kondo"
repository = "https://github.com/tbillington/kondo"
readme = "README.md"
categories = ["command-line-utilities"]
license = "MIT"
exclude = ["test_dir"]
edition = "2018"


[dependencies]
walkdir = "2"

[profile.release]
incremental = false
lto = true
codegen-units = 1
21 changes: 21 additions & 0 deletions LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
MIT License

Copyright (c) 2020 Trent Billington

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
45 changes: 45 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
# Kondo 🧹

Cleans unneeded directories and files from your system.

It will identify the disk space savings you would get from deleting temporary/unnecessary files from project directories, such as `target` from Cargo projects and `node_modules` from Node projects. Currently `kondo` doesn't actually delete any files.

Supports:

- Cargo projects
- Node projects
- Unity Projects

## Roadmap

- Actually delete (with prompt)
- Handle Unity cache, editor cache

## Operation

Running `kondo` without a directory specified will run in the current directory.

```
$ kondo
```

Supplying an argument will tell `kondo` where to start.

```
$ kondo code/my_project
```

## Example Output

```
$ kondo ~
Scanning "C:/Users/Trent"
3 projects found
Calculating savings per project
(redacted 1000~ lines)
385.6MB UnityTestApp (Unity) C:\Users\Trent\code\UnityTestApp
458.7MB tokio (Cargo) C:\Users\Trent\code\tokio
1.5GB ui-testing (Node) C:\Users\Trent\code\ui-testing
4.0GB rust-analyzer (Cargo) C:\Users\Trent\code\rust-analyzer
9.5GB possible savings
```
197 changes: 197 additions & 0 deletions src/main.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,197 @@
use std::{env, io, path};
use walkdir;

const SYMLINK_FOLLOW: bool = true;

const FILE_CARGO_TOML: &str = "Cargo.toml";
const FILE_PACKAGE_JSON: &str = "package.json";
const FILE_ASSEMBLY_CSHARP: &str = "Assembly-CSharp.csproj";

const PROJECT_CARGO_DIRS: [&str; 1] = ["target"];
const PROJECT_NODE_DIRS: [&str; 1] = ["node_modules"];
const PROJECT_UNITY_DIRS: [&str; 7] = [
"Library",
"Temp",
"Obj",
"Logs",
"MemoryCaptures",
"Build",
"Builds",
];

#[derive(Clone, Debug)]
enum ProjectType {
Cargo,
Node,
Unity,
}

#[derive(Clone, Debug)]
struct ProjectDir {
r#type: ProjectType,
path: path::PathBuf,
}

fn is_hidden(entry: &walkdir::DirEntry) -> bool {
entry
.file_name()
.to_str()
.map(|s| s.starts_with("."))
.unwrap_or(false)
}

fn scan<P: AsRef<path::Path>>(path: &P) -> Vec<ProjectDir> {
walkdir::WalkDir::new(path)
.follow_links(SYMLINK_FOLLOW)
.into_iter()
.filter_entry(|e| !is_hidden(e))
.filter_map(|e| e.ok())
.filter_map(|entry| {
if entry.file_type().is_file() {
Some(ProjectDir {
r#type: match entry.file_name().to_str() {
Some(FILE_CARGO_TOML) => ProjectType::Cargo,
Some(FILE_PACKAGE_JSON) => ProjectType::Node,
Some(FILE_ASSEMBLY_CSHARP) => ProjectType::Unity,
_ => return None,
},
path: entry
.path()
.parent()
.expect("it's a file, so it should definitely have a parent...")
.to_path_buf(),
})
} else {
None
}
})
.collect()
}

fn dir_size(path: &path::Path) -> u64 {
walkdir::WalkDir::new(path)
.follow_links(SYMLINK_FOLLOW)
.into_iter()
.filter_map(|e| e.ok())
.filter(|e| e.file_type().is_file())
.map(|e: walkdir::DirEntry| e.metadata())
.filter_map(|md| md.ok())
.map(|e| e.len())
.sum()
}

fn pretty_size(size: u64) -> String {
let size = size as f64;
const KIBIBYTE: f64 = 1024.0;
const MEBIBYTE: f64 = 1_048_576.0;
const GIBIBYTE: f64 = 1_073_741_824.0;
const TEBIBYTE: f64 = 1_099_511_627_776.0;
const PEBIBYTE: f64 = 1_125_899_906_842_624.0;
const EXBIBYTE: f64 = 1_152_921_504_606_846_976.0;

let (size, symbol) = if size < KIBIBYTE {
(size, "B")
} else if size < MEBIBYTE {
(size / KIBIBYTE, "KB")
} else if size < GIBIBYTE {
(size / MEBIBYTE, "MB")
} else if size < TEBIBYTE {
(size / GIBIBYTE, "GB")
} else if size < PEBIBYTE {
(size / TEBIBYTE, "TB")
} else if size < EXBIBYTE {
(size / PEBIBYTE, "PB")
} else {
(size / EXBIBYTE, "EB")
};

format!("{:.1}{}", size, symbol)
}

fn main() -> Result<(), Box<dyn std::error::Error>> {
use io::Write;
let dir = {
let mut args: Vec<String> = env::args().collect();
if args.len() == 2 {
path::PathBuf::from(args.pop().unwrap())
} else {
env::current_dir()?
}
};

let stdout = io::stdout();
let mut write_handle = stdout.lock();

writeln!(&mut write_handle, "Scanning {:?}", dir)?;

let mut project_dirs = scan(&dir);

{
// Remove child directories if they have a parent in the list
let mut i = 0;
'outer: while i < project_dirs.len() {
let mut j = i + 1;

while j < project_dirs.len() {
let (p1, p2) = (&project_dirs[i].path, &project_dirs[j].path);

if p1.starts_with(p2) {
project_dirs.remove(i);
continue 'outer;
} else if p2.starts_with(p1) {
project_dirs.remove(j);
continue;
}

j += 1;
}

i += 1;
}
}

writeln!(&mut write_handle, "{} projects found", project_dirs.len())?;

writeln!(&mut write_handle, "Calculating savings per project")?;

let mut total = 0;

let mut project_sizes: Vec<(u64, String)> = project_dirs
.iter()
.map(|ProjectDir { r#type, path }| {
let (name, dirs) = match r#type {
ProjectType::Cargo => ("Cargo", PROJECT_CARGO_DIRS.iter()),
ProjectType::Node => ("Node", PROJECT_NODE_DIRS.iter()),
ProjectType::Unity => ("Unity", PROJECT_UNITY_DIRS.iter()),
};

let size = dirs.map(|p| dir_size(&path.join(p))).sum();
total += size;

(
size,
format!(
"{} ({}) {}",
path.strip_prefix(&dir)
.unwrap()
.file_name()
.map(|n| n.to_str().unwrap())
.unwrap_or("."),
name,
path.display()
),
)
})
.filter(|(size, _)| *size > 1)
.collect();

project_sizes.sort_unstable_by_key(|p| p.0);

for (size, project) in project_sizes.iter() {
writeln!(&mut write_handle, "{:>9} {}", pretty_size(*size), project)?;
}

writeln!(&mut write_handle, "{} possible savings", pretty_size(total))?;

Ok(())
}

0 comments on commit 30bd6db

Please sign in to comment.