-**This software is still in an early stage of development. Check out the issues, and feel free to contribute!**
+This is a detached fork of the [UAD project](https://github.com/0x192/universal-android-debloater). This aims to improve privacy and efficiency (energy, speed, memory) by removing unnecessary and obscure system apps.
+This can also improve security by reducing the [attack surface](https://en.wikipedia.org/wiki/Attack_surface). Read [the wiki](https://github.com/Universal-Debloater-Alliance/universal-android-debloater-next-generation/wiki) for more details.
-## Summary
+## Documentation
-This is a complete rewrite in Rust of the [UAD project](https://gitlab.com/W1nst0n/universal-android-debloater),
-which aims to improve privacy and battery performance by removing unnecessary
-and obscure system apps.
-This can also contribute to improving security by reducing [the attack surface](https://en.wikipedia.org/wiki/Attack_surface).
+Everything about UAD-ng (and related stuff) can be found on the Wiki, such as:
-Packages are as well documented as possible to provide a better understanding
-of what you can delete or not. The worst issue that could happen is removing
-an essential system package needed during boot causing then an unfortunate
-bootloop. After about 5 failed system boots, the phone will automatically reboot
-in recovery mode, and you'll have to perform a FACTORY RESET. Make a backup first!
+- [Getting started](https://github.com/Universal-Debloater-Alliance/universal-android-debloater-next-generation/wiki/Getting-started)
+- Features of this app
+- [Usage guide](https://github.com/Universal-Debloater-Alliance/universal-android-debloater-next-generation/wiki/Usage)
+- Suggested Android app replacements
+- How to get the cutting-edge version by [building the source-code](https://github.com/Universal-Debloater-Alliance/universal-android-debloater-next-generation/wiki/Building-from-source)
+- Weird things OEMs do
+- [Suggested apps for analyzing APKs](https://github.com/Universal-Debloater-Alliance/universal-android-debloater-next-generation/wiki/How-to-contribute#useful-apps)
-In any case, you **CANNOT** brick your device with this software!
-That's the main point, right?
+## Privacy
-## Features
+UAD-ng does not collect or transmit any user data. The only external connections are `GET` requests to GitHub for fetching the [package list](https://github.com/Universal-Debloater-Alliance/universal-android-debloater-next-generation/blob/main/resources/assets/uad_lists.json) ([src/core/uad_lists.rs](src/core/uad_lists.rs)) and checking for updates ([src/core/update.rs](src/core/update.rs)).
-- [x] Uninstall/Disable and Restore/Enable system packages
-- [x] Multi-user support (e.g. apps in work profiles)
-- [x] Export/Import your selection in `uad_exported_selection.txt`
-- [x] Multi-device support: you can connect multiple phones at the same time
-- [x] All your actions are logged, so you never forget what you've done
+## Contact
-NB : System apps cannot truly be uninstalled without root (see the [FAQ](https://github.com/Universal-Debloater-Alliance/universal-android-debloater/wiki/FAQ))
+**For real-time communication and support, consider joining our Discord guild:**
-## Universal Debloat Lists
+[](https://discord.gg/CzwbMCPEZa)
-- [x] GFAM (Google/Facebook/Amazon/Microsoft)
-- [x] AOSP
-- [x] Manufacturers (OEM)
-- [x] Mobile carriers
-- [x] Qualcomm / Mediatek / Miscellaneous
+**If you prefer using Matrix, we have a bridge to Discord:**
-## Manufacturers debloat lists
-* [ ] Archos
-* [X] Asus
-* [ ] Blackberry
-* [X] Fairphone
-* [ ] Gionee
-* [X] Google
-* [x] Honor
-* [ ] HTC
-* [X] Huawei
-* [X] iQOO
-* [X] LG
-* [X] Lenovo
-* [X] Motorola
-* [X] Nokia
-* [X] Nubia
-* [X] Nothing Phone
-* [X] OnePlus
-* [X] Oppo
-* [X] Realme
-* [X] Samsung
-* [X] Sony
-* [X] Tecno
-* [X] TCL
-* [X] Unihertz
-* [X] Vivo/iQOO
-* [X] Wiko
-* [X] Xiaomi
-* [X] ZTE
+[](https://matrix.to/#/#uad-ng:matrix.org)
-## Mobile carriers debloat lists
+## Friends
-| Country | Carriers |
-| ------- | ------------------------------- |
-| France | Orange, SFR, Free, Bouygues |
-| USA | T-Mobile, Verizon, Sprint, AT&T |
-| Germany | Telekom |
-| UK | EE |
+Several projects integrate with or depend on UAD-ng's data and tools:
-## How to use it
+- **[Canta](https://github.com/samolego/Canta)** — A mobile Android debloater that uses Shizuku for rootless privilege escalation. It integrates with UAD-ng's Universal Debloat List to provide safe package recommendations without requiring a PC.
-- **Read the [FAQ](https://github.com/Universal-Debloater-Alliance/universal-android-debloater/wiki/FAQ)!**
-- **Do a proper backup of your data! You can never be too careful!**
-- Enable _Developer Options_ on your smartphone.
-- Turn on _USB Debugging_ from the developer panel.
-- From the settings, disconnect from any OEM accounts (when you delete an OEM
- account package it could lock you on the lock screen because the phone can't
- associate your identity anymore)
-- Install ADB (see the instructions by clicking on your OS below):
-
-
- WINDOWS
-
- - Download [android platform tools](https://dl.google.com/android/repository/platform-tools-latest-windows.zip)
- and unzip it somewhere.
- - [Add the android platform tools to your PATH](https://www.architectryan.com/2018/03/17/add-to-the-path-on-windows-10/)
- **OR** make sure to launch UAD from the same directory.
-
- - [Install USB drivers for your device](https://developer.android.com/studio/run/oem-usb#Drivers)
- - Check your device is detected:
-
- ```bash
- adb devices
- ```
-
-
-
-
-- Download the latest release of UAD GUI for your Operating System [here](https://github.com/Universal-Debloater-Alliance/universal-android-debloater/releases). Take the `opengl` version only if the default version (with a Vulkan backend) doesn't launch.
-
-**NOTE:** Chinese phone users may need to use the AOSP list to remove some stock
-apps because those Chinese manufacturers (especially Xiaomi and Huawei) have been
-using the name of AOSP packages for their own (modified & closed-source) apps.
-
-**IMPORTANT NOTE:** You will have to run this software whenever your OEM pushes
-an update to your phone as some _uninstalled_ system apps could be reinstalled.
-
-## How to contribute
-
-Hey-hey-hey! Don't go away so fast! This is a community project.
-That means I need you! I'm sure you want to make this project better anyway.
-
-==> [How to contribute](https://github.com/Universal-Debloater-Alliance/universal-android-debloater/wiki)
+- **Projects by [Muntashir Akon](https://github.com/MuntashirAkon):**
+ - **[AppManager](https://github.com/MuntashirAkon/AppManager)** — An advanced Android app manager with powerful debloating features.
+ - **[android-debloat-list](https://github.com/MuntashirAkon/android-debloat-list)** — A comprehensive, community-driven list of Android packages to debloat, based on UAD-ng's list.
## Special thanks
-- [@mawilms](https://github.com/mawilms) for his LotRO plugin manager ([Lembas](https://github.com/mawilms/lembas))
- which helped me a lot to understand how to use the [Iced](https://github.com/hecrj/iced)
- GUI library.
+- [@0x192](https://github.com/0x192) who created the original UAD project.
+- [@mawilms](https://github.com/mawilms) for his LotRO plugin manager ([Lembas](https://github.com/mawilms/lembas)) which helped a lot to understand how to use the [Iced](https://github.com/iced-rs/iced) GUI library.
- [@casperstorm](https://github.com/casperstorm) for the UI/UX inspiration.
diff --git a/RELEASE.md b/RELEASE.md
new file mode 100644
index 0000000..c029638
--- /dev/null
+++ b/RELEASE.md
@@ -0,0 +1,38 @@
+# Release management
+
+## Semantic versioning
+
+We're making use of [semantic versioning](https://semver.org/). We use semantic versioning for two things:
+
+1. GitHub Milestones
+1. UAD-ng releases
+
+Speaking of milestones: it could be that we have a bug-fix release (e.g. 1.0.3), but a contributor submits a PR that adds a new feature. What do we do? Merge after we released 1.0.3? Change the name of the milestone to for example 1.1.0? Or another approach?
+
+In that case, we should closely review the PR and 'compare' it with what semantic versioning has to say about the submitted feature. If the changes are significant enough, we're renaming the milestone to (for example) 1.1.0.
+
+## Checklist before releasing a new version
+
+- [ ] Make sure the Milestone is completed and if not, check what needs to be done to complete it.
+- [ ] Make sure all merged PRs regarding the application follow the Conventional Commit Messages style. This makes sure that when generating a changelog, the changes look consistent, which in turn improves readability.
+- [ ] Make sure all merged PRs have the correct labels assigned, as the changelog is generated based on labels.
+- [ ] Create a release preparation PR that bumps the UAD-ng version in `Cargo.toml` and `Cargo.lock`.
+
+When all the above has been checked, you can push a tag to `main` to trigger the GitHub Action that creates a release:
+
+- Create the tag: `git tag -s v1.2.3 -am '1.2.3'`
+- Push the tag: `git push origin v1.2.3`
+
+Change the version number to whatever version we're releasing.
+
+## Development process
+
+1. Update dependencies right after a new release, so that we start a new milestone with updated dependencies
+1. On-going development of bug-fixes and new features etc, along with fixing potential bugs, potentially due to the updated dependencies
+1. Release
+
+## Faulty releases
+
+If we publish a faulty release, for example containing a critical bug, this is how we should deal with it:
+
+We issue a hotfix and keep the faulty release but we'll add warnings to the faulty release in the changelog.
diff --git a/build.rs b/build.rs
new file mode 100644
index 0000000..e2bbb62
--- /dev/null
+++ b/build.rs
@@ -0,0 +1,11 @@
+const META: &str = "resources/assets/manifest.rc";
+
+fn main() -> Result<(), Box> {
+ println!("cargo::rerun-if-changed={META}");
+ if std::env::var("CARGO_CFG_TARGET_FAMILY")? == "windows" {
+ embed_resource::compile(META, embed_resource::NONE)
+ .manifest_optional()
+ .unwrap();
+ }
+ Ok(())
+}
diff --git a/clippy.toml b/clippy.toml
new file mode 100644
index 0000000..ea830ad
--- /dev/null
+++ b/clippy.toml
@@ -0,0 +1,7 @@
+disallowed-types = [
+ { path = "iced::widget::Text", reason = "Use [`crate::gui::widgets::text`] instead. For further details, see #523 and #858" },
+]
+
+disallowed-methods= [
+ { path = "iced::widget::text", reason = "Use [`crate::gui::widgets::text`] instead. For further details, see #523 and #858" },
+]
diff --git a/crates/uad-cli/Cargo.toml b/crates/uad-cli/Cargo.toml
new file mode 100644
index 0000000..6045f95
--- /dev/null
+++ b/crates/uad-cli/Cargo.toml
@@ -0,0 +1,52 @@
+[package]
+name = "uad-cli"
+version.workspace = true
+authors.workspace = true
+license.workspace = true
+homepage.workspace = true
+repository.workspace = true
+readme.workspace = true
+keywords.workspace = true
+categories = ["command-line-utilities"]
+edition.workspace = true
+
+[[bin]]
+name = "uad"
+path = "src/main.rs"
+
+[dependencies]
+uad-core = { path = "../uad-core" }
+clap.workspace = true
+clap_complete = "4.4"
+tokio.workspace = true
+serde.workspace = true
+serde_json.workspace = true
+log.workspace = true
+chrono.workspace = true
+toml.workspace = true
+dirs.workspace = true
+ureq.workspace = true
+retry.workspace = true
+csv.workspace = true
+rustyline = "14.0"
+
+[lints.rust]
+deprecated_safe = "warn"
+
+[lints.clippy]
+undocumented_unsafe_blocks = "deny"
+exit = "deny"
+panic_in_result_fn = "warn"
+infinite_loop = "warn"
+mem_forget = "warn"
+implicit_clone = "warn"
+format_push_string = "warn"
+large_include_file = "warn"
+shadow_unrelated = "warn"
+struct_field_names = "allow" # annoying
+
+disallowed_types = "deny"
+disallowed_methods = "deny"
+
+allow_attributes_without_reason = "warn"
+pedantic = { level = "warn", priority = -1 }
diff --git a/crates/uad-cli/examples/usage.sh b/crates/uad-cli/examples/usage.sh
new file mode 100755
index 0000000..ab3192e
--- /dev/null
+++ b/crates/uad-cli/examples/usage.sh
@@ -0,0 +1,44 @@
+#!/usr/bin/env bash
+
+# Example usage script for UAD CLI
+
+# Check if uad-cli is available
+if ! command -v uad &> /dev/null; then
+ echo "uad command not found. Please build and install uad-cli first."
+ exit 1
+fi
+
+echo "=== UAD CLI Usage Examples ==="
+echo
+
+echo "1. List connected devices:"
+uad devices
+echo
+
+echo "2. List all enabled packages:"
+uad list --state enabled | head -20
+echo "... (showing first 20)"
+echo
+
+echo "3. Search for Google packages:"
+uad list --search google | head -10
+echo "... (showing first 10)"
+echo
+
+echo "4. Show info about a package (example):"
+echo "uad info com.google.android.gms"
+echo
+
+echo "5. Dry-run uninstall (safe to test):"
+echo "uad uninstall com.example.package --dry-run"
+echo
+
+echo "6. Start interactive mode:"
+echo "uad repl"
+echo
+
+echo "=== Generate shell completions ==="
+echo "For bash: uad completions bash > ~/.local/share/bash-completion/completions/uad"
+echo "For zsh: uad completions zsh > ~/.local/share/zsh/site-functions/_uad"
+echo "For fish: uad completions fish > ~/.config/fish/completions/uad.fish"
+
diff --git a/crates/uad-cli/src/commands.rs b/crates/uad-cli/src/commands.rs
new file mode 100644
index 0000000..62286bd
--- /dev/null
+++ b/crates/uad-cli/src/commands.rs
@@ -0,0 +1,470 @@
+use clap::CommandFactory;
+use clap_complete::{Shell, generate};
+use std::collections::{HashMap, HashSet};
+use std::io::Write;
+use uad_core::adb::{ACommand, PmListPacksFlag};
+use uad_core::sync::{
+ CorePackage, Phone, User, apply_pkg_state_commands, get_devices_list, get_package_state,
+ run_adb_shell_action,
+};
+use uad_core::uad_lists::{Package, PackageState, Removal, UadList, load_debloat_lists};
+use uad_core::utils::{matches_search, truncate_description};
+
+use crate::device::{NO_DEVICES_FOUND, get_target_device, get_user};
+use crate::filters::{ListFilter, RemovalFilter, StateFilter};
+use crate::{Cli, print_or_exit, println_or_exit};
+
+/// List all connected Android devices
+pub fn list_devices() -> Result<(), Box> {
+ println_or_exit!("Scanning for connected devices...");
+ let devices = get_devices_list();
+
+ if devices.is_empty() {
+ return Err(NO_DEVICES_FOUND.into());
+ }
+
+ println_or_exit!("\nFound {} device(s):\n", devices.len());
+ for device in &devices {
+ println_or_exit!(" Model: {}", device.model);
+ println_or_exit!(" Serial: {}", device.adb_id);
+ println_or_exit!(" Android SDK: {}", device.android_sdk);
+
+ if !device.user_list.is_empty() {
+ println_or_exit!(" Users: {} user(s)", device.user_list.len());
+ for user in &device.user_list {
+ let protected = if user.protected { " (protected)" } else { "" };
+ println_or_exit!(" - User ID: {}{}", user.id, protected);
+ }
+ }
+ println_or_exit!();
+ }
+
+ Ok(())
+}
+
+/// Context for package filtering and display
+pub struct PackageListContext {
+ pub state_filter: Option,
+ pub removal_filter: Option,
+ pub list_filter: Option,
+ pub search: Option,
+}
+
+impl PackageListContext {
+ /// Check if package passes all filters
+ pub fn filter_package(
+ &self,
+ pkg_name: &str,
+ pkg_info: Option<&Package>,
+ pkg_state: PackageState,
+ ) -> bool {
+ // Removal filter
+ if let Some(removal) = self.removal_filter {
+ if !removal.matches(pkg_info) {
+ return false;
+ }
+ }
+
+ // State filter
+ if let Some(state) = self.state_filter {
+ if !state.matches(pkg_state) {
+ return false;
+ }
+ }
+
+ // List filter
+ if let Some(list) = self.list_filter {
+ if !list.matches(pkg_info) {
+ return false;
+ }
+ }
+
+ // Search filter
+ if let Some(ref search_term) = self.search {
+ let description = pkg_info.map(|p| p.description.as_str());
+ if !matches_search(pkg_name, search_term, description) {
+ return false;
+ }
+ }
+
+ true
+ }
+
+ /// Determine what information to show based on active filters
+ pub fn display_config(&self) -> DisplayConfig {
+ DisplayConfig {
+ show_state: self.state_filter.is_none_or(|f| !f.is_specific()),
+ show_removal: self.removal_filter.is_none_or(|f| !f.is_specific()),
+ }
+ }
+}
+
+pub struct DisplayConfig {
+ pub show_state: bool,
+ pub show_removal: bool,
+}
+
+/// List packages on a device with filtering
+pub fn list_packages(
+ device: Option,
+ state_filter: Option,
+ removal_filter: Option,
+ list_filter: Option,
+ search: Option,
+ user_id: Option,
+) -> Result<(), Box> {
+ let target_device = get_target_device(device)?;
+ let uad_lists = load_debloat_lists(false).unwrap_or_else(|lists| lists);
+
+ println_or_exit!(
+ "Listing packages on: {} ({})\n",
+ target_device.model,
+ target_device.adb_id
+ );
+
+ let context = PackageListContext {
+ state_filter,
+ removal_filter,
+ list_filter,
+ search,
+ };
+
+ let pm_flag = state_filter.and_then(StateFilter::to_pm_flag);
+ let system_packages = ACommand::new()
+ .shell(&target_device.adb_id)
+ .pm()
+ .list_packages_sys(pm_flag, user_id)?;
+
+ let displayed_count = display_package_list(
+ &system_packages,
+ &uad_lists,
+ &target_device.adb_id,
+ user_id,
+ &context,
+ )?;
+
+ if displayed_count == 0 {
+ println_or_exit!(" No packages found matching the specified filters.");
+ } else {
+ println_or_exit!("\nTotal: {} package(s)", displayed_count);
+ }
+
+ Ok(())
+}
+
+/// Display a list of packages with their info
+pub fn display_package_list(
+ packages: &[String],
+ uad_lists: &HashMap,
+ device_serial: &str,
+ user_id: Option,
+ context: &PackageListContext,
+) -> Result> {
+ let config = context.display_config();
+ let mut displayed_count = 0;
+
+ let enabled_packages: HashSet = ACommand::new()
+ .shell(device_serial)
+ .pm()
+ .list_packages_sys(Some(PmListPacksFlag::OnlyEnabled), user_id)
+ .unwrap_or_default()
+ .into_iter()
+ .collect();
+ let disabled_packages: HashSet = ACommand::new()
+ .shell(device_serial)
+ .pm()
+ .list_packages_sys(Some(PmListPacksFlag::OnlyDisabled), user_id)
+ .unwrap_or_default()
+ .into_iter()
+ .collect();
+
+ for pkg_name in packages {
+ let pkg_info = uad_lists.get(pkg_name);
+
+ let pkg_state = if enabled_packages.contains(pkg_name) {
+ PackageState::Enabled
+ } else if disabled_packages.contains(pkg_name) {
+ PackageState::Disabled
+ } else {
+ PackageState::Uninstalled
+ };
+
+ if !context.filter_package(pkg_name, pkg_info, pkg_state) {
+ continue;
+ }
+
+ display_package_entry(pkg_name, pkg_info, pkg_state, &config);
+ displayed_count += 1;
+ }
+
+ Ok(displayed_count)
+}
+
+/// Display a single package entry
+pub fn display_package_entry(
+ pkg_name: &str,
+ pkg_info: Option<&Package>,
+ pkg_state: PackageState,
+ config: &DisplayConfig,
+) {
+ print_or_exit!("[");
+
+ if let Some(info) = pkg_info {
+ if config.show_removal {
+ print_or_exit!("{}", info.removal);
+ if config.show_state {
+ print_or_exit!(" - ");
+ }
+ }
+ if config.show_state {
+ print_or_exit!("{}", pkg_state);
+ }
+ print_or_exit!("] {}", pkg_name);
+ if !info.description.is_empty() {
+ print_or_exit!(" - {}", truncate_description(&info.description, 80));
+ }
+ } else {
+ if config.show_removal {
+ print_or_exit!("Unlisted");
+ if config.show_state {
+ print_or_exit!(" - ");
+ }
+ }
+ if config.show_state {
+ print_or_exit!("{}", pkg_state);
+ }
+ print_or_exit!("] {}", pkg_name);
+ }
+
+ println_or_exit!();
+}
+
+/// Change the state of one or more packages
+pub fn change_package_state(
+ packages: &[String],
+ device: Option,
+ user_id: Option,
+ dry_run: bool,
+ target_state: PackageState,
+ action_name: &str,
+) -> Result<(), Box> {
+ if packages.is_empty() {
+ return Err("No packages specified".into());
+ }
+
+ let target_device = get_target_device(device)?;
+ let user = get_user(&target_device, user_id)?;
+ let uad_lists = load_debloat_lists(false).unwrap_or_else(|lists| lists);
+
+ println!(
+ "{} {} package(s) on: {} ({})\n",
+ action_name,
+ packages.len(),
+ target_device.model,
+ target_device.adb_id
+ );
+
+ if dry_run {
+ println!("DRY RUN - No changes will be made\n");
+ }
+
+ for pkg_name in packages {
+ process_package_state_change(
+ pkg_name,
+ &target_device,
+ user,
+ target_state,
+ dry_run,
+ &uad_lists,
+ )?;
+ println!();
+ }
+
+ if dry_run {
+ println!("Dry run completed. No changes were made.");
+ } else {
+ println!("Operation completed successfully.");
+ }
+
+ Ok(())
+}
+
+/// Process state change for a single package
+fn process_package_state_change(
+ pkg_name: &str,
+ device: &Phone,
+ user: User,
+ target_state: PackageState,
+ dry_run: bool,
+ uad_lists: &HashMap,
+) -> Result<(), Box> {
+ let current_state = get_package_state(&device.adb_id, pkg_name, Some(user.id))
+ .ok_or("Package not found on device")?;
+
+ println!(" {} ({})", pkg_name, current_state);
+
+ if current_state == target_state {
+ println!(" → Already in target state, skipping");
+ return Ok(());
+ }
+
+ let pkg_info = uad_lists.get(pkg_name);
+ if let Some(info) = pkg_info {
+ if info.removal == Removal::Unsafe {
+ println!(" ⚠ WARNING: This package is marked as UNSAFE to remove!");
+ }
+ }
+
+ let core_pkg = CorePackage {
+ name: pkg_name.to_string(),
+ description: pkg_info.map(|p| p.description.clone()).unwrap_or_default(),
+ removal: pkg_info.map(|p| p.removal).unwrap_or(Removal::Unlisted),
+ state: current_state,
+ list: pkg_info.map(|p| p.list).unwrap_or(UadList::Unlisted),
+ };
+
+ let commands = apply_pkg_state_commands(&core_pkg, target_state, user, device);
+
+ if dry_run {
+ for cmd in &commands {
+ println!(" Would run: {}", cmd);
+ }
+ } else {
+ execute_with_fallback(
+ pkg_name,
+ target_state,
+ &core_pkg,
+ user,
+ device,
+ &commands,
+ " ",
+ )?;
+ }
+
+ Ok(())
+}
+
+/// Execute commands and verify package state with fallback
+pub fn execute_with_fallback(
+ package: &str,
+ target_state: PackageState,
+ core_pkg: &CorePackage,
+ user: User,
+ device: &Phone,
+ commands: &[String],
+ indent: &str,
+) -> Result<(), Box> {
+ // Capture the before-state of packages on other users for cross-user detection
+ let before_cross_user_states =
+ uad_core::sync::capture_cross_user_states(package, &device.adb_id, user.id, device);
+
+ // Execute commands
+ for cmd in commands {
+ match run_adb_shell_action(&device.adb_id, cmd.as_str()) {
+ Ok(_) => println!("{}✓ {}", indent, cmd),
+ Err(e) => {
+ return Err(format!("{indent}✗ Failed to execute `{cmd}`: {e:?}").into());
+ }
+ }
+ }
+
+ // Verify package state and attempt fallback if needed
+ let actual_state = match get_package_state(&device.adb_id, package, Some(user.id)) {
+ Some(state) => state,
+ None if target_state == PackageState::Uninstalled => PackageState::Uninstalled,
+ None => {
+ return Err(format!(
+ "Package '{package}' was not found on device for user {}",
+ user.id
+ )
+ .into());
+ }
+ };
+
+ if actual_state != target_state {
+ println!(
+ "{}⚠ Package state verification failed: expected {:?}, got {:?}",
+ indent, target_state, actual_state
+ );
+
+ // Attempt fallback
+ if let Ok(fallback_action) =
+ uad_core::sync::attempt_fallback(core_pkg, target_state, actual_state, user, device)
+ {
+ println!("{}↻ Fallback: {}", indent, fallback_action);
+ } else {
+ println!("{}✗ No fallback available", indent);
+ }
+ }
+
+ // Check for cross-user behavior if operation succeeded
+ if actual_state == target_state {
+ if let Some(notification) = uad_core::sync::detect_cross_user_behavior(
+ package,
+ device.adb_id.as_str(),
+ user.id,
+ target_state,
+ actual_state,
+ device,
+ &before_cross_user_states,
+ ) {
+ println!("{}ℹ {}", indent, notification);
+ }
+ }
+
+ Ok(())
+}
+
+/// Show detailed information about a package
+pub fn show_package_info(
+ package: &str,
+ device: Option,
+ user_id: Option,
+) -> Result<(), Box> {
+ println!("Package: {}\n", package);
+
+ let uad_lists = load_debloat_lists(false).unwrap_or_else(|lists| lists);
+
+ if let Some(pkg_info) = uad_lists.get(package) {
+ println!("UAD Information:");
+ println!(" List: {}", pkg_info.list);
+ println!(" Removal: {}", pkg_info.removal);
+ println!(" Description: {}", pkg_info.description);
+ println!();
+ } else {
+ println!(" Not found in UAD lists (unlisted package)\n");
+ }
+
+ if let Some(device_id) = device {
+ let target_device = get_target_device(Some(device_id))?;
+ let user = get_user(&target_device, user_id)?;
+ println!("Device: {} ({})", target_device.model, target_device.adb_id);
+ println!("User: {}", user.id);
+
+ let state = get_package_state(&target_device.adb_id, package, Some(user.id))
+ .ok_or("Package not found on device")?;
+ println!(" State: {}", state);
+ }
+
+ Ok(())
+}
+
+/// Update UAD package lists from remote repository
+pub fn update_lists() -> Result<(), Box> {
+ println!("Updating UAD package lists from remote repository...");
+
+ match load_debloat_lists(true) {
+ Ok(_lists) => {
+ println!("✓ Successfully updated package lists");
+ Ok(())
+ }
+ Err(_lists) => Err("Failed to update lists from remote, using cached version".into()),
+ }
+}
+
+/// Generate shell completion script
+pub fn generate_completions(shell: Shell) {
+ let mut cmd = Cli::command();
+ let name = cmd.get_name().to_string();
+ generate(shell, &mut cmd, name, &mut std::io::stdout());
+}
diff --git a/crates/uad-cli/src/device.rs b/crates/uad-cli/src/device.rs
new file mode 100644
index 0000000..54fee8c
--- /dev/null
+++ b/crates/uad-cli/src/device.rs
@@ -0,0 +1,47 @@
+use uad_core::sync::{Phone, User, get_devices_list};
+
+pub const NO_DEVICES_FOUND: &str =
+ "No devices found. Make sure ADB is installed and devices are connected.";
+
+/// Get target device, either by serial or first available
+pub fn get_target_device(device: Option) -> Result> {
+ let devices = get_devices_list();
+
+ if devices.is_empty() {
+ return Err(NO_DEVICES_FOUND.into());
+ }
+
+ let target_device = if let Some(device_id) = device {
+ devices
+ .iter()
+ .find(|d| d.adb_id == device_id)
+ .ok_or("Device not found")?
+ .clone()
+ } else {
+ if devices.len() > 1 {
+ eprintln!(
+ "Warning: Multiple devices found, using first one: {}",
+ devices[0].adb_id
+ );
+ }
+ devices[0].clone()
+ };
+
+ Ok(target_device)
+}
+
+/// Get user from device, creating a basic one if not found
+pub fn get_user(device: &Phone, user_id: Option) -> Result> {
+ let uid = user_id.unwrap_or(0);
+
+ if let Some(user) = device.user_list.iter().find(|u| u.id == uid) {
+ Ok(*user)
+ } else {
+ // Create a basic user if not found in list
+ Ok(User {
+ id: uid,
+ index: 0,
+ protected: false,
+ })
+ }
+}
diff --git a/crates/uad-cli/src/filters.rs b/crates/uad-cli/src/filters.rs
new file mode 100644
index 0000000..5ae156f
--- /dev/null
+++ b/crates/uad-cli/src/filters.rs
@@ -0,0 +1,98 @@
+use clap::ValueEnum;
+use uad_core::adb::PmListPacksFlag;
+use uad_core::uad_lists::{Package, PackageState, Removal, UadList};
+
+#[derive(Debug, Clone, Copy, ValueEnum)]
+pub enum StateFilter {
+ /// Show all packages regardless of state
+ All,
+ /// Show only enabled packages
+ Enabled,
+ /// Show only disabled packages
+ Disabled,
+ /// Show only uninstalled packages
+ Uninstalled,
+}
+
+#[derive(Debug, Clone, Copy, ValueEnum)]
+pub enum RemovalFilter {
+ All,
+ Recommended,
+ Advanced,
+ Expert,
+ Unsafe,
+ Unlisted,
+}
+
+#[derive(Debug, Clone, Copy, ValueEnum)]
+pub enum ListFilter {
+ All,
+ Aosp,
+ Carrier,
+ Google,
+ Misc,
+ Oem,
+ Pending,
+ Unlisted,
+}
+
+impl StateFilter {
+ pub fn to_pm_flag(self) -> Option {
+ match self {
+ Self::Enabled => Some(PmListPacksFlag::OnlyEnabled),
+ Self::Disabled => Some(PmListPacksFlag::OnlyDisabled),
+ Self::Uninstalled | Self::All => Some(PmListPacksFlag::IncludeUninstalled),
+ }
+ }
+
+ pub fn matches(self, pkg_state: PackageState) -> bool {
+ match self {
+ Self::All => true,
+ Self::Enabled => pkg_state == PackageState::Enabled,
+ Self::Disabled => pkg_state == PackageState::Disabled,
+ Self::Uninstalled => pkg_state == PackageState::Uninstalled,
+ }
+ }
+
+ pub fn is_specific(self) -> bool {
+ matches!(self, Self::Enabled | Self::Disabled | Self::Uninstalled)
+ }
+}
+
+impl RemovalFilter {
+ pub fn matches(self, pkg_info: Option<&Package>) -> bool {
+ match pkg_info {
+ Some(info) => match self {
+ Self::All => true,
+ Self::Recommended => info.removal == Removal::Recommended,
+ Self::Advanced => info.removal == Removal::Advanced,
+ Self::Expert => info.removal == Removal::Expert,
+ Self::Unsafe => info.removal == Removal::Unsafe,
+ Self::Unlisted => info.removal == Removal::Unlisted,
+ },
+ None => matches!(self, Self::All | Self::Unlisted),
+ }
+ }
+
+ pub fn is_specific(self) -> bool {
+ !matches!(self, Self::All)
+ }
+}
+
+impl ListFilter {
+ pub fn matches(self, pkg_info: Option<&Package>) -> bool {
+ match pkg_info {
+ Some(info) => match self {
+ Self::All => true,
+ Self::Aosp => info.list == UadList::Aosp,
+ Self::Carrier => info.list == UadList::Carrier,
+ Self::Google => info.list == UadList::Google,
+ Self::Misc => info.list == UadList::Misc,
+ Self::Oem => info.list == UadList::Oem,
+ Self::Pending => info.list == UadList::Pending,
+ Self::Unlisted => info.list == UadList::Unlisted,
+ },
+ None => matches!(self, Self::All | Self::Unlisted),
+ }
+ }
+}
diff --git a/crates/uad-cli/src/main.rs b/crates/uad-cli/src/main.rs
new file mode 100644
index 0000000..f473e28
--- /dev/null
+++ b/crates/uad-cli/src/main.rs
@@ -0,0 +1,251 @@
+#![allow(
+ clippy::needless_continue,
+ clippy::collapsible_if,
+ clippy::uninlined_format_args,
+ clippy::map_unwrap_or,
+ clippy::unnecessary_wraps,
+ reason = "Suppress non-critical pedantic/style lints to keep build green"
+)]
+
+use clap::{Parser, Subcommand};
+use clap_complete::Shell;
+use std::process::ExitCode;
+use uad_core::uad_lists::PackageState;
+
+mod commands;
+mod device;
+mod filters;
+mod output;
+mod repl;
+
+use filters::{ListFilter, RemovalFilter, StateFilter};
+
+#[derive(Parser)]
+#[command(name = "uad")]
+#[command(about = "Universal Android Debloater - Command Line Interface", long_about = None)]
+#[command(version)]
+#[command(propagate_version = true)]
+pub struct Cli {
+ #[command(subcommand)]
+ command: Commands,
+}
+
+#[derive(Subcommand)]
+enum Commands {
+ /// List connected Android devices
+ Devices,
+
+ /// List packages on a device
+ #[command(name = "list", visible_alias = "ls")]
+ List {
+ /// Device serial number (optional, uses first device if not specified)
+ #[arg(short, long)]
+ device: Option,
+
+ /// Filter by package state
+ #[arg(short, long, value_enum)]
+ state: Option,
+
+ /// Filter by removal category
+ #[arg(short, long, value_enum)]
+ removal: Option,
+
+ /// Filter by UAD list
+ #[arg(short, long, value_enum)]
+ list: Option,
+
+ /// Search pattern (matches package name or description)
+ #[arg(short = 'q', long)]
+ search: Option,
+
+ /// User ID (defaults to 0)
+ #[arg(short, long)]
+ user: Option,
+ },
+
+ /// Uninstall packages (default removal action)
+ #[command(visible_alias = "rm")]
+ Uninstall {
+ /// Package names to uninstall
+ packages: Vec,
+
+ /// Device serial number (optional, uses first device if not specified)
+ #[arg(short, long)]
+ device: Option,
+
+ /// User ID (defaults to 0)
+ #[arg(short, long)]
+ user: Option,
+
+ /// Dry run - show what would be done without actually doing it
+ #[arg(long)]
+ dry_run: bool,
+ },
+
+ /// Restore (reinstall) packages
+ #[command(visible_alias = "restore")]
+ Enable {
+ /// Package names to restore/enable
+ packages: Vec,
+
+ /// Device serial number (optional, uses first device if not specified)
+ #[arg(short, long)]
+ device: Option,
+
+ /// User ID (defaults to 0)
+ #[arg(short, long)]
+ user: Option,
+
+ /// Dry run - show what would be done without actually doing it
+ #[arg(long)]
+ dry_run: bool,
+ },
+
+ /// Disable packages (keeps data but prevents execution)
+ Disable {
+ /// Package names to disable
+ packages: Vec,
+
+ /// Device serial number (optional, uses first device if not specified)
+ #[arg(short, long)]
+ device: Option,
+
+ /// User ID (defaults to 0)
+ #[arg(short, long)]
+ user: Option,
+
+ /// Dry run - show what would be done without actually doing it
+ #[arg(long)]
+ dry_run: bool,
+ },
+
+ /// Show detailed information about a package
+ Info {
+ /// Package name
+ package: String,
+
+ /// Device serial number (optional, uses first device if not specified)
+ #[arg(short, long)]
+ device: Option,
+
+ /// User ID (defaults to 0)
+ #[arg(short, long)]
+ user: Option,
+ },
+
+ /// Update UAD package lists from remote repository
+ Update,
+
+ /// Generate shell completion script
+ Completions {
+ /// Shell to generate completions for
+ #[arg(value_enum)]
+ shell: Shell,
+ },
+
+ /// Start interactive REPL mode
+ #[command(visible_alias = "shell")]
+ Repl {
+ /// Device serial number (optional, uses first device if not specified)
+ #[arg(short, long)]
+ device: Option,
+
+ /// User ID (defaults to 0)
+ #[arg(short, long)]
+ user: Option,
+ },
+}
+
+#[tokio::main]
+async fn main() -> ExitCode {
+ match run() {
+ Ok(()) => ExitCode::SUCCESS,
+ Err(err) => {
+ eprintln!("Error: {err}");
+ ExitCode::FAILURE
+ }
+ }
+}
+
+fn run() -> Result<(), Box> {
+ let cli = Cli::parse();
+
+ match cli.command {
+ Commands::Devices => {
+ commands::list_devices()?;
+ }
+ Commands::List {
+ device,
+ state,
+ removal,
+ list,
+ search,
+ user,
+ } => {
+ commands::list_packages(device, state, removal, list, search, user)?;
+ }
+ Commands::Uninstall {
+ packages,
+ device,
+ user,
+ dry_run,
+ } => {
+ commands::change_package_state(
+ &packages,
+ device,
+ user,
+ dry_run,
+ PackageState::Uninstalled,
+ "Uninstalling",
+ )?;
+ }
+ Commands::Enable {
+ packages,
+ device,
+ user,
+ dry_run,
+ } => {
+ commands::change_package_state(
+ &packages,
+ device,
+ user,
+ dry_run,
+ PackageState::Enabled,
+ "Enabling",
+ )?;
+ }
+ Commands::Disable {
+ packages,
+ device,
+ user,
+ dry_run,
+ } => {
+ commands::change_package_state(
+ &packages,
+ device,
+ user,
+ dry_run,
+ PackageState::Disabled,
+ "Disabling",
+ )?;
+ }
+ Commands::Info {
+ package,
+ device,
+ user,
+ } => {
+ commands::show_package_info(&package, device, user)?;
+ }
+ Commands::Update => {
+ commands::update_lists()?;
+ }
+ Commands::Completions { shell } => {
+ commands::generate_completions(shell);
+ }
+ Commands::Repl { device, user } => {
+ repl::repl_mode(device, user)?;
+ }
+ }
+
+ Ok(())
+}
diff --git a/crates/uad-cli/src/output.rs b/crates/uad-cli/src/output.rs
new file mode 100644
index 0000000..cff4724
--- /dev/null
+++ b/crates/uad-cli/src/output.rs
@@ -0,0 +1,18 @@
+/// Helper macro to handle broken pipe errors gracefully
+/// When piping to commands like `head`, we want to exit cleanly when the pipe closes
+#[macro_export]
+macro_rules! println_or_exit {
+ () => {
+ let _ = writeln!(std::io::stdout());
+ };
+ ($($arg:tt)*) => {
+ let _ = writeln!(std::io::stdout(), $($arg)*);
+ };
+}
+
+#[macro_export]
+macro_rules! print_or_exit {
+ ($($arg:tt)*) => {
+ let _ = write!(std::io::stdout(), $($arg)*);
+ };
+}
diff --git a/crates/uad-cli/src/repl.rs b/crates/uad-cli/src/repl.rs
new file mode 100644
index 0000000..eeee0c6
--- /dev/null
+++ b/crates/uad-cli/src/repl.rs
@@ -0,0 +1,374 @@
+use rustyline::DefaultEditor;
+use rustyline::error::ReadlineError;
+use std::collections::HashMap;
+use std::io::Write;
+use uad_core::adb::ACommand;
+use uad_core::sync::{CorePackage, Phone, User, apply_pkg_state_commands, get_package_state};
+use uad_core::uad_lists::{Package, PackageState, Removal, UadList, load_debloat_lists};
+
+use crate::commands::{PackageListContext, display_package_list, execute_with_fallback};
+use crate::device::{get_target_device, get_user};
+use crate::filters::StateFilter;
+use crate::println_or_exit;
+
+enum ReplAction {
+ Continue,
+ Exit,
+}
+
+/// Start interactive REPL mode
+pub fn repl_mode(
+ device: Option,
+ user_id: Option,
+) -> Result<(), Box> {
+ println!("Universal Android Debloater - Interactive Mode");
+ println!("Type 'help' for available commands, 'exit' or 'quit' to leave\n");
+
+ let target_device = get_target_device(device)?;
+ let user = get_user(&target_device, user_id)?;
+
+ println!(
+ "Connected to: {} ({})",
+ target_device.model, target_device.adb_id
+ );
+ println!("User: {}\n", user.id);
+
+ let uad_lists = load_debloat_lists(false).unwrap_or_else(|lists| lists);
+ let mut rl = DefaultEditor::new()?;
+
+ // Try to load history
+ let history_file = dirs::cache_dir().map(|d| d.join("uad").join("cli_history.txt"));
+ if let Some(ref path) = history_file {
+ let _ = rl.load_history(path);
+ }
+
+ loop {
+ let readline = rl.readline("uad> ");
+ match readline {
+ Ok(line) => {
+ match handle_repl_line(&line, &mut rl, &target_device, user, user_id, &uad_lists) {
+ Ok(ReplAction::Continue) => {}
+ Ok(ReplAction::Exit) => break,
+ Err(e) => {
+ eprintln!("Error: {}", e);
+ }
+ }
+ }
+ Err(ReadlineError::Interrupted) => {
+ println!("Interrupted (Ctrl-C). Type 'exit' to quit.");
+ continue;
+ }
+ Err(ReadlineError::Eof) => {
+ println!("Goodbye!");
+ break;
+ }
+ Err(err) => {
+ eprintln!("Error: {:?}", err);
+ break;
+ }
+ }
+ }
+
+ // Save history
+ if let Some(ref path) = history_file {
+ if let Some(parent) = path.parent() {
+ let _ = std::fs::create_dir_all(parent);
+ }
+ let _ = rl.save_history(path);
+ }
+
+ Ok(())
+}
+
+/// Handle a single line of REPL input
+fn handle_repl_line(
+ line: &str,
+ rl: &mut DefaultEditor,
+ device: &Phone,
+ user: User,
+ user_id: Option,
+ uad_lists: &HashMap,
+) -> Result> {
+ let line = line.trim();
+ if line.is_empty() {
+ return Ok(ReplAction::Continue);
+ }
+
+ let _ = rl.add_history_entry(line);
+
+ let parts: Vec<&str> = line.split_whitespace().collect();
+ if parts.is_empty() {
+ return Ok(ReplAction::Continue);
+ }
+
+ match parts[0] {
+ "help" => print_repl_help(),
+ "exit" | "quit" => {
+ println!("Goodbye!");
+ return Ok(ReplAction::Exit);
+ }
+ "list" | "ls" => {
+ handle_list_command(&parts[1..], device, user_id, uad_lists)?;
+ }
+ "info" => {
+ handle_info_command(&parts[1..], device, user.id, uad_lists)?;
+ }
+ "uninstall" | "rm" => {
+ handle_state_change_command(
+ &parts[1..],
+ device,
+ user,
+ PackageState::Uninstalled,
+ "Uninstalling",
+ uad_lists,
+ )?;
+ }
+ "enable" | "restore" => {
+ handle_state_change_command(
+ &parts[1..],
+ device,
+ user,
+ PackageState::Enabled,
+ "Enabling",
+ uad_lists,
+ )?;
+ }
+ "disable" => {
+ handle_state_change_command(
+ &parts[1..],
+ device,
+ user,
+ PackageState::Disabled,
+ "Disabling",
+ uad_lists,
+ )?;
+ }
+ "device" => {
+ println!(
+ "Device: {} ({}), Android SDK: {}, User: {}",
+ device.model, device.adb_id, device.android_sdk, user.id
+ );
+ }
+ "clear" => {
+ print!("\x1B[2J\x1B[1;1H");
+ }
+ _ => {
+ eprintln!(
+ "Unknown command: '{}'. Type 'help' for available commands.",
+ parts[0]
+ );
+ }
+ }
+
+ Ok(ReplAction::Continue)
+}
+
+/// Parse REPL arguments into filters
+struct ReplListArgs {
+ state_filter: Option,
+ search_term: Option,
+}
+
+impl ReplListArgs {
+ fn parse(args: &[&str]) -> Result {
+ let mut state_filter = None;
+ let mut search_term = None;
+ let mut i = 0;
+
+ while i < args.len() {
+ match args[i] {
+ "--state" | "-s" => {
+ if i + 1 >= args.len() {
+ return Err("--state requires a value".to_string());
+ }
+ state_filter = match args[i + 1].to_lowercase().as_str() {
+ "enabled" => Some(StateFilter::Enabled),
+ "disabled" => Some(StateFilter::Disabled),
+ "uninstalled" => Some(StateFilter::Uninstalled),
+ "all" => Some(StateFilter::All),
+ _ => return Err(format!("Invalid state: {}", args[i + 1])),
+ };
+ i += 2;
+ }
+ "--search" | "-q" => {
+ if i + 1 >= args.len() {
+ return Err("--search requires a value".to_string());
+ }
+ search_term = Some(args[i + 1].to_string());
+ i += 2;
+ }
+ _ => {
+ return Err(format!("Unknown option: {}", args[i]));
+ }
+ }
+ }
+
+ Ok(Self {
+ state_filter,
+ search_term,
+ })
+ }
+}
+
+/// Handle list command in REPL
+fn handle_list_command(
+ args: &[&str],
+ device: &Phone,
+ user_id: Option,
+ uad_lists: &HashMap,
+) -> Result<(), Box> {
+ let parsed = ReplListArgs::parse(args)?;
+
+ let pm_flag = parsed.state_filter.and_then(StateFilter::to_pm_flag);
+ let system_packages = ACommand::new()
+ .shell(&device.adb_id)
+ .pm()
+ .list_packages_sys(pm_flag, user_id)?;
+
+ let context = PackageListContext {
+ state_filter: parsed.state_filter,
+ removal_filter: None,
+ list_filter: None,
+ search: parsed.search_term,
+ };
+
+ let displayed_count = display_package_list(
+ &system_packages,
+ uad_lists,
+ &device.adb_id,
+ user_id,
+ &context,
+ )?;
+
+ if displayed_count == 0 {
+ println_or_exit!(" No packages found.");
+ } else {
+ println_or_exit!("\nTotal: {} package(s)", displayed_count);
+ }
+
+ Ok(())
+}
+
+/// Handle info command in REPL
+fn handle_info_command(
+ args: &[&str],
+ device: &Phone,
+ user_id: u16,
+ uad_lists: &HashMap,
+) -> Result<(), Box> {
+ if args.is_empty() {
+ eprintln!("Usage: info ");
+ return Ok(());
+ }
+
+ let package = args[0];
+ println!("Package: {}", package);
+
+ if let Some(pkg_info) = uad_lists.get(package) {
+ println!(" List: {}", pkg_info.list);
+ println!(" Removal: {}", pkg_info.removal);
+ println!(" Description: {}", pkg_info.description);
+ } else {
+ println!(" Not found in UAD lists (unlisted package)");
+ }
+
+ let state = get_package_state(&device.adb_id, package, Some(user_id))
+ .ok_or("Package not found on device")?;
+ println!(" State: {}", state);
+
+ Ok(())
+}
+
+/// Handle state change command in REPL
+fn handle_state_change_command(
+ args: &[&str],
+ device: &Phone,
+ user: User,
+ target_state: PackageState,
+ action_name: &str,
+ uad_lists: &HashMap,
+) -> Result<(), Box> {
+ if args.is_empty() {
+ eprintln!(
+ "Usage: {} [package_name...]",
+ action_name.to_lowercase()
+ );
+ return Ok(());
+ }
+
+ for pkg_name in args {
+ process_package_change(pkg_name, device, user, target_state, action_name, uad_lists)?;
+ }
+
+ Ok(())
+}
+
+/// Process state change for a single package in REPL
+fn process_package_change(
+ pkg_name: &str,
+ device: &Phone,
+ user: User,
+ target_state: PackageState,
+ action_name: &str,
+ uad_lists: &HashMap,
+) -> Result<(), Box> {
+ let current_state = get_package_state(&device.adb_id, pkg_name, Some(user.id))
+ .ok_or("Package not found on device")?;
+
+ println!("{} {} (current: {})", action_name, pkg_name, current_state);
+
+ if current_state == target_state {
+ println!(" → Already in target state, skipping");
+ return Ok(());
+ }
+
+ let pkg_info = uad_lists.get(pkg_name);
+ if let Some(info) = pkg_info {
+ if info.removal == Removal::Unsafe {
+ println!(" ⚠ WARNING: This package is marked as UNSAFE to remove!");
+ }
+ }
+
+ let core_pkg = CorePackage {
+ name: pkg_name.to_string(),
+ description: pkg_info.map(|p| p.description.clone()).unwrap_or_default(),
+ removal: pkg_info.map(|p| p.removal).unwrap_or(Removal::Unlisted),
+ state: current_state,
+ list: pkg_info.map(|p| p.list).unwrap_or(UadList::Unlisted),
+ };
+
+ let commands = apply_pkg_state_commands(&core_pkg, target_state, user, device);
+
+ execute_with_fallback(
+ pkg_name,
+ target_state,
+ &core_pkg,
+ user,
+ device,
+ &commands,
+ " ",
+ )
+}
+
+/// Print REPL help message
+fn print_repl_help() {
+ println!("Available commands:");
+ println!(" list [--state ] [--search ]");
+ println!(" List packages with optional filters");
+ println!(" info ");
+ println!(" Show information about a package");
+ println!(" uninstall [package_name...]");
+ println!(" Uninstall one or more packages");
+ println!(" enable [package_name...]");
+ println!(" Enable/restore one or more packages");
+ println!(" disable [package_name...]");
+ println!(" Disable one or more packages");
+ println!(" device");
+ println!(" Show current device information");
+ println!(" clear");
+ println!(" Clear the screen");
+ println!(" help");
+ println!(" Show this help message");
+ println!(" exit, quit");
+ println!(" Exit the interactive mode");
+}
diff --git a/crates/uad-core/Cargo.toml b/crates/uad-core/Cargo.toml
new file mode 100644
index 0000000..f7d3a43
--- /dev/null
+++ b/crates/uad-core/Cargo.toml
@@ -0,0 +1,52 @@
+[package]
+name = "uad-core"
+version.workspace = true
+authors.workspace = true
+license.workspace = true
+homepage.workspace = true
+repository.workspace = true
+readme.workspace = true
+keywords.workspace = true
+categories = ["command-line-utilities"]
+edition.workspace = true
+
+[features]
+default = []
+self-update = ["dep:flate2", "dep:tar"]
+
+[dependencies]
+serde.workspace = true
+serde_json.workspace = true
+log.workspace = true
+chrono.workspace = true
+toml.workspace = true
+dirs.workspace = true
+ureq.workspace = true
+retry.workspace = true
+csv.workspace = true
+flate2 = { workspace = true, optional = true }
+tar = { workspace = true, optional = true }
+
+[target.'cfg(target_os = "windows")'.dependencies]
+win32console.workspace = true
+
+[lints.rust]
+deprecated_safe = "warn"
+
+[lints.clippy]
+undocumented_unsafe_blocks = "forbid"
+exit = "deny"
+panic_in_result_fn = "warn"
+infinite_loop = "warn"
+mem_forget = "warn"
+implicit_clone = "warn"
+format_push_string = "warn"
+large_include_file = "warn"
+shadow_unrelated = "warn"
+struct_field_names = "allow" # annoying
+
+disallowed_types = "deny"
+disallowed_methods = "deny"
+
+allow_attributes_without_reason = "warn"
+pedantic = { level = "warn", priority = -1 }
diff --git a/crates/uad-core/src/adb.rs b/crates/uad-core/src/adb.rs
new file mode 100644
index 0000000..f2335e0
--- /dev/null
+++ b/crates/uad-core/src/adb.rs
@@ -0,0 +1,503 @@
+#![deny(clippy::unwrap_used)]
+
+//! This module is intended to group everything that's "intrinsic" of ADB.
+//!
+//! Following the design philosophy of most of Rust `std`,
+//! `*Command` are intended to be "thin wrappers" (low-overhead abstractions)
+//! around the ADB CLI or `adb_client`
+//! ([in the future](https://github.com/Universal-Debloater-Alliance/universal-android-debloater-next-generation/issues/700) ),
+//! which implies:
+//! - no "magic"
+//! - no custom commands
+//! - no chaining ("piping") of existing commands
+//!
+//! This guarantees a 1-to-1 mapping between methods and cmds,
+//! thereby reducing surprises such as:
+//! - Non-atomic operations: consider what happens if a pack changes state
+//! in the middle of listing enabled and disabled packs!
+//! - Non-standard semantics: what would happen if a new ADB version
+//! supports a feature we already defined,
+//! but has _slightly_ different behavior?
+//!
+//! Despite being "low-level", we can still "have cake and eat it too";
+//! After all, what's the point of an abstraction if it doesn't come with goodies?:
+//! We can reserve some artistic license, such as:
+//! - pre-parsing or validanting output, to provide types with invariants
+//! - strongly-typed rather than "stringly-typed" APIs
+//! - nicer IDE support
+//! - compile-time prevention of malformed cmds
+//! - implicit enforcement of a narrow set of operations
+//!
+//! About that last point, if there's ever a need for an ADB feature
+//! which these APIs don't expose,
+//! please, **PLEASE** refrain from falling-back to any `Command`-like API.
+//! Rather, please extend these APIs in a consistent way.
+//!
+//! Thank you! ❤️
+//!
+//! For comprehensive info about ADB,
+//! [see this](https://android.googlesource.com/platform/packages/modules/adb/+/refs/heads/master/docs/)
+
+use std::rc::Rc;
+
+#[cfg(target_os = "windows")]
+use std::os::windows::process::CommandExt;
+
+use crate::utils::is_all_w_c;
+use log::{error, info, warn};
+
+/// Convert ADB output bytes to a trimmed UTF-8 string.
+/// Uses lossy conversion to prevent panics on non-UTF8 output from certain OEMs.
+#[must_use]
+pub fn to_trimmed_utf8(v: &[u8]) -> String {
+ String::from_utf8_lossy(v).trim_end().to_string()
+}
+
+#[cfg(debug_assertions)]
+#[must_use]
+fn is_version_triple(s: &str) -> bool {
+ let mut components = s.split('.');
+ for _ in 0..3 {
+ if !components
+ .next()
+ .is_some_and(|comp| comp.as_bytes().iter().all(u8::is_ascii_digit))
+ {
+ return false;
+ }
+ }
+ if components.next().is_some() {
+ return false;
+ }
+ true
+}
+
+/// Builder object for an Android Debug Bridge CLI command,
+/// using the type-state and new-type patterns.
+///
+/// This is not intended to model the entire ADB API.
+/// It only models the subset that concerns UADNG.
+///
+/// [More info here](https://developer.android.com/tools/adb)
+#[derive(Debug)]
+pub struct ACommand(std::process::Command);
+impl ACommand {
+ /// `adb` command builder
+ #[must_use]
+ pub fn new() -> Self {
+ Self(std::process::Command::new("adb"))
+ }
+
+ /// `shell` sub-command builder.
+ ///
+ /// If `device_serial` is empty, it lets ADB choose the default device.
+ #[must_use]
+ pub fn shell>(mut self, device_serial: S) -> ShellCommand {
+ let serial = device_serial.as_ref();
+ if !serial.is_empty() {
+ self.0.args(["-s", serial]);
+ }
+ self.0.arg("shell");
+ ShellCommand(self)
+ }
+
+ /// Header-less list of attached devices (as serials) and their statuses:
+ /// - USB
+ /// - TCP/IP: WIFI, Ethernet, etc...
+ /// - Local emulators
+ ///
+ /// Status can be (but not limited to):
+ /// - "unauthorized"
+ /// - "device"
+ pub fn devices(mut self) -> Result, String> {
+ self.0.arg("devices");
+ Ok(self
+ .run()?
+ .lines()
+ .skip(1) // header
+ .map(|dev_stat| {
+ let tab_idx = dev_stat
+ // OS-specific?
+ .find('\t')
+ // True on Linux,
+ // no matter if ADB is piped or connected to terminal
+ .expect("There must be 1 tab after serial");
+ (
+ // serial
+ dev_stat[..tab_idx].to_string(),
+ // status
+ dev_stat[(tab_idx + 1)..].to_string(),
+ )
+ })
+ .collect())
+ }
+
+ /// `version` sub-command
+ ///
+ /// ## Format
+ /// This is just a sample,
+ /// we don't know which guarantees are stable (yet):
+ /// ```txt
+ /// Android Debug Bridge version 1.0.41
+ /// Version 34.0.5-debian
+ /// Installed as /usr/lib/android-sdk/platform-tools/adb
+ /// Running on Linux 6.12.12-amd64 (x86_64)
+ /// ```
+ ///
+ /// The expected format should be like:
+ /// ```txt
+ /// Android Debug Bridge version ..
+ /// Version ..-
+ /// Installed as /platform-tools/adb[.exe]
+ /// Running on ()
+ /// ```
+ #[expect(clippy::panic_in_result_fn, reason = "Assertions are fine")]
+ pub fn version(mut self) -> Result {
+ self.0.arg("version");
+ let out = self.run()?;
+
+ #[cfg(debug_assertions)]
+ {
+ const ADBV: &str = "Android Debug Bridge version ";
+ const V: &str = "Version ";
+
+ let mut lns = out.lines();
+
+ assert!(
+ lns.next()
+ .is_some_and(|ln| ln.starts_with(ADBV) && is_version_triple(&ln[ADBV.len()..]))
+ );
+ assert!(lns.next().is_some_and(|ln| ln.starts_with(V)
+ && is_version_triple(&ln[V.len()..ln.find('-').unwrap_or(ln.len())])));
+ // missing test for valid path
+ assert!(lns.next().is_some_and(|ln| ln.starts_with("Installed as ")
+ && (ln.ends_with("adb") || ln.ends_with("adb.exe"))));
+ // missing test for x86/ARM (both 64b)
+ assert!(lns.next().is_some_and(|ln| ln.starts_with("Running on ")));
+ if lns.next().is_some() {
+ unreachable!("Expected < 5 lines")
+ }
+ }
+
+ Ok(out)
+ }
+
+ /// General executor
+ fn run(self) -> Result {
+ let mut cmd = self.0;
+ #[cfg(target_os = "windows")]
+ let cmd = cmd.creation_flags(0x0800_0000); // do not open a cmd window
+
+ info!(
+ "Ran command: adb {}",
+ cmd.get_args()
+ .map(|s| s.to_str().unwrap_or_else(|| unreachable!()))
+ .collect::>()
+ .join(" ")
+ );
+ match cmd.output() {
+ Err(e) => {
+ error!("ADB: {e}");
+ Err("Cannot run ADB, likely not found".to_string())
+ }
+ Ok(o) => {
+ let stdout = to_trimmed_utf8(&o.stdout);
+ if o.status.success() {
+ Ok(stdout)
+ } else {
+ let stderr = to_trimmed_utf8(&o.stderr);
+ // ADB does really weird things:
+ // Some errors are not redirected to `stderr`
+ let err = if stdout.is_empty() { stderr } else { stdout };
+ Err(err)
+ }
+ }
+ }
+ }
+}
+
+impl Default for ACommand {
+ fn default() -> Self {
+ Self::new()
+ }
+}
+
+/// Builder object for a command that runs on the device's default `sh` implementation.
+/// Typically MKSH, but could be Ash.
+///
+/// [More info](https://chromium.googlesource.com/aosp/platform/system/core/+/refs/heads/upstream/shell_and_utilities).
+#[derive(Debug)]
+pub struct ShellCommand(ACommand);
+impl ShellCommand {
+ /// `pm` command builder
+ pub fn pm(mut self) -> PmCommand {
+ self.0.0.arg("pm");
+ PmCommand(self)
+ }
+ /// Query a device property value, by its key.
+ /// These can be of any type:
+ /// - `boolean`
+ /// - `int`
+ /// - chars
+ /// - etc...
+ ///
+ /// So to avoid lossy conversions, we return strs
+ pub fn getprop(mut self, key: &str) -> Result {
+ self.0.0.args(["getprop", key]);
+ self.0.run()
+ }
+ /// Reboots device
+ pub fn reboot(mut self) -> Result {
+ self.0.0.arg("reboot");
+ self.0.run()
+ }
+
+ /// Execute an arbitrary shell action string on the device's default shell.
+ /// The action string is passed as a single argument to `adb shell` and
+ /// interpreted by the remote shell (which splits on spaces).
+ pub fn raw(mut self, action: &str) -> Result {
+ self.0.0.arg(action);
+ self.0.run()
+ }
+}
+
+#[must_use]
+pub const fn is_pkg_component(s: &[u8]) -> bool {
+ if s.is_empty() {
+ return false;
+ }
+ s[0].is_ascii_alphabetic()
+ && if s.len() > 1 {
+ is_all_w_c(s.split_at(1).1)
+ } else {
+ true
+ }
+}
+
+/// String with the invariant of being a valid package-name.
+/// See [`PackageId::new`] for validation details.
+#[derive(Debug, Clone, PartialEq, Eq, Hash)]
+pub struct PackageId(Rc);
+impl PackageId {
+ /// Creates a package-ID if it's `"android"` or valid according to:
+ /// -
+ /// -
+ #[must_use]
+ pub fn new(p_id: &str) -> Option {
+ if p_id == "android" {
+ return Some(Self(p_id.into()));
+ }
+ let mut components = p_id.split('.');
+ for _ in 0..2 {
+ if !components
+ .next()
+ .is_some_and(|comp| is_pkg_component(comp.as_bytes()))
+ {
+ return None;
+ }
+ }
+ if components.all(|comp| is_pkg_component(comp.as_bytes())) {
+ Some(Self(p_id.into()))
+ } else {
+ None
+ }
+ }
+}
+
+/// `pm list packages` flag/state/type
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub enum PmListPacksFlag {
+ /// `-u`, not to be confused with `-a`
+ IncludeUninstalled,
+ /// `-e`
+ OnlyEnabled,
+ /// `-d`
+ OnlyDisabled,
+}
+impl PmListPacksFlag {
+ // is there a trait for this?
+ fn to_str(self) -> &'static str {
+ match self {
+ Self::IncludeUninstalled => "-u",
+ Self::OnlyEnabled => "-e",
+ Self::OnlyDisabled => "-d",
+ }
+ }
+}
+#[expect(clippy::to_string_trait_impl, reason = "This is not user-facing")]
+impl ToString for PmListPacksFlag {
+ fn to_string(&self) -> String {
+ self.to_str().to_string()
+ }
+}
+
+const PACK_PREFIX: &str = "package:";
+
+pub const PM_CLEAR_PACK: &str = "pm clear";
+
+/// Builder object for an Android Package Manager command.
+///
+#[derive(Debug)]
+#[must_use]
+pub struct PmCommand(ShellCommand);
+impl PmCommand {
+ /// `list packages -s` sub-command, [`PACK_PREFIX`] stripped from each element.
+ ///
+ /// `Ok` variant:
+ /// - isn't 100% guaranteed to contain valid pack-IDs
+ /// but you can assume it does (except in `unsafe {}` blocks)
+ /// - isn't sorted
+ /// - duplicates never _seem_ to happen, but don't assume uniqueness
+ pub fn list_packages_sys(
+ mut self,
+ f: Option,
+ user_id: Option,
+ ) -> Result, String> {
+ let cmd = &mut self.0.0.0;
+
+ cmd.args(["list", "packages", "-s"]);
+ if let Some(s) = f {
+ cmd.arg(s.to_str());
+ }
+ if let Some(u) = user_id {
+ cmd.arg("--user");
+ cmd.arg(u.to_string());
+ }
+
+ self.0.0.run().map(|pack_ls| {
+ pack_ls
+ .lines()
+ .filter_map(|p_ln| {
+ debug_assert!(p_ln.starts_with(PACK_PREFIX));
+ let p = &p_ln[PACK_PREFIX.len()..];
+ if PackageId::new(p).is_some() {
+ Some(String::from(p))
+ } else {
+ warn!("skipping nonstandard package name: {p:?}");
+ None
+ }
+ })
+ .collect()
+ })
+ }
+
+ /// `list users` sub-command, deserialized/parsed.
+ ///
+ /// -
+ /// -
+ pub fn list_users(mut self) -> Result, String> {
+ self.0.0.0.args(["list", "users"]);
+ Ok(self
+ .0
+ .0
+ .run()?
+ .lines()
+ .skip(1) // omit header
+ .map(|ln| {
+ // this could be optimized by making more API-stability assumptions
+ let ln = ln.trim_ascii_start();
+ let ln = ln.strip_prefix("UserInfo").unwrap_or(ln).trim_ascii_start();
+ let ln = ln.strip_prefix('{').unwrap_or(ln).trim_ascii();
+ //let run;
+ let ln = if let Some(l) = ln.strip_suffix("running") {
+ //run = true;
+ l.trim_ascii_end()
+ } else {
+ //run = false;
+ ln
+ };
+ let ln = ln.strip_suffix('}').unwrap_or(ln).trim_ascii_end();
+ // https://android.googlesource.com/platform/frameworks/base/+/refs/heads/main/core/java/android/content/pm/UserInfo.java
+ // The format looks stable today, but google may change it in future Android versions
+ // (and very old Androids might differ). Keep parsing defensive.
+ // Expected shape: "UserInfo{::}[ running]"
+
+ let mut comps = ln.split(':');
+
+ let id = comps
+ .next()
+ .expect("There must be at least 1 ':'-separated component")
+ .parse()
+ .expect("string assumed to be UID numeral");
+ //let name = comps
+ // .next()
+ // .expect("There must be at least 2 ':'-separated components. 2nd is user-name");
+ //let flags = u32::from_str_radix(
+ // comps.next().expect(
+ // "There must be at least 3 ':'-separated components. 3rd is user bit-flags",
+ // ),
+ // 16,
+ //)
+ //.expect("string assumed to be hexadecimal bit-flags");
+ UserInfo {
+ id,
+ //name: name.into(),
+ //flags,
+ //running: run,
+ }
+ })
+ .collect())
+ }
+}
+
+/// Mirror of AOSP `UserInfo` Java Class, with an extra field
+#[derive(Debug, Clone)]
+pub struct UserInfo {
+ id: u16,
+ //name: Box,
+ //flags: u32,
+ //running: bool,
+}
+impl UserInfo {
+ #[must_use]
+ pub const fn get_id(&self) -> u16 {
+ self.id
+ }
+ /*
+ /// Check if the user was logged-in at the time `pm list users` was invoked
+ #[must_use]
+ #[allow(dead_code, reason = "Currently unused by UI; kept for future features")]
+ pub const fn was_running(&self) -> bool {
+ self.running
+ }
+ */
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn invalid_pack_ids() {
+ for p_id in [
+ "",
+ " ",
+ ".",
+ "nodots",
+ "com..example",
+ "net.hello.",
+ "org.0example",
+ "org._foobar",
+ "the.🎂.is.a.lie",
+ "EXCLAMATION!!!!",
+ ] {
+ assert_eq!(PackageId::new(p_id), None);
+ }
+ }
+
+ #[test]
+ fn valid_pack_ids() {
+ for p_id in [
+ "A.a",
+ "x.X",
+ "org.example",
+ "net.hello",
+ "uwu.owo",
+ "Am0Gu5.Zuz",
+ "net.net.net.net.net.net.net.net.net.net.net",
+ "com.github.w1nst0n",
+ "this_.String_.is_.not_.real_",
+ ] {
+ assert_ne!(PackageId::new(p_id), None);
+ }
+ }
+}
diff --git a/crates/uad-core/src/config.rs b/crates/uad-core/src/config.rs
new file mode 100644
index 0000000..5c41d78
--- /dev/null
+++ b/crates/uad-core/src/config.rs
@@ -0,0 +1,150 @@
+use crate::CACHE_DIR;
+use crate::CONFIG_DIR;
+use crate::sync::User;
+use crate::utils::DisplayablePath;
+use log::error;
+use serde::{Deserialize, Serialize};
+use std::fs;
+use std::path::PathBuf;
+use std::sync::LazyLock;
+
+const DEFAULT_THEME: &str = "Auto (follow system theme)";
+
+#[derive(Default, Debug, Serialize, Deserialize, Clone)]
+pub struct Config {
+ pub general: GeneralSettings,
+ #[serde(skip_serializing_if = "Vec::is_empty", default = "Vec::new")]
+ pub devices: Vec,
+}
+
+#[derive(Debug, Serialize, Deserialize, Clone)]
+pub struct GeneralSettings {
+ pub theme: String,
+ pub expert_mode: bool,
+ pub backup_folder: PathBuf,
+}
+
+#[derive(Default, Debug, Clone)]
+pub struct BackupSettings {
+ pub backups: Vec,
+ pub selected: Option,
+ pub users: Vec,
+ pub selected_user: Option,
+ pub backup_state: String,
+}
+
+#[derive(Debug, Serialize, Deserialize, Clone, Default)]
+pub struct DeviceSettings {
+ /// Unique serial identifier
+ pub device_id: String,
+ pub disable_mode: bool, // should be `enum RemovalMode`
+ pub multi_user_mode: bool,
+ #[serde(skip)]
+ pub backup: BackupSettings,
+}
+
+impl Default for GeneralSettings {
+ fn default() -> Self {
+ Self {
+ theme: DEFAULT_THEME.to_string(),
+ expert_mode: false,
+ backup_folder: CACHE_DIR.join("backups"),
+ }
+ }
+}
+
+static CONFIG_FILE: LazyLock = LazyLock::new(|| CONFIG_DIR.join("config.toml"));
+
+impl Config {
+ pub fn save_device_settings(
+ &mut self,
+ device_settings: DeviceSettings,
+ general: GeneralSettings,
+ ) {
+ if let Some(device) = self
+ .devices
+ .iter_mut()
+ .find(|x| x.device_id == device_settings.device_id)
+ {
+ *device = device_settings;
+ } else {
+ self.devices.push(device_settings);
+ }
+ self.general = general;
+ let toml = toml::to_string(&self).unwrap();
+ fs::write(&*CONFIG_FILE, toml).expect("Could not write config file to disk!");
+ }
+
+ #[must_use]
+ pub fn load_configuration_file() -> Self {
+ match fs::read_to_string(&*CONFIG_FILE) {
+ Ok(s) => match toml::from_str(&s) {
+ Ok(config) => return config,
+ Err(e) => error!("Invalid config file: `{e}`"),
+ },
+ Err(e) => error!("Failed to read config file: `{e}`"),
+ }
+ error!("Restoring default config file");
+ let toml = toml::to_string(&Self::default()).unwrap();
+ fs::write(&*CONFIG_FILE, toml).expect("Could not write config file to disk!");
+ Self::default()
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ //! Unit tests
+
+ use super::*;
+ use std::path::Path;
+
+ // create a clean default config file for testing
+ fn create_default_config_file() {
+ let toml = toml::to_string(&Config::default()).unwrap();
+ fs::write(&*CONFIG_FILE, toml).expect("Could not write config file to disk!");
+ }
+
+ #[test]
+ fn test_create_default_config_file() {
+ create_default_config_file();
+ assert!(CONFIG_FILE.exists());
+ }
+
+ #[test]
+ fn test_load_configuration_file() {
+ create_default_config_file();
+ let config = Config::load_configuration_file();
+ // non-deterministic
+ //assert_eq!(config.devices.len(), 0);
+ assert_eq!(config.general.theme, DEFAULT_THEME);
+ assert!(!config.general.expert_mode);
+ assert_eq!(config.general.backup_folder, CACHE_DIR.join("backups"));
+ }
+
+ // non-deterministic
+ /*
+ #[test]
+ fn test_save_changes() {
+ let mut settings = Settings::default();
+ let device_id = "test_device".to_string();
+ settings.device.device_id = device_id.clone();
+ Config::save_changes(&settings, &device_id);
+ let config = Config::load_configuration_file();
+ assert_eq!(config.devices[0].device_id, device_id);
+ }
+ */
+
+ #[test]
+ fn test_default_config() {
+ let config = Config::default();
+ assert_eq!(config.devices.len(), 0);
+ assert_eq!(config.general.theme, DEFAULT_THEME);
+ assert!(!config.general.expert_mode);
+ assert_eq!(config.general.backup_folder, CACHE_DIR.join("backups"));
+ }
+
+ #[test]
+ fn test_config_file_path() {
+ assert_eq!(&*CONFIG_FILE, Path::new(&*CONFIG_DIR.join("config.toml")));
+ }
+}
diff --git a/crates/uad-core/src/lib.rs b/crates/uad-core/src/lib.rs
new file mode 100644
index 0000000..be3e5b4
--- /dev/null
+++ b/crates/uad-core/src/lib.rs
@@ -0,0 +1,23 @@
+#![allow(
+ clippy::missing_panics_doc,
+ clippy::missing_errors_doc,
+ clippy::collapsible_if,
+ clippy::uninlined_format_args,
+ clippy::result_unit_err,
+ reason = "Doc+style pedantic lints are out-of-scope for this pass"
+)]
+
+pub mod adb;
+pub mod config;
+pub mod save;
+pub mod sync;
+pub mod uad_lists;
+pub mod update;
+pub mod utils;
+
+use std::path::PathBuf;
+use std::sync::LazyLock;
+pub static CONFIG_DIR: LazyLock =
+ LazyLock::new(|| utils::setup_uad_dir(&dirs::config_dir().expect("Can't detect config dir")));
+pub static CACHE_DIR: LazyLock =
+ LazyLock::new(|| utils::setup_uad_dir(&dirs::cache_dir().expect("Can't detect cache dir")));
diff --git a/src/core/save.rs b/crates/uad-core/src/save.rs
similarity index 56%
rename from src/core/save.rs
rename to crates/uad-core/src/save.rs
index 3a6697d..8c1db07 100644
--- a/src/core/save.rs
+++ b/crates/uad-core/src/save.rs
@@ -1,34 +1,31 @@
-use crate::core::config::DeviceSettings;
-use crate::core::sync::{apply_pkg_state_commands, CorePackage, Phone, User};
-use crate::core::utils::DisplayablePath;
-use crate::gui::widgets::package_row::PackageRow;
-use crate::CACHE_DIR;
+use crate::config::{Config, DeviceSettings};
+use crate::sync::{CorePackage, Phone, User, apply_pkg_state_commands};
+use crate::utils::DisplayablePath;
+use log::{error, info, warn};
use serde::{Deserialize, Serialize};
-use static_init::dynamic;
-use std::fs;
-use std::path::{Path, PathBuf};
-
-#[dynamic]
-pub static BACKUP_DIR: PathBuf = CACHE_DIR.join("backups");
+use std::{
+ fs,
+ path::{Path, PathBuf},
+};
#[derive(Default, Deserialize, Serialize, Debug, Clone, PartialEq, Eq)]
-struct PhoneBackup {
- device_id: String,
- users: Vec,
+pub struct PhoneBackup {
+ pub device_id: String,
+ pub users: Vec,
}
#[derive(Default, Deserialize, Serialize, Debug, Clone, PartialEq, Eq)]
-struct UserBackup {
- id: u16,
- packages: Vec,
+pub struct UserBackup {
+ pub id: u16,
+ pub packages: Vec,
}
-// Backup all `Uninstalled` and `Disabled` packages
-pub async fn backup_phone(
+/// Backup all `Uninstalled` and `Disabled` packages
+pub fn backup_phone(
users: Vec,
device_id: String,
- phone_packages: Vec>,
-) -> Result<(), String> {
+ phone_packages: &[Vec],
+) -> Result {
let mut backup = PhoneBackup {
device_id: device_id.clone(),
..PhoneBackup::default()
@@ -40,29 +37,27 @@ pub async fn backup_phone(
..UserBackup::default()
};
- for p in phone_packages[u.index].clone() {
- user_backup.packages.push(CorePackage {
- name: p.name.clone(),
- state: p.state,
- });
+ for p in phone_packages[u.index].iter().cloned() {
+ user_backup.packages.push(p);
}
backup.users.push(user_backup);
}
match serde_json::to_string_pretty(&backup) {
Ok(json) => {
- let backup_path = &*BACKUP_DIR.join(device_id);
+ let backup_dir: PathBuf = Config::load_configuration_file().general.backup_folder;
+ let backup_path = &*backup_dir.join(device_id);
if let Err(e) = fs::create_dir_all(backup_path) {
- error!("BACKUP: could not create backup dir: {}", e);
+ error!("BACKUP: could not create backup dir: {e}");
return Err(e.to_string());
- };
+ }
let backup_filename =
format!("{}.json", chrono::Local::now().format("%Y-%m-%d_%H-%M-%S"));
match fs::write(backup_path.join(backup_filename), json) {
- Ok(_) => Ok(()),
+ Ok(()) => Ok(true),
Err(err) => Err(err.to_string()),
}
}
@@ -71,34 +66,30 @@ pub async fn backup_phone(
}
pub fn list_available_backups(dir: &Path) -> Vec {
- #[allow(clippy::option_if_let_else)]
match fs::read_dir(dir) {
Ok(files) => files
- .filter_map(|e| e.ok())
+ .filter_map(Result::ok)
.map(|e| DisplayablePath { path: e.path() })
.collect::>(),
Err(_) => vec![],
}
}
+#[must_use]
pub fn list_available_backup_user(backup: DisplayablePath) -> Vec {
match fs::read_to_string(backup.path) {
- Ok(data) => {
- let phone_backup: PhoneBackup =
- serde_json::from_str(&data).expect("Unable to parse backup file");
-
- let mut users = vec![];
- for u in phone_backup.users {
- users.push(User {
- id: u.id,
- index: 0,
- protected: false,
- });
- }
- users
- }
+ Ok(data) => serde_json::from_str::(&data)
+ .expect("Unable to parse backup file")
+ .users
+ .into_iter()
+ .map(|u| User {
+ id: u.id,
+ index: 0,
+ protected: false,
+ })
+ .collect(),
Err(e) => {
- error!("[BACKUP]: Selected backup file not found: {}", e);
+ error!("[BACKUP]: Selected backup file not found: {e}");
vec![]
}
}
@@ -106,15 +97,22 @@ pub fn list_available_backup_user(backup: DisplayablePath) -> Vec {
#[derive(Debug)]
pub struct BackupPackage {
+ pub i_user: usize,
pub index: usize,
pub commands: Vec,
}
+#[derive(Debug)]
+pub struct RestoreResult {
+ pub packages: Vec,
+ pub skipped_count: usize,
+}
+
pub fn restore_backup(
selected_device: &Phone,
- packages: &[Vec],
+ packages: &[Vec],
settings: &DeviceSettings,
-) -> Result, String> {
+) -> Result {
match fs::read_to_string(
settings
.backup
@@ -129,30 +127,31 @@ pub fn restore_backup(
serde_json::from_str(&data).expect("Unable to parse backup file");
let mut commands = vec![];
+ let mut skipped_packages = 0;
for u in phone_backup.users {
- let index = match selected_device.user_list.iter().find(|x| x.id == u.id) {
+ let i_user = match selected_device.user_list.iter().find(|x| x.id == u.id) {
Some(i) => i.index,
None => return Err(format!("user {} doesn't exist", u.id)),
};
for (i, backup_package) in u.packages.iter().enumerate() {
- let package: CorePackage;
- match packages[index]
+ let package: CorePackage = if let Some(p) = packages[i_user]
.iter()
.find(|x| x.name == backup_package.name)
{
- Some(p) => package = p.into(),
- None => {
- return Err(format!(
- "{} not found for user {}",
- backup_package.name, u.id
- ))
- }
- }
+ p.clone()
+ } else {
+ skipped_packages += 1;
+ warn!(
+ "{} not found for user {} - skipping package during restore",
+ backup_package.name, u.id
+ );
+ continue;
+ };
let p_commands = apply_pkg_state_commands(
&package,
backup_package.state,
- &settings
+ settings
.backup
.selected_user
.ok_or("field should be Some type")?,
@@ -160,19 +159,29 @@ pub fn restore_backup(
);
if !p_commands.is_empty() {
commands.push(BackupPackage {
+ i_user,
index: i,
commands: p_commands,
});
}
}
}
+ if skipped_packages > 0 {
+ info!(
+ "Restore completed with {skipped_packages} packages skipped (not found on device)"
+ );
+ }
if !commands.is_empty() {
commands.push(BackupPackage {
+ i_user: 0,
index: 0,
commands: vec![],
});
}
- Ok(commands)
+ Ok(RestoreResult {
+ packages: commands,
+ skipped_count: skipped_packages,
+ })
}
Err(e) => Err(e.to_string()),
}
diff --git a/crates/uad-core/src/sync.rs b/crates/uad-core/src/sync.rs
new file mode 100644
index 0000000..f90b6ee
--- /dev/null
+++ b/crates/uad-core/src/sync.rs
@@ -0,0 +1,663 @@
+use crate::{
+ adb::{ACommand as AdbCommand, PM_CLEAR_PACK, PackageId},
+ uad_lists::PackageState,
+};
+use log::{error, info};
+use retry::{OperationResult, delay::Fixed, retry};
+use serde::{Deserialize, Serialize};
+
+/// An Android device, typically a phone
+#[derive(Debug, Clone, PartialEq, Eq)]
+pub struct Phone {
+ /// Non-market name
+ pub model: String, // could be `Copy`
+ /// Android API level version
+ pub android_sdk: u8,
+ /// In theory, `len < u16::MAX` _should_ always be `true`.
+ /// In practice, `len <= u8::MAX`.
+ pub user_list: Vec,
+ /// Unique serial identifier
+ pub adb_id: String, // could be `Copy`
+}
+
+impl Default for Phone {
+ fn default() -> Self {
+ Self {
+ model: "fetching devices...".to_string(),
+ android_sdk: 0,
+ user_list: vec![],
+ adb_id: String::default(),
+ }
+ }
+}
+
+impl std::fmt::Display for Phone {
+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+ write!(f, "{}", self.model)
+ }
+}
+
+/// `UserInfo` but relevant to UAD
+#[derive(Default, Debug, Clone, Copy, PartialEq, Eq)]
+pub struct User {
+ pub id: u16,
+ pub index: usize,
+ pub protected: bool,
+}
+
+impl std::fmt::Display for User {
+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+ write!(f, "user {}", self.id)
+ }
+}
+
+/// An enum to contain different variants for errors yielded by ADB.
+#[derive(Debug, Clone)]
+pub enum AdbError {
+ Generic(String),
+}
+
+/// Run an arbitrary shell action via the typed ADB wrapper.
+/// This replaces the deprecated `adb_shell_command`.
+///
+/// If `serial` is empty, it lets ADB choose the default device.
+pub fn run_adb_shell_action>(
+ device_serial: S,
+ action: &str,
+) -> Result {
+ let serial = device_serial.as_ref();
+
+ match AdbCommand::new().shell(serial).raw(action) {
+ Ok(o) => {
+ if ["Error", "Failure"].iter().any(|&e| o.contains(e)) {
+ let friendly_msg = make_friendly_error_message(&o, action);
+ return Err(AdbError::Generic(friendly_msg));
+ }
+ info!("{action} -> {o}");
+ Ok(o)
+ }
+ Err(err) => {
+ if !err.contains("[not installed for") {
+ let friendly_msg = make_friendly_error_message(&err, action);
+ return Err(AdbError::Generic(friendly_msg));
+ }
+ Err(AdbError::Generic(err))
+ }
+ }
+}
+
+/// Convert common OEM-specific ADB error messages into user-friendly explanations.
+fn make_friendly_error_message(error_output: &str, action: &str) -> String {
+ // Common Samsung errors
+ if error_output.contains("DELETE_FAILED_USER_RESTRICTED") {
+ return format!(
+ "Cannot uninstall: This package is restricted by the device manufacturer (Samsung Knox or similar).\n\
+ Error: {error_output}\n\
+ Tip: Try disabling the package instead, or check device settings for Knox/security restrictions."
+ );
+ }
+
+ if error_output.contains("NOT_INSTALLED_FOR_USER") {
+ return format!(
+ "Package is not installed for the current user.\n\
+ Error: {error_output}\n\
+ Tip: The package may be installed for a different user profile or work profile."
+ );
+ }
+
+ // Empty package name error
+ if error_output.contains("Shell cannot change component state for null") {
+ return format!(
+ "Invalid package: Empty package name detected.\n\
+ Error: {error_output}\n\
+ Tip: Please refresh the package list and try again."
+ );
+ }
+
+ // Generic permission errors
+ if error_output.contains("Permission denied")
+ || error_output.contains("INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE")
+ {
+ return format!(
+ "Permission denied: Insufficient privileges to perform this action.\n\
+ Error: {error_output}\n\
+ Tip: This may require root access or the package is protected by the system."
+ );
+ }
+
+ // Work profile / managed device errors
+ if error_output.contains("DELETE_FAILED_DEVICE_POLICY_MANAGER") {
+ return format!(
+ "Cannot modify: Package is managed by device policy (MDM/EMM).\n\
+ Error: {error_output}\n\
+ Tip: Contact your IT administrator if this is a work device."
+ );
+ }
+
+ // Generic failure with context
+ format!("{action} -> {error_output}")
+}
+
+/// If `None`, returns an empty String, not " --user 0"
+#[must_use]
+pub fn user_flag(user_id: Option) -> String {
+ user_id
+ .map(|user| format!(" --user {}", user.id))
+ .unwrap_or_default()
+}
+
+// Minimum information for processing adb commands
+#[derive(Debug, Deserialize, Serialize, Clone, PartialEq, Eq)]
+pub struct CorePackage {
+ pub name: String,
+ pub description: String,
+ #[serde(default)]
+ pub removal: crate::uad_lists::Removal,
+ #[serde(default)]
+ pub state: PackageState,
+ #[serde(default)]
+ pub list: crate::uad_lists::UadList,
+}
+
+#[must_use]
+pub fn apply_pkg_state_commands(
+ package: &CorePackage,
+ wanted_state: PackageState,
+ selected_user: User,
+ phone: &Phone,
+) -> Vec {
+ // https://github.com/Universal-Debloater-Alliance/universal-android-debloater/wiki/ADB-reference
+ // ALWAYS PUT THE COMMAND THAT CHANGES THE PACKAGE STATE FIRST!
+ let commands = match wanted_state {
+ PackageState::Enabled => match package.state {
+ PackageState::Disabled => vec!["pm enable"],
+ PackageState::Uninstalled => match phone.android_sdk {
+ i if i >= 23 => vec!["cmd package install-existing"],
+ 21 | 22 => vec!["pm unhide"],
+ 19 | 20 => vec!["pm unblock", PM_CLEAR_PACK],
+ _ => unreachable!("already prevented by the GUI"),
+ },
+ _ => vec![],
+ },
+ PackageState::Disabled => match package.state {
+ PackageState::Uninstalled | PackageState::Enabled => {
+ if supports_disabling(phone) {
+ vec!["pm disable-user", "am force-stop", PM_CLEAR_PACK]
+ } else {
+ vec![]
+ }
+ }
+ _ => vec![],
+ },
+ PackageState::Uninstalled => match package.state {
+ PackageState::Enabled | PackageState::Disabled => match phone.android_sdk {
+ sdk if sdk >= 23 => vec!["pm uninstall"], // > Marshmallow (6.0)
+ 21 | 22 => vec!["pm hide", PM_CLEAR_PACK], // Lollipop (5.x)
+ _ => vec!["pm block", PM_CLEAR_PACK], // Disable mode is unavailable on older devices because the specific ADB commands need root
+ },
+ _ => vec![],
+ },
+ PackageState::All => vec![],
+ }; // this should be a `tinyvec`, as `len <= 4`
+
+ let user = supports_multi_user(phone).then_some(selected_user);
+ request_builder(&commands, &package.name, user)
+}
+
+/// Build a command request to be sent via ADB to a device.
+/// `commands` accepts one or more ADB shell commands
+/// which act on a common `package` and `user`.
+#[must_use]
+pub fn request_builder(commands: &[&str], package: &str, user: Option) -> Vec {
+ // Defense-in-depth: `package` is interpolated verbatim into a device-shell
+ // action, so refuse any invalid name/ID. Every current caller already
+ // reconciles the name against the live device package list before reaching
+ // here, so this rejects nothing legitimate — it just keeps the no-injection
+ // guarantee local to the sink instead of relying on each caller to sanitise.
+ // Fail closed: emit no command for a malformed name rather than an injectable
+ // device-shell string.
+ if PackageId::new(package).is_none() {
+ error!("request_builder: refusing invalid package name: {package:?}");
+ return Vec::new();
+ }
+ let maybe_user_flag = user_flag(user);
+ commands
+ .iter()
+ .map(|c| format!("{c}{maybe_user_flag} {package}"))
+ .collect()
+}
+
+/// Get the model by querying the `ro.product.model` property.
+///
+/// If `serial` is empty, it lets ADB choose the default device.
+#[must_use]
+pub fn get_device_model(serial: &str) -> String {
+ AdbCommand::new()
+ .shell(serial)
+ .getprop("ro.product.model")
+ .unwrap_or_else(|err| {
+ eprintln!("ERROR: {err}");
+ error!("{err}");
+ if err.contains("adb: no devices/emulators found") {
+ "no devices/emulators found".to_string()
+ } else {
+ err
+ }
+ })
+}
+
+/// Get the brand by querying the `ro.product.brand` property.
+///
+/// If `serial` is empty, it lets ADB choose the default device.
+#[must_use]
+pub fn get_device_brand(serial: &str) -> String {
+ AdbCommand::new()
+ .shell(serial)
+ .getprop("ro.product.brand")
+ // `trim` is just-in-case
+ .map(|s| s.trim().to_string())
+ .unwrap_or_default()
+}
+
+/// Get Android SDK version by querying the
+// `ro.build.version.sdk` property or defaulting to 0.
+///
+/// If `device_serial` is empty, it lets ADB choose the default device.
+#[must_use]
+pub fn get_android_sdk(device_serial: &str) -> u8 {
+ AdbCommand::new()
+ .shell(device_serial)
+ .getprop("ro.build.version.sdk")
+ .map_or(0, |sdk| {
+ sdk.parse().expect("SDK version numeral must be valid")
+ })
+}
+
+/// Capture the current state of a package across all non-protected users.
+/// This is used to detect cross-user behavior by comparing before and after states.
+///
+/// Only includes users where the package exists (Some state). Users where the package
+/// doesn't exist (None) are not tracked.
+#[must_use]
+pub fn capture_cross_user_states(
+ package_name: &str,
+ device_serial: &str,
+ target_user_id: u16,
+ phone: &Phone,
+) -> Vec<(u16, PackageState)> {
+ phone
+ .user_list
+ .iter()
+ .filter(|u| !u.protected && u.id != target_user_id)
+ .filter_map(|u| {
+ verify_package_state(package_name, device_serial, Some(u.id)).map(|state| (u.id, state))
+ })
+ .collect()
+}
+
+/// Detect cross-user behavior and return appropriate notification message.
+/// This handles unexpected cross-user behavior:
+/// - Case A: Uninstall → Restore (package appears on other users)
+/// - Case B: Uninstall → Uninstall (package disappears from other users that previously had it)
+/// - Case C: Restore → Restore (package appears on other users)
+#[must_use]
+pub fn detect_cross_user_behavior(
+ package_name: &str,
+ device_serial: &str,
+ target_user_id: u16,
+ wanted_state: PackageState,
+ actual_state: PackageState,
+ phone: &Phone,
+ before_states: &[(u16, PackageState)],
+) -> Option {
+ // Only check if operation was successful on target user
+ if actual_state != wanted_state {
+ return None;
+ }
+
+ // Only check if we have multiple users
+ if phone.user_list.len() < 2 {
+ return None;
+ }
+
+ let after_states =
+ check_cross_user_package_existence(package_name, device_serial, target_user_id, phone);
+
+ match wanted_state {
+ PackageState::Uninstalled => {
+ if after_states.is_empty() {
+ // Case B: Uninstall → Uninstall (check if all users lost package)
+ let affected_users: Vec<_> = before_states
+ .iter()
+ .filter(|(uid, before_state)| {
+ // Only flag if the package was installed/enabled/disabled before
+ *before_state != PackageState::Uninstalled
+ // And is NOT in after_states (doesn't exist in usable state anymore)
+ && !after_states.iter().any(|(after_uid, _)| after_uid == uid)
+ })
+ .map(|(uid, _)| uid)
+ .collect();
+
+ if affected_users.is_empty() {
+ None
+ } else {
+ let user_list = affected_users
+ .iter()
+ .map(|uid| format!("user {uid}"))
+ .collect::>()
+ .join(", ");
+
+ Some(format!(
+ "Detected cross-user uninstall: package was also uninstalled from {user_list} after uninstalling from user {target_user_id}"
+ ))
+ }
+ } else {
+ // Case A: Uninstall → Restore (package appears on other users)
+ let user_list = after_states
+ .iter()
+ .map(|(uid, state)| format!("user {uid} ({state:?})"))
+ .collect::>()
+ .join(", ");
+
+ Some(format!(
+ "Detected cross-user restoration: package exists on {user_list} after uninstalling from user {target_user_id}"
+ ))
+ }
+ }
+ PackageState::Enabled | PackageState::Disabled => {
+ // Case C: Restore → Restore (package appears on other users)
+
+ // Check if a user didn't have the package before (not tracked or package didn't exist).
+ // Detects packages that appear on users where they didn't exist previously (OEM cross-user restoration).
+ let was_package_absent_before = |uid: &u16| {
+ before_states
+ .iter()
+ .find(|(before_uid, _)| before_uid == uid)
+ .is_none_or(|(_, before_state)| *before_state == PackageState::Uninstalled)
+ };
+
+ let newly_appeared: Vec<_> = after_states
+ .iter()
+ .filter(|(uid, _after_state)| was_package_absent_before(uid))
+ .collect();
+
+ if newly_appeared.is_empty() {
+ None
+ } else {
+ let user_list = newly_appeared
+ .iter()
+ .map(|(uid, state)| format!("user {uid} ({state:?})"))
+ .collect::>()
+ .join(", ");
+
+ Some(format!(
+ "Detected cross-user restoration: package exists on {user_list} after {} from user {target_user_id}",
+ if wanted_state == PackageState::Enabled {
+ "enabling"
+ } else {
+ "disabling"
+ }
+ ))
+ }
+ }
+ PackageState::All => None,
+ }
+}
+
+#[must_use]
+pub const fn supports_disabling(dev: &Phone) -> bool {
+ // >= Marshmallow (6.0)
+ dev.android_sdk >= 23
+}
+
+/// Check if it might support multi-user mode,
+/// by simply comparing SDK version.
+/// `true` isn't reliable, you can only trust `false`.
+///
+/// See:
+/// -
+/// -
+#[must_use]
+pub const fn supports_multi_user(dev: &Phone) -> bool {
+ // >= Lollipop (5.0)
+ dev.android_sdk >= 21
+}
+
+/// Check if a `user_id` is protected on a device by trying
+/// to list associated packages.
+///
+/// If `device_serial` is empty, it lets ADB choose the default device.
+pub fn is_protected_user>(user_id: u16, device_serial: S) -> bool {
+ AdbCommand::new()
+ .shell(device_serial)
+ .pm()
+ .list_packages_sys(None, Some(user_id))
+ .is_err()
+}
+
+#[must_use]
+pub fn list_users_idx_prot(device_serial: &str) -> Vec {
+ AdbCommand::new()
+ .shell(device_serial)
+ .pm()
+ .list_users()
+ .map(|out| {
+ out.into_iter()
+ .enumerate()
+ .map(|(i, user)| {
+ let id = user.get_id();
+ User {
+ id,
+ index: i,
+ protected: is_protected_user(id, device_serial),
+ }
+ })
+ .collect()
+ })
+ .unwrap_or_default()
+}
+
+/// This matches serials (`getprop ro.serialno`)
+/// that are authorized by the user.
+#[must_use]
+pub fn get_devices_list() -> Vec {
+ retry(
+ Fixed::from_millis(500).take(if cfg!(debug_assertions) { 3 } else { 10 }),
+ || match AdbCommand::new().devices() {
+ Ok(devices) => {
+ let mut device_list: Vec = vec![];
+ if devices.iter().all(|(_, stat)| stat != "device") {
+ return OperationResult::Retry(vec![]);
+ }
+ for device in devices {
+ let serial = &device.0;
+ device_list.push(Phone {
+ model: format!("{} {}", get_device_brand(serial), get_device_model(serial)),
+ android_sdk: get_android_sdk(serial),
+ user_list: list_users_idx_prot(serial),
+ adb_id: serial.clone(),
+ });
+ }
+ OperationResult::Ok(device_list)
+ }
+ Err(err) => {
+ error!("get_devices_list() -> {err}");
+ let test: Vec = vec![];
+ OperationResult::Retry(test)
+ }
+ },
+ )
+ .unwrap_or_default()
+}
+
+#[must_use]
+pub fn initial_load() -> bool {
+ match AdbCommand::new().devices() {
+ Ok(_devices) => true,
+ Err(_err) => false,
+ }
+}
+
+/// Get the current state of a package on a device
+#[must_use]
+pub fn get_package_state(
+ device_serial: &str,
+ package_name: &str,
+ user_id: Option,
+) -> Option {
+ use crate::adb::{ACommand as AdbCommand, PmListPacksFlag};
+
+ // Check if package is enabled
+ if let Ok(enabled_packages) = AdbCommand::new()
+ .shell(device_serial)
+ .pm()
+ .list_packages_sys(Some(PmListPacksFlag::OnlyEnabled), user_id)
+ && enabled_packages.contains(&package_name.to_string())
+ {
+ return Some(PackageState::Enabled);
+ }
+
+ // Check if package is disabled
+ if let Ok(disabled_packages) = AdbCommand::new()
+ .shell(device_serial)
+ .pm()
+ .list_packages_sys(Some(PmListPacksFlag::OnlyDisabled), user_id)
+ && disabled_packages.contains(&package_name.to_string())
+ {
+ return Some(PackageState::Disabled);
+ }
+
+ // Check if package exists at all (including uninstalled)
+ if let Ok(all_packages) = AdbCommand::new()
+ .shell(device_serial)
+ .pm()
+ .list_packages_sys(Some(PmListPacksFlag::IncludeUninstalled), user_id)
+ && all_packages.contains(&package_name.to_string())
+ {
+ return Some(PackageState::Uninstalled);
+ }
+
+ // Package not found at all - it doesn't exist on this device/user
+ None
+}
+
+/// Verify the current state of a package on a device.
+/// Returns the package state, or `None` if the package doesn't exist.
+#[must_use]
+pub fn verify_package_state(
+ package_name: &str,
+ device_serial: &str,
+ user_id: Option,
+) -> Option {
+ get_package_state(device_serial, package_name, user_id)
+}
+
+/// Check if a package exists on any other users besides the target user.
+/// This helps detect OEM-specific cross-user restoration behavior.
+///
+/// Only includes users where the package exists in a non-uninstalled state
+/// (i.e., Enabled or Disabled).
+#[must_use]
+pub fn check_cross_user_package_existence(
+ package_name: &str,
+ device_serial: &str,
+ target_user_id: u16,
+ phone: &Phone,
+) -> Vec<(u16, PackageState)> {
+ let mut other_user_states = Vec::new();
+
+ for user in &phone.user_list {
+ if user.id != target_user_id
+ && !user.protected
+ && let Some(state) = verify_package_state(package_name, device_serial, Some(user.id))
+ && state != PackageState::Uninstalled
+ {
+ other_user_states.push((user.id, state));
+ }
+ }
+
+ other_user_states
+}
+
+/// Creates a `CorePackage` with the specified state, preserving other fields from the original.
+fn package_with_state(package: &CorePackage, state: PackageState) -> CorePackage {
+ CorePackage {
+ state,
+ ..package.clone()
+ }
+}
+
+/// Executes the first available command and returns the result.
+fn execute_first_command(commands: &[String], phone: &Phone) -> Result<(), String> {
+ if commands.is_empty() {
+ return Err("No command available".to_string());
+ }
+ AdbCommand::new()
+ .shell(&phone.adb_id)
+ .raw(&commands[0])
+ .map(|_| ())
+ .map_err(|err| err.clone())
+}
+
+/// Attempt fallback action when package state verification fails
+pub fn attempt_fallback(
+ package: &CorePackage,
+ wanted_state: PackageState,
+ actual_state: PackageState,
+ user: User,
+ phone: &Phone,
+) -> Result {
+ match (wanted_state, actual_state) {
+ // Case 1: Tried to uninstall but package was reinstalled -> disable it
+ (PackageState::Uninstalled, PackageState::Enabled) => {
+ let pkg = package_with_state(package, PackageState::Enabled);
+ let commands = apply_pkg_state_commands(&pkg, PackageState::Disabled, user, phone);
+ execute_first_command(&commands, phone)
+ .map(|()| "disabled package instead of uninstalling".to_string())
+ .map_err(|e| format!("Failed to disable package: {e}"))
+ }
+
+ // Case 2: Tried to disable but package re-enabled itself -> try uninstall
+ (PackageState::Disabled, PackageState::Enabled) => {
+ let pkg = package_with_state(package, PackageState::Enabled);
+ let commands = apply_pkg_state_commands(&pkg, PackageState::Uninstalled, user, phone);
+ execute_first_command(&commands, phone)
+ .map_err(|e| format!("Failed to uninstall: {e}"))?;
+
+ // Verify the package was actually uninstalled
+ match verify_package_state(&package.name, &phone.adb_id, Some(user.id)) {
+ Some(PackageState::Uninstalled) | None => {
+ Ok("uninstalled package instead of disabling".to_string())
+ }
+ _ => Err("Package still exists after uninstall attempt".to_string()),
+ }
+ }
+
+ // Case 3: Tried to enable but package was disabled -> try uninstall then reinstall
+ (PackageState::Enabled, PackageState::Disabled) => {
+ let pkg = package_with_state(package, PackageState::Disabled);
+ let uninstall_cmds =
+ apply_pkg_state_commands(&pkg, PackageState::Uninstalled, user, phone);
+ execute_first_command(&uninstall_cmds, phone)
+ .map_err(|e| format!("Failed to uninstall for reinstall: {e}"))?;
+
+ // Now try to reinstall/enable
+ let pkg_uninstalled = package_with_state(package, PackageState::Uninstalled);
+ let enable_cmds =
+ apply_pkg_state_commands(&pkg_uninstalled, PackageState::Enabled, user, phone);
+
+ if enable_cmds.is_empty() {
+ return Ok("uninstalled package but couldn't reinstall".to_string());
+ }
+
+ execute_first_command(&enable_cmds, phone)
+ .map(|()| "uninstalled and reinstalled package to enable it".to_string())
+ .map_err(|e| format!("Failed to reinstall package: {e}"))
+ }
+
+ // Other cases - no fallback available
+ _ => Err(format!(
+ "No fallback available for wanted state {wanted_state:?} and actual state {actual_state:?}"
+ )),
+ }
+}
diff --git a/src/core/uad_lists.rs b/crates/uad-core/src/uad_lists.rs
similarity index 50%
rename from src/core/uad_lists.rs
rename to crates/uad-core/src/uad_lists.rs
index cf09d06..35cade9 100644
--- a/src/core/uad_lists.rs
+++ b/crates/uad-core/src/uad_lists.rs
@@ -1,16 +1,26 @@
-use crate::core::utils::{format_diff_time_from_now, last_modified_date};
use crate::CACHE_DIR;
-use retry::{delay::Fixed, retry, OperationResult};
+use crate::utils::{format_diff_time_from_now, last_modified_date};
+use log::warn;
+use retry::{OperationResult, delay::Fixed, retry};
use serde::{Deserialize, Serialize};
use serde_json;
+use std::borrow::Cow;
use std::collections::HashMap;
use std::fs;
-use std::path::{Path, PathBuf};
+use std::path::PathBuf;
+
+pub const LIST_FNAME: &str = "uad_lists.json";
+
+#[allow(
+ clippy::large_include_file,
+ reason = "https://github.com/Universal-Debloater-Alliance/universal-android-debloater-next-generation/discussions/608"
+)]
+// not `const`, because it's too big
+pub static DATA: &str = include_str!("../../../resources/assets/uad_lists.json");
#[derive(Deserialize, Debug, Clone, PartialEq, Hash, Eq)]
#[serde(rename_all = "camelCase")]
pub struct Package {
- id: String,
pub list: UadList,
pub description: String,
dependencies: Vec,
@@ -19,7 +29,7 @@ pub struct Package {
pub removal: Removal,
}
-#[derive(Default, Deserialize, Debug, Clone, Copy, PartialEq, Eq, Hash)]
+#[derive(Default, Deserialize, Serialize, Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum UadList {
#[default]
All,
@@ -42,7 +52,7 @@ pub enum UadListState {
impl std::fmt::Display for UadListState {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
- let date = last_modified_date(CACHE_DIR.join("uad_lists.json"));
+ let date = last_modified_date(CACHE_DIR.join(LIST_FNAME));
let s = match self {
Self::Downloading => "Checking updates...".to_string(),
Self::Done => format!("Done (last was {})", format_diff_time_from_now(date)),
@@ -63,24 +73,31 @@ impl UadList {
Self::Pending,
Self::Unlisted,
];
+
+ #[must_use]
+ pub const fn as_str(self) -> &'static str {
+ match self {
+ Self::All => "All lists",
+ Self::Aosp => "aosp",
+ Self::Carrier => "carrier",
+ Self::Google => "google",
+ Self::Misc => "misc",
+ Self::Oem => "oem",
+ Self::Pending => "pending",
+ Self::Unlisted => "unlisted",
+ }
+ }
}
impl std::fmt::Display for UadList {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
- write!(
- f,
- "{}",
- match self {
- Self::All => "All lists",
- Self::Aosp => "aosp",
- Self::Carrier => "carrier",
- Self::Google => "google",
- Self::Misc => "misc",
- Self::Oem => "oem",
- Self::Pending => "pending",
- Self::Unlisted => "unlisted",
- }
- )
+ f.write_str(self.as_str())
+ }
+}
+
+impl From for Cow<'_, str> {
+ fn from(list: UadList) -> Self {
+ Cow::Borrowed(list.as_str())
}
}
@@ -103,7 +120,7 @@ impl std::fmt::Display for PackageState {
f,
"{}",
match self {
- Self::All => "All packages",
+ Self::All => "All states",
Self::Enabled => "Enabled",
Self::Uninstalled => "Uninstalled",
Self::Disabled => "Disabled",
@@ -133,15 +150,15 @@ impl Opposite for PackageState {
}
// Bad names. To be changed!
-#[derive(Default, Debug, Deserialize, Clone, Copy, PartialEq, Eq, Hash)]
+#[derive(Default, Debug, Deserialize, Serialize, Clone, Copy, PartialEq, Eq, Hash)]
pub enum Removal {
- All,
#[default]
Recommended,
Advanced,
Expert,
Unsafe,
Unlisted,
+ All,
}
impl Removal {
@@ -153,79 +170,93 @@ impl Removal {
Self::Unsafe,
Self::Unlisted,
];
+ pub const CATEGORIES: [Self; 5] = [
+ Self::Recommended,
+ Self::Advanced,
+ Self::Expert,
+ Self::Unsafe,
+ Self::Unlisted,
+ ];
+
+ #[must_use]
+ pub const fn as_str(self) -> &'static str {
+ match self {
+ Self::All => "All removals",
+ Self::Recommended => "Recommended",
+ Self::Advanced => "Advanced",
+ Self::Expert => "Expert",
+ Self::Unsafe => "Unsafe",
+ Self::Unlisted => "Unlisted",
+ }
+ }
}
impl std::fmt::Display for Removal {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
- write!(
- f,
- "{}",
- match self {
- Self::All => "All",
- Self::Recommended => "Recommended",
- Self::Advanced => "Advanced",
- Self::Expert => "Expert",
- Self::Unsafe => "Unsafe",
- Self::Unlisted => "Unlisted",
- }
- )
+ f.write_str(self.as_str())
}
}
-type PackageHashMap = HashMap;
-pub fn load_debloat_lists(remote: bool) -> (Result, bool) {
- let cached_uad_lists: PathBuf = CACHE_DIR.join("uad_lists.json");
+impl From for Cow<'_, str> {
+ fn from(list: Removal) -> Self {
+ Cow::Borrowed(list.as_str())
+ }
+}
+
+pub type PackageHashMap = HashMap;
+pub fn load_debloat_lists(remote: bool) -> Result {
+ let cached_uad_lists: PathBuf = CACHE_DIR.join(LIST_FNAME);
let mut error = false;
- let list: Vec = if remote {
+ let list: PackageHashMap = if remote {
retry(Fixed::from_millis(1000).take(60), || {
- match ureq::get(
- "https://raw.githubusercontent.com/Universal-Debloater-Alliance/universal-android-debloater/\
- main/resources/assets/uad_lists.json",
- )
+ match ureq::get(format!(
+ "https://raw.githubusercontent.com\
+ /Universal-Debloater-Alliance\
+ /universal-android-debloater\
+ /main\
+ /resources\
+ /assets\
+ /{LIST_FNAME}"
+ ))
.call()
{
- Ok(data) => {
- let text = data.into_string().expect("response should be Ok type");
+ Ok(mut data) => {
+ // https://github.com/Universal-Debloater-Alliance/universal-android-debloater-next-generation/discussions/608
+ let text = data
+ .body_mut()
+ .with_config()
+ .limit(1 << (3 + 10 + 10))
+ .read_to_string()
+ .expect("remote list is bigger than 8MiB");
fs::write(cached_uad_lists.clone(), &text).expect("Unable to write file");
- let list = serde_json::from_str(&text).expect("Unable to parse");
+ let list: PackageHashMap =
+ serde_json::from_str(&text).expect("Unable to parse");
OperationResult::Ok(list)
}
Err(e) => {
- warn!("Could not load remote debloat list: {}", e);
+ warn!("Could not load remote debloat list: {e}");
error = true;
- OperationResult::Retry(Vec::::new())
+ OperationResult::Retry(PackageHashMap::new())
}
}
})
- .map_or_else(|_| get_local_lists(), |list| list)
+ .unwrap_or_else(|_| get_local_lists())
} else {
warn!("Could not load remote debloat list");
get_local_lists()
};
- // TODO: Do it without intermediary Vec?
- let mut package_lists = HashMap::new();
- for p in list {
- let name = p.id.clone();
- package_lists.insert(name, p);
- }
- if error {
- (Err(package_lists), remote)
- } else {
- (Ok(package_lists), remote)
- }
+ (if error { Err } else { Ok })(list)
}
-fn get_local_lists() -> Vec {
- const DATA: &str = include_str!("../../resources/assets/uad_lists.json");
- let cached_uad_lists = CACHE_DIR.join("uad_lists.json");
-
- if Path::new(&cached_uad_lists).exists() {
- let data = fs::read_to_string(cached_uad_lists).unwrap();
- serde_json::from_str(&data).expect("Unable to parse")
- } else {
- serde_json::from_str(DATA).expect("Unable to parse")
- }
+fn get_local_lists() -> PackageHashMap {
+ let cached_uad_lists = CACHE_DIR.join(LIST_FNAME);
+ serde_json::from_str(
+ fs::read_to_string(cached_uad_lists)
+ .as_deref()
+ .unwrap_or(DATA),
+ )
+ .expect("Unable to parse")
}
#[cfg(test)]
@@ -233,7 +264,6 @@ mod tests {
use super::*;
#[test]
fn test_parse_json() {
- const DATA: &str = include_str!("../../resources/assets/uad_lists.json");
- let _: Vec = serde_json::from_str(DATA).expect("Unable to parse");
+ let _: PackageHashMap = serde_json::from_str(DATA).expect("Unable to parse");
}
}
diff --git a/src/core/update.rs b/crates/uad-core/src/update.rs
similarity index 75%
rename from src/core/update.rs
rename to crates/uad-core/src/update.rs
index 8a948bd..51e52e4 100644
--- a/src/core/update.rs
+++ b/crates/uad-core/src/update.rs
@@ -2,7 +2,9 @@ use serde::Deserialize;
#[cfg(feature = "self-update")]
use {
- retry::{delay::Fibonacci, retry, OperationResult},
+ crate::utils::NAME,
+ log::{debug, error},
+ retry::{OperationResult, delay::Fibonacci, retry},
std::fs,
std::io,
std::io::copy,
@@ -52,15 +54,15 @@ impl std::fmt::Display for SelfUpdateStatus {
/// Download a file from the internet
#[cfg(feature = "self-update")]
-pub async fn download_file(url: T, dest_file: PathBuf) -> Result<(), String> {
- let url = url.to_string();
- debug!("downloading file from {}", &url);
+#[allow(clippy::unused_async, reason = "`.call` is equivalent to `.await`")]
+pub async fn download_file(url: &str, dest_file: PathBuf) -> Result<(), String> {
+ debug!("downloading file from {url}");
- match ureq::get(&url).call() {
- Ok(res) => {
+ match ureq::get(url).call() {
+ Ok(mut res) => {
let mut file = fs::File::create(dest_file).map_err(|e| e.to_string())?;
- if let Err(e) = copy(&mut res.into_reader(), &mut file) {
+ if let Err(e) = copy(&mut res.body_mut().as_reader(), &mut file) {
return Err(e.to_string());
}
}
@@ -74,7 +76,7 @@ pub async fn download_file(url: T, dest_file: PathBuf) -> Re
/// then returns both the original file name (new version) and temp path (old version)
#[cfg(feature = "self-update")]
pub async fn download_update_to_temp_file(
- bin_name: String,
+ bin_name: &str,
release: Release,
) -> Result<(PathBuf, PathBuf), ()> {
let current_bin_path = std::env::current_exe().map_err(|_| ())?;
@@ -107,13 +109,13 @@ pub async fn download_update_to_temp_file(
let archive_path = current_bin_path.parent().ok_or(())?.join(&asset_name);
- if let Err(e) = download_file(asset.download_url, archive_path.clone()).await {
- error!("Couldn't download UAD update: {}", e);
+ if let Err(e) = download_file(&asset.download_url, archive_path.clone()).await {
+ error!("Couldn't download {NAME} update: {e}");
return Err(());
}
if extract_binary_from_tar(&archive_path, &download_path).is_err() {
- error!("Couldn't extract UAD release tarball");
+ error!("Couldn't extract {NAME} release tarball");
return Err(());
}
@@ -130,8 +132,8 @@ pub async fn download_update_to_temp_file(
.cloned()
.ok_or(())?;
- if let Err(e) = download_file(asset.download_url, download_path.clone()).await {
- error!("Couldn't download UAD update: {}", e);
+ if let Err(e) = download_file(&asset.download_url, download_path.clone()).await {
+ error!("Couldn't download {NAME} update: {}", e);
return Err(());
}
}
@@ -144,17 +146,17 @@ pub async fn download_update_to_temp_file(
let mut permissions = fs::metadata(&download_path).map_err(|_| ())?.permissions();
permissions.set_mode(0o755);
if let Err(e) = fs::set_permissions(&download_path, permissions) {
- error!("[SelfUpdate] Couldn't set permission to temp file: {}", e);
+ error!("[SelfUpdate] Couldn't set permission to temp file: {e}");
return Err(());
}
}
if let Err(e) = rename(¤t_bin_path, &tmp_path) {
- error!("[SelfUpdate] Couldn't rename binary path: {}", e);
+ error!("[SelfUpdate] Couldn't rename from current to temporary binary path: {e}");
return Err(());
}
if let Err(e) = rename(&download_path, ¤t_bin_path) {
- error!("[SelfUpdate] Couldn't rename binary path: {}", e);
+ error!("[SelfUpdate] Couldn't rename from downloaded to current binary path: {e}");
return Err(());
}
@@ -166,37 +168,34 @@ pub fn get_latest_release() -> Result