File image-janitor-0.2.0.obscpio of Package image-janitor

07070100000000000041ED00000000000000000000000268E7A1E500000000000000000000000000000000000000000000001C00000000image-janitor-0.2.0/.github07070100000001000041ED00000000000000000000000268E7A1E500000000000000000000000000000000000000000000002600000000image-janitor-0.2.0/.github/workflows07070100000002000081A400000000000000000000000168E7A1E50000013C000000000000000000000000000000000000002F00000000image-janitor-0.2.0/.github/workflows/rust.ymlname: Rust

on:
  push:
    branches: [ "main" ]
  pull_request:
    branches: [ "main" ]

env:
  CARGO_TERM_COLOR: always

jobs:
  build:

    runs-on: ubuntu-latest

    steps:
    - uses: actions/checkout@v4
    - name: Build
      run: cargo build --verbose
    - name: Run tests
      run: cargo test --verbose
07070100000003000081A400000000000000000000000168E7A1E500000008000000000000000000000000000000000000001F00000000image-janitor-0.2.0/.gitignore/target
07070100000004000081A400000000000000000000000168E7A1E500000265000000000000000000000000000000000000001E00000000image-janitor-0.2.0/AGENTS.md# Rules for AGENTS

## Dev environment tips
- When working on a feature, first implement the changes, check it builds and passes existing tests, create a git commit, then create a testcase and do a separate git commit as fixup
- Never try to do git push

## Testing instructions
- From the package root you can just call `cargo test`. The commit should pass all tests before you commit anything
- Fix any test or type errors until the whole suite is green.
- Add or update tests for the code you change, even if nobody asked.

## Commit instruction
- Always run `cargo clippy` and `cargo test` before committing.
07070100000005000081A400000000000000000000000168E7A1E50000437A000000000000000000000000000000000000001F00000000image-janitor-0.2.0/Cargo.lock# This file is automatically @generated by Cargo.
# It is not intended for manual editing.
version = 4

[[package]]
name = "aho-corasick"
version = "1.1.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8e60d3430d3a69478ad0993f19238d2df97c507009a52b3c10addcd7f6bcb916"
dependencies = [
 "memchr",
]

[[package]]
name = "anstream"
version = "0.6.21"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "43d5b281e737544384e969a5ccad3f1cdd24b48086a0fc1b2a5262a26b8f4f4a"
dependencies = [
 "anstyle",
 "anstyle-parse",
 "anstyle-query",
 "anstyle-wincon",
 "colorchoice",
 "is_terminal_polyfill",
 "utf8parse",
]

[[package]]
name = "anstyle"
version = "1.0.13"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5192cca8006f1fd4f7237516f40fa183bb07f8fbdfedaa0036de5ea9b0b45e78"

[[package]]
name = "anstyle-parse"
version = "0.2.7"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4e7644824f0aa2c7b9384579234ef10eb7efb6a0deb83f9630a49594dd9c15c2"
dependencies = [
 "utf8parse",
]

[[package]]
name = "anstyle-query"
version = "1.1.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9e231f6134f61b71076a3eab506c379d4f36122f2af15a9ff04415ea4c3339e2"
dependencies = [
 "windows-sys 0.60.2",
]

[[package]]
name = "anstyle-wincon"
version = "3.0.10"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3e0633414522a32ffaac8ac6cc8f748e090c5717661fddeea04219e2344f5f2a"
dependencies = [
 "anstyle",
 "once_cell_polyfill",
 "windows-sys 0.60.2",
]

[[package]]
name = "anyhow"
version = "1.0.100"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a23eb6b1614318a8071c9b2521f36b424b2c83db5eb3a0fead4a6c0809af6e61"

[[package]]
name = "bitflags"
version = "2.9.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2261d10cca569e4643e526d8dc2e62e433cc8aba21ab764233731f8d369bf394"

[[package]]
name = "cfg-if"
version = "1.0.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2fd1289c04a9ea8cb22300a459a72a385d7c73d3259e2ed7dcb2af674838cfa9"

[[package]]
name = "clap"
version = "4.5.48"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e2134bb3ea021b78629caa971416385309e0131b351b25e01dc16fb54e1b5fae"
dependencies = [
 "clap_builder",
 "clap_derive",
]

[[package]]
name = "clap_builder"
version = "4.5.48"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c2ba64afa3c0a6df7fa517765e31314e983f51dda798ffba27b988194fb65dc9"
dependencies = [
 "anstream",
 "anstyle",
 "clap_lex",
 "strsim",
]

[[package]]
name = "clap_derive"
version = "4.5.47"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "bbfd7eae0b0f1a6e63d4b13c9c478de77c2eb546fba158ad50b4203dc24b9f9c"
dependencies = [
 "heck",
 "proc-macro2",
 "quote",
 "syn",
]

[[package]]
name = "clap_lex"
version = "0.7.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b94f61472cee1439c0b966b47e3aca9ae07e45d070759512cd390ea2bebc6675"

[[package]]
name = "colorchoice"
version = "1.0.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b05b61dc5112cbb17e4b6cd61790d9845d13888356391624cbe7e41efeac1e75"

[[package]]
name = "env_logger"
version = "0.10.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4cd405aab171cb85d6735e5c8d9db038c17d3ca007a4d2c25f337935c3d90580"
dependencies = [
 "humantime",
 "is-terminal",
 "log",
 "regex",
 "termcolor",
]

[[package]]
name = "errno"
version = "0.3.14"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "39cab71617ae0d63f51a36d69f866391735b51691dbda63cf6f96d042b63efeb"
dependencies = [
 "libc",
 "windows-sys 0.61.2",
]

[[package]]
name = "fastrand"
version = "2.3.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "37909eebbb50d72f9059c3b6d82c0463f2ff062c9e95845c43a6c9c0355411be"

[[package]]
name = "getrandom"
version = "0.3.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "26145e563e54f2cadc477553f1ec5ee650b00862f0a58bcd12cbdc5f0ea2d2f4"
dependencies = [
 "cfg-if",
 "libc",
 "r-efi",
 "wasi",
]

[[package]]
name = "glob"
version = "0.3.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0cc23270f6e1808e30a928bdc84dea0b9b4136a8bc82338574f23baf47bbd280"

[[package]]
name = "heck"
version = "0.5.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2304e00983f87ffb38b55b444b5e3b60a884b5d30c0fca7d82fe33449bbe55ea"

[[package]]
name = "hermit-abi"
version = "0.5.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "fc0fef456e4baa96da950455cd02c081ca953b141298e41db3fc7e36b1da849c"

[[package]]
name = "humantime"
version = "2.3.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "135b12329e5e3ce057a9f972339ea52bc954fe1e9358ef27f95e89716fbc5424"

[[package]]
name = "image-janitor"
version = "0.2.0"
dependencies = [
 "anyhow",
 "clap",
 "env_logger",
 "glob",
 "lazy_static",
 "log",
 "path-clean",
 "regex",
 "tempfile",
 "thiserror",
 "walkdir",
]

[[package]]
name = "is-terminal"
version = "0.4.16"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e04d7f318608d35d4b61ddd75cbdaee86b023ebe2bd5a66ee0915f0bf93095a9"
dependencies = [
 "hermit-abi",
 "libc",
 "windows-sys 0.59.0",
]

[[package]]
name = "is_terminal_polyfill"
version = "1.70.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7943c866cc5cd64cbc25b2e01621d07fa8eb2a1a23160ee81ce38704e97b8ecf"

[[package]]
name = "lazy_static"
version = "1.5.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "bbd2bcb4c963f2ddae06a2efc7e9f3591312473c50c6685e1f298068316e66fe"

[[package]]
name = "libc"
version = "0.2.176"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "58f929b4d672ea937a23a1ab494143d968337a5f47e56d0815df1e0890ddf174"

[[package]]
name = "linux-raw-sys"
version = "0.11.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "df1d3c3b53da64cf5760482273a98e575c651a67eec7f77df96b5b642de8f039"

[[package]]
name = "log"
version = "0.4.28"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "34080505efa8e45a4b816c349525ebe327ceaa8559756f0356cba97ef3bf7432"

[[package]]
name = "memchr"
version = "2.7.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f52b00d39961fc5b2736ea853c9cc86238e165017a493d1d5c8eac6bdc4cc273"

[[package]]
name = "once_cell"
version = "1.21.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "42f5e15c9953c5e4ccceeb2e7382a716482c34515315f7b03532b8b4e8393d2d"

[[package]]
name = "once_cell_polyfill"
version = "1.70.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a4895175b425cb1f87721b59f0f286c2092bd4af812243672510e1ac53e2e0ad"

[[package]]
name = "path-clean"
version = "1.0.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "17359afc20d7ab31fdb42bb844c8b3bb1dabd7dcf7e68428492da7f16966fcef"

[[package]]
name = "proc-macro2"
version = "1.0.101"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "89ae43fd86e4158d6db51ad8e2b80f313af9cc74f5c0e03ccb87de09998732de"
dependencies = [
 "unicode-ident",
]

[[package]]
name = "quote"
version = "1.0.41"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ce25767e7b499d1b604768e7cde645d14cc8584231ea6b295e9c9eb22c02e1d1"
dependencies = [
 "proc-macro2",
]

[[package]]
name = "r-efi"
version = "5.3.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "69cdb34c158ceb288df11e18b4bd39de994f6657d83847bdffdbd7f346754b0f"

[[package]]
name = "regex"
version = "1.11.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8b5288124840bee7b386bc413c487869b360b2b4ec421ea56425128692f2a82c"
dependencies = [
 "aho-corasick",
 "memchr",
 "regex-automata",
 "regex-syntax",
]

[[package]]
name = "regex-automata"
version = "0.4.11"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "833eb9ce86d40ef33cb1306d8accf7bc8ec2bfea4355cbdebb3df68b40925cad"
dependencies = [
 "aho-corasick",
 "memchr",
 "regex-syntax",
]

[[package]]
name = "regex-syntax"
version = "0.8.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "caf4aa5b0f434c91fe5c7f1ecb6a5ece2130b02ad2a590589dda5146df959001"

[[package]]
name = "rustix"
version = "1.1.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "cd15f8a2c5551a84d56efdc1cd049089e409ac19a3072d5037a17fd70719ff3e"
dependencies = [
 "bitflags",
 "errno",
 "libc",
 "linux-raw-sys",
 "windows-sys 0.61.2",
]

[[package]]
name = "same-file"
version = "1.0.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "93fc1dc3aaa9bfed95e02e6eadabb4baf7e3078b0bd1b4d7b6b0b68378900502"
dependencies = [
 "winapi-util",
]

[[package]]
name = "strsim"
version = "0.11.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7da8b5736845d9f2fcb837ea5d9e2628564b3b043a70948a3f0b778838c5fb4f"

[[package]]
name = "syn"
version = "2.0.106"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ede7c438028d4436d71104916910f5bb611972c5cfd7f89b8300a8186e6fada6"
dependencies = [
 "proc-macro2",
 "quote",
 "unicode-ident",
]

[[package]]
name = "tempfile"
version = "3.23.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2d31c77bdf42a745371d260a26ca7163f1e0924b64afa0b688e61b5a9fa02f16"
dependencies = [
 "fastrand",
 "getrandom",
 "once_cell",
 "rustix",
 "windows-sys 0.61.2",
]

[[package]]
name = "termcolor"
version = "1.4.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "06794f8f6c5c898b3275aebefa6b8a1cb24cd2c6c79397ab15774837a0bc5755"
dependencies = [
 "winapi-util",
]

[[package]]
name = "thiserror"
version = "1.0.69"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b6aaf5339b578ea85b50e080feb250a3e8ae8cfcdff9a461c9ec2904bc923f52"
dependencies = [
 "thiserror-impl",
]

[[package]]
name = "thiserror-impl"
version = "1.0.69"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4fee6c4efc90059e10f81e6d42c60a18f76588c3d74cb83a0b242a2b6c7504c1"
dependencies = [
 "proc-macro2",
 "quote",
 "syn",
]

[[package]]
name = "unicode-ident"
version = "1.0.19"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f63a545481291138910575129486daeaf8ac54aee4387fe7906919f7830c7d9d"

[[package]]
name = "utf8parse"
version = "0.2.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "06abde3611657adf66d383f00b093d7faecc7fa57071cce2578660c9f1010821"

[[package]]
name = "walkdir"
version = "2.5.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "29790946404f91d9c5d06f9874efddea1dc06c5efe94541a7d6863108e3a5e4b"
dependencies = [
 "same-file",
 "winapi-util",
]

[[package]]
name = "wasi"
version = "0.14.7+wasi-0.2.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "883478de20367e224c0090af9cf5f9fa85bed63a95c1abf3afc5c083ebc06e8c"
dependencies = [
 "wasip2",
]

[[package]]
name = "wasip2"
version = "1.0.1+wasi-0.2.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0562428422c63773dad2c345a1882263bbf4d65cf3f42e90921f787ef5ad58e7"
dependencies = [
 "wit-bindgen",
]

[[package]]
name = "winapi-util"
version = "0.1.11"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c2a7b1c03c876122aa43f3020e6c3c3ee5c05081c9a00739faf7503aeba10d22"
dependencies = [
 "windows-sys 0.61.2",
]

[[package]]
name = "windows-link"
version = "0.2.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5"

[[package]]
name = "windows-sys"
version = "0.59.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1e38bc4d79ed67fd075bcc251a1c39b32a1776bbe92e5bef1f0bf1f8c531853b"
dependencies = [
 "windows-targets 0.52.6",
]

[[package]]
name = "windows-sys"
version = "0.60.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f2f500e4d28234f72040990ec9d39e3a6b950f9f22d3dba18416c35882612bcb"
dependencies = [
 "windows-targets 0.53.5",
]

[[package]]
name = "windows-sys"
version = "0.61.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ae137229bcbd6cdf0f7b80a31df61766145077ddf49416a728b02cb3921ff3fc"
dependencies = [
 "windows-link",
]

[[package]]
name = "windows-targets"
version = "0.52.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9b724f72796e036ab90c1021d4780d4d3d648aca59e491e6b98e725b84e99973"
dependencies = [
 "windows_aarch64_gnullvm 0.52.6",
 "windows_aarch64_msvc 0.52.6",
 "windows_i686_gnu 0.52.6",
 "windows_i686_gnullvm 0.52.6",
 "windows_i686_msvc 0.52.6",
 "windows_x86_64_gnu 0.52.6",
 "windows_x86_64_gnullvm 0.52.6",
 "windows_x86_64_msvc 0.52.6",
]

[[package]]
name = "windows-targets"
version = "0.53.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4945f9f551b88e0d65f3db0bc25c33b8acea4d9e41163edf90dcd0b19f9069f3"
dependencies = [
 "windows-link",
 "windows_aarch64_gnullvm 0.53.1",
 "windows_aarch64_msvc 0.53.1",
 "windows_i686_gnu 0.53.1",
 "windows_i686_gnullvm 0.53.1",
 "windows_i686_msvc 0.53.1",
 "windows_x86_64_gnu 0.53.1",
 "windows_x86_64_gnullvm 0.53.1",
 "windows_x86_64_msvc 0.53.1",
]

[[package]]
name = "windows_aarch64_gnullvm"
version = "0.52.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "32a4622180e7a0ec044bb555404c800bc9fd9ec262ec147edd5989ccd0c02cd3"

[[package]]
name = "windows_aarch64_gnullvm"
version = "0.53.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a9d8416fa8b42f5c947f8482c43e7d89e73a173cead56d044f6a56104a6d1b53"

[[package]]
name = "windows_aarch64_msvc"
version = "0.52.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "09ec2a7bb152e2252b53fa7803150007879548bc709c039df7627cabbd05d469"

[[package]]
name = "windows_aarch64_msvc"
version = "0.53.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b9d782e804c2f632e395708e99a94275910eb9100b2114651e04744e9b125006"

[[package]]
name = "windows_i686_gnu"
version = "0.52.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8e9b5ad5ab802e97eb8e295ac6720e509ee4c243f69d781394014ebfe8bbfa0b"

[[package]]
name = "windows_i686_gnu"
version = "0.53.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "960e6da069d81e09becb0ca57a65220ddff016ff2d6af6a223cf372a506593a3"

[[package]]
name = "windows_i686_gnullvm"
version = "0.52.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0eee52d38c090b3caa76c563b86c3a4bd71ef1a819287c19d586d7334ae8ed66"

[[package]]
name = "windows_i686_gnullvm"
version = "0.53.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "fa7359d10048f68ab8b09fa71c3daccfb0e9b559aed648a8f95469c27057180c"

[[package]]
name = "windows_i686_msvc"
version = "0.52.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "240948bc05c5e7c6dabba28bf89d89ffce3e303022809e73deaefe4f6ec56c66"

[[package]]
name = "windows_i686_msvc"
version = "0.53.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1e7ac75179f18232fe9c285163565a57ef8d3c89254a30685b57d83a38d326c2"

[[package]]
name = "windows_x86_64_gnu"
version = "0.52.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "147a5c80aabfbf0c7d901cb5895d1de30ef2907eb21fbbab29ca94c5b08b1a78"

[[package]]
name = "windows_x86_64_gnu"
version = "0.53.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9c3842cdd74a865a8066ab39c8a7a473c0778a3f29370b5fd6b4b9aa7df4a499"

[[package]]
name = "windows_x86_64_gnullvm"
version = "0.52.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "24d5b23dc417412679681396f2b49f3de8c1473deb516bd34410872eff51ed0d"

[[package]]
name = "windows_x86_64_gnullvm"
version = "0.53.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0ffa179e2d07eee8ad8f57493436566c7cc30ac536a3379fdf008f47f6bb7ae1"

[[package]]
name = "windows_x86_64_msvc"
version = "0.52.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "589f6da84c646204747d1270a2a5661ea66ed1cced2631d546fdfb155959f9ec"

[[package]]
name = "windows_x86_64_msvc"
version = "0.53.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d6bbff5f0aada427a1e5a6da5f1f98158182f26556f345ac9e04d36d0ebed650"

[[package]]
name = "wit-bindgen"
version = "0.46.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f17a85883d4e6d00e8a97c586de764dabcc06133f7f1d55dce5cdc070ad7fe59"
07070100000006000081A400000000000000000000000168E7A1E50000013A000000000000000000000000000000000000001F00000000image-janitor-0.2.0/Cargo.toml[package]
name = "image-janitor"
version = "0.2.0"
edition = "2021"

[dependencies]
anyhow = "1.0"
clap = { version = "4.4", features = ["derive"] }
env_logger = "0.10"
lazy_static = "1.4"
log = "0.4"
regex = "1"
thiserror = "1.0"
walkdir = "2"
glob = "0.3"
path-clean = "1.0.1"

[dev-dependencies]
tempfile = "3"
07070100000007000081A400000000000000000000000168E7A1E5000046AC000000000000000000000000000000000000001C00000000image-janitor-0.2.0/LICENSE                    GNU GENERAL PUBLIC LICENSE
                       Version 2, June 1991

 Copyright (C) 1989, 1991 Free Software Foundation, Inc.,
 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
 Everyone is permitted to copy and distribute verbatim copies
 of this license document, but changing it is not allowed.

                            Preamble

  The licenses for most software are designed to take away your
freedom to share and change it.  By contrast, the GNU General Public
License is intended to guarantee your freedom to share and change free
software--to make sure the software is free for all its users.  This
General Public License applies to most of the Free Software
Foundation's software and to any other program whose authors commit to
using it.  (Some other Free Software Foundation software is covered by
the GNU Lesser General Public License instead.)  You can apply it to
your programs, too.

  When we speak of free software, we are referring to freedom, not
price.  Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
this service if you wish), that you receive source code or can get it
if you want it, that you can change the software or use pieces of it
in new free programs; and that you know you can do these things.

  To protect your rights, we need to make restrictions that forbid
anyone to deny you these rights or to ask you to surrender the rights.
These restrictions translate to certain responsibilities for you if you
distribute copies of the software, or if you modify it.

  For example, if you distribute copies of such a program, whether
gratis or for a fee, you must give the recipients all the rights that
you have.  You must make sure that they, too, receive or can get the
source code.  And you must show them these terms so they know their
rights.

  We protect your rights with two steps: (1) copyright the software, and
(2) offer you this license which gives you legal permission to copy,
distribute and/or modify the software.

  Also, for each author's protection and ours, we want to make certain
that everyone understands that there is no warranty for this free
software.  If the software is modified by someone else and passed on, we
want its recipients to know that what they have is not the original, so
that any problems introduced by others will not reflect on the original
authors' reputations.

  Finally, any free program is threatened constantly by software
patents.  We wish to avoid the danger that redistributors of a free
program will individually obtain patent licenses, in effect making the
program proprietary.  To prevent this, we have made it clear that any
patent must be licensed for everyone's free use or not licensed at all.

  The precise terms and conditions for copying, distribution and
modification follow.

                    GNU GENERAL PUBLIC LICENSE
   TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION

  0. This License applies to any program or other work which contains
a notice placed by the copyright holder saying it may be distributed
under the terms of this General Public License.  The "Program", below,
refers to any such program or work, and a "work based on the Program"
means either the Program or any derivative work under copyright law:
that is to say, a work containing the Program or a portion of it,
either verbatim or with modifications and/or translated into another
language.  (Hereinafter, translation is included without limitation in
the term "modification".)  Each licensee is addressed as "you".

Activities other than copying, distribution and modification are not
covered by this License; they are outside its scope.  The act of
running the Program is not restricted, and the output from the Program
is covered only if its contents constitute a work based on the
Program (independent of having been made by running the Program).
Whether that is true depends on what the Program does.

  1. You may copy and distribute verbatim copies of the Program's
source code as you receive it, in any medium, provided that you
conspicuously and appropriately publish on each copy an appropriate
copyright notice and disclaimer of warranty; keep intact all the
notices that refer to this License and to the absence of any warranty;
and give any other recipients of the Program a copy of this License
along with the Program.

You may charge a fee for the physical act of transferring a copy, and
you may at your option offer warranty protection in exchange for a fee.

  2. You may modify your copy or copies of the Program or any portion
of it, thus forming a work based on the Program, and copy and
distribute such modifications or work under the terms of Section 1
above, provided that you also meet all of these conditions:

    a) You must cause the modified files to carry prominent notices
    stating that you changed the files and the date of any change.

    b) You must cause any work that you distribute or publish, that in
    whole or in part contains or is derived from the Program or any
    part thereof, to be licensed as a whole at no charge to all third
    parties under the terms of this License.

    c) If the modified program normally reads commands interactively
    when run, you must cause it, when started running for such
    interactive use in the most ordinary way, to print or display an
    announcement including an appropriate copyright notice and a
    notice that there is no warranty (or else, saying that you provide
    a warranty) and that users may redistribute the program under
    these conditions, and telling the user how to view a copy of this
    License.  (Exception: if the Program itself is interactive but
    does not normally print such an announcement, your work based on
    the Program is not required to print an announcement.)

These requirements apply to the modified work as a whole.  If
identifiable sections of that work are not derived from the Program,
and can be reasonably considered independent and separate works in
themselves, then this License, and its terms, do not apply to those
sections when you distribute them as separate works.  But when you
distribute the same sections as part of a whole which is a work based
on the Program, the distribution of the whole must be on the terms of
this License, whose permissions for other licensees extend to the
entire whole, and thus to each and every part regardless of who wrote it.

Thus, it is not the intent of this section to claim rights or contest
your rights to work written entirely by you; rather, the intent is to
exercise the right to control the distribution of derivative or
collective works based on the Program.

In addition, mere aggregation of another work not based on the Program
with the Program (or with a work based on the Program) on a volume of
a storage or distribution medium does not bring the other work under
the scope of this License.

  3. You may copy and distribute the Program (or a work based on it,
under Section 2) in object code or executable form under the terms of
Sections 1 and 2 above provided that you also do one of the following:

    a) Accompany it with the complete corresponding machine-readable
    source code, which must be distributed under the terms of Sections
    1 and 2 above on a medium customarily used for software interchange; or,

    b) Accompany it with a written offer, valid for at least three
    years, to give any third party, for a charge no more than your
    cost of physically performing source distribution, a complete
    machine-readable copy of the corresponding source code, to be
    distributed under the terms of Sections 1 and 2 above on a medium
    customarily used for software interchange; or,

    c) Accompany it with the information you received as to the offer
    to distribute corresponding source code.  (This alternative is
    allowed only for noncommercial distribution and only if you
    received the program in object code or executable form with such
    an offer, in accord with Subsection b above.)

The source code for a work means the preferred form of the work for
making modifications to it.  For an executable work, complete source
code means all the source code for all modules it contains, plus any
associated interface definition files, plus the scripts used to
control compilation and installation of the executable.  However, as a
special exception, the source code distributed need not include
anything that is normally distributed (in either source or binary
form) with the major components (compiler, kernel, and so on) of the
operating system on which the executable runs, unless that component
itself accompanies the executable.

If distribution of executable or object code is made by offering
access to copy from a designated place, then offering equivalent
access to copy the source code from the same place counts as
distribution of the source code, even though third parties are not
compelled to copy the source along with the object code.

  4. You may not copy, modify, sublicense, or distribute the Program
except as expressly provided under this License.  Any attempt
otherwise to copy, modify, sublicense or distribute the Program is
void, and will automatically terminate your rights under this License.
However, parties who have received copies, or rights, from you under
this License will not have their licenses terminated so long as such
parties remain in full compliance.

  5. You are not required to accept this License, since you have not
signed it.  However, nothing else grants you permission to modify or
distribute the Program or its derivative works.  These actions are
prohibited by law if you do not accept this License.  Therefore, by
modifying or distributing the Program (or any work based on the
Program), you indicate your acceptance of this License to do so, and
all its terms and conditions for copying, distributing or modifying
the Program or works based on it.

  6. Each time you redistribute the Program (or any work based on the
Program), the recipient automatically receives a license from the
original licensor to copy, distribute or modify the Program subject to
these terms and conditions.  You may not impose any further
restrictions on the recipients' exercise of the rights granted herein.
You are not responsible for enforcing compliance by third parties to
this License.

  7. If, as a consequence of a court judgment or allegation of patent
infringement or for any other reason (not limited to patent issues),
conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License.  If you cannot
distribute so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you
may not distribute the Program at all.  For example, if a patent
license would not permit royalty-free redistribution of the Program by
all those who receive copies directly or indirectly through you, then
the only way you could satisfy both it and this License would be to
refrain entirely from distribution of the Program.

If any portion of this section is held invalid or unenforceable under
any particular circumstance, the balance of the section is intended to
apply and the section as a whole is intended to apply in other
circumstances.

It is not the purpose of this section to induce you to infringe any
patents or other property right claims or to contest validity of any
such claims; this section has the sole purpose of protecting the
integrity of the free software distribution system, which is
implemented by public license practices.  Many people have made
generous contributions to the wide range of software distributed
through that system in reliance on consistent application of that
system; it is up to the author/donor to decide if he or she is willing
to distribute software through any other system and a licensee cannot
impose that choice.

This section is intended to make thoroughly clear what is believed to
be a consequence of the rest of this License.

  8. If the distribution and/or use of the Program is restricted in
certain countries either by patents or by copyrighted interfaces, the
original copyright holder who places the Program under this License
may add an explicit geographical distribution limitation excluding
those countries, so that distribution is permitted only in or among
countries not thus excluded.  In such case, this License incorporates
the limitation as if written in the body of this License.

  9. The Free Software Foundation may publish revised and/or new versions
of the General Public License from time to time.  Such new versions will
be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.

Each version is given a distinguishing version number.  If the Program
specifies a version number of this License which applies to it and "any
later version", you have the option of following the terms and conditions
either of that version or of any later version published by the Free
Software Foundation.  If the Program does not specify a version number of
this License, you may choose any version ever published by the Free Software
Foundation.

  10. If you wish to incorporate parts of the Program into other free
programs whose distribution conditions are different, write to the author
to ask for permission.  For software which is copyrighted by the Free
Software Foundation, write to the Free Software Foundation; we sometimes
make exceptions for this.  Our decision will be guided by the two goals
of preserving the free status of all derivatives of our free software and
of promoting the sharing and reuse of software generally.

                            NO WARRANTY

  11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY
FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW.  EXCEPT WHEN
OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES
PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED
OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.  THE ENTIRE RISK AS
TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU.  SHOULD THE
PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING,
REPAIR OR CORRECTION.

  12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR
REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES,
INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING
OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED
TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY
YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER
PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE
POSSIBILITY OF SUCH DAMAGES.

                     END OF TERMS AND CONDITIONS

            How to Apply These Terms to Your New Programs

  If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.

  To do so, attach the following notices to the program.  It is safest
to attach them to the start of each source file to most effectively
convey the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.

    <one line to give the program's name and a brief idea of what it does.>
    Copyright (C) <year>  <name of author>

    This program is free software; you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation; either version 2 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License along
    with this program; if not, write to the Free Software Foundation, Inc.,
    51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.

Also add information on how to contact you by electronic and paper mail.

If the program is interactive, make it output a short notice like this
when it starts in an interactive mode:

    Gnomovision version 69, Copyright (C) year name of author
    Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
    This is free software, and you are welcome to redistribute it
    under certain conditions; type `show c' for details.

The hypothetical commands `show w' and `show c' should show the appropriate
parts of the General Public License.  Of course, the commands you use may
be called something other than `show w' and `show c'; they could even be
mouse-clicks or menu items--whatever suits your program.

You should also get your employer (if you work as a programmer) or your
school, if any, to sign a "copyright disclaimer" for the program, if
necessary.  Here is a sample; alter the names:

  Yoyodyne, Inc., hereby disclaims all copyright interest in the program
  `Gnomovision' (which makes passes at compilers) written by James Hacker.

  <signature of Ty Coon>, 1 April 1989
  Ty Coon, President of Vice

This General Public License does not permit incorporating your program into
proprietary programs.  If your program is a subroutine library, you may
consider it more useful to permit linking proprietary applications with the
library.  If this is what you want to do, use the GNU Lesser General
Public License instead of this License.
07070100000008000081A400000000000000000000000168E7A1E500000B27000000000000000000000000000000000000001E00000000image-janitor-0.2.0/README.md# Image Janitor

Image Janitor is a command-line tool for cleaning up unused kernel drivers and firmware from a Linux system. It helps to reduce the size of a Linux image by removing unnecessary files.

## Features

*   **Driver Cleanup**: Removes unused kernel drivers.
*   **Firmware Cleanup**: Removes unused firmware files.
*   **Configuration**: Uses configuration files to determine which files to keep and which to delete.
*   **Dependency Resolution**: Resolves dependencies between kernel modules to avoid breaking the system.

## Usage

### Driver Cleanup

To clean up unused kernel drivers, run the following command:

```bash
image-janitor driver-cleanup
```

By default, the command will perform a dry run and only show the files that would be deleted. To actually delete the files, use the `--delete` flag:

```bash
image-janitor driver-cleanup --delete
```

You can also specify the directory containing the kernel modules and the configuration files to use:

```bash
image-janitor driver-cleanup --module-dir /path/to/modules --config-files /path/to/config1,/path/to/config2
```

### Firmware Cleanup

To clean up unused firmware, run the following command:

```bash
image-janitor fw-cleanup
```

By default, the command will perform a dry run and only show the files that would be deleted. To actually delete the files, use the `--delete` flag:

```bash
image-janitor fw-cleanup --delete
```

You can also specify the directory containing the kernel modules and the firmware files:

```bash
image-janitor fw-cleanup --module-dir /path/to/modules --firmware-dir /path/to/firmware
```

## Building from Source

To build the project from source, you will need to have Rust installed. You can then clone the repository and build the project using Cargo:

```bash
git clone https://github.com/fcrozat/image-janitor.git
cd image-janitor
cargo build --release
```

The executable will be located in the `target/release` directory.

## Configuration

The configuration files use a simple format. Each line contains a regular expression that is matched against the path of a file. If the path matches a regular expression, the file is kept. If the path does not match any regular expression, the file is deleted.

You can also specify which files to delete by prefixing the regular expression with a `-`. For example, to delete all files in the `drivers/net` directory, you would add the following line to your configuration file:

```
-drivers/net/.*
```

The configuration files also support architecture-specific sections. For example, to specify that a driver should only be kept on x86_64 systems, you would add the following lines to your configuration file:

```
<x86_64>
drivers/net/ethernet/intel/.*
</x86_64>
```

Configuration files used for [Agama](https://agama-project.github.io/) installer are available in the `data` subdirectory.
07070100000009000041ED00000000000000000000000268E7A1E500000000000000000000000000000000000000000000001900000000image-janitor-0.2.0/data0707010000000A000081A400000000000000000000000168E7A1E500001F36000000000000000000000000000000000000002500000000image-janitor-0.2.0/data/module.list# modules that _might_ be useful during installation
#
# Lines starting with '-' specify modules to drop.
# The lines below are actually perl regexps, so be careful.
#
# If a module is specified both to be added and dropped, it is dropped.
#
# Arch-dependend blocks start with <ARCH> and end with </ARCH> (on separate lines).
#
kernel/drivers/base/
kernel/drivers/block/
-kernel/drivers/block/paride
kernel/drivers/cdrom/cdrom.ko
kernel/drivers/cdrom/viocd.ko
kernel/drivers/i2o/
kernel/drivers/ide/
kernel/drivers/ata/
#-kernel/drivers/ata/pata_
kernel/drivers/firewire/
kernel/drivers/input/
-kernel/drivers/input/joystick
-kernel/drivers/input/gameport
kernel/drivers/iseries/
kernel/drivers/md/
kernel/drivers/mmc/
kernel/drivers/net/
-kernel/drivers/net/aironet
-kernel/drivers/net/appletalk/
-kernel/drivers/net/arcnet/
-kernel/drivers/net/hamradio/
-kernel/drivers/net/irda/
-kernel/drivers/net/ppp/
-kernel/drivers/net/wan/
-kernel/drivers/net/ppp_async.ko
kernel/drivers/net/rionet.ko
kernel/drivers/dca/
kernel/drivers/parport/
-kernel/drivers/parport/parport_serial.ko
kernel/drivers/pnp/
kernel/drivers/scsi/
-kernel/drivers/scsi/ses.ko
kernel/drivers/usb/common/
kernel/drivers/usb/storage/
kernel/drivers/usb/host/
kernel/drivers/usb/core/
kernel/drivers/usb/net/
kernel/drivers/usb/serial/
kernel/drivers/usb/input/usbhid.ko
kernel/drivers/hid/
-kernel/drivers/hid/hid-prodikeys.ko
kernel/drivers/char/nvram.ko
kernel/drivers/char/agp/
kernel/drivers/message/fusion/
kernel/drivers/message/i2o/
kernel/drivers/ps3/
kernel/drivers/mtd/devices/ps3vram.ko
kernel/drivers/mtd/mtd.ko
kernel/drivers/mtd/mtd_blkdevs.ko
kernel/drivers/mtd/mtdblock.ko
kernel/drivers/misc/ioc4.ko
kernel/drivers/ssb/
kernel/drivers/leds/led-class.ko
kernel/drivers/mmc/core/

kernel/fs/9p/
kernel/fs/autofs4/
kernel/fs/binfmt_misc.ko
kernel/fs/btrfs/
kernel/fs/cifs/
kernel/fs/configfs/
kernel/fs/cramfs/
kernel/fs/dmapi/
kernel/fs/efivarfs/
kernel/fs/exfat/
kernel/fs/exofs/libore.ko
kernel/fs/exportfs/
kernel/fs/ext2/
kernel/fs/ext3/
kernel/fs/ext4/
kernel/fs/fat/
kernel/fs/fscache/
kernel/fs/fuse/
kernel/fs/hfs/
kernel/fs/hfsplus/
kernel/fs/hpfs/
kernel/fs/isofs/
kernel/fs/jbd/
kernel/fs/jbd2/
kernel/fs/jfs/
kernel/fs/lockd/
kernel/fs/mbcache.ko
kernel/fs/ncpfs/
kernel/fs/nfs/
kernel/fs/nfs_common/
kernel/fs/nfsd/
kernel/fs/nls/
kernel/fs/ntfs/
kernel/fs/overlayfs/
kernel/fs/smb/
kernel/fs/smbfs/
kernel/fs/squashfs/
kernel/fs/udf/
kernel/fs/vboxsf/
kernel/fs/vfat/
kernel/fs/xfs/

kernel/net/9p/
kernel/net/sunrpc/sunrpc.ko
kernel/net/sunrpc/auth_gss/auth_rpcgss.ko
kernel/net/packet/
kernel/net/rfkill/rfkill.ko
kernel/net/iucv/
kernel/net/ipv6/ipv6.ko
kernel/net/ipv4/gre.ko
kernel/net/ieee80211/
kernel/net/mac80211/mac80211.ko
kernel/net/mac80211/rc80211_simple.ko
kernel/net/wireless/
kernel/net/wimax/
kernel/net/ceph/
kernel/net/802/tr.ko
kernel/net/802/fddi.ko
kernel/net/phonet/phonet.ko
kernel/net/ieee802154/ieee802154.ko
kernel/net/mac802154/
kernel/net/dsa/dsa_core.ko
kernel/net/ipv4/ip_tunnel.ko
kernel/net/dns_resolver/dns_resolver.ko
kernel/net/ipv4/inet_lro.ko
kernel/net/8021q/
kernel/net/802/garp.ko
kernel/net/802/stp.ko
kernel/net/802/mrp.ko
kernel/net/llc/
kernel/net/qrtr

kernel/drivers/power/power_supply.ko
kernel/drivers/firmware/
kernel/drivers/acpi/
kernel/drivers/char/ipmi/
kernel/drivers/video/backlight/
kernel/drivers/mfd/
kernel/drivers/cpufreq/
kernel/arch/x86/kernel/
kernel/drivers/platform/
kernel/drivers/pci/hotplug/pci_hotplug.ko
kernel/sound/soundcore.ko
kernel/sound/core/snd.ko
kernel/drivers/hwmon/hwmon.ko
kernel/drivers/thermal/thermal_sys.ko

# kernel pcmcia
# see data/initrd/initrd_base.list
/pcmcia/
-kernel/drivers/char/pcmcia/synclink_cs.ko
-/sound/pcmcia/

kernel/lib/
kernel/arch/ia64/sn/kernel
kernel/drivers/sn
extra/megaide.ko

kernel/arch/s390/
kernel/drivers/s390/

kernel/crypto/
kernel/arch/[^/]*/crypto/
kernel/drivers/crypto/geode-aes.ko

kernel/drivers/video/vga16fb.ko
kernel/drivers/video/vgastate.ko
kernel/drivers/video/output.ko
kernel/drivers/video/fb_sys_fops.ko
kernel/drivers/video/sysimgblt.ko
kernel/drivers/video/sysfillrect.ko
kernel/drivers/video/syscopyarea.ko
kernel/drivers/video/fbdev/core/

kernel/arch/i386/kernel/msr.ko

kernel/drivers/xen/blkfront/
kernel/drivers/xen/netfront/
kernel/drivers/xen/core/
kernel/drivers/xen/xen-scsiback.ko
kernel/drivers/video/fbdev/xen-fbfront.ko

kernel/drivers/bcma/

kernel/drivers/rtc/
kernel/drivers/mfd/wm8350.ko
kernel/drivers/misc/eeprom/eeprom_93cx6.ko
kernel/drivers/mfd/mc13783-core.ko
kernel/drivers/mfd/mc13xxx-core.ko
kernel/drivers/mfd/mfd-core.ko
kernel/drivers/mfd/sm501.ko

kernel/arch/powerpc/sysdev/bestcomm/bestcomm-fec.ko

kernel/drivers/virtio/

kernel/drivers/usb/wusbcore/
kernel/drivers/uwb/

kernel/drivers/misc/tifm_core.ko
kernel/drivers/usb/misc/ftdi-elan.ko

kernel/drivers/mfd/pcf50633-core.ko

kernel/drivers/connector/
kernel/drivers/uio/uio.ko
kernel/drivers/uio/uio_hv_generic.ko
kernel/drivers/misc/cb710/
kernel/drivers/mfd/ab3100-core.ko
kernel/drivers/gpu/drm/
# kernel/drivers/gpu/drm/drm.ko
kernel/drivers/video/sis/
kernel/drivers/video/fbdev/hyperv_fb.ko

kernel/drivers/misc/lis3lv02d/lis3lv02d.ko
kernel/drivers/misc/cs5535-mfgpt.ko
kernel/drivers/gpio/
kernel/drivers/ptp/
kernel/drivers/pps/pps_core.ko
kernel/drivers/usb/class/cdc-wdm.ko

kernel/drivers/hv/
kernel/drivers/staging/hv/
kernel/drivers/staging/rtl.*

kernel/drivers/usb/misc/ezusb.ko
kernel/drivers/media/rc/rc-core.ko
kernel/sound/ac97_bus.ko
kernel/drivers/target/target_core_mod.ko

kernel/drivers/leds/led-class.ko
kernel/drivers/rapidio/rapidio.ko
kernel/drivers/ntb/ntb.ko

kernel/drivers/target/iscsi/iscsi_target_mod.ko
kernel/drivers/infiniband/

kernel/drivers/vhost/vringh.ko

kernel/drivers/of/
kernel/drivers/tty/serial/jsm/
kernel/drivers/i2c/
kernel/drivers/nvme/
kernel/drivers/nvdimm/
kernel/drivers/usb/dwc2/
kernel/drivers/usb/dwc3/
kernel/drivers/usb/core/ledtrig-usbport.ko
kernel/drivers/phy/
kernel/drivers/regulator/
kernel/drivers/pci/host/
kernel/drivers/pci/controller/
kernel/drivers/mailbox/
kernel/drivers/pinctrl/
kernel/drivers/watchdog/
kernel/drivers/usb/typec/
kernel/drivers/usb/chipidea/
kernel/drivers/usb/phy/
kernel/drivers/usb/isp1760/

kernel/drivers/dma/bcm2835-dma.ko
kernel/drivers/dma/tegra20-apb-dma.ko

kernel/drivers/virt/vboxguest/

# RPi4
kernel/drivers/reset/reset-raspberrypi.ko
kernel/drivers/clk/bcm/clk-raspberrypi.ko
kernel/drivers/cpufreq/raspberrypi-cpufreq.ko
kernel/drivers/cpufreq/cpufreq-dt.ko
kernel/drivers/mmc/host/sdhci-iproc.ko
kernel/drivers/gpio/gpio-raspberrypi-exp.ko
kernel/drivers/net/mdio/mdio-bcm-unimac.ko

kernel/drivers/reset/reset-rzg2l-usbphy-ctrl.ko

# Lenovo X13s (aarch64)
kernel/drivers/clk/qcom/clk-rpmh.ko
kernel/drivers/clk/qcom/dispcc-sc8280xp.ko
kernel/drivers/clk/qcom/gcc-sc8280xp.ko
kernel/drivers/clk/qcom/gpucc-sc8280xp.ko
kernel/drivers/hwspinlock/qcom_hwspinlock.ko
kernel/drivers/interconnect/qcom/qnoc-sc8280xp.ko
kernel/drivers/leds/rgb/leds-qcom-lpg.ko
kernel/drivers/nvmem/nvmem_qcom-spmi-sdam.ko
kernel/drivers/remoteproc/qcom_q6v5.ko
kernel/drivers/remoteproc/qcom_q6v5_pas.ko
kernel/drivers/soc/qcom/pmic_glink.ko
kernel/drivers/soc/qcom/pmic_glink_altmode.ko
kernel/drivers/soc/qcom/smp2p.ko
kernel/drivers/spmi/spmi-pmic-arb.ko
kernel/drivers/spmi/spmi-mtk-pmif.ko

# Qcom rb3gen2
kernel/drivers/interconnect/qcom/qnoc-sc7280.ko
kernel/drivers/ufs/host/ufs-qcom.ko

kernel/drivers/soc/mediatek/mtk-pmic-wrap.ko
kernel/drivers/power/supply/mt6360_charger.ko
kernel/drivers/nvmem/nvmem_mtk-efuse.ko
kernel/drivers/clk/

kernel/drivers/spi/
kernel/drivers/dma/pl330.ko

# kmps
updates/

# ofed-kmp
-updates/drivers/infiniband/
-updates/net/rds/
-updates/net/sunrpc/
-updates/fs/lockd/
-updates/fs/nfs*

<ppc64le>
# for the source of this module list, see bsc#1213879 comment 35
-kernel/drivers/net/wireless/
-kernel/net/ieee80211/
-kernel/net/mac80211/
-kernel/net/wireless/
-kernel/net/wimax/
-kernel/drivers/gpu/
-kernel/drivers/video/
</ppc64le>
0707010000000B000081A400000000000000000000000168E7A1E5000001AE000000000000000000000000000000000000002B00000000image-janitor-0.2.0/data/module.list.extra# This is an extension of the module.list file specially for Agama. It is loaded
# in addition to the module.list file to allow extra overrides or hot fixes
# without touching the original file. The original file should not be touched to
# allow easy updates from the installation-images repository.

# keep the nvmem drivers (https://bugzilla.suse.com/show_bug.cgi?id=1243350)
kernel/drivers/nvmem
kernel/drivers/dma/fsl-edma.ko
0707010000000C000041ED00000000000000000000000268E7A1E500000000000000000000000000000000000000000000001800000000image-janitor-0.2.0/src0707010000000D000081A400000000000000000000000168E7A1E50000034E000000000000000000000000000000000000002300000000image-janitor-0.2.0/src/command.rsuse crate::error::JanitorError;
use std::process::Command;

pub trait CommandRunner {
    fn run(&self, command: &str, args: &[&str]) -> Result<String, JanitorError>;
}

pub struct SystemCommandRunner;

impl CommandRunner for SystemCommandRunner {
    fn run(&self, command: &str, args: &[&str]) -> Result<String, JanitorError> {
        let output = Command::new(command)
            .args(args)
            .output()
            .map_err(|e| JanitorError::Command(format!("Failed to execute '{}': {}", command, e)))?;

        if !output.status.success() {
            return Err(JanitorError::Command(format!(
                "'{}' command failed: {}",
                command,
                String::from_utf8_lossy(&output.stderr)
            )));
        }

        Ok(String::from_utf8(output.stdout).unwrap().trim().to_string())
    }
}
0707010000000E000081A400000000000000000000000168E7A1E500001368000000000000000000000000000000000000002200000000image-janitor-0.2.0/src/config.rsuse crate::command::CommandRunner;
use crate::error::JanitorError;
use log::{debug, info};
use regex::Regex;
use std::fs;

/// Reads the configuration files and returns two lists of regexes: one for keeping and one for deleting.
pub fn read_config(
    paths: &[&str],
    runner: &dyn CommandRunner,
) -> Result<(Vec<Regex>, Vec<Regex>), JanitorError> {
    let mut lines = Vec::<String>::new();
    for path in paths {
        info!("Reading config file: {}", path);
        let content = fs::read_to_string(path)
            .map_err(|e| JanitorError::ConfigRead(path.to_string(), e))?;
        lines.extend(content.lines().map(String::from));
    }

    let lines = lines
        .into_iter()
        .filter(|l| !l.is_empty() && !l.starts_with('#'))
        .collect();

    let arch = get_arch(runner)?;
    debug!("Current architecture: {}", arch);
    let filtered_lines = arch_filter(lines, &arch);

    let (delete_lines, keep_lines): (Vec<_>, Vec<_>) = filtered_lines
        .into_iter()
        .partition(|l| l.starts_with('-'));

    let to_keep = keep_lines
        .into_iter()
        .map(|l| Regex::new(&l).map_err(JanitorError::Regex))
        .collect::<Result<Vec<_>, _>>()?;

    let to_delete = delete_lines
        .into_iter()
        .map(|l| Regex::new(l.strip_prefix('-').unwrap()).map_err(JanitorError::Regex))
        .collect::<Result<Vec<_>, _>>()?;

    Ok((to_keep, to_delete))
}

fn get_arch(runner: &dyn CommandRunner) -> Result<String, JanitorError> {
    runner.run("arch", &[])
}

fn arch_filter(lines: Vec<String>, arch: &str) -> Vec<String> {
    let mut filtered = Vec::new();
    let mut skipping = false;
    let mut arch_tag: Option<String> = None;

    let start_tag_re = Regex::new(r"^\s*<(\w+)\s*>\s*$").unwrap();
    let end_tag_re = Regex::new(r"^\s*</\w+\s*>\s*$").unwrap();

    for line in lines {
        if let Some(captures) = start_tag_re.captures(&line) {
            let tag = captures.get(1).unwrap().as_str().to_string();
            skipping = tag != arch;
            arch_tag = Some(tag);
            continue;
        }

        if end_tag_re.is_match(&line) {
            skipping = false;
            arch_tag = None;
            continue;
        }

        if skipping {
            debug!(
                "Ignoring {} specific line: {}",
                arch_tag.as_deref().unwrap_or(""),
                line
            );
        } else {
            filtered.push(line);
        }
    }

    filtered
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::command::CommandRunner;
    use crate::error::JanitorError;
    use std::collections::HashMap;

    struct MockCommandRunner {
        commands: HashMap<String, String>,
    }

    impl CommandRunner for MockCommandRunner {
        fn run(&self, command: &str, _args: &[&str]) -> Result<String, JanitorError> {
            self.commands
                .get(command)
                .cloned()
                .ok_or_else(|| JanitorError::Command(format!("Command not found: {}", command)))
        }
    }

    #[test]
    fn test_arch_filter() {
        let lines = vec![
            "<x86_64>".to_string(),
            "intel_driver".to_string(),
            "</x86_64>".to_string(),
            "<aarch64>".to_string(),
            "arm_driver".to_string(),
            "</aarch64>".to_string(),
            "<ppc64le>".to_string(),
            "power_driver".to_string(),
            "</ppc64le>".to_string(),
            "<s390x>".to_string(),
            "ibm_driver".to_string(),
            "</s390x>".to_string(),
            "common_driver".to_string(),
        ];

        let x86_64_lines = arch_filter(lines.clone(), "x86_64");
        assert_eq!(x86_64_lines, vec!["intel_driver", "common_driver"]);

        let aarch64_lines = arch_filter(lines.clone(), "aarch64");
        assert_eq!(aarch64_lines, vec!["arm_driver", "common_driver"]);

        let ppc64le_lines = arch_filter(lines.clone(), "ppc64le");
        assert_eq!(ppc64le_lines, vec!["power_driver", "common_driver"]);

        let s390x_lines = arch_filter(lines.clone(), "s390x");
        assert_eq!(s390x_lines, vec!["ibm_driver", "common_driver"]);
    }

    #[test]
    fn test_read_config_with_arch() {
        let mut commands = HashMap::new();
        commands.insert("arch".to_string(), "x86_64".to_string());
        let runner = MockCommandRunner { commands };

        let temp_dir = tempfile::tempdir().unwrap();
        let config_path = temp_dir.path().join("test.conf");
        fs::write(
            &config_path,
            "<x86_64>\n-delete_me\n</x86_64>\n<aarch64>\n-not_me\n</aarch64>\nkeep_me",
        )
        .unwrap();

        let (to_keep, to_delete) =
            read_config(&[config_path.to_str().unwrap()], &runner).unwrap();

        assert_eq!(to_keep.len(), 1);
        assert_eq!(to_delete.len(), 1);
        assert!(to_keep[0].is_match("keep_me"));
        assert!(to_delete[0].is_match("delete_me"));
    }
}
0707010000000F000081A400000000000000000000000168E7A1E50000196D000000000000000000000000000000000000002200000000image-janitor-0.2.0/src/driver.rsuse crate::command::CommandRunner;
use crate::config;
use crate::error::JanitorError;
use crate::util;
use log::{debug, info, warn};
use std::collections::{HashMap, HashSet};
use std::fs;
use std::path::{Path, PathBuf};
use walkdir::WalkDir;

#[derive(Debug, Clone, PartialEq, Eq, Hash)]
struct Driver {
    name: String,
    path: PathBuf,
    deps: Vec<String>,
}

impl Driver {
    fn from_file(path: &Path, runner: &dyn CommandRunner) -> Result<Self, JanitorError> {
        let deps_str = match runner.run("/usr/sbin/modinfo", &["-F", "depends", path.to_str().unwrap()]) {
            Ok(s) => s,
            Err(e) => {
                warn!("modinfo for {} failed: {}", path.display(), e);
                String::new()
            }
        };

        let deps = deps_str
            .trim()
            .split(',')
            .filter(|s| !s.is_empty())
            .map(String::from)
            .collect();

        let name = path
            .file_name()
            .unwrap()
            .to_str()
            .unwrap()
            .split('.')
            .next()
            .unwrap()
            .to_string();

        Ok(Driver { name, path: path.to_path_buf(), deps })
    }
}

pub fn cleanup_drivers(
    config_paths: &[&str],
    module_dir: &Path,
    delete: bool,
    runner: &dyn CommandRunner,
) -> Result<(), JanitorError> {
    let (to_keep_re, to_delete_re) = config::read_config(config_paths, runner)?;
    let kernel_dir = util::find_kernel_dir(module_dir)?;
    info!("Scanning kernel modules in {}", kernel_dir.display());

    let mut driver_map = HashMap::new();
    for entry in WalkDir::new(&kernel_dir) {
        let entry = entry?;
        let path = entry.path();
        if path.is_file()
            && (
                path.extension().is_some_and(|e| e == "ko") ||
                path.to_str().is_some_and(|s| s.ends_with(".ko.xz")) ||
                path.to_str().is_some_and(|s| s.ends_with(".ko.zst"))
            )
        {
            let driver = Driver::from_file(path, runner)?;
            driver_map.insert(driver.name.clone(), driver);
        }
    }

    let mut to_keep: HashSet<Driver> = HashSet::new();

    for driver in driver_map.values() {
        let kernel_path = driver.path.strip_prefix(&kernel_dir).unwrap().to_str()
            .ok_or_else(|| JanitorError::InvalidPath(driver.path.clone()))?;

        if to_delete_re.iter().any(|r| r.is_match(kernel_path)) {
            debug!("Marked for deletion by config: {}", driver.path.display());
        } else if to_keep_re.iter().any(|r| r.is_match(kernel_path)) {
            debug!("Marked for keeping by config: {}", driver.path.display());
            to_keep.insert(driver.clone());
        }
    }

    info!("Checking driver dependencies...");
    let mut worklist: Vec<Driver> = to_keep.iter().cloned().collect();
    while let Some(driver) = worklist.pop() {
        for dep_name in &driver.deps {
            if let Some(dep_driver) = driver_map.get(dep_name) {
                // If the dependency was not already in to_keep, add it and
                // put it on the worklist to process its dependencies.
                if to_keep.insert(dep_driver.clone()) {
                    info!("Keep dependant driver {}", dep_driver.path.display());
                    worklist.push(dep_driver.clone());
                }
            }
        }
    }

    let to_delete: Vec<_> = driver_map.values()
        .filter(|d| !to_keep.contains(d))
        .collect();

    info!("Found {} drivers to delete", to_delete.len());
    debug!("Drivers to delete: {:?}", to_delete.iter().map(|d| &d.path).collect::<Vec<_>>());

    if delete {
        for driver in to_delete {
            info!("Deleting {}", driver.path.display());
            fs::remove_file(&driver.path)?;
        }
    }

    Ok(())
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::command::CommandRunner;
    use std::collections::HashMap;
    use tempfile::tempdir;

    struct MockCommandRunner {
        responses: HashMap<String, String>,
    }

    impl CommandRunner for MockCommandRunner {
        fn run(&self, command: &str, args: &[&str]) -> Result<String, JanitorError> {
            let key = if args.is_empty() {
                command.to_string()
            } else {
                format!("{} {}", command, args.join(" "))
            };
            self.responses.get(&key).cloned().ok_or(JanitorError::Command(format!("Not mocked: {}", key)))
        }
    }

    #[test]
    fn test_cleanup_drivers() {
        let temp_dir = tempdir().unwrap();
        let module_dir = temp_dir.path();
        let kernel_dir = module_dir.join("6.1.0-test");
        fs::create_dir_all(&kernel_dir).unwrap();

        let mod_a_path = kernel_dir.join("a.ko");
        let mod_b_path = kernel_dir.join("b.ko");
        let mod_c_path = kernel_dir.join("c.ko");
        let mod_d_path = kernel_dir.join("d.ko");

        fs::write(&mod_a_path, "").unwrap();
        fs::write(&mod_b_path, "").unwrap();
        fs::write(&mod_c_path, "").unwrap();
        fs::write(&mod_d_path, "").unwrap();

        let config_path = temp_dir.path().join("test.conf");
        fs::write(&config_path, "a.ko").unwrap();

        let mut responses = HashMap::new();
        responses.insert(
            format!("/usr/sbin/modinfo -F depends {}", mod_a_path.display()),
            "b".to_string(),
        );
        responses.insert(
            format!("/usr/sbin/modinfo -F depends {}", mod_b_path.display()),
            "c".to_string(),
        );
        responses.insert(
            format!("/usr/sbin/modinfo -F depends {}", mod_c_path.display()),
            "".to_string(),
        );
        responses.insert(
            format!("/usr/sbin/modinfo -F depends {}", mod_d_path.display()),
            "".to_string(),
        );
        responses.insert("arch".to_string(), "x86_64".to_string());

        let runner = MockCommandRunner { responses };

        // Test dry run
        cleanup_drivers(&[config_path.to_str().unwrap()], module_dir, false, &runner).unwrap();
        assert!(mod_a_path.exists());
        assert!(mod_b_path.exists());
        assert!(mod_c_path.exists());
        assert!(mod_d_path.exists());

        // Test delete
        cleanup_drivers(&[config_path.to_str().unwrap()], module_dir, true, &runner).unwrap();
        assert!(mod_a_path.exists());
        assert!(mod_b_path.exists());
        assert!(mod_c_path.exists());
        assert!(!mod_d_path.exists());
    }
}
07070100000010000081A400000000000000000000000168E7A1E500000265000000000000000000000000000000000000002100000000image-janitor-0.2.0/src/error.rsuse std::path::PathBuf;
use thiserror::Error;

#[derive(Error, Debug)]
pub enum JanitorError {
    #[error("I/O error")]
    Io(#[from] std::io::Error),

    #[error("Regex error")]
    Regex(#[from] regex::Error),

    #[error("Walkdir error")]
    Walkdir(#[from] walkdir::Error),

    #[error("Command failed: {0}")]
    Command(String),

    #[error("No kernel modules directory found in {0}")]
    NoKernelDir(PathBuf),

    #[error("Path does not have a string representation: {0}")]
    InvalidPath(PathBuf),

    #[error("Could not read config file '{0}': {1}")]
    ConfigRead(String, std::io::Error),
}
07070100000011000081A400000000000000000000000168E7A1E500004CD0000000000000000000000000000000000000002400000000image-janitor-0.2.0/src/firmware.rsuse crate::command::CommandRunner;
use crate::error::JanitorError;
use crate::util;
use log::{debug, info};
use path_clean::PathClean;
use std::collections::HashSet;
use std::fs;
use std::path::{Path, PathBuf};
use walkdir::WalkDir;

fn find_kernel_modules(kernel_dir: &Path) -> Result<Vec<PathBuf>, JanitorError> {
    let mut modules = Vec::new();
    for entry in WalkDir::new(kernel_dir) {
        let entry = entry?;
        let path = entry.path();
        if path.is_file()
            && (path.extension().is_some_and(|e| e == "ko")
                || path.to_str().is_some_and(|s| s.ends_with(".ko.xz"))
                || path.to_str().is_some_and(|s| s.ends_with(".ko.zst")))
        {
            modules.push(path.to_path_buf());
        }
    }
    Ok(modules)
}

fn get_firmware_deps_for_module(
    module_path: &Path,
    runner: &dyn CommandRunner,
) -> Result<Vec<String>, JanitorError> {
    let firmware_list = runner.run(
        "/usr/sbin/modinfo",
        &["-F", "firmware", module_path.to_str().unwrap()],
    )?;
    Ok(firmware_list.lines().map(String::from).collect())
}

fn find_firmware_files_from_name(
    fw_name: &str,
    fw_dir: &Path,
) -> Result<Vec<PathBuf>, JanitorError> {
    let pattern = fw_dir.join(fw_name).to_string_lossy().to_string();

    if !fw_name.contains('*') {
        let paths_to_check = vec![
            PathBuf::from(&pattern),
            PathBuf::from(format!("{}.xz", pattern)),
            PathBuf::from(format!("{}.zst", pattern)),
        ];
        Ok(paths_to_check
            .into_iter()
            .filter(|p| p.exists())
            .collect())
    } else {
        let mut results = HashSet::new();
        for ext in ["", ".xz", ".zst"] {
            let pattern_with_ext = format!("{}{}", pattern, ext);
            results.extend(
                glob::glob(&pattern_with_ext)
                    .expect("Failed to read glob pattern")
                    .filter_map(Result::ok),
            );
        }
        Ok(results.into_iter().collect())
    }
}

fn get_required_firmware(
    kernel_dir: &Path,
    fw_dir: &Path,
    runner: &dyn CommandRunner,
) -> Result<HashSet<PathBuf>, JanitorError> {
    let mut required = HashSet::new();
    let kernel_modules = find_kernel_modules(kernel_dir)?;

    for module_path in kernel_modules {
        let firmware_names = get_firmware_deps_for_module(&module_path, runner)?;
        for fw_name in firmware_names {
            let firmware_files = find_firmware_files_from_name(&fw_name, fw_dir)?;
            for fw_file in firmware_files {
                let symlinks = resolve_symlinks(&fw_file, fw_dir)?;
                required.extend(symlinks);
            }
        }
    }
    Ok(required)
}

fn resolve_symlinks(path: &Path, base_dir: &Path) -> Result<Vec<PathBuf>, JanitorError> {
    let mut paths_to_keep = vec![path.to_path_buf()];
    let mut current_path = path.to_path_buf();

    // Limit the number of symlink hops to avoid infinite loops.
    for _ in 0..10 {
        if !fs::symlink_metadata(&current_path)?.file_type().is_symlink() {
            // Not a symlink, so we're at the end of the chain.
            break;
        }

        let target = fs::read_link(&current_path)?;
        // The target of a symlink can be a relative path. We need to resolve it
        // relative to the directory containing the symlink.
        let parent_dir = current_path.parent().unwrap_or_else(|| Path::new(""));
        current_path = parent_dir.join(target).clean();

        // If the resolved path is not within the base directory, we stop.
        if !current_path.starts_with(base_dir) {
            debug!(
                "Symlink target {} is outside the firmware directory.",
                current_path.display()
            );
            return Ok(paths_to_keep);
        }

        // If the path doesn't exist, it's a broken link.
        if !current_path.exists() {
            debug!("Broken symlink found: {}", current_path.display());
            return Ok(paths_to_keep);
        }

        debug!(
            "Adding symlink target {} -> {}",
            path.display(),
            current_path.display()
        );
        paths_to_keep.push(current_path.clone());
    }

    Ok(paths_to_keep)
}

fn remove_unused_files(
    fw_dir: &Path,
    required_fw: &HashSet<PathBuf>,
    delete: bool,
) -> Result<u64, JanitorError> {
    info!("Scanning for unused firmware files...");
    let mut unused_size = 0;

    for entry in WalkDir::new(fw_dir).into_iter().filter_map(Result::ok) {
        let path = entry.path();
        if path.is_file() {
            let relative_path = path.strip_prefix(fw_dir).unwrap().to_path_buf();
            if !required_fw.contains(&relative_path) {
                unused_size += fs::metadata(path)?.len();
                if delete {
                    info!("Deleting unused firmware {}", path.display());
                    fs::remove_file(path)?;
                } else {
                    debug!("Found unused firmware {}", path.display());
                }
            }
        }
    }
    Ok(unused_size)
}

fn remove_dangling_symlinks(fw_dir: &Path) -> Result<(), JanitorError> {
    info!("Removing dangling symlinks...");
    for entry in WalkDir::new(fw_dir).into_iter().filter_map(Result::ok) {
        let path = entry.path();
        if path.is_symlink() {
            // fs::metadata follows symlinks, so it will return an error for a dangling one.
            if fs::metadata(path).is_err() {
                info!("Deleting dangling symlink {}", path.display());
                fs::remove_file(path)?;
            }
        }
    }
    Ok(())
}

fn remove_empty_directories(fw_dir: &Path) -> Result<(), JanitorError> {
    info!("Removing empty directories...");
    // We need to walk from the deepest directories up to ensure parent directories become empty.
    let mut dirs_to_check: Vec<PathBuf> = WalkDir::new(fw_dir)
        .into_iter()
        .filter_map(Result::ok)
        .filter(|e| e.path().is_dir())
        .map(|e| e.path().to_path_buf())
        .collect();

    // Sort by depth, deepest first.
    dirs_to_check.sort_by_key(|p| std::cmp::Reverse(p.components().count()));

    for dir_path in dirs_to_check {
        // Only remove if it's empty and not the root firmware directory itself.
        if dir_path != fw_dir && fs::read_dir(&dir_path)?.next().is_none() {
            info!("Deleting empty directory {}", dir_path.display());
            fs::remove_dir(dir_path)?;
        }
    }
    Ok(())
}

pub fn cleanup_firmware(
    module_dir: &Path,
    fw_dir: &Path,
    delete: bool,
    runner: &dyn CommandRunner,
) -> Result<(), JanitorError> {
    let kernel_dir = util::find_kernel_dir(module_dir)?;
    info!("Scanning kernel modules in {}", kernel_dir.display());

    let required_fw_abs = get_required_firmware(&kernel_dir, fw_dir, runner)?;
    let required_fw: HashSet<_> = required_fw_abs.into_iter()
        .map(|p| p.strip_prefix(fw_dir).unwrap().to_path_buf())
        .collect();

    let unused_size = remove_unused_files(fw_dir, &required_fw, delete)?;

    if delete {
        remove_dangling_symlinks(fw_dir)?;
        remove_empty_directories(fw_dir)?;
    }

    info!("Potential savings: {} ({} MiB)", unused_size, unused_size >> 20);

    Ok(())
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::command::CommandRunner;
    use std::collections::HashMap;
    use std::os::unix::fs::symlink;
    use tempfile::tempdir;

    struct MockCommandRunner {
        responses: HashMap<String, String>,
    }

    impl CommandRunner for MockCommandRunner {
        fn run(&self, command: &str, args: &[&str]) -> Result<String, JanitorError> {
            let key = if args.is_empty() {
                command.to_string()
            } else {
                format!("{} {}", command, args.join(" "))
            };
            self.responses.get(&key).cloned().ok_or(JanitorError::Command(format!("Not mocked: {}", key)))
        }
    }

    #[test]
    fn test_get_required_firmware() {
        let temp_dir = tempdir().unwrap();
        let kernel_dir = temp_dir.path().join("lib/modules/6.1.0-test");
        fs::create_dir_all(&kernel_dir).unwrap();
        let fw_dir = temp_dir.path().join("lib/firmware");
        fs::create_dir_all(&fw_dir).unwrap();

        let mod1_path = kernel_dir.join("mod1.ko");
        fs::write(&mod1_path, "").unwrap();
        let fw1_path = fw_dir.join("fw1.bin");
        fs::write(&fw1_path, "").unwrap();

        let mut responses = HashMap::new();
        responses.insert(
            format!("/usr/sbin/modinfo -F firmware {}", mod1_path.display()),
            "fw1.bin".to_string(),
        );
        let runner = MockCommandRunner { responses };

        let required_fw = get_required_firmware(&kernel_dir, &fw_dir, &runner).unwrap();
        assert_eq!(required_fw.len(), 1);
        assert!(required_fw.contains(&fw1_path));
    }

    #[test]
    fn test_get_required_firmware_with_wildcard() {
        let temp_dir = tempdir().unwrap();
        let kernel_dir = temp_dir.path().join("lib/modules/6.1.0-test");
        fs::create_dir_all(&kernel_dir).unwrap();
        let fw_dir = temp_dir.path().join("lib/firmware");
        fs::create_dir_all(&fw_dir).unwrap();

        let mod1_path = kernel_dir.join("mod1.ko");
        fs::write(&mod1_path, "").unwrap();

        let fw_file1 = fw_dir.join("brcm/brcmfmac43430-sdio.bin");
        let fw_file2 = fw_dir.join("brcm/brcmfmac43430-sdio.txt");
        fs::create_dir_all(fw_dir.join("brcm")).unwrap();
        fs::write(&fw_file1, "").unwrap();
        fs::write(&fw_file2, "").unwrap();

        let mut responses = HashMap::new();
        responses.insert(
            format!("/usr/sbin/modinfo -F firmware {}", mod1_path.display()),
            "brcm/brcmfmac*-sdio.bin".to_string(),
        );
        let runner = MockCommandRunner { responses };

        let required_fw = get_required_firmware(&kernel_dir, &fw_dir, &runner).unwrap();
        assert_eq!(required_fw.len(), 1);
        assert!(required_fw.contains(&fw_file1));
        assert!(!required_fw.contains(&fw_file2));
    }

    #[test]
    fn test_resolve_symlinks_single_file() {
        let temp_dir = tempdir().unwrap();
        let file_path = temp_dir.path().join("file.bin");
        fs::write(&file_path, "data").unwrap();

        let resolved = resolve_symlinks(&file_path, temp_dir.path()).unwrap();
        assert_eq!(resolved, vec![file_path]);
    }

    #[test]
    fn test_resolve_symlinks_linear_chain() {
        let temp_dir = tempdir().unwrap();
        let base_dir = temp_dir.path();
        let file_path = base_dir.join("file.bin");
        let link1_path = base_dir.join("link1");
        let link2_path = base_dir.join("link2");
        let link3_path = base_dir.join("link3");

        fs::write(&file_path, "data").unwrap();
        symlink(&file_path, &link1_path).unwrap();
        symlink(&link1_path, &link2_path).unwrap();
        symlink(&link2_path, &link3_path).unwrap();

        let resolved = resolve_symlinks(&link3_path, base_dir).unwrap();

        // The new implementation returns the starting link and all intermediate links/targets.
        assert_eq!(resolved.len(), 4);
        assert!(resolved.contains(&file_path));
        assert!(resolved.contains(&link1_path));
        assert!(resolved.contains(&link2_path));
        assert!(resolved.contains(&link3_path));
    }

    #[test]
    fn test_resolve_symlinks_broken_link() {
        let temp_dir = tempdir().unwrap();
        let base_dir = temp_dir.path();
        let link_path = base_dir.join("link");

        symlink("non_existent_file", &link_path).unwrap();

        let resolved = resolve_symlinks(&link_path, base_dir).unwrap();
        // fs::canonicalize fails on broken links, so only the original path is returned.
        assert_eq!(resolved, vec![link_path]);
    }

    #[test]
    fn test_resolve_symlinks_cycle() {
        let temp_dir = tempdir().unwrap();
        let base_dir = temp_dir.path();
        let link1_path = base_dir.join("link1");
        let link2_path = base_dir.join("link2");

        symlink(&link2_path, &link1_path).unwrap();
        symlink(&link1_path, &link2_path).unwrap();

        let resolved = resolve_symlinks(&link1_path, base_dir).unwrap();
        // fs::canonicalize fails on link cycles, so only the original path is returned.
        assert_eq!(resolved.len(), 1);
        assert!(resolved.contains(&link1_path));
    }

    #[test]
    fn test_remove_unused_files() {
        let temp_dir = tempdir().unwrap();
        let fw_dir = temp_dir.path();

        let required_file_path = PathBuf::from("required.bin");
        let unused_file_path = PathBuf::from("unused.bin");

        fs::write(fw_dir.join(&required_file_path), "required_data").unwrap();
        fs::write(fw_dir.join(&unused_file_path), "unused_data").unwrap();

        let mut required_fw = HashSet::new();
        required_fw.insert(required_file_path.clone());

        // Test without deleting
        let unused_size = remove_unused_files(fw_dir, &required_fw, false).unwrap();
        assert_eq!(unused_size, 11); // "unused_data".len()
        assert!(fw_dir.join(&unused_file_path).exists());
        assert!(fw_dir.join(&required_file_path).exists());

        // Test with deleting
        let unused_size_del = remove_unused_files(fw_dir, &required_fw, true).unwrap();
        assert_eq!(unused_size_del, 11);
        assert!(!fw_dir.join(&unused_file_path).exists());
        assert!(fw_dir.join(&required_file_path).exists());
    }

    #[test]
    fn test_remove_dangling_symlinks() {
        let temp_dir = tempdir().unwrap();
        let fw_dir = temp_dir.path();

        let target_file = fw_dir.join("target.bin");
        let valid_symlink = fw_dir.join("valid_link");
        let dangling_symlink = fw_dir.join("dangling_link");

        fs::write(&target_file, "data").unwrap();
        symlink(&target_file, &valid_symlink).unwrap();
        symlink("non_existent_file", &dangling_symlink).unwrap();

        assert!(dangling_symlink.is_symlink());

        remove_dangling_symlinks(fw_dir).unwrap();

        assert!(valid_symlink.exists());
        assert!(!dangling_symlink.exists());
        assert!(!dangling_symlink.is_symlink()); // Should be completely gone
    }

    #[test]
    fn test_remove_empty_directories() {
        let temp_dir = tempdir().unwrap();
        let fw_dir = temp_dir.path();

        // Create a structure of directories
        let dir_a = fw_dir.join("a");
        let dir_b = dir_a.join("b"); // Will be empty
        let dir_c = dir_a.join("c");
        let dir_d = fw_dir.join("d"); // Will be empty

        fs::create_dir_all(&dir_b).unwrap();
        fs::create_dir_all(&dir_c).unwrap();
        fs::create_dir_all(&dir_d).unwrap();

        // Add a file to make dir_c non-empty
        fs::write(dir_c.join("file.txt"), "data").unwrap();

        assert!(dir_b.exists());
        assert!(dir_d.exists());

        remove_empty_directories(fw_dir).unwrap();

        // Assert empty directories are removed
        assert!(!dir_b.exists());
        assert!(!dir_d.exists());

        // Assert non-empty directories (and the root) remain
        assert!(dir_a.exists());
        assert!(dir_c.exists());
        assert!(fw_dir.exists());

        // Run again to ensure it handles the case where 'a' is now empty
        fs::remove_dir_all(&dir_c).unwrap();
        remove_empty_directories(fw_dir).unwrap();
        assert!(!dir_a.exists());
    }

    #[test]
    fn test_find_kernel_modules() {
        let temp_dir = tempdir().unwrap();
        let kernel_dir = temp_dir.path();

        let mod1 = kernel_dir.join("module1.ko");
        let mod2 = kernel_dir.join("module2.ko.xz");
        let mod3 = kernel_dir.join("module3.ko.zst");
        let not_a_mod = kernel_dir.join("not_a_module.txt");
        let nested_dir = kernel_dir.join("nested");
        fs::create_dir(&nested_dir).unwrap();
        let nested_mod = nested_dir.join("nested.ko");

        fs::write(&mod1, "").unwrap();
        fs::write(&mod2, "").unwrap();
        fs::write(&mod3, "").unwrap();
        fs::write(&not_a_mod, "").unwrap();
        fs::write(&nested_mod, "").unwrap();

        let mut found = find_kernel_modules(kernel_dir).unwrap();
        found.sort();

        let mut expected = vec![mod1, mod2, mod3, nested_mod];
        expected.sort();

        assert_eq!(found, expected);
    }

    #[test]
    fn test_find_firmware_files_from_name() {
        let temp_dir = tempdir().unwrap();
        let fw_dir = temp_dir.path();

        let fw1 = fw_dir.join("iwlwifi-1.bin");
        let fw2_xz = fw_dir.join("iwlwifi-2.bin.xz");
        let fw3_zst = fw_dir.join("iwlwifi-3.bin.zst");
        let other_file = fw_dir.join("other.txt");

        fs::write(&fw1, "").unwrap();
        fs::write(&fw2_xz, "").unwrap();
        fs::write(&fw3_zst, "").unwrap();
        fs::write(&other_file, "").unwrap();

        // Test exact name matching with compressed variants
        let mut found1 = find_firmware_files_from_name("iwlwifi-1.bin", fw_dir).unwrap();
        found1.sort();
        assert_eq!(found1, vec![fw1.clone()]);

        let mut found2 = find_firmware_files_from_name("iwlwifi-2.bin", fw_dir).unwrap();
        found2.sort();
        assert_eq!(found2, vec![fw2_xz.clone()]);

        // Test glob matching
        let mut found_glob = find_firmware_files_from_name("iwlwifi-*", fw_dir).unwrap();
        found_glob.sort();
        let mut expected_glob = vec![fw1.clone(), fw2_xz.clone(), fw3_zst.clone()];
        expected_glob.sort();
        assert_eq!(found_glob, expected_glob);
    }

    #[test]
    fn test_get_required_firmware_with_wildcard_and_compression() {
        let temp_dir = tempdir().unwrap();
        let kernel_dir = temp_dir.path().join("lib/modules/6.1.0-test");
        fs::create_dir_all(&kernel_dir).unwrap();
        let fw_dir = temp_dir.path().join("lib/firmware");
        fs::create_dir_all(&fw_dir).unwrap();

        let mod1_path = kernel_dir.join("mod1.ko");
        fs::write(&mod1_path, "").unwrap();

        let fw_file1 = fw_dir.join("brcm/brcmfmac43430-sdio.bin.xz");
        let fw_file2 = fw_dir.join("brcm/brcmfmac43430-sdio.txt");
        fs::create_dir_all(fw_dir.join("brcm")).unwrap();
        fs::write(&fw_file1, "").unwrap();
        fs::write(&fw_file2, "").unwrap();

        let mut responses = HashMap::new();
        responses.insert(
            format!("/usr/sbin/modinfo -F firmware {}", mod1_path.display()),
            "brcm/brcmfmac*-sdio.bin".to_string(),
        );
        let runner = MockCommandRunner { responses };

        let required_fw = get_required_firmware(&kernel_dir, &fw_dir, &runner).unwrap();
        assert_eq!(required_fw.len(), 1);
        assert!(required_fw.contains(&fw_file1));
        assert!(!required_fw.contains(&fw_file2));
    }

    #[test]
    fn test_resolve_symlinks_relative() {
        let temp_dir = tempdir().unwrap();
        let base_dir = temp_dir.path();
        let file_path = base_dir.join("file.bin");
        let dir1 = base_dir.join("dir1");
        let dir2 = dir1.join("dir2");
        let link_path = dir2.join("link");

        fs::create_dir_all(&dir2).unwrap();
        fs::write(&file_path, "data").unwrap();
        symlink("../../file.bin", &link_path).unwrap();

        let resolved = resolve_symlinks(&link_path, base_dir).unwrap();

        assert_eq!(resolved.len(), 2);
        assert!(resolved.contains(&file_path));
        assert!(resolved.contains(&link_path));
    }
}
07070100000012000081A400000000000000000000000168E7A1E500000060000000000000000000000000000000000000001F00000000image-janitor-0.2.0/src/lib.rspub mod config;
pub mod driver;
pub mod error;
pub mod firmware;
pub mod util;
pub mod command;
07070100000013000081A400000000000000000000000168E7A1E500000997000000000000000000000000000000000000002000000000image-janitor-0.2.0/src/main.rsuse anyhow::Result;
use clap::Parser;
use env_logger::Env;
use image_janitor::{command::SystemCommandRunner, driver, firmware};
use log::info;
use std::path::PathBuf;

#[derive(Parser)]
#[command(author, version, about, long_about = None)]
struct Cli {
    #[command(subcommand)]
    command: Commands,

    /// Enable verbose logging.
    #[arg(short, long, default_value_t = false)]
    verbose: bool,
}

#[derive(clap::Subcommand)]
enum Commands {
    /// Cleans up unused kernel drivers.
    DriverCleanup {
        /// Really delete the files.
        #[arg(long)]
        delete: bool,

        /// Directory with kernel modules.
        #[arg(long, default_value = "/lib/modules")]
        module_dir: PathBuf,

        /// Paths to module list configuration files.
        #[arg(long, default_value = "module.list,module.list.extra")]
        config_files: String,
    },
    /// Cleans up unused firmware.
    FwCleanup {
        /// Really delete the files.
        #[arg(long)]
        delete: bool,

        /// Directory with kernel modules.
        #[arg(long, default_value = "/lib/modules")]
        module_dir: PathBuf,

        /// Directory with firmware files.
        #[arg(long, default_value = "/lib/firmware")]
        firmware_dir: PathBuf,
    },
}

fn main() -> Result<()> {
    let cli = Cli::parse();

    let log_level = if cli.verbose { "debug" } else { "info" };
    env_logger::Builder::from_env(Env::default().default_filter_or(log_level)).init();

    let runner = SystemCommandRunner;

    match &cli.command {
        Commands::DriverCleanup {
            delete,
            module_dir,
            config_files,
        } => {
            info!(
                "Driver cleanup running. Delete: {}, Module Dir: {}",
                delete,
                module_dir.display()
            );
            let config_paths: Vec<&str> = config_files.split(',').collect();
            driver::cleanup_drivers(&config_paths, module_dir, *delete, &runner)?;
        }
        Commands::FwCleanup {
            delete,
            module_dir,
            firmware_dir,
        } => {
            info!(
                "Firmware cleanup running. Delete: {}, Module Dir: {}, Firmware Dir: {}",
                delete,
                module_dir.display(),
                firmware_dir.display()
            );
            firmware::cleanup_firmware(module_dir, firmware_dir, *delete, &runner)?;
        }
    }

    Ok(())
}07070100000014000081A400000000000000000000000168E7A1E5000008FE000000000000000000000000000000000000002000000000image-janitor-0.2.0/src/util.rsuse crate::error::JanitorError;
use std::fs;
use std::path::{Path, PathBuf};

pub fn find_kernel_dir(module_dir: &Path) -> Result<PathBuf, JanitorError> {
    if !module_dir.exists() {
        return Err(JanitorError::NoKernelDir(module_dir.to_path_buf()));
    }
    let mut entries = fs::read_dir(module_dir)?
        .filter_map(Result::ok)
        .map(|e| e.path())
        .filter(|p| p.is_dir())
        .collect::<Vec<_>>();

    // Sort to get a deterministic order (e.g., latest version).
    entries.sort();

    // In the Live ISO there should be just one kernel installed, but if there are more,
    // we take the last one, which is likely the newest version.
    entries
        .pop()
        .ok_or_else(|| JanitorError::NoKernelDir(module_dir.to_path_buf()))
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::error::JanitorError;
    use std::fs;

    #[test]
    fn test_find_kernel_dir_success() {
        let temp_dir = tempfile::tempdir().unwrap();
        let modules_dir = temp_dir.path();
        let kernel_dir_name = "6.1.0-test";
        let kernel_dir = modules_dir.join(kernel_dir_name);
        fs::create_dir(&kernel_dir).unwrap();

        let found_dir = find_kernel_dir(modules_dir).unwrap();
        assert_eq!(found_dir, kernel_dir);
    }

    #[test]
    fn test_find_kernel_dir_no_subdirectories() {
        let temp_dir = tempfile::tempdir().unwrap();
        let modules_dir = temp_dir.path();

        let result = find_kernel_dir(modules_dir);
        assert!(matches!(result, Err(JanitorError::NoKernelDir(_))));
    }

    #[test]
    fn test_find_kernel_dir_non_existent_path() {
        let temp_dir = tempfile::tempdir().unwrap();
        let modules_dir = temp_dir.path().join("non_existent");

        let result = find_kernel_dir(&modules_dir);
        assert!(matches!(result, Err(JanitorError::NoKernelDir(_))));
    }

    #[test]
    fn test_find_kernel_dir_prefers_last_entry() {
        let temp_dir = tempfile::tempdir().unwrap();
        let modules_dir = temp_dir.path();
        fs::create_dir(modules_dir.join("6.0.0-test")).unwrap();
        fs::create_dir(modules_dir.join("6.1.0-test")).unwrap(); // This should be picked due to sorting

        assert!(find_kernel_dir(modules_dir).unwrap().ends_with("6.1.0-test"));
    }
}07070100000000000000000000000000000000000000010000000000000000000000000000000000000000000000000000000B00000000TRAILER!!!173 blocks
openSUSE Build Service is sponsored by