| 1 | use apt_sources::key_management::create_inline_signature; |
| 2 | use apt_sources::launchpad::{ |
| 3 | download_ppa_signing_key, validate_ppa, validate_ppa_components, PpaInfo, PpaValidationResult, |
| 4 | LAUNCHPAD_PPA_URL, |
| 5 | }; |
| 6 | use apt_sources::{ |
| 7 | distribution::{get_system_info, Distribution}, |
| 8 | legacy::LegacyRepositories, |
| 9 | signature::Signature, |
| 10 | sources_manager::{ |
| 11 | FileFormat as SourcesFileFormat, SourcesManager, DEFAULT_KEYRING_PATH, DEFAULT_SOURCES_PATH, |
| 12 | }, |
| 13 | utils::strip_auth_from_url, |
| 14 | Repositories, Repository, RepositoryType, |
| 15 | }; |
| 16 | use clap::Parser; |
| 17 | use colored::*; |
| 18 | use indicatif::{ProgressBar, ProgressStyle}; |
| 19 | use log::{debug, error, info, warn}; |
| 20 | use reqwest; |
| 21 | #[allow(unused_imports)] // Required for Cert::from_str |
| 22 | use sequoia_openpgp::parse::Parse; |
| 23 | use sequoia_openpgp::Cert; |
| 24 | use serde_json; |
| 25 | use std::collections::HashSet; |
| 26 | use std::fs; |
| 27 | use std::io::{self, Write}; |
| 28 | use std::path::{Path, PathBuf}; |
| 29 | use std::process; |
| 30 | use std::str::FromStr; |
| 31 | use url::Url; |
| 32 | |
| 33 | /// Create HTTP client for making requests |
| 34 | fn create_http_client() -> Result<reqwest::blocking::Client, String> { |
| 35 | reqwest::blocking::Client::builder() |
| 36 | .timeout(std::time::Duration::from_secs(30)) |
| 37 | .build() |
| 38 | .map_err(|e| format!("Failed to create HTTP client: {}", e)) |
| 39 | } |
| 40 | |
| 41 | /// Format network errors in a user-friendly way |
| 42 | fn format_network_error(error: &reqwest::Error) -> String { |
| 43 | if error.is_timeout() { |
| 44 | "Connection timeout - please check your internet connection".to_string() |
| 45 | } else if error.is_connect() { |
| 46 | "Failed to connect - please check your internet connection".to_string() |
| 47 | } else { |
| 48 | error.to_string() |
| 49 | } |
| 50 | } |
| 51 | |
| 52 | #[derive(Parser, Debug, Clone)] |
| 53 | #[command( |
| 54 | name = "apt-add-repository", |
| 55 | about = "Add APT repository to sources.list.d", |
| 56 | long_about = None, |
| 57 | after_help = "Examples: |
| 58 | apt-add-repository ppa:user/ppa-name |
| 59 | apt-add-repository http://ppa.launchpad.net/example/ppa/ubuntu |
| 60 | apt-add-repository \"deb http://archive.ubuntu.com/ubuntu focal main\" |
| 61 | apt-add-repository -s http://archive.ubuntu.com/ubuntu |
| 62 | apt-add-repository -s # Enable existing disabled deb-src entries |
| 63 | apt-add-repository -ss # Enable + create missing deb-src entries |
| 64 | apt-add-repository \"ppa:user/ppa1 ppa:user/ppa2\" # Add multiple repositories |
| 65 | echo \"ppa:user/ppa-name\" | apt-add-repository - |
| 66 | cat repos.txt | apt-add-repository -" |
| 67 | )] |
| 68 | struct Args { |
| 69 | /// Repository specification (PPA, URL, or full line, or '-' to read from stdin) |
| 70 | #[arg(required_unless_present_any = ["list", "component", "enable_source"])] |
| 71 | repository: Option<String>, |
| 72 | |
| 73 | /// Don't update package cache after adding |
| 74 | #[arg(short = 'n', long = "no-update")] |
| 75 | no_update: bool, |
| 76 | |
| 77 | /// Enable source repositories (-s to enable existing, -ss to create missing) |
| 78 | #[arg(short = 's', long = "source", action = clap::ArgAction::Count)] |
| 79 | enable_source: u8, |
| 80 | |
| 81 | /// Assume yes to all queries |
| 82 | #[arg(short = 'y', long = "yes")] |
| 83 | assume_yes: bool, |
| 84 | |
| 85 | /// Remove the repository instead of adding |
| 86 | #[arg(short = 'r', long = "remove")] |
| 87 | remove: bool, |
| 88 | |
| 89 | /// Directory for sources files |
| 90 | #[arg(short = 'd', long = "directory", default_value = DEFAULT_SOURCES_PATH)] |
| 91 | directory: String, |
| 92 | |
| 93 | /// Directory for keyring files |
| 94 | #[arg(long = "keyring-dir", default_value = DEFAULT_KEYRING_PATH)] |
| 95 | keyring_dir: String, |
| 96 | |
| 97 | /// Add repository for specified pocket |
| 98 | #[arg(short = 'p', long = "pocket")] |
| 99 | pocket: Option<String>, |
| 100 | |
| 101 | /// Use specified keyserver URL |
| 102 | #[arg(short = 'k', long = "keyserver")] |
| 103 | keyserver: Option<String>, |
| 104 | |
| 105 | /// Add component to all matching repositories |
| 106 | #[arg(long = "component", conflicts_with = "remove")] |
| 107 | component: Option<String>, |
| 108 | |
| 109 | /// Output format (deb822 or legacy) |
| 110 | #[arg(long = "format", default_value = "deb822", value_parser = clap::value_parser!(OutputFormat))] |
| 111 | format: OutputFormat, |
| 112 | |
| 113 | /// Preview changes without applying them |
| 114 | #[arg(long = "dry-run")] |
| 115 | dry_run: bool, |
| 116 | |
| 117 | /// Login to Launchpad to access private PPAs |
| 118 | #[arg(long = "login")] |
| 119 | login: bool, |
| 120 | |
| 121 | /// List all configured APT repositories |
| 122 | #[arg(long = "list", conflicts_with_all = ["repository", "remove", "component", "pocket"])] |
| 123 | list: bool, |
| 124 | |
| 125 | /// Refresh signing keys for all PPAs |
| 126 | #[arg(long = "refresh-keys", conflicts_with_all = ["repository", "remove", "component", "pocket", "list"])] |
| 127 | refresh_keys: bool, |
| 128 | |
| 129 | /// Use inline Signed-By instead of separate keyring files (recommended) |
| 130 | #[arg(long = "inline-key")] |
| 131 | inline_key: bool, |
| 132 | } |
| 133 | |
| 134 | #[derive(Debug, Clone)] |
| 135 | struct ParsedRepository { |
| 136 | repository: Repository, |
| 137 | filename: String, |
| 138 | ppa_info: Option<PpaInfo>, |
| 139 | } |
| 140 | |
| 141 | #[derive(Debug, Clone, Copy, PartialEq)] |
| 142 | enum OutputFormat { |
| 143 | Deb822, |
| 144 | Legacy, |
| 145 | } |
| 146 | |
| 147 | impl From<OutputFormat> for SourcesFileFormat { |
| 148 | fn from(format: OutputFormat) -> Self { |
| 149 | match format { |
| 150 | OutputFormat::Deb822 => SourcesFileFormat::Deb822, |
| 151 | OutputFormat::Legacy => SourcesFileFormat::Legacy, |
| 152 | } |
| 153 | } |
| 154 | } |
| 155 | |
| 156 | impl std::str::FromStr for OutputFormat { |
| 157 | type Err = String; |
| 158 | |
| 159 | fn from_str(s: &str) -> Result<Self, Self::Err> { |
| 160 | match s.to_lowercase().as_str() { |
| 161 | "deb822" | "sources" => Ok(OutputFormat::Deb822), |
| 162 | "legacy" | "list" => Ok(OutputFormat::Legacy), |
| 163 | _ => Err(format!("Invalid format: {}. Use 'deb822' or 'legacy'", s)), |
| 164 | } |
| 165 | } |
| 166 | } |
| 167 | |
| 168 | #[derive(Debug)] |
| 169 | enum RepositorySpec { |
| 170 | Component(String), |
| 171 | Pocket(String), |
| 172 | Repository(ParsedRepository), |
| 173 | } |
| 174 | |
| 175 | // PpaInfo struct is now imported from apt_sources::ppa |
| 176 | |
| 177 | // get_distribution_info is replaced by Distribution::current() from apt_sources::distribution |
| 178 | |
| 179 | // get_system_info is now imported from apt_sources::distribution |
| 180 | |
| 181 | fn get_distribution_specific_filename( |
| 182 | base_name: &str, |
| 183 | extension: &str, |
| 184 | distribution: &Distribution, |
| 185 | ) -> String { |
| 186 | let dist_name = distribution.to_string().to_lowercase(); |
| 187 | // For main repos (base_name == "custom" or contains the distribution name), use distribution name |
| 188 | if base_name == "custom" || base_name.contains(&dist_name) { |
| 189 | format!("{}.{}", dist_name, extension) |
| 190 | } else { |
| 191 | format!("{}.{}", base_name, extension) |
| 192 | } |
| 193 | } |
| 194 | |
| 195 | fn determine_repository_filepath( |
| 196 | parsed: &ParsedRepository, |
| 197 | args: &Args, |
| 198 | distribution: &Distribution, |
| 199 | ) -> Result<PathBuf, String> { |
| 200 | // Check if this is a main distribution repository |
| 201 | let is_main_repo = distribution.is_main_repository(&parsed.repository); |
| 202 | |
| 203 | if is_main_repo { |
| 204 | // For main distribution repositories, prefer to use the main distribution file |
| 205 | let main_file = match (&distribution, args.format) { |
| 206 | (Distribution::Ubuntu, OutputFormat::Deb822) => { |
| 207 | Path::new(&args.directory).join("ubuntu.sources") |
| 208 | } |
| 209 | (Distribution::Ubuntu, OutputFormat::Legacy) => { |
| 210 | get_main_sources_list_path(&args.directory) |
| 211 | } |
| 212 | (Distribution::Debian, OutputFormat::Deb822) => { |
| 213 | Path::new(&args.directory).join("debian.sources") |
| 214 | } |
| 215 | (Distribution::Debian, OutputFormat::Legacy) => { |
| 216 | get_main_sources_list_path(&args.directory) |
| 217 | } |
| 218 | _ => { |
| 219 | // For other distributions, fall back to sources.list.d |
| 220 | return Ok(Path::new(&args.directory).join(&parsed.filename)); |
| 221 | } |
| 222 | }; |
| 223 | |
| 224 | Ok(main_file) |
| 225 | } else { |
| 226 | // For third-party repositories, use sources.list.d |
| 227 | Ok(Path::new(&args.directory).join(&parsed.filename)) |
| 228 | } |
| 229 | } |
| 230 | |
| 231 | fn is_main_distribution_file(path: &Path) -> bool { |
| 232 | if let Some(filename) = path.file_name().and_then(|n| n.to_str()) { |
| 233 | matches!( |
| 234 | filename, |
| 235 | "sources.list" | "ubuntu.sources" | "ubuntu.list" | "debian.sources" | "debian.list" |
| 236 | ) |
| 237 | } else { |
| 238 | false |
| 239 | } |
| 240 | } |
| 241 | |
| 242 | /// Derive the path to sources.list from the sources.list.d directory. |
| 243 | /// For example, /etc/apt/sources.list.d -> /etc/apt/sources.list |
| 244 | fn get_main_sources_list_path(sources_dir: &str) -> PathBuf { |
| 245 | Path::new(sources_dir) |
| 246 | .parent() |
| 247 | .unwrap_or(Path::new("/etc/apt")) |
| 248 | .join("sources.list") |
| 249 | } |
| 250 | |
| 251 | // download_key_from_keyserver - wrapper with progress indicator |
| 252 | fn download_key_from_keyserver(fingerprint: &str, keyserver_url: &str) -> Result<String, String> { |
| 253 | let spinner = ProgressBar::new_spinner(); |
| 254 | spinner.set_style( |
| 255 | ProgressStyle::default_spinner() |
| 256 | .template("{spinner:.green} {msg}") |
| 257 | .unwrap(), |
| 258 | ); |
| 259 | spinner.set_message(format!( |
| 260 | "Downloading key {} from keyserver {}...", |
| 261 | fingerprint, keyserver_url |
| 262 | )); |
| 263 | spinner.enable_steady_tick(std::time::Duration::from_millis(100)); |
| 264 | |
| 265 | let result = |
| 266 | apt_sources::keyserver::download_key_from_keyserver_sync(fingerprint, keyserver_url); |
| 267 | |
| 268 | match result { |
| 269 | Ok(key_data) => { |
| 270 | spinner.finish_with_message(format!("Successfully downloaded key {}", fingerprint)); |
| 271 | Ok(key_data) |
| 272 | } |
| 273 | Err(e) => { |
| 274 | spinner.finish_and_clear(); |
| 275 | Err(e) |
| 276 | } |
| 277 | } |
| 278 | } |
| 279 | |
| 280 | #[cfg(feature = "launchpad")] |
| 281 | fn validate_ppa_launchpadlib( |
| 282 | ppa_info: &PpaInfo, |
| 283 | auth_required: bool, |
| 284 | ) -> Result<PpaValidationResult, String> { |
| 285 | debug!( |
| 286 | "Validating PPA {}/{} using launchpadlib", |
| 287 | ppa_info.user, ppa_info.name |
| 288 | ); |
| 289 | validate_ppa(ppa_info, auth_required).map_err(|e| e.to_string()) |
| 290 | } |
| 291 | |
| 292 | /// Validate PPA and provide user-friendly error messages |
| 293 | fn validate_ppa_with_suggestions(ppa_info: &PpaInfo) -> Result<PpaValidationResult, String> { |
| 294 | info!( |
| 295 | "Checking if PPA {}/{} exists...", |
| 296 | ppa_info.user, ppa_info.name |
| 297 | ); |
| 298 | |
| 299 | let result = validate_ppa(ppa_info, false).map_err(|e| e.to_string())?; |
| 300 | |
| 301 | if !result.exists { |
| 302 | if result.is_private { |
| 303 | return Err(format!( |
| 304 | "PPA {}/{} is private.\n\ |
| 305 | To access private PPAs:\n\ |
| 306 | 1. Use the --login flag to authenticate with Launchpad\n\ |
| 307 | 2. Ensure you're subscribed to this PPA\n\ |
| 308 | 3. Check that apt-add-repository was built with launchpad support", |
| 309 | ppa_info.user, ppa_info.name |
| 310 | )); |
| 311 | } else { |
| 312 | return Err(format!( |
| 313 | "PPA {}/{} not found.\n\ |
| 314 | Suggestions:\n\ |
| 315 | - Check the PPA name for typos\n\ |
| 316 | - Verify the user '{}' exists on Launchpad\n\ |
| 317 | - Browse available PPAs at https://launchpad.net/~{}/+ppas", |
| 318 | ppa_info.user, ppa_info.name, ppa_info.user, ppa_info.user |
| 319 | )); |
| 320 | } |
| 321 | } |
| 322 | |
| 323 | Ok(result) |
| 324 | } |
| 325 | |
| 326 | #[cfg(feature = "launchpad")] |
| 327 | fn get_private_ppa_url(ppa_info: &PpaInfo) -> Result<Url, String> { |
| 328 | debug!( |
| 329 | "Getting private PPA URL for {}/{}", |
| 330 | ppa_info.user, ppa_info.name |
| 331 | ); |
| 332 | apt_sources::launchpad::get_private_ppa_url(ppa_info).map_err(|e| e.to_string()) |
| 333 | } |
| 334 | |
| 335 | #[cfg(feature = "launchpad")] |
| 336 | fn download_ppa_key_launchpadlib( |
| 337 | ppa_info: &PpaInfo, |
| 338 | auth_required: bool, |
| 339 | ) -> Result<String, String> { |
| 340 | debug!( |
| 341 | "Using launchpadlib to download PPA key for {}/{}", |
| 342 | ppa_info.user, ppa_info.name |
| 343 | ); |
| 344 | |
| 345 | let signing_key = |
| 346 | download_ppa_signing_key(ppa_info, auth_required).map_err(|e| e.to_string())?; |
| 347 | |
| 348 | // Additionally check expiration |
| 349 | let cert = Cert::from_str(&signing_key.key_data) |
| 350 | .map_err(|e| format!("Failed to parse PGP key for expiration check: {}", e))?; |
| 351 | |
| 352 | if let Some(expiration_error) = apt_sources::key_management::check_key_expiration(&cert) { |
| 353 | let expiration_warning = expiration_error.to_string(); |
| 354 | if expiration_warning.contains("expired") { |
| 355 | error!("Key expiration: {}", expiration_warning); |
| 356 | return Err(format!("Cannot use expired key: {}", expiration_warning)); |
| 357 | } else { |
| 358 | warn!("Key expiration warning: {}", expiration_warning); |
| 359 | } |
| 360 | } |
| 361 | |
| 362 | info!( |
| 363 | "Downloaded and verified PPA signing key with fingerprint: {}", |
| 364 | signing_key.fingerprint |
| 365 | ); |
| 366 | Ok(signing_key.key_data) |
| 367 | } |
| 368 | |
| 369 | // verify_key_fingerprint - wrapper that adds expiration check and logging |
| 370 | fn verify_key_fingerprint(key_data: &str, expected_fingerprint: &str) -> Result<(), String> { |
| 371 | debug!( |
| 372 | "Verifying key fingerprint against expected: {}", |
| 373 | expected_fingerprint |
| 374 | ); |
| 375 | |
| 376 | // Use the crate's fingerprint verification |
| 377 | apt_sources::key_management::verify_key_fingerprint(key_data, expected_fingerprint) |
| 378 | .map_err(|e| e.to_string())?; |
| 379 | |
| 380 | // Additionally check expiration |
| 381 | let cert = Cert::from_str(key_data) |
| 382 | .map_err(|e| format!("Failed to parse PGP key for expiration check: {}", e))?; |
| 383 | |
| 384 | if let Some(expiration_error) = apt_sources::key_management::check_key_expiration(&cert) { |
| 385 | let expiration_warning = expiration_error.to_string(); |
| 386 | if expiration_warning.contains("expired") { |
| 387 | error!("Key expiration: {}", expiration_warning); |
| 388 | return Err(format!("Cannot use expired key: {}", expiration_warning)); |
| 389 | } else { |
| 390 | warn!("Key expiration warning: {}", expiration_warning); |
| 391 | } |
| 392 | } |
| 393 | |
| 394 | debug!("Key fingerprint verification successful"); |
| 395 | Ok(()) |
| 396 | } |
| 397 | |
| 398 | fn download_ppa_key(ppa_info: &PpaInfo, keyserver: Option<&str>) -> Result<String, String> { |
| 399 | info!( |
| 400 | "Downloading signing key for PPA {}/{}...", |
| 401 | ppa_info.user, ppa_info.name |
| 402 | ); |
| 403 | |
| 404 | let key_data = if let Some(keyserver_url) = keyserver { |
| 405 | // Use custom keyserver - need to get fingerprint first |
| 406 | debug!("Using custom keyserver: {}", keyserver_url); |
| 407 | let api_url = format!( |
| 408 | "https://api.launchpad.net/1.0/~{}/+archive/ubuntu/{}", |
| 409 | ppa_info.user, ppa_info.name |
| 410 | ); |
| 411 | |
| 412 | let client = create_http_client()?; |
| 413 | let ppa_response = client |
| 414 | .get(&api_url) |
| 415 | .header("Accept", "application/json") |
| 416 | .send() |
| 417 | .map_err(|e| format!("Failed to fetch PPA metadata: {}", format_network_error(&e)))?; |
| 418 | |
| 419 | if !ppa_response.status().is_success() { |
| 420 | return Err(format!( |
| 421 | "PPA not found: {}/{}", |
| 422 | ppa_info.user, ppa_info.name |
| 423 | )); |
| 424 | } |
| 425 | |
| 426 | let ppa_data: serde_json::Value = ppa_response |
| 427 | .json() |
| 428 | .map_err(|e| format!("Failed to parse PPA metadata: {}", e))?; |
| 429 | |
| 430 | let fingerprint = ppa_data |
| 431 | .get("signing_key_fingerprint") |
| 432 | .and_then(|v| v.as_str()) |
| 433 | .ok_or_else(|| "PPA has no signing key configured".to_string())?; |
| 434 | |
| 435 | let key = download_key_from_keyserver(fingerprint, keyserver_url)?; |
| 436 | |
| 437 | // Verify the key fingerprint matches what we expect |
| 438 | verify_key_fingerprint(&key, fingerprint)?; |
| 439 | key |
| 440 | } else { |
| 441 | // Use library function for default Launchpad download |
| 442 | download_ppa_signing_key(ppa_info, false) |
| 443 | .map_err(|e| e.to_string())? |
| 444 | .key_data |
| 445 | }; |
| 446 | |
| 447 | info!("Downloaded PPA signing key"); |
| 448 | Ok(key_data) |
| 449 | } |
| 450 | |
| 451 | fn save_key_to_keyring( |
| 452 | key_data: &str, |
| 453 | keyring_dir: &str, |
| 454 | ppa_info: &PpaInfo, |
| 455 | ) -> Result<PathBuf, String> { |
| 456 | // The key data from Launchpad is already in armored format, |
| 457 | // but let's parse it to validate it's a proper key |
| 458 | let cert = Cert::from_str(key_data).map_err(|e| format!("Failed to parse PGP key: {}", e))?; |
| 459 | |
| 460 | // Verify the key is valid |
| 461 | let policy = sequoia_openpgp::policy::StandardPolicy::new(); |
| 462 | if cert.with_policy(&policy, None).is_err() { |
| 463 | return Err("Invalid or expired PGP key".to_string()); |
| 464 | } |
| 465 | |
| 466 | // Save to keyring directory |
| 467 | // Use .asc extension for ASCII-armored keys (apt prefers this) |
| 468 | let keyring_path = Path::new(keyring_dir).join(ppa_info.keyring_filename()); |
| 469 | |
| 470 | // Check if keyring directory exists |
| 471 | if !Path::new(keyring_dir).exists() { |
| 472 | fs::create_dir_all(keyring_dir) |
| 473 | .map_err(|e| format!("Failed to create keyring directory: {}", e))?; |
| 474 | } |
| 475 | |
| 476 | // Write the key in ASCII-armored format |
| 477 | // Since the data from Launchpad is already armored, we can write it directly |
| 478 | fs::write(&keyring_path, key_data) |
| 479 | .map_err(|e| format!("Failed to write key to file: {}", e))?; |
| 480 | |
| 481 | Ok(keyring_path) |
| 482 | } |
| 483 | |
| 484 | /// Save the PPA key and return the appropriate Signature. |
| 485 | /// If inline_key is true and format is Deb822, tries inline signature first, |
| 486 | /// falling back to keyring file on failure. |
| 487 | fn save_ppa_key( |
| 488 | key_data: &str, |
| 489 | ppa_info: &PpaInfo, |
| 490 | keyring_dir: &str, |
| 491 | use_inline: bool, |
| 492 | ) -> Option<Signature> { |
| 493 | if use_inline { |
| 494 | match create_inline_signature(key_data) { |
| 495 | Ok(inline_sig) => { |
| 496 | info!("Using inline Signed-By (embedded key)"); |
| 497 | return Some(inline_sig); |
| 498 | } |
| 499 | Err(e) => { |
| 500 | warn!("Failed to create inline signature: {}", e); |
| 501 | warn!("Falling back to keyring file"); |
| 502 | } |
| 503 | } |
| 504 | } |
| 505 | |
| 506 | match save_key_to_keyring(key_data, keyring_dir, ppa_info) { |
| 507 | Ok(keyring_path) => { |
| 508 | info!("Signing key saved to {}", keyring_path.display()); |
| 509 | Some(Signature::KeyPath(keyring_path)) |
| 510 | } |
| 511 | Err(e) => { |
| 512 | warn!("Failed to save signing key: {}", e); |
| 513 | warn!("The repository will be added without signature verification."); |
| 514 | None |
| 515 | } |
| 516 | } |
| 517 | } |
| 518 | |
| 519 | fn parse_repository_line( |
| 520 | line: &str, |
| 521 | ) -> Result< |
| 522 | ( |
| 523 | Vec<RepositoryType>, |
| 524 | Url, |
| 525 | String, |
| 526 | Vec<String>, |
| 527 | Option<PathBuf>, |
| 528 | ), |
| 529 | String, |
| 530 | > { |
| 531 | let parts: Vec<&str> = line.split_whitespace().collect(); |
| 532 | |
| 533 | if parts.is_empty() { |
| 534 | return Err("Empty repository line".to_string()); |
| 535 | } |
| 536 | |
| 537 | let mut idx = 0; |
| 538 | let mut signed_by = None; |
| 539 | let mut _arch = None; |
| 540 | |
| 541 | // Parse repository type |
| 542 | let types = match parts[idx] { |
| 543 | "deb" => vec![RepositoryType::Binary], |
| 544 | "deb-src" => vec![RepositoryType::Source], |
| 545 | _ => return Err("Repository line must start with 'deb' or 'deb-src'".to_string()), |
| 546 | }; |
| 547 | idx += 1; |
| 548 | |
| 549 | // Parse options if present |
| 550 | if idx < parts.len() && parts[idx].starts_with('[') { |
| 551 | let options_end = parts |
| 552 | .iter() |
| 553 | .position(|&p| p.ends_with(']')) |
| 554 | .ok_or("Unclosed options bracket")?; |
| 555 | |
| 556 | let options_str = parts[idx..=options_end].join(" "); |
| 557 | let options_str = options_str.trim_start_matches('[').trim_end_matches(']'); |
| 558 | |
| 559 | for option in options_str.split_whitespace() { |
| 560 | if let Some((key, value)) = option.split_once('=') { |
| 561 | match key { |
| 562 | "arch" => _arch = Some(value.to_string()), |
| 563 | "signed-by" => signed_by = Some(PathBuf::from(value)), |
| 564 | _ => {} // Ignore other options for now |
| 565 | } |
| 566 | } |
| 567 | } |
| 568 | |
| 569 | idx = options_end + 1; |
| 570 | } |
| 571 | |
| 572 | if idx + 2 >= parts.len() { |
| 573 | return Err("Invalid repository line format".to_string()); |
| 574 | } |
| 575 | |
| 576 | let uri = Url::parse(parts[idx]).map_err(|e| format!("Invalid URL: {}", e))?; |
| 577 | |
| 578 | // Strip auth data from URL for storage |
| 579 | let (clean_uri, auth_data) = strip_auth_from_url(&uri); |
| 580 | if auth_data.is_some() { |
| 581 | debug!("Repository URL contains authentication data, stripping for storage"); |
| 582 | } |
| 583 | |
| 584 | let suite = parts[idx + 1].to_string(); |
| 585 | let components = parts[idx + 2..].iter().map(|&s| s.to_string()).collect(); |
| 586 | |
| 587 | Ok((types, clean_uri, suite, components, signed_by)) |
| 588 | } |
| 589 | |
| 590 | fn parse_repository_spec( |
| 591 | spec: &str, |
| 592 | enable_source_count: u8, |
| 593 | args: &Args, |
| 594 | distribution: &Distribution, |
| 595 | codename: &str, |
| 596 | ) -> Result<RepositorySpec, String> { |
| 597 | // Check if it's just a component name (universe, multiverse, etc.) |
| 598 | let valid_components = match &distribution { |
| 599 | Distribution::Ubuntu => vec!["main", "universe", "multiverse", "restricted"], |
| 600 | Distribution::Debian => vec!["main", "contrib", "non-free", "non-free-firmware"], |
| 601 | Distribution::Other(_) => vec![ |
| 602 | "main", |
| 603 | "universe", |
| 604 | "multiverse", |
| 605 | "restricted", |
| 606 | "contrib", |
| 607 | "non-free", |
| 608 | "non-free-firmware", |
| 609 | ], |
| 610 | }; |
| 611 | if valid_components.contains(&spec) { |
| 612 | debug!( |
| 613 | "Adding component {} to existing {} repositories", |
| 614 | spec, distribution |
| 615 | ); |
| 616 | return Ok(RepositorySpec::Component(spec.to_string())); |
| 617 | } |
| 618 | |
| 619 | // Check if it's a pocket specification (e.g., focal-proposed, bionic-backports) |
| 620 | let valid_pockets = vec!["proposed", "backports", "security", "updates"]; |
| 621 | for pocket in &valid_pockets { |
| 622 | if spec.ends_with(&format!("-{}", pocket)) { |
| 623 | debug!("Adding pocket {} repositories", spec); |
| 624 | return Ok(RepositorySpec::Pocket(spec.to_string())); |
| 625 | } |
| 626 | } |
| 627 | |
| 628 | // Check if it's a PPA |
| 629 | if spec.starts_with("ppa:") { |
| 630 | let ppa_info = PpaInfo::parse(spec)?; |
| 631 | |
| 632 | let types = if enable_source_count > 0 { |
| 633 | HashSet::from([RepositoryType::Binary, RepositoryType::Source]) |
| 634 | } else { |
| 635 | HashSet::from([RepositoryType::Binary]) |
| 636 | }; |
| 637 | |
| 638 | // Generate PPA URL (with authentication for private PPAs if needed) |
| 639 | let uri = if args.login { |
| 640 | // For private PPAs, we need to get the subscription URL from launchpadlib |
| 641 | #[cfg(feature = "launchpad")] |
| 642 | { |
| 643 | get_private_ppa_url(&ppa_info)? |
| 644 | } |
| 645 | #[cfg(not(feature = "launchpad"))] |
| 646 | { |
| 647 | return Err("Private PPA support requires the 'launchpad' feature".to_string()); |
| 648 | } |
| 649 | } else { |
| 650 | Url::parse(&format!( |
| 651 | "{}/{}/{}/ubuntu", |
| 652 | LAUNCHPAD_PPA_URL, ppa_info.user, ppa_info.name |
| 653 | )) |
| 654 | .unwrap() |
| 655 | }; |
| 656 | |
| 657 | // Validate components for PPA |
| 658 | let components = if let Some(ref comps) = args.component { |
| 659 | // User specified components - validate them |
| 660 | let comp_vec = vec![comps.clone()]; |
| 661 | validate_ppa_components(&comp_vec)?; |
| 662 | comp_vec |
| 663 | } else { |
| 664 | vec!["main".to_string()] |
| 665 | }; |
| 666 | |
| 667 | let repository = Repository { |
| 668 | enabled: Some(true), |
| 669 | types, |
| 670 | architectures: None, |
| 671 | uris: vec![uri], |
| 672 | suites: vec![codename.to_string()], |
| 673 | components: Some(components), |
| 674 | signature: None, // Will be set after key download |
| 675 | x_repolib_name: Some(format!("ppa:{}/{}", ppa_info.user, ppa_info.name)), |
| 676 | ..Default::default() |
| 677 | }; |
| 678 | |
| 679 | let extension = match args.format { |
| 680 | OutputFormat::Legacy => "list", |
| 681 | OutputFormat::Deb822 => "sources", |
| 682 | }; |
| 683 | let filename = format!( |
| 684 | "{}-ubuntu-{}-{}.{}", |
| 685 | ppa_info.user, ppa_info.name, codename, extension |
| 686 | ); |
| 687 | |
| 688 | return Ok(RepositorySpec::Repository(ParsedRepository { |
| 689 | repository, |
| 690 | filename, |
| 691 | ppa_info: Some(ppa_info), |
| 692 | })); |
| 693 | } |
| 694 | |
| 695 | // Check if it's a full deb line |
| 696 | if spec.starts_with("deb ") || spec.starts_with("deb-src ") { |
| 697 | let (parsed_types, uri, suite, components, signed_by) = parse_repository_line(spec)?; |
| 698 | |
| 699 | // Check if this is a PPA URL and validate components |
| 700 | if uri |
| 701 | .host_str() |
| 702 | .map_or(false, |h| h.contains("ppa.launchpadcontent.net")) |
| 703 | { |
| 704 | validate_ppa_components(&components)?; |
| 705 | } |
| 706 | |
| 707 | let mut types = HashSet::new(); |
| 708 | for t in parsed_types { |
| 709 | types.insert(t); |
| 710 | } |
| 711 | |
| 712 | if enable_source_count > 0 { |
| 713 | types.insert(RepositoryType::Source); |
| 714 | } |
| 715 | |
| 716 | let mut repository = Repository { |
| 717 | enabled: Some(true), |
| 718 | types, |
| 719 | architectures: None, |
| 720 | uris: vec![uri.clone()], |
| 721 | suites: vec![suite], |
| 722 | components: Some(components), |
| 723 | ..Default::default() |
| 724 | }; |
| 725 | |
| 726 | if let Some(keypath) = signed_by { |
| 727 | repository.signature = Some(Signature::KeyPath(keypath)); |
| 728 | } |
| 729 | |
| 730 | let filename = generate_filename(uri.as_str(), args.format, &distribution); |
| 731 | |
| 732 | return Ok(RepositorySpec::Repository(ParsedRepository { |
| 733 | repository, |
| 734 | filename, |
| 735 | ppa_info: None, |
| 736 | })); |
| 737 | } |
| 738 | |
| 739 | // Try to parse as URL |
| 740 | let uri = Url::parse(spec).map_err(|_| { |
| 741 | "Invalid repository specification. Expected PPA, URL, or full deb line".to_string() |
| 742 | })?; |
| 743 | |
| 744 | // Strip auth data from URL for storage |
| 745 | let (clean_uri, auth_data) = strip_auth_from_url(&uri); |
| 746 | if auth_data.is_some() { |
| 747 | info!("Repository URL contains authentication data, which will be stored securely"); |
| 748 | } |
| 749 | |
| 750 | // Use system codename and default to 'main' component |
| 751 | let (suite, components) = default_suite_components(&codename); |
| 752 | |
| 753 | let types = if enable_source_count > 0 { |
| 754 | HashSet::from([RepositoryType::Binary, RepositoryType::Source]) |
| 755 | } else { |
| 756 | HashSet::from([RepositoryType::Binary]) |
| 757 | }; |
| 758 | |
| 759 | let repository = Repository { |
| 760 | enabled: Some(true), |
| 761 | types, |
| 762 | architectures: None, |
| 763 | uris: vec![clean_uri.clone()], |
| 764 | suites: vec![suite], |
| 765 | components: Some(components), |
| 766 | ..Default::default() |
| 767 | }; |
| 768 | |
| 769 | let filename = generate_filename(uri.as_str(), args.format, &distribution); |
| 770 | |
| 771 | Ok(RepositorySpec::Repository(ParsedRepository { |
| 772 | repository, |
| 773 | filename, |
| 774 | ppa_info: None, |
| 775 | })) |
| 776 | } |
| 777 | |
| 778 | fn default_suite_components(system_codename: &str) -> (String, Vec<String>) { |
| 779 | // Match original apt-add-repository behavior: |
| 780 | // - Suite defaults to system codename |
| 781 | // - Components default to 'main' |
| 782 | (system_codename.to_string(), vec!["main".to_string()]) |
| 783 | } |
| 784 | |
| 785 | fn generate_filename(url: &str, format: OutputFormat, distribution: &Distribution) -> String { |
| 786 | let extension = match format { |
| 787 | OutputFormat::Legacy => "list", |
| 788 | OutputFormat::Deb822 => "sources", |
| 789 | }; |
| 790 | |
| 791 | let Ok(parsed_url) = Url::parse(url) else { |
| 792 | return get_distribution_specific_filename("custom", extension, distribution); |
| 793 | }; |
| 794 | |
| 795 | // Check if this is a main distribution repository |
| 796 | if distribution.is_main_repository(&Repository { |
| 797 | uris: vec![parsed_url.clone()], |
| 798 | ..Default::default() |
| 799 | }) { |
| 800 | return get_distribution_specific_filename("custom", extension, distribution); |
| 801 | } |
| 802 | |
| 803 | // Use library function for non-main repos |
| 804 | apt_sources::utils::generate_filename_from_url(&parsed_url, extension) |
| 805 | } |
| 806 | |
| 807 | fn add_pocket_repository( |
| 808 | pocket_spec: &str, |
| 809 | args: &Args, |
| 810 | enable_source_count: u8, |
| 811 | distribution: &Distribution, |
| 812 | ) -> Result<(), String> { |
| 813 | info!("Adding pocket repository: {}", pocket_spec); |
| 814 | |
| 815 | // Parse the pocket specification (e.g., "focal-proposed" -> suite="focal-proposed", pocket="proposed") |
| 816 | let parts: Vec<&str> = pocket_spec.rsplitn(2, '-').collect(); |
| 817 | if parts.len() != 2 { |
| 818 | return Err("Invalid pocket specification".to_string()); |
| 819 | } |
| 820 | |
| 821 | let pocket = parts[0]; |
| 822 | let _base_suite = parts[1]; |
| 823 | |
| 824 | // Create repository for the pocket |
| 825 | let types = if enable_source_count > 0 { |
| 826 | HashSet::from([RepositoryType::Binary, RepositoryType::Source]) |
| 827 | } else { |
| 828 | HashSet::from([RepositoryType::Binary]) |
| 829 | }; |
| 830 | |
| 831 | // Determine components based on distribution |
| 832 | // All pockets (proposed, backports, security, updates) use the same components |
| 833 | let components: Vec<String> = match &distribution { |
| 834 | Distribution::Ubuntu => vec!["main", "universe", "multiverse", "restricted"], |
| 835 | Distribution::Debian => vec!["main", "contrib", "non-free"], |
| 836 | Distribution::Other(_) => distribution.default_components(), |
| 837 | } |
| 838 | .into_iter() |
| 839 | .map(|s| s.to_string()) |
| 840 | .collect(); |
| 841 | |
| 842 | // Use distribution-specific mirror URLs |
| 843 | let mirror_url = match &distribution { |
| 844 | Distribution::Ubuntu => "http://archive.ubuntu.com/ubuntu/", |
| 845 | Distribution::Debian => "http://deb.debian.org/debian/", |
| 846 | Distribution::Other(name) => { |
| 847 | return Err(format!( |
| 848 | "Pocket repository support not available for distribution '{}'", |
| 849 | name |
| 850 | )); |
| 851 | } |
| 852 | }; |
| 853 | |
| 854 | let repository = Repository { |
| 855 | enabled: Some(true), |
| 856 | types, |
| 857 | architectures: None, |
| 858 | uris: vec![Url::parse(mirror_url).unwrap()], |
| 859 | suites: vec![pocket_spec.to_string()], |
| 860 | components: Some(components), |
| 861 | ..Default::default() |
| 862 | }; |
| 863 | |
| 864 | let extension = match args.format { |
| 865 | OutputFormat::Legacy => "list", |
| 866 | OutputFormat::Deb822 => "sources", |
| 867 | }; |
| 868 | |
| 869 | // Use distribution-specific filename |
| 870 | let filename = format!( |
| 871 | "{}-{}.{}", |
| 872 | distribution.to_string().to_lowercase(), |
| 873 | pocket, |
| 874 | extension |
| 875 | ); |
| 876 | let parsed = ParsedRepository { |
| 877 | repository, |
| 878 | filename, |
| 879 | ppa_info: None, |
| 880 | }; |
| 881 | |
| 882 | add_parsed_repository(parsed, args, distribution) |
| 883 | } |
| 884 | |
| 885 | fn add_component_to_existing_repos( |
| 886 | component: &str, |
| 887 | directory: &str, |
| 888 | dry_run: bool, |
| 889 | distribution: &Distribution, |
| 890 | ) -> Result<(), String> { |
| 891 | info!( |
| 892 | "Adding component '{}' to existing {} repositories", |
| 893 | component, distribution |
| 894 | ); |
| 895 | |
| 896 | // Find all .sources files that contain distribution repositories |
| 897 | let sources_dir = Path::new(directory); |
| 898 | if !sources_dir.exists() { |
| 899 | return Err(format!("Sources directory {} does not exist", directory)); |
| 900 | } |
| 901 | |
| 902 | let mut modified_count = 0; |
| 903 | |
| 904 | for entry in |
| 905 | fs::read_dir(sources_dir).map_err(|e| format!("Failed to read directory: {}", e))? |
| 906 | { |
| 907 | let entry = entry.map_err(|e| format!("Failed to read directory entry: {}", e))?; |
| 908 | let path = entry.path(); |
| 909 | |
| 910 | if path.extension().and_then(|s| s.to_str()) != Some("sources") { |
| 911 | continue; |
| 912 | } |
| 913 | |
| 914 | // Read and parse the repository file |
| 915 | let content = fs::read_to_string(&path) |
| 916 | .map_err(|e| format!("Failed to read {}: {}", path.display(), e))?; |
| 917 | |
| 918 | let repos = Repositories::from_str(&content) |
| 919 | .map_err(|e| format!("Failed to parse {}: {}", path.display(), e))?; |
| 920 | |
| 921 | let mut modified = false; |
| 922 | let mut updated_repos = Vec::new(); |
| 923 | |
| 924 | for repo in repos.iter() { |
| 925 | let mut repo_clone = repo.clone(); |
| 926 | |
| 927 | // Check if this is a main distribution repository and doesn't already have the component |
| 928 | let dominated = distribution.is_main_repository(repo) |
| 929 | && repo_clone |
| 930 | .components |
| 931 | .as_ref() |
| 932 | .map_or(false, |c| !c.contains(&component.to_string())); |
| 933 | |
| 934 | if dominated { |
| 935 | if let Some(components) = &mut repo_clone.components { |
| 936 | if dry_run { |
| 937 | info!("Would add component '{}' to {}", component, path.display()); |
| 938 | } else { |
| 939 | components.push(component.to_string()); |
| 940 | info!("Adding component '{}' to {}", component, path.display()); |
| 941 | } |
| 942 | modified = true; |
| 943 | } |
| 944 | } |
| 945 | |
| 946 | updated_repos.push(repo_clone); |
| 947 | } |
| 948 | |
| 949 | if modified && !dry_run { |
| 950 | let updated_repositories = Repositories::new(updated_repos); |
| 951 | let output = updated_repositories.to_string(); |
| 952 | fs::write(&path, output) |
| 953 | .map_err(|e| format!("Failed to write {}: {}", path.display(), e))?; |
| 954 | modified_count += 1; |
| 955 | } |
| 956 | } |
| 957 | |
| 958 | if modified_count == 0 && !dry_run { |
| 959 | warn!( |
| 960 | "No {} repositories found to add component '{}' to", |
| 961 | distribution, component |
| 962 | ); |
| 963 | } else if !dry_run { |
| 964 | info!("Modified {} repository file(s)", modified_count); |
| 965 | } |
| 966 | |
| 967 | Ok(()) |
| 968 | } |
| 969 | |
| 970 | fn enable_sources_globally(args: &Args) -> Result<(), String> { |
| 971 | info!( |
| 972 | "Enabling source repositories globally (level: {})", |
| 973 | args.enable_source |
| 974 | ); |
| 975 | |
| 976 | let mut enabled_count = 0; |
| 977 | let mut created_count = 0; |
| 978 | let mut warned_count = 0; |
| 979 | let mut errors = Vec::new(); |
| 980 | |
| 981 | // Scan both .sources and .list files |
| 982 | let sources_dir = Path::new(&args.directory); |
| 983 | if sources_dir.exists() { |
| 984 | for entry in |
| 985 | fs::read_dir(sources_dir).map_err(|e| format!("Failed to read directory: {}", e))? |
| 986 | { |
| 987 | let entry = entry.map_err(|e| format!("Failed to read directory entry: {}", e))?; |
| 988 | let path = entry.path(); |
| 989 | |
| 990 | if !path.is_file() { |
| 991 | continue; |
| 992 | } |
| 993 | |
| 994 | // Handle .sources files (DEB822 format) |
| 995 | if path.extension().and_then(|s| s.to_str()) == Some("sources") { |
| 996 | match enable_sources_in_deb822_file(&path, args.enable_source, args.dry_run) { |
| 997 | Ok((enabled, created)) => { |
| 998 | enabled_count += enabled; |
| 999 | created_count += created; |
| 1000 | } |
| 1001 | Err(e) => { |
| 1002 | errors.push(format!("{}: {}", path.display(), e)); |
| 1003 | } |
| 1004 | } |
| 1005 | } |
| 1006 | // Handle .list files (legacy format) |
| 1007 | else if path.extension().and_then(|s| s.to_str()) == Some("list") { |
| 1008 | match enable_sources_in_legacy_file(&path, args.enable_source, args.dry_run) { |
| 1009 | Ok((enabled, created, warned)) => { |
| 1010 | enabled_count += enabled; |
| 1011 | created_count += created; |
| 1012 | warned_count += warned; |
| 1013 | } |
| 1014 | Err(e) => { |
| 1015 | errors.push(format!("{}: {}", path.display(), e)); |
| 1016 | } |
| 1017 | } |
| 1018 | } |
| 1019 | } |
| 1020 | } |
| 1021 | |
| 1022 | // Also handle main sources.list |
| 1023 | let main_sources = get_main_sources_list_path(&args.directory); |
| 1024 | if main_sources.exists() { |
| 1025 | match enable_sources_in_legacy_file(&main_sources, args.enable_source, args.dry_run) { |
| 1026 | Ok((enabled, created, warned)) => { |
| 1027 | enabled_count += enabled; |
| 1028 | created_count += created; |
| 1029 | warned_count += warned; |
| 1030 | } |
| 1031 | Err(e) => { |
| 1032 | errors.push(format!("sources.list: {}", e)); |
| 1033 | } |
| 1034 | } |
| 1035 | } |
| 1036 | |
| 1037 | // Report results |
| 1038 | if args.dry_run { |
| 1039 | info!("Dry run complete - would have:"); |
| 1040 | } else { |
| 1041 | info!("Source enablement complete:"); |
| 1042 | } |
| 1043 | |
| 1044 | if enabled_count > 0 { |
| 1045 | info!(" Enabled {} disabled deb-src entries", enabled_count); |
| 1046 | } |
| 1047 | if created_count > 0 { |
| 1048 | info!(" Created {} new deb-src entries", created_count); |
| 1049 | } |
| 1050 | if warned_count > 0 && args.enable_source == 1 { |
| 1051 | info!( |
| 1052 | " Found {} missing deb-src entries (use -ss to create them)", |
| 1053 | warned_count |
| 1054 | ); |
| 1055 | } |
| 1056 | |
| 1057 | if !errors.is_empty() { |
| 1058 | error!("Errors encountered:"); |
| 1059 | for err in errors { |
| 1060 | error!(" {}", err); |
| 1061 | } |
| 1062 | return Err("Some operations failed".to_string()); |
| 1063 | } |
| 1064 | |
| 1065 | if enabled_count == 0 && created_count == 0 && warned_count == 0 { |
| 1066 | info!("No source repositories needed enabling or creation"); |
| 1067 | } |
| 1068 | |
| 1069 | Ok(()) |
| 1070 | } |
| 1071 | |
| 1072 | fn enable_sources_in_deb822_file( |
| 1073 | file_path: &Path, |
| 1074 | enable_source_count: u8, |
| 1075 | dry_run: bool, |
| 1076 | ) -> Result<(u32, u32), String> { |
| 1077 | debug!("Processing DEB822 file: {}", file_path.display()); |
| 1078 | |
| 1079 | let content = |
| 1080 | fs::read_to_string(file_path).map_err(|e| format!("Failed to read file: {}", e))?; |
| 1081 | |
| 1082 | let repos = Repositories::from_str(&content) |
| 1083 | .map_err(|e| format!("Failed to parse DEB822 file: {}", e))?; |
| 1084 | |
| 1085 | let mut enabled_count = 0; |
| 1086 | let mut created_count = 0; |
| 1087 | let mut modified = false; |
| 1088 | let mut updated_repos = Vec::new(); |
| 1089 | |
| 1090 | // First pass: Enable disabled deb-src entries that have matching enabled deb entries |
| 1091 | for repo in repos.iter() { |
| 1092 | let mut repo_clone = repo.clone(); |
| 1093 | |
| 1094 | // Only process disabled source-only repos with a matching binary repo |
| 1095 | let dominated = !repo.enabled.unwrap_or(true) |
| 1096 | && repo.types.contains(&RepositoryType::Source) |
| 1097 | && !repo.types.contains(&RepositoryType::Binary) |
| 1098 | && find_matching_binary_repo(&repos, repo).is_some(); |
| 1099 | |
| 1100 | if dominated { |
| 1101 | if dry_run { |
| 1102 | info!("Would enable disabled deb-src in {}", file_path.display()); |
| 1103 | } else { |
| 1104 | repo_clone.enabled = Some(true); |
| 1105 | info!("Enabled disabled deb-src in {}", file_path.display()); |
| 1106 | } |
| 1107 | enabled_count += 1; |
| 1108 | modified = true; |
| 1109 | } |
| 1110 | |
| 1111 | updated_repos.push(repo_clone); |
| 1112 | } |
| 1113 | |
| 1114 | // Second pass: Create missing deb-src entries if enable_source > 1 |
| 1115 | if enable_source_count > 1 { |
| 1116 | let mut new_repos = Vec::new(); |
| 1117 | |
| 1118 | for repo in repos.iter() { |
| 1119 | // Only process enabled binary-only repos without a matching source repo |
| 1120 | let dominated = repo.enabled.unwrap_or(true) |
| 1121 | && repo.types.contains(&RepositoryType::Binary) |
| 1122 | && !repo.types.contains(&RepositoryType::Source) |
| 1123 | && !has_matching_source_repo(&repos, repo); |
| 1124 | |
| 1125 | if !dominated { |
| 1126 | continue; |
| 1127 | } |
| 1128 | |
| 1129 | // Create a new source repository |
| 1130 | let mut source_repo = repo.clone(); |
| 1131 | source_repo.types = HashSet::from([RepositoryType::Source]); |
| 1132 | |
| 1133 | if dry_run { |
| 1134 | info!( |
| 1135 | "Would create missing deb-src for binary repo in {}", |
| 1136 | file_path.display() |
| 1137 | ); |
| 1138 | } else { |
| 1139 | new_repos.push(source_repo); |
| 1140 | info!( |
| 1141 | "Created missing deb-src for binary repo in {}", |
| 1142 | file_path.display() |
| 1143 | ); |
| 1144 | } |
| 1145 | created_count += 1; |
| 1146 | modified = true; |
| 1147 | } |
| 1148 | |
| 1149 | // Add new repositories to updated list |
| 1150 | if !dry_run { |
| 1151 | updated_repos.extend(new_repos); |
| 1152 | } |
| 1153 | } |
| 1154 | |
| 1155 | // Write changes if modified and not dry run |
| 1156 | if modified && !dry_run { |
| 1157 | let updated_repositories = Repositories::new(updated_repos); |
| 1158 | let output = updated_repositories.to_string(); |
| 1159 | fs::write(file_path, output).map_err(|e| format!("Failed to write file: {}", e))?; |
| 1160 | } |
| 1161 | |
| 1162 | Ok((enabled_count, created_count)) |
| 1163 | } |
| 1164 | |
| 1165 | fn enable_sources_in_legacy_file( |
| 1166 | file_path: &Path, |
| 1167 | enable_source_count: u8, |
| 1168 | dry_run: bool, |
| 1169 | ) -> Result<(u32, u32, u32), String> { |
| 1170 | debug!("Processing legacy file: {}", file_path.display()); |
| 1171 | |
| 1172 | let content = |
| 1173 | fs::read_to_string(file_path).map_err(|e| format!("Failed to read file: {}", e))?; |
| 1174 | |
| 1175 | let mut lines: Vec<String> = content.lines().map(|s| s.to_string()).collect(); |
| 1176 | let mut enabled_count = 0; |
| 1177 | let mut created_count = 0; |
| 1178 | let mut warned_count = 0; |
| 1179 | let mut modified = false; |
| 1180 | |
| 1181 | // First pass: Enable disabled deb-src lines |
| 1182 | for i in 0..lines.len() { |
| 1183 | let trimmed = lines[i].trim(); |
| 1184 | if trimmed.starts_with("# deb-src ") || trimmed.starts_with("#deb-src ") { |
| 1185 | // This is a commented-out deb-src line |
| 1186 | let uncommented = trimmed.trim_start_matches("# ").trim_start_matches("#"); |
| 1187 | |
| 1188 | // Check if there's a matching enabled deb line |
| 1189 | let lines_refs: Vec<&str> = lines.iter().map(|s| s.as_str()).collect(); |
| 1190 | if has_matching_deb_line(&lines_refs, uncommented) { |
| 1191 | if dry_run { |
| 1192 | info!( |
| 1193 | "Would enable disabled deb-src line in {}", |
| 1194 | file_path.display() |
| 1195 | ); |
| 1196 | } else { |
| 1197 | lines[i] = uncommented.to_string(); |
| 1198 | info!("Enabled disabled deb-src line in {}", file_path.display()); |
| 1199 | } |
| 1200 | enabled_count += 1; |
| 1201 | modified = true; |
| 1202 | } |
| 1203 | } |
| 1204 | } |
| 1205 | |
| 1206 | // Second pass: Handle missing deb-src entries |
| 1207 | let mut new_lines = Vec::new(); |
| 1208 | for line in &lines { |
| 1209 | let trimmed = line.trim(); |
| 1210 | if trimmed.starts_with("deb ") && !trimmed.starts_with("deb-src ") { |
| 1211 | // This is an enabled deb line |
| 1212 | let source_line = trimmed.replace("deb ", "deb-src "); |
| 1213 | |
| 1214 | // Check if there's already a matching deb-src line |
| 1215 | let lines_refs: Vec<&str> = lines.iter().map(|s| s.as_str()).collect(); |
| 1216 | if !has_matching_source_line(&lines_refs, &source_line) { |
| 1217 | if enable_source_count == 1 { |
| 1218 | // Just warn about missing source |
| 1219 | debug!("Missing deb-src for: {}", trimmed); |
| 1220 | warned_count += 1; |
| 1221 | } else if enable_source_count > 1 { |
| 1222 | // Create the missing deb-src line |
| 1223 | if dry_run { |
| 1224 | info!( |
| 1225 | "Would create missing deb-src line in {}", |
| 1226 | file_path.display() |
| 1227 | ); |
| 1228 | } else { |
| 1229 | new_lines.push(source_line); |
| 1230 | info!("Created missing deb-src line in {}", file_path.display()); |
| 1231 | } |
| 1232 | created_count += 1; |
| 1233 | modified = true; |
| 1234 | } |
| 1235 | } |
| 1236 | } |
| 1237 | } |
| 1238 | |
| 1239 | // Add new lines |
| 1240 | if !new_lines.is_empty() && !dry_run { |
| 1241 | lines.extend(new_lines); |
| 1242 | modified = true; |
| 1243 | } |
| 1244 | |
| 1245 | // Write changes if modified and not dry run |
| 1246 | if modified && !dry_run { |
| 1247 | let output = lines.join("\n") + "\n"; |
| 1248 | fs::write(file_path, output).map_err(|e| format!("Failed to write file: {}", e))?; |
| 1249 | } |
| 1250 | |
| 1251 | Ok((enabled_count, created_count, warned_count)) |
| 1252 | } |
| 1253 | |
| 1254 | fn find_matching_binary_repo<'a>( |
| 1255 | repos: &'a Repositories, |
| 1256 | source_repo: &Repository, |
| 1257 | ) -> Option<&'a Repository> { |
| 1258 | for repo in repos.iter() { |
| 1259 | if !repo.enabled.unwrap_or(true) { |
| 1260 | continue; // Skip disabled repositories |
| 1261 | } |
| 1262 | |
| 1263 | // Check if this is a binary repository with matching URIs, suites, and components |
| 1264 | if repo.types.contains(&RepositoryType::Binary) |
| 1265 | && repo.uris == source_repo.uris |
| 1266 | && repo.suites == source_repo.suites |
| 1267 | && repo.components == source_repo.components |
| 1268 | { |
| 1269 | return Some(repo); |
| 1270 | } |
| 1271 | } |
| 1272 | None |
| 1273 | } |
| 1274 | |
| 1275 | fn has_matching_source_repo(repos: &Repositories, binary_repo: &Repository) -> bool { |
| 1276 | for repo in repos.iter() { |
| 1277 | // Check if this is a source repository with matching URIs, suites, and components |
| 1278 | if repo.types.contains(&RepositoryType::Source) |
| 1279 | && repo.uris == binary_repo.uris |
| 1280 | && repo.suites == binary_repo.suites |
| 1281 | && repo.components == binary_repo.components |
| 1282 | { |
| 1283 | return true; |
| 1284 | } |
| 1285 | } |
| 1286 | false |
| 1287 | } |
| 1288 | |
| 1289 | fn has_matching_deb_line(lines: &[&str], deb_src_line: &str) -> bool { |
| 1290 | // Convert deb-src line to equivalent deb line |
| 1291 | let deb_line = deb_src_line.replace("deb-src ", "deb "); |
| 1292 | |
| 1293 | for line in lines { |
| 1294 | let trimmed = line.trim(); |
| 1295 | if trimmed == deb_line { |
| 1296 | return true; |
| 1297 | } |
| 1298 | } |
| 1299 | false |
| 1300 | } |
| 1301 | |
| 1302 | fn has_matching_source_line(lines: &[&str], source_line: &str) -> bool { |
| 1303 | for line in lines { |
| 1304 | let trimmed = line.trim(); |
| 1305 | // Check both enabled and disabled source lines |
| 1306 | if trimmed == source_line |
| 1307 | || trimmed == format!("# {}", source_line) |
| 1308 | || trimmed == format!("#{}", source_line) |
| 1309 | { |
| 1310 | return true; |
| 1311 | } |
| 1312 | } |
| 1313 | false |
| 1314 | } |
| 1315 | |
| 1316 | fn add_repositories_from_stdin( |
| 1317 | args: &Args, |
| 1318 | distribution: &Distribution, |
| 1319 | codename: &str, |
| 1320 | ) -> Result<(), String> { |
| 1321 | info!("Reading repository specifications from stdin..."); |
| 1322 | |
| 1323 | use std::io::{BufRead, BufReader}; |
| 1324 | |
| 1325 | let stdin = io::stdin(); |
| 1326 | let reader = BufReader::new(stdin); |
| 1327 | |
| 1328 | let mut success_count = 0; |
| 1329 | let mut error_count = 0; |
| 1330 | let mut errors = Vec::new(); |
| 1331 | |
| 1332 | for (line_num, line_result) in reader.lines().enumerate() { |
| 1333 | let line = match line_result { |
| 1334 | Ok(l) => l, |
| 1335 | Err(e) => { |
| 1336 | error!("Failed to read line {}: {}", line_num + 1, e); |
| 1337 | error_count += 1; |
| 1338 | continue; |
| 1339 | } |
| 1340 | }; |
| 1341 | |
| 1342 | // Skip empty lines and comments |
| 1343 | let trimmed = line.trim(); |
| 1344 | if trimmed.is_empty() || trimmed.starts_with('#') { |
| 1345 | continue; |
| 1346 | } |
| 1347 | |
| 1348 | info!("Processing: {}", trimmed); |
| 1349 | |
| 1350 | // Create a temporary args with the repository from stdin |
| 1351 | let mut temp_args = args.clone(); |
| 1352 | temp_args.repository = Some(trimmed.to_string()); |
| 1353 | |
| 1354 | // Process this repository |
| 1355 | match add_single_repository(&temp_args, distribution, codename) { |
| 1356 | Ok(()) => { |
| 1357 | success_count += 1; |
| 1358 | } |
| 1359 | Err(e) => { |
| 1360 | error_count += 1; |
| 1361 | errors.push(format!("Line {}: {} - {}", line_num + 1, trimmed, e)); |
| 1362 | } |
| 1363 | } |
| 1364 | } |
| 1365 | |
| 1366 | // Report results |
| 1367 | if error_count > 0 { |
| 1368 | error!( |
| 1369 | "Added {} repositories, {} failed:", |
| 1370 | success_count, error_count |
| 1371 | ); |
| 1372 | for err in errors { |
| 1373 | error!(" {}", err); |
| 1374 | } |
| 1375 | return Err(format!("{} repositories failed to add", error_count)); |
| 1376 | } else if success_count == 0 { |
| 1377 | warn!("No repositories were added (empty input or all lines were comments)"); |
| 1378 | } else { |
| 1379 | info!("Successfully added {} repositories", success_count); |
| 1380 | } |
| 1381 | |
| 1382 | Ok(()) |
| 1383 | } |
| 1384 | |
| 1385 | fn add_single_repository( |
| 1386 | args: &Args, |
| 1387 | distribution: &Distribution, |
| 1388 | codename: &str, |
| 1389 | ) -> Result<(), String> { |
| 1390 | let repository = args |
| 1391 | .repository |
| 1392 | .as_ref() |
| 1393 | .ok_or_else(|| "Repository specification required".to_string())?; |
| 1394 | |
| 1395 | debug!("Adding repository: {}", repository); |
| 1396 | |
| 1397 | // Handle -p/--pocket flag |
| 1398 | if let Some(pocket) = &args.pocket { |
| 1399 | let pocket_spec = format!("{}-{}", codename, pocket); |
| 1400 | return add_pocket_repository(&pocket_spec, args, args.enable_source, distribution); |
| 1401 | } |
| 1402 | |
| 1403 | let spec = parse_repository_spec(repository, args.enable_source, args, distribution, codename)?; |
| 1404 | |
| 1405 | match spec { |
| 1406 | RepositorySpec::Component(component) => { |
| 1407 | add_component_to_existing_repos(&component, &args.directory, args.dry_run, distribution) |
| 1408 | } |
| 1409 | RepositorySpec::Pocket(pocket_spec) => { |
| 1410 | add_pocket_repository(&pocket_spec, args, args.enable_source, distribution) |
| 1411 | } |
| 1412 | RepositorySpec::Repository(parsed) => add_parsed_repository(parsed, args, distribution), |
| 1413 | } |
| 1414 | } |
| 1415 | |
| 1416 | fn add_repository(args: &Args, distribution: &Distribution, codename: &str) -> Result<(), String> { |
| 1417 | let repository = args |
| 1418 | .repository |
| 1419 | .as_ref() |
| 1420 | .ok_or_else(|| "Repository specification required".to_string())?; |
| 1421 | |
| 1422 | // Check if we should read from stdin |
| 1423 | if repository == "-" { |
| 1424 | return add_repositories_from_stdin(args, distribution, codename); |
| 1425 | } |
| 1426 | |
| 1427 | // Check if multiple repositories are specified (space-separated) |
| 1428 | let repositories: Vec<&str> = repository.split_whitespace().collect(); |
| 1429 | if repositories.len() > 1 { |
| 1430 | info!("Adding {} repositories...", repositories.len()); |
| 1431 | return add_multiple_repositories(&repositories, args, distribution, codename); |
| 1432 | } |
| 1433 | |
| 1434 | // Otherwise, add single repository |
| 1435 | add_single_repository(args, distribution, codename) |
| 1436 | } |
| 1437 | |
| 1438 | fn add_multiple_repositories( |
| 1439 | repositories: &[&str], |
| 1440 | args: &Args, |
| 1441 | distribution: &Distribution, |
| 1442 | codename: &str, |
| 1443 | ) -> Result<(), String> { |
| 1444 | let mut success_count = 0; |
| 1445 | let mut error_count = 0; |
| 1446 | let mut errors = Vec::new(); |
| 1447 | |
| 1448 | // Create progress bar |
| 1449 | let pb = ProgressBar::new(repositories.len() as u64); |
| 1450 | pb.set_style( |
| 1451 | ProgressStyle::default_bar() |
| 1452 | .template("{spinner:.green} [{bar:40.cyan/blue}] {pos}/{len} ({percent}%) {msg}") |
| 1453 | .unwrap() |
| 1454 | .progress_chars("#>-"), |
| 1455 | ); |
| 1456 | pb.set_message("Adding repositories..."); |
| 1457 | |
| 1458 | for (_index, repo_spec) in repositories.iter().enumerate() { |
| 1459 | pb.set_message(format!("Processing: {}", repo_spec)); |
| 1460 | |
| 1461 | // Create a temporary args with the current repository |
| 1462 | let mut temp_args = args.clone(); |
| 1463 | temp_args.repository = Some(repo_spec.to_string()); |
| 1464 | |
| 1465 | // Add this repository |
| 1466 | match add_single_repository(&temp_args, distribution, codename) { |
| 1467 | Ok(()) => { |
| 1468 | success_count += 1; |
| 1469 | pb.println(format!("✓ Successfully added: {}", repo_spec)); |
| 1470 | } |
| 1471 | Err(e) => { |
| 1472 | error_count += 1; |
| 1473 | errors.push(format!("Repository '{}': {}", repo_spec, e)); |
| 1474 | pb.println(format!("✗ Failed to add '{}': {}", repo_spec, e)); |
| 1475 | } |
| 1476 | } |
| 1477 | |
| 1478 | pb.inc(1); |
| 1479 | } |
| 1480 | |
| 1481 | pb.finish_with_message("Done"); |
| 1482 | |
| 1483 | // Summary |
| 1484 | info!( |
| 1485 | "\nSummary: {} succeeded, {} failed", |
| 1486 | success_count, error_count |
| 1487 | ); |
| 1488 | |
| 1489 | if error_count > 0 { |
| 1490 | error!("\nThe following repositories failed to add:"); |
| 1491 | for err in &errors { |
| 1492 | error!(" - {}", err); |
| 1493 | } |
| 1494 | return Err(format!( |
| 1495 | "{} out of {} repositories failed to add", |
| 1496 | error_count, |
| 1497 | repositories.len() |
| 1498 | )); |
| 1499 | } |
| 1500 | |
| 1501 | Ok(()) |
| 1502 | } |
| 1503 | |
| 1504 | /// Check a DEB822 sources file for duplicate repositories |
| 1505 | fn check_deb822_for_duplicate( |
| 1506 | path: &Path, |
| 1507 | new_uris: &HashSet<String>, |
| 1508 | new_suites: &HashSet<String>, |
| 1509 | new_components: &HashSet<String>, |
| 1510 | new_types: &HashSet<RepositoryType>, |
| 1511 | ) -> Option<(PathBuf, String)> { |
| 1512 | let content = match fs::read_to_string(path) { |
| 1513 | Ok(c) => c, |
| 1514 | Err(e) => { |
| 1515 | debug!("Failed to read {}: {}", path.display(), e); |
| 1516 | return None; |
| 1517 | } |
| 1518 | }; |
| 1519 | |
| 1520 | let repos = match Repositories::from_str(&content) { |
| 1521 | Ok(r) => r, |
| 1522 | Err(e) => { |
| 1523 | debug!("Failed to parse {}: {}", path.display(), e); |
| 1524 | return None; |
| 1525 | } |
| 1526 | }; |
| 1527 | |
| 1528 | for repo in repos.iter() { |
| 1529 | if is_duplicate_repository(repo, new_uris, new_suites, new_components, new_types) { |
| 1530 | return Some(( |
| 1531 | path.to_path_buf(), |
| 1532 | format!("DEB822 format in {}", path.display()), |
| 1533 | )); |
| 1534 | } |
| 1535 | } |
| 1536 | None |
| 1537 | } |
| 1538 | |
| 1539 | /// Check a legacy .list file for duplicate repositories |
| 1540 | fn check_legacy_for_duplicate( |
| 1541 | path: &Path, |
| 1542 | new_uris: &HashSet<String>, |
| 1543 | new_suites: &HashSet<String>, |
| 1544 | new_components: &HashSet<String>, |
| 1545 | new_types: &HashSet<RepositoryType>, |
| 1546 | ) -> Option<(PathBuf, String)> { |
| 1547 | let content = match fs::read_to_string(path) { |
| 1548 | Ok(c) => c, |
| 1549 | Err(e) => { |
| 1550 | debug!("Failed to read {}: {}", path.display(), e); |
| 1551 | return None; |
| 1552 | } |
| 1553 | }; |
| 1554 | |
| 1555 | for (line_num, line) in content.lines().enumerate() { |
| 1556 | let line = line.trim(); |
| 1557 | if line.is_empty() || line.starts_with('#') { |
| 1558 | continue; |
| 1559 | } |
| 1560 | |
| 1561 | let Ok(repos) = line.parse::<LegacyRepositories>() else { |
| 1562 | continue; |
| 1563 | }; |
| 1564 | |
| 1565 | for legacy_repo in repos.iter() { |
| 1566 | let repo = Repository::from(legacy_repo); |
| 1567 | if is_duplicate_repository(&repo, new_uris, new_suites, new_components, new_types) { |
| 1568 | return Some(( |
| 1569 | path.to_path_buf(), |
| 1570 | format!( |
| 1571 | "Legacy format in {} at line {}", |
| 1572 | path.display(), |
| 1573 | line_num + 1 |
| 1574 | ), |
| 1575 | )); |
| 1576 | } |
| 1577 | } |
| 1578 | } |
| 1579 | None |
| 1580 | } |
| 1581 | |
| 1582 | fn find_duplicate_repository( |
| 1583 | new_repo: &Repository, |
| 1584 | sources_dir: &str, |
| 1585 | ) -> Result<Option<(PathBuf, String)>, String> { |
| 1586 | debug!("Checking for duplicate repositories"); |
| 1587 | |
| 1588 | // Normalize the new repository for comparison |
| 1589 | let new_uris: HashSet<String> = new_repo.uris.iter().map(|u| u.to_string()).collect(); |
| 1590 | let new_suites: HashSet<String> = new_repo.suites.iter().cloned().collect(); |
| 1591 | let new_components: HashSet<String> = new_repo |
| 1592 | .components |
| 1593 | .as_ref() |
| 1594 | .map(|c| c.iter().cloned().collect()) |
| 1595 | .unwrap_or_default(); |
| 1596 | let new_types: HashSet<RepositoryType> = new_repo.types.clone(); |
| 1597 | |
| 1598 | // Scan sources.list.d directory |
| 1599 | let sources_path = Path::new(sources_dir); |
| 1600 | if sources_path.exists() { |
| 1601 | for entry in |
| 1602 | fs::read_dir(sources_path).map_err(|e| format!("Failed to read directory: {}", e))? |
| 1603 | { |
| 1604 | let entry = entry.map_err(|e| format!("Failed to read directory entry: {}", e))?; |
| 1605 | let path = entry.path(); |
| 1606 | |
| 1607 | if !path.is_file() { |
| 1608 | continue; |
| 1609 | } |
| 1610 | |
| 1611 | let ext = path.extension().and_then(|s| s.to_str()); |
| 1612 | let result = match ext { |
| 1613 | Some("sources") => check_deb822_for_duplicate( |
| 1614 | &path, |
| 1615 | &new_uris, |
| 1616 | &new_suites, |
| 1617 | &new_components, |
| 1618 | &new_types, |
| 1619 | ), |
| 1620 | Some("list") => check_legacy_for_duplicate( |
| 1621 | &path, |
| 1622 | &new_uris, |
| 1623 | &new_suites, |
| 1624 | &new_components, |
| 1625 | &new_types, |
| 1626 | ), |
| 1627 | _ => None, |
| 1628 | }; |
| 1629 | |
| 1630 | if result.is_some() { |
| 1631 | return Ok(result); |
| 1632 | } |
| 1633 | } |
| 1634 | } |
| 1635 | |
| 1636 | // Also check main sources.list |
| 1637 | let main_sources = get_main_sources_list_path(sources_dir); |
| 1638 | if main_sources.exists() { |
| 1639 | if let Some(result) = check_legacy_for_duplicate( |
| 1640 | &main_sources, |
| 1641 | &new_uris, |
| 1642 | &new_suites, |
| 1643 | &new_components, |
| 1644 | &new_types, |
| 1645 | ) { |
| 1646 | return Ok(Some(result)); |
| 1647 | } |
| 1648 | } |
| 1649 | |
| 1650 | Ok(None) |
| 1651 | } |
| 1652 | |
| 1653 | fn is_duplicate_repository( |
| 1654 | existing: &Repository, |
| 1655 | new_uris: &HashSet<String>, |
| 1656 | new_suites: &HashSet<String>, |
| 1657 | new_components: &HashSet<String>, |
| 1658 | new_types: &HashSet<RepositoryType>, |
| 1659 | ) -> bool { |
| 1660 | // Check if disabled |
| 1661 | if !existing.enabled.unwrap_or(true) { |
| 1662 | return false; |
| 1663 | } |
| 1664 | |
| 1665 | // Compare URIs (must have at least one matching URI) |
| 1666 | let existing_uris: HashSet<String> = existing.uris.iter().map(|u| u.to_string()).collect(); |
| 1667 | if existing_uris.is_disjoint(new_uris) { |
| 1668 | return false; |
| 1669 | } |
| 1670 | |
| 1671 | // Compare suites (must have at least one matching suite) |
| 1672 | let existing_suites: HashSet<String> = existing.suites.iter().cloned().collect(); |
| 1673 | if existing_suites.is_disjoint(new_suites) { |
| 1674 | return false; |
| 1675 | } |
| 1676 | |
| 1677 | // Compare components (must have overlapping components) |
| 1678 | let existing_components: HashSet<String> = existing |
| 1679 | .components |
| 1680 | .as_ref() |
| 1681 | .map(|c| c.iter().cloned().collect()) |
| 1682 | .unwrap_or_default(); |
| 1683 | if !existing_components.is_empty() |
| 1684 | && !new_components.is_empty() |
| 1685 | && existing_components.is_disjoint(new_components) |
| 1686 | { |
| 1687 | return false; |
| 1688 | } |
| 1689 | |
| 1690 | // Compare types (must have at least one matching type) |
| 1691 | let existing_types: HashSet<RepositoryType> = existing.types.clone(); |
| 1692 | !existing_types.is_disjoint(new_types) |
| 1693 | } |
| 1694 | |
| 1695 | fn add_parsed_repository( |
| 1696 | mut parsed: ParsedRepository, |
| 1697 | args: &Args, |
| 1698 | distribution: &Distribution, |
| 1699 | ) -> Result<(), String> { |
| 1700 | // Check for duplicate repository before proceeding |
| 1701 | debug!("Checking for duplicate repository"); |
| 1702 | match find_duplicate_repository(&parsed.repository, &args.directory) { |
| 1703 | Ok(Some((_file_path, location))) => { |
| 1704 | if args.assume_yes { |
| 1705 | warn!("Repository already exists in {}", location); |
| 1706 | warn!("Skipping duplicate repository"); |
| 1707 | return Ok(()); |
| 1708 | } else { |
| 1709 | eprint!( |
| 1710 | "Repository already exists in {}.\nAdd it anyway? [y/N] ", |
| 1711 | location |
| 1712 | ); |
| 1713 | io::stdout().flush().unwrap(); |
| 1714 | let mut input = String::new(); |
| 1715 | io::stdin().read_line(&mut input).unwrap(); |
| 1716 | if !input.trim().eq_ignore_ascii_case("y") { |
| 1717 | return Err("Repository already exists, not adding duplicate".to_string()); |
| 1718 | } |
| 1719 | info!("Adding duplicate repository as requested"); |
| 1720 | } |
| 1721 | } |
| 1722 | Ok(None) => { |
| 1723 | debug!("No duplicate repository found"); |
| 1724 | } |
| 1725 | Err(e) => { |
| 1726 | warn!("Error checking for duplicates: {}", e); |
| 1727 | // Continue anyway - better to add a potential duplicate than fail |
| 1728 | } |
| 1729 | } |
| 1730 | |
| 1731 | // Handle PPA key download |
| 1732 | if let Some(ref ppa_info) = parsed.ppa_info { |
| 1733 | // Validate PPA first |
| 1734 | info!("Checking PPA availability..."); |
| 1735 | |
| 1736 | #[cfg(feature = "launchpad")] |
| 1737 | let validation_result = if args.login || args.keyserver.is_none() { |
| 1738 | validate_ppa_launchpadlib(ppa_info, args.login)? |
| 1739 | } else { |
| 1740 | validate_ppa_with_suggestions(ppa_info)? |
| 1741 | }; |
| 1742 | |
| 1743 | #[cfg(not(feature = "launchpad"))] |
| 1744 | let validation_result = validate_ppa_with_suggestions(ppa_info)?; |
| 1745 | |
| 1746 | // Inform about debug symbols if available |
| 1747 | if validation_result.publishes_debug_symbols { |
| 1748 | info!("This PPA publishes debug symbols. To enable debug symbols, add the component 'main/debug'."); |
| 1749 | } |
| 1750 | |
| 1751 | if !args.assume_yes && !args.dry_run { |
| 1752 | eprint!( |
| 1753 | "You are about to add the following PPA: |
| 1754 | {} |
| 1755 | More info: https://launchpad.net/~{}/+archive/ubuntu/{} |
| 1756 | Press [ENTER] to continue or Ctrl-c to cancel.", |
| 1757 | validation_result.display_name, ppa_info.user, ppa_info.name |
| 1758 | ); |
| 1759 | io::stdout().flush().unwrap(); |
| 1760 | let mut input = String::new(); |
| 1761 | io::stdin().read_line(&mut input).unwrap(); |
| 1762 | } |
| 1763 | |
| 1764 | // Download and save the PPA signing key |
| 1765 | if args.dry_run { |
| 1766 | info!("Would download and verify PPA signing key"); |
| 1767 | let keyring_path = Path::new(&args.keyring_dir).join(ppa_info.keyring_filename()); |
| 1768 | info!("Would save signing key to {}", keyring_path.display()); |
| 1769 | parsed.repository.signature = Some(Signature::KeyPath(keyring_path)); |
| 1770 | } else { |
| 1771 | info!("Getting signing key for PPA..."); |
| 1772 | |
| 1773 | // Use launchpadlib if available and needed |
| 1774 | #[cfg(feature = "launchpad")] |
| 1775 | let key_result = if args.login || args.keyserver.is_none() { |
| 1776 | download_ppa_key_launchpadlib(ppa_info, args.login) |
| 1777 | } else { |
| 1778 | download_ppa_key(ppa_info, args.keyserver.as_deref()) |
| 1779 | }; |
| 1780 | |
| 1781 | #[cfg(not(feature = "launchpad"))] |
| 1782 | let key_result = download_ppa_key(ppa_info, args.keyserver.as_deref()); |
| 1783 | |
| 1784 | match key_result { |
| 1785 | Ok(key_data) => { |
| 1786 | let use_inline = args.inline_key && args.format == OutputFormat::Deb822; |
| 1787 | parsed.repository.signature = |
| 1788 | save_ppa_key(&key_data, ppa_info, &args.keyring_dir, use_inline); |
| 1789 | } |
| 1790 | Err(e) => { |
| 1791 | warn!("Failed to download PPA signing key: {}", e); |
| 1792 | warn!("The repository will be added without signature verification."); |
| 1793 | } |
| 1794 | } |
| 1795 | } |
| 1796 | } |
| 1797 | |
| 1798 | // Determine the appropriate file path |
| 1799 | let filepath = determine_repository_filepath(&parsed, args, distribution)?; |
| 1800 | |
| 1801 | // Check if directory exists |
| 1802 | let parent_dir = filepath |
| 1803 | .parent() |
| 1804 | .ok_or_else(|| "Invalid file path".to_string())?; |
| 1805 | if !parent_dir.exists() { |
| 1806 | return Err(format!( |
| 1807 | "Directory {} does not exist.\n\ |
| 1808 | Suggestions:\n\ |
| 1809 | - Create the directory with: sudo mkdir -p {}\n\ |
| 1810 | - Check if you have the correct permissions\n\ |
| 1811 | - Verify the path is correct", |
| 1812 | parent_dir.display(), |
| 1813 | parent_dir.display() |
| 1814 | )); |
| 1815 | } |
| 1816 | |
| 1817 | // Check if file already exists |
| 1818 | let file_exists = filepath.exists(); |
| 1819 | let is_main_file = is_main_distribution_file(&filepath); |
| 1820 | |
| 1821 | if file_exists && !is_main_file && !args.assume_yes { |
| 1822 | eprint!( |
| 1823 | "Repository file {} already exists. Overwrite? [y/N] ", |
| 1824 | filepath.display() |
| 1825 | ); |
| 1826 | io::stdout().flush().unwrap(); |
| 1827 | let mut input = String::new(); |
| 1828 | io::stdin().read_line(&mut input).unwrap(); |
| 1829 | if !input.trim().eq_ignore_ascii_case("y") { |
| 1830 | return Err("Aborted".to_string()); |
| 1831 | } |
| 1832 | } |
| 1833 | |
| 1834 | // Create content based on format |
| 1835 | let content = match args.format { |
| 1836 | OutputFormat::Legacy => { |
| 1837 | // Generate legacy .list format |
| 1838 | LegacyRepositories::from(&parsed.repository).to_string() |
| 1839 | } |
| 1840 | OutputFormat::Deb822 => { |
| 1841 | // Create Repositories container and serialize to DEB822 format |
| 1842 | let repos = Repositories::new(vec![parsed.repository.clone()]); |
| 1843 | repos.to_string() |
| 1844 | } |
| 1845 | }; |
| 1846 | |
| 1847 | if args.dry_run { |
| 1848 | // Show what would be written |
| 1849 | if file_exists && is_main_file { |
| 1850 | info!( |
| 1851 | "Would append repository to existing file {}", |
| 1852 | filepath.display() |
| 1853 | ); |
| 1854 | } else { |
| 1855 | info!("Would write repository to {}", filepath.display()); |
| 1856 | } |
| 1857 | info!("Repository content that would be written:"); |
| 1858 | for line in content.lines() { |
| 1859 | info!(" {}", line); |
| 1860 | } |
| 1861 | |
| 1862 | if !args.no_update { |
| 1863 | info!("Would run: apt update"); |
| 1864 | } |
| 1865 | } else { |
| 1866 | // Write to file - append if it's a main distribution file, otherwise overwrite |
| 1867 | if file_exists && is_main_file { |
| 1868 | // For main distribution files, append the repository |
| 1869 | match args.format { |
| 1870 | OutputFormat::Legacy => { |
| 1871 | // For legacy format, just append the lines |
| 1872 | let mut file = fs::OpenOptions::new() |
| 1873 | .append(true) |
| 1874 | .open(&filepath) |
| 1875 | .map_err(|e| format!("Failed to open file for appending: {}", e))?; |
| 1876 | |
| 1877 | // Add a newline if the file doesn't end with one |
| 1878 | let existing_content = fs::read_to_string(&filepath) |
| 1879 | .map_err(|e| format!("Failed to read existing file: {}", e))?; |
| 1880 | if !existing_content.ends_with('\n') { |
| 1881 | use std::io::Write; |
| 1882 | writeln!(file).map_err(|e| format!("Failed to write newline: {}", e))?; |
| 1883 | } |
| 1884 | |
| 1885 | // Write the new content |
| 1886 | write!(file, "{}", content) |
| 1887 | .map_err(|e| format!("Failed to append to file: {}", e))?; |
| 1888 | } |
| 1889 | OutputFormat::Deb822 => { |
| 1890 | // For DEB822 format, we need to merge repositories |
| 1891 | let existing_content = fs::read_to_string(&filepath) |
| 1892 | .map_err(|e| format!("Failed to read existing file: {}", e))?; |
| 1893 | |
| 1894 | let repos = Repositories::from_str(&existing_content) |
| 1895 | .map_err(|e| format!("Failed to parse existing repositories: {}", e))?; |
| 1896 | |
| 1897 | // Create a new vector with existing repos plus the new one |
| 1898 | let mut all_repos: Vec<Repository> = repos.iter().cloned().collect(); |
| 1899 | all_repos.push(parsed.repository.clone()); |
| 1900 | |
| 1901 | // Write the merged content |
| 1902 | let merged_repos = Repositories::new(all_repos); |
| 1903 | fs::write(&filepath, merged_repos.to_string()) |
| 1904 | .map_err(|e| format!("Failed to write merged repositories: {}", e))?; |
| 1905 | } |
| 1906 | } |
| 1907 | info!("Repository appended to {}", filepath.display()); |
| 1908 | } else { |
| 1909 | // For non-main files, just write/overwrite |
| 1910 | fs::write(&filepath, &content).map_err(|e| format!("Failed to write file: {}", e))?; |
| 1911 | info!("Repository added to {}", filepath.display()); |
| 1912 | } |
| 1913 | |
| 1914 | // Update package cache unless disabled |
| 1915 | if !args.no_update { |
| 1916 | let spinner = ProgressBar::new_spinner(); |
| 1917 | spinner.set_style( |
| 1918 | ProgressStyle::default_spinner() |
| 1919 | .template("{spinner:.green} {msg}") |
| 1920 | .unwrap(), |
| 1921 | ); |
| 1922 | spinner.set_message("Updating package cache..."); |
| 1923 | spinner.enable_steady_tick(std::time::Duration::from_millis(100)); |
| 1924 | |
| 1925 | let status = process::Command::new("apt") |
| 1926 | .arg("update") |
| 1927 | .status() |
| 1928 | .map_err(|e| { |
| 1929 | spinner.finish_and_clear(); |
| 1930 | format!("Failed to run apt update: {}", e) |
| 1931 | })?; |
| 1932 | |
| 1933 | if !status.success() { |
| 1934 | spinner.finish_with_message("apt update failed"); |
| 1935 | warn!("apt update failed"); |
| 1936 | } else { |
| 1937 | spinner.finish_with_message("Package cache updated successfully"); |
| 1938 | } |
| 1939 | } |
| 1940 | } |
| 1941 | |
| 1942 | Ok(()) |
| 1943 | } |
| 1944 | |
| 1945 | /// Warn about key expiration if applicable |
| 1946 | fn warn_key_expiration(key_data: &str, ppa_info: &PpaInfo) { |
| 1947 | let Ok(cert) = Cert::from_str(key_data) else { |
| 1948 | return; |
| 1949 | }; |
| 1950 | let policy = sequoia_openpgp::policy::StandardPolicy::new(); |
| 1951 | let Ok(valid_cert) = cert.with_policy(&policy, None) else { |
| 1952 | return; |
| 1953 | }; |
| 1954 | let Some(expiration) = valid_cert.primary_key().key_expiration_time() else { |
| 1955 | return; |
| 1956 | }; |
| 1957 | |
| 1958 | let now = std::time::SystemTime::now(); |
| 1959 | if expiration < now { |
| 1960 | warn!("Key for {}/{} has expired!", ppa_info.user, ppa_info.name); |
| 1961 | } else if let Ok(duration) = expiration.duration_since(now) { |
| 1962 | let days = duration.as_secs() / 86400; |
| 1963 | if days < 30 { |
| 1964 | warn!( |
| 1965 | "Key for {}/{} expires in {} days", |
| 1966 | ppa_info.user, ppa_info.name, days |
| 1967 | ); |
| 1968 | } |
| 1969 | } |
| 1970 | } |
| 1971 | |
| 1972 | /// Collect PPAs from DEB822 sources file |
| 1973 | fn collect_ppas_from_deb822( |
| 1974 | path: &Path, |
| 1975 | ppa_repos: &mut Vec<(PathBuf, PpaInfo, Option<Signature>)>, |
| 1976 | ) { |
| 1977 | let content = match fs::read_to_string(path) { |
| 1978 | Ok(c) => c, |
| 1979 | Err(e) => { |
| 1980 | warn!("Failed to read {}: {}", path.display(), e); |
| 1981 | return; |
| 1982 | } |
| 1983 | }; |
| 1984 | |
| 1985 | let repos = match Repositories::from_str(&content) { |
| 1986 | Ok(r) => r, |
| 1987 | Err(e) => { |
| 1988 | warn!("Failed to parse {}: {}", path.display(), e); |
| 1989 | return; |
| 1990 | } |
| 1991 | }; |
| 1992 | |
| 1993 | for repo in repos.iter() { |
| 1994 | if let Some(ppa_info) = PpaInfo::from_repository(repo) { |
| 1995 | ppa_repos.push((path.to_path_buf(), ppa_info, repo.signature.clone())); |
| 1996 | } |
| 1997 | } |
| 1998 | } |
| 1999 | |
| 2000 | /// Collect PPAs from legacy .list file |
| 2001 | fn collect_ppas_from_legacy( |
| 2002 | path: &Path, |
| 2003 | keyring_dir: &str, |
| 2004 | ppa_repos: &mut Vec<(PathBuf, PpaInfo, Option<Signature>)>, |
| 2005 | ) { |
| 2006 | let content = match fs::read_to_string(path) { |
| 2007 | Ok(c) => c, |
| 2008 | Err(e) => { |
| 2009 | warn!("Failed to read {}: {}", path.display(), e); |
| 2010 | return; |
| 2011 | } |
| 2012 | }; |
| 2013 | |
| 2014 | for line in content.lines() { |
| 2015 | let line = line.trim(); |
| 2016 | if line.is_empty() || line.starts_with('#') { |
| 2017 | continue; |
| 2018 | } |
| 2019 | |
| 2020 | let Ok(repos) = line.parse::<LegacyRepositories>() else { |
| 2021 | continue; |
| 2022 | }; |
| 2023 | |
| 2024 | for legacy_repo in repos.iter() { |
| 2025 | let repo = Repository::from(legacy_repo); |
| 2026 | if let Some(ppa_info) = PpaInfo::from_repository(&repo) { |
| 2027 | let keyring_path = Path::new(keyring_dir).join(ppa_info.keyring_filename()); |
| 2028 | let signature = if keyring_path.exists() { |
| 2029 | Some(Signature::KeyPath(keyring_path)) |
| 2030 | } else { |
| 2031 | None |
| 2032 | }; |
| 2033 | ppa_repos.push((path.to_path_buf(), ppa_info, signature)); |
| 2034 | break; // Only one PPA per line |
| 2035 | } |
| 2036 | } |
| 2037 | } |
| 2038 | } |
| 2039 | |
| 2040 | fn refresh_ppa_keys(args: &Args) -> Result<(), String> { |
| 2041 | info!("Refreshing signing keys for all PPAs..."); |
| 2042 | |
| 2043 | let mut ppa_repos = Vec::new(); |
| 2044 | |
| 2045 | // Scan sources.list.d directory for PPAs |
| 2046 | let sources_dir = Path::new(&args.directory); |
| 2047 | if sources_dir.exists() { |
| 2048 | for entry in |
| 2049 | fs::read_dir(sources_dir).map_err(|e| format!("Failed to read directory: {}", e))? |
| 2050 | { |
| 2051 | let entry = entry.map_err(|e| format!("Failed to read directory entry: {}", e))?; |
| 2052 | let path = entry.path(); |
| 2053 | |
| 2054 | if !path.is_file() { |
| 2055 | continue; |
| 2056 | } |
| 2057 | |
| 2058 | match path.extension().and_then(|s| s.to_str()) { |
| 2059 | Some("sources") => collect_ppas_from_deb822(&path, &mut ppa_repos), |
| 2060 | Some("list") => collect_ppas_from_legacy(&path, &args.keyring_dir, &mut ppa_repos), |
| 2061 | _ => {} |
| 2062 | } |
| 2063 | } |
| 2064 | } |
| 2065 | |
| 2066 | if ppa_repos.is_empty() { |
| 2067 | println!("No PPAs found to refresh keys for."); |
| 2068 | return Ok(()); |
| 2069 | } |
| 2070 | |
| 2071 | println!("Found {} PPA(s) to refresh keys for", ppa_repos.len()); |
| 2072 | |
| 2073 | let mut updated_count = 0; |
| 2074 | let mut failed_count = 0; |
| 2075 | let mut errors = Vec::new(); |
| 2076 | |
| 2077 | for (_source_file, ppa_info, _existing_signature) in &ppa_repos { |
| 2078 | println!( |
| 2079 | "\nRefreshing key for PPA: {}/{}", |
| 2080 | ppa_info.user, ppa_info.name |
| 2081 | ); |
| 2082 | |
| 2083 | // Download the new key |
| 2084 | #[cfg(feature = "launchpad")] |
| 2085 | let key_result = if args.keyserver.is_none() { |
| 2086 | download_ppa_key_launchpadlib(ppa_info, false) |
| 2087 | } else { |
| 2088 | download_ppa_key(ppa_info, args.keyserver.as_deref()) |
| 2089 | }; |
| 2090 | |
| 2091 | #[cfg(not(feature = "launchpad"))] |
| 2092 | let key_result = download_ppa_key(ppa_info, args.keyserver.as_deref()); |
| 2093 | |
| 2094 | let key_data = match key_result { |
| 2095 | Ok(data) => data, |
| 2096 | Err(e) => { |
| 2097 | failed_count += 1; |
| 2098 | errors.push(format!("{}/{}: {}", ppa_info.user, ppa_info.name, e)); |
| 2099 | continue; |
| 2100 | } |
| 2101 | }; |
| 2102 | |
| 2103 | // Check if we have an existing keyring file |
| 2104 | let keyring_path = Path::new(&args.keyring_dir).join(ppa_info.keyring_filename()); |
| 2105 | |
| 2106 | // Check if the key has changed |
| 2107 | let key_changed = match fs::read_to_string(&keyring_path) { |
| 2108 | Ok(existing_key) => existing_key != key_data, |
| 2109 | Err(_) => true, |
| 2110 | }; |
| 2111 | |
| 2112 | if !key_changed { |
| 2113 | debug!("Key for {}/{} is up to date", ppa_info.user, ppa_info.name); |
| 2114 | continue; |
| 2115 | } |
| 2116 | |
| 2117 | if args.dry_run { |
| 2118 | info!( |
| 2119 | "Would update signing key for {}/{}", |
| 2120 | ppa_info.user, ppa_info.name |
| 2121 | ); |
| 2122 | updated_count += 1; |
| 2123 | warn_key_expiration(&key_data, ppa_info); |
| 2124 | continue; |
| 2125 | } |
| 2126 | |
| 2127 | // Save the new key |
| 2128 | match save_key_to_keyring(&key_data, &args.keyring_dir, ppa_info) { |
| 2129 | Ok(new_keyring_path) => { |
| 2130 | info!( |
| 2131 | "Updated signing key saved to {}", |
| 2132 | new_keyring_path.display() |
| 2133 | ); |
| 2134 | updated_count += 1; |
| 2135 | warn_key_expiration(&key_data, ppa_info); |
| 2136 | } |
| 2137 | Err(e) => { |
| 2138 | failed_count += 1; |
| 2139 | errors.push(format!( |
| 2140 | "{}/{}: Failed to save key - {}", |
| 2141 | ppa_info.user, ppa_info.name, e |
| 2142 | )); |
| 2143 | } |
| 2144 | } |
| 2145 | } |
| 2146 | |
| 2147 | // Report results |
| 2148 | if args.dry_run { |
| 2149 | println!("\nDry run - Key refresh summary:"); |
| 2150 | println!(" Would update: {}", updated_count); |
| 2151 | } else { |
| 2152 | println!("\nKey refresh complete:"); |
| 2153 | println!(" Updated: {}", updated_count); |
| 2154 | } |
| 2155 | println!( |
| 2156 | " Up to date: {}", |
| 2157 | ppa_repos.len() - updated_count - failed_count |
| 2158 | ); |
| 2159 | println!( |
| 2160 | " {}: {}", |
| 2161 | if args.dry_run { |
| 2162 | "Failed to check" |
| 2163 | } else { |
| 2164 | "Failed" |
| 2165 | }, |
| 2166 | failed_count |
| 2167 | ); |
| 2168 | |
| 2169 | if !errors.is_empty() { |
| 2170 | error!("\nErrors encountered:"); |
| 2171 | for err in errors { |
| 2172 | error!(" {}", err); |
| 2173 | } |
| 2174 | } |
| 2175 | |
| 2176 | Ok(()) |
| 2177 | } |
| 2178 | |
| 2179 | /// Collect repositories from a legacy sources.list file |
| 2180 | fn collect_repos_from_sources_list( |
| 2181 | path: &Path, |
| 2182 | all_repos: &mut Vec<(String, PathBuf, RepoFormat, Repository)>, |
| 2183 | ) { |
| 2184 | let content = match fs::read_to_string(path) { |
| 2185 | Ok(c) => c, |
| 2186 | Err(e) => { |
| 2187 | warn!("Failed to read {}: {}", path.display(), e); |
| 2188 | return; |
| 2189 | } |
| 2190 | }; |
| 2191 | |
| 2192 | for (line_num, line) in content.lines().enumerate() { |
| 2193 | let line = line.trim(); |
| 2194 | if line.is_empty() || line.starts_with('#') { |
| 2195 | continue; |
| 2196 | } |
| 2197 | |
| 2198 | let Ok(repos) = line.parse::<LegacyRepositories>() else { |
| 2199 | debug!( |
| 2200 | "Failed to parse line {} in {}", |
| 2201 | line_num + 1, |
| 2202 | path.display() |
| 2203 | ); |
| 2204 | continue; |
| 2205 | }; |
| 2206 | |
| 2207 | for legacy_repo in repos.iter() { |
| 2208 | all_repos.push(( |
| 2209 | format!("sources.list:{}", line_num + 1), |
| 2210 | path.to_path_buf(), |
| 2211 | RepoFormat::Legacy, |
| 2212 | Repository::from(legacy_repo), |
| 2213 | )); |
| 2214 | } |
| 2215 | } |
| 2216 | } |
| 2217 | |
| 2218 | /// Print details of a single repository |
| 2219 | fn print_repository_details(source: &str, path: &Path, format: RepoFormat, repo: &Repository) { |
| 2220 | let format_str = match format { |
| 2221 | RepoFormat::Deb822 => "DEB822".green(), |
| 2222 | RepoFormat::Legacy => "Legacy".yellow(), |
| 2223 | }; |
| 2224 | println!( |
| 2225 | "{} {} [{}]", |
| 2226 | "Source:".bold(), |
| 2227 | source.bright_blue(), |
| 2228 | format_str |
| 2229 | ); |
| 2230 | println!( |
| 2231 | " {}: {}", |
| 2232 | "File".dimmed(), |
| 2233 | path.display().to_string().bright_cyan() |
| 2234 | ); |
| 2235 | |
| 2236 | let enabled_str = if repo.enabled.unwrap_or(true) { |
| 2237 | "enabled".green() |
| 2238 | } else { |
| 2239 | "disabled".red() |
| 2240 | }; |
| 2241 | println!(" {}: {}", "Status".dimmed(), enabled_str); |
| 2242 | |
| 2243 | let types: Vec<&str> = repo |
| 2244 | .types |
| 2245 | .iter() |
| 2246 | .map(|t| match t { |
| 2247 | RepositoryType::Binary => "deb", |
| 2248 | RepositoryType::Source => "deb-src", |
| 2249 | }) |
| 2250 | .collect(); |
| 2251 | println!(" Types: {}", types.join(", ")); |
| 2252 | |
| 2253 | for uri in &repo.uris { |
| 2254 | println!(" URI: {}", uri); |
| 2255 | } |
| 2256 | |
| 2257 | println!(" Suites: {}", repo.suites.join(", ")); |
| 2258 | |
| 2259 | if let Some(components) = &repo.components { |
| 2260 | println!(" Components: {}", components.join(" ")); |
| 2261 | } |
| 2262 | |
| 2263 | if !repo.architectures().is_empty() { |
| 2264 | println!(" Architectures: {}", repo.architectures().join(" ")); |
| 2265 | } |
| 2266 | |
| 2267 | if let Some(signature) = &repo.signature { |
| 2268 | match signature { |
| 2269 | Signature::KeyPath(p) => println!(" Signed-By: {}", p.display()), |
| 2270 | Signature::KeyBlock(_) => println!(" Signed-By: [embedded key]"), |
| 2271 | } |
| 2272 | } |
| 2273 | |
| 2274 | println!(); // Empty line between repositories |
| 2275 | } |
| 2276 | |
| 2277 | fn list_repositories(args: &Args) -> Result<(), String> { |
| 2278 | info!("Listing all configured APT repositories"); |
| 2279 | |
| 2280 | let mut all_repos = Vec::new(); |
| 2281 | let sources_manager = SourcesManager::new(&args.directory, &args.keyring_dir); |
| 2282 | |
| 2283 | // Scan all repository files using SourcesManager |
| 2284 | let repo_files = sources_manager.scan_all_repositories()?; |
| 2285 | |
| 2286 | for (path, repositories) in repo_files { |
| 2287 | let filename = path.file_name().unwrap_or_default().to_string_lossy(); |
| 2288 | let format = if path.extension().and_then(|s| s.to_str()) == Some("sources") { |
| 2289 | RepoFormat::Deb822 |
| 2290 | } else { |
| 2291 | RepoFormat::Legacy |
| 2292 | }; |
| 2293 | |
| 2294 | for repo in repositories.iter() { |
| 2295 | all_repos.push((filename.to_string(), path.clone(), format, repo.clone())); |
| 2296 | } |
| 2297 | } |
| 2298 | |
| 2299 | // Also check sources.list if it exists |
| 2300 | let sources_list = get_main_sources_list_path(&args.directory); |
| 2301 | if sources_list.exists() { |
| 2302 | collect_repos_from_sources_list(&sources_list, &mut all_repos); |
| 2303 | } |
| 2304 | |
| 2305 | // Display the repositories |
| 2306 | if all_repos.is_empty() { |
| 2307 | println!("No repositories configured."); |
| 2308 | } else { |
| 2309 | println!("\n{}\n", "Configured APT repositories:".bold()); |
| 2310 | for (source, path, format, repo) in &all_repos { |
| 2311 | print_repository_details(source, path, *format, repo); |
| 2312 | } |
| 2313 | } |
| 2314 | |
| 2315 | Ok(()) |
| 2316 | } |
| 2317 | |
| 2318 | #[derive(Debug, Clone, Copy)] |
| 2319 | enum RepoFormat { |
| 2320 | Deb822, |
| 2321 | Legacy, |
| 2322 | } |
| 2323 | |
| 2324 | fn remove_repository( |
| 2325 | args: &Args, |
| 2326 | distribution: &Distribution, |
| 2327 | codename: &str, |
| 2328 | ) -> Result<(), String> { |
| 2329 | let repository = args |
| 2330 | .repository |
| 2331 | .as_ref() |
| 2332 | .ok_or_else(|| "Repository specification required".to_string())?; |
| 2333 | |
| 2334 | info!("Removing repository: {}", repository); |
| 2335 | |
| 2336 | let spec = parse_repository_spec(repository, 0, args, distribution, codename)?; |
| 2337 | |
| 2338 | let parsed = match spec { |
| 2339 | RepositorySpec::Component(_) => { |
| 2340 | return Err( |
| 2341 | "Cannot remove individual components. Remove the entire repository instead." |
| 2342 | .to_string(), |
| 2343 | ) |
| 2344 | } |
| 2345 | RepositorySpec::Pocket(_) => { |
| 2346 | return Err( |
| 2347 | "Cannot remove individual pockets. Remove the entire repository instead." |
| 2348 | .to_string(), |
| 2349 | ) |
| 2350 | } |
| 2351 | RepositorySpec::Repository(parsed) => parsed, |
| 2352 | }; |
| 2353 | |
| 2354 | // Determine where the repository should be located |
| 2355 | let filepath = determine_repository_filepath(&parsed, args, distribution)?; |
| 2356 | |
| 2357 | if !filepath.exists() { |
| 2358 | // If the expected file doesn't exist, also check the standard location |
| 2359 | let fallback_path = Path::new(&args.directory).join(&parsed.filename); |
| 2360 | if fallback_path.exists() && fallback_path != filepath { |
| 2361 | return remove_repository_from_file(&fallback_path, &parsed, args); |
| 2362 | } |
| 2363 | |
| 2364 | return Err(format!( |
| 2365 | "Repository not found in {} or {}", |
| 2366 | filepath.display(), |
| 2367 | fallback_path.display() |
| 2368 | )); |
| 2369 | } |
| 2370 | |
| 2371 | remove_repository_from_file(&filepath, &parsed, args) |
| 2372 | } |
| 2373 | |
| 2374 | /// Log what keyring files would be or were removed for a PPA |
| 2375 | fn handle_ppa_keyring_removal(ppa_info: &PpaInfo, keyring_dir: &str, dry_run: bool) { |
| 2376 | for ext in ["asc", "gpg"] { |
| 2377 | let keyring_filename = format!("{}-{}-keyring.{}", ppa_info.user, ppa_info.name, ext); |
| 2378 | let keyring_path = Path::new(keyring_dir).join(&keyring_filename); |
| 2379 | |
| 2380 | if keyring_path.exists() { |
| 2381 | if dry_run { |
| 2382 | info!( |
| 2383 | "Would remove associated keyring: {}", |
| 2384 | keyring_path.display() |
| 2385 | ); |
| 2386 | } else { |
| 2387 | fs::remove_file(&keyring_path).ok(); // Ignore errors |
| 2388 | info!("Associated keyring removed from {}", keyring_path.display()); |
| 2389 | } |
| 2390 | } |
| 2391 | } |
| 2392 | } |
| 2393 | |
| 2394 | /// Run apt update with a spinner |
| 2395 | fn run_apt_update() { |
| 2396 | let spinner = ProgressBar::new_spinner(); |
| 2397 | spinner.set_style( |
| 2398 | ProgressStyle::default_spinner() |
| 2399 | .template("{spinner:.green} {msg}") |
| 2400 | .unwrap(), |
| 2401 | ); |
| 2402 | spinner.set_message("Updating package cache..."); |
| 2403 | spinner.enable_steady_tick(std::time::Duration::from_millis(100)); |
| 2404 | |
| 2405 | match process::Command::new("apt").arg("update").status() { |
| 2406 | Ok(status) if status.success() => { |
| 2407 | spinner.finish_with_message("Package cache updated successfully"); |
| 2408 | } |
| 2409 | _ => { |
| 2410 | spinner.finish_with_message("apt update failed"); |
| 2411 | warn!("apt update failed"); |
| 2412 | } |
| 2413 | } |
| 2414 | } |
| 2415 | |
| 2416 | /// Remove repository entry from a DEB822 format file |
| 2417 | fn remove_from_deb822_file(filepath: &Path, target: &Repository) -> Result<(), String> { |
| 2418 | let content = |
| 2419 | fs::read_to_string(filepath).map_err(|e| format!("Failed to read file: {}", e))?; |
| 2420 | |
| 2421 | let repos = Repositories::from_str(&content) |
| 2422 | .map_err(|e| format!("Failed to parse repositories: {}", e))?; |
| 2423 | |
| 2424 | let all_repos: Vec<Repository> = repos.iter().cloned().collect(); |
| 2425 | let initial_count = all_repos.len(); |
| 2426 | let filtered_repos: Vec<Repository> = all_repos |
| 2427 | .into_iter() |
| 2428 | .filter(|repo| !repositories_match(repo, target)) |
| 2429 | .collect(); |
| 2430 | |
| 2431 | if filtered_repos.len() == initial_count { |
| 2432 | return Err("Repository not found in file".to_string()); |
| 2433 | } |
| 2434 | |
| 2435 | let remaining_repos = Repositories::new(filtered_repos); |
| 2436 | fs::write(filepath, remaining_repos.to_string()) |
| 2437 | .map_err(|e| format!("Failed to write file: {}", e))?; |
| 2438 | |
| 2439 | info!("Repository removed from {}", filepath.display()); |
| 2440 | Ok(()) |
| 2441 | } |
| 2442 | |
| 2443 | /// Remove repository entry from a legacy format file |
| 2444 | fn remove_from_legacy_file(filepath: &Path, target: &Repository) -> Result<(), String> { |
| 2445 | let content = |
| 2446 | fs::read_to_string(filepath).map_err(|e| format!("Failed to read file: {}", e))?; |
| 2447 | |
| 2448 | let to_remove = LegacyRepositories::from(target).to_string(); |
| 2449 | let remove_lines: HashSet<String> = to_remove.lines().map(|s| s.trim().to_string()).collect(); |
| 2450 | |
| 2451 | let mut new_lines = Vec::new(); |
| 2452 | let mut removed = false; |
| 2453 | |
| 2454 | for line in content.lines() { |
| 2455 | if remove_lines.contains(line.trim()) { |
| 2456 | removed = true; |
| 2457 | } else { |
| 2458 | new_lines.push(line); |
| 2459 | } |
| 2460 | } |
| 2461 | |
| 2462 | if !removed { |
| 2463 | return Err("Repository not found in file".to_string()); |
| 2464 | } |
| 2465 | |
| 2466 | let new_content = new_lines.join("\n") + "\n"; |
| 2467 | fs::write(filepath, new_content).map_err(|e| format!("Failed to write file: {}", e))?; |
| 2468 | |
| 2469 | info!("Repository removed from {}", filepath.display()); |
| 2470 | Ok(()) |
| 2471 | } |
| 2472 | |
| 2473 | fn remove_repository_from_file( |
| 2474 | filepath: &Path, |
| 2475 | parsed: &ParsedRepository, |
| 2476 | args: &Args, |
| 2477 | ) -> Result<(), String> { |
| 2478 | let is_main_file = is_main_distribution_file(filepath); |
| 2479 | |
| 2480 | // Confirm with user if needed |
| 2481 | if !args.assume_yes && !args.dry_run { |
| 2482 | let prompt = if is_main_file { |
| 2483 | format!("Remove repository from {}? [y/N] ", filepath.display()) |
| 2484 | } else { |
| 2485 | format!("Remove repository file {}? [y/N] ", filepath.display()) |
| 2486 | }; |
| 2487 | eprint!("{}", prompt); |
| 2488 | io::stdout().flush().unwrap(); |
| 2489 | let mut input = String::new(); |
| 2490 | io::stdin().read_line(&mut input).unwrap(); |
| 2491 | if !input.trim().eq_ignore_ascii_case("y") { |
| 2492 | return Err("Aborted".to_string()); |
| 2493 | } |
| 2494 | } |
| 2495 | |
| 2496 | // Handle dry run |
| 2497 | if args.dry_run { |
| 2498 | if is_main_file { |
| 2499 | info!("Would remove repository entry from {}", filepath.display()); |
| 2500 | info!("Repository to remove:"); |
| 2501 | let content = match args.format { |
| 2502 | OutputFormat::Legacy => LegacyRepositories::from(&parsed.repository).to_string(), |
| 2503 | OutputFormat::Deb822 => { |
| 2504 | Repositories::new(vec![parsed.repository.clone()]).to_string() |
| 2505 | } |
| 2506 | }; |
| 2507 | for line in content.lines() { |
| 2508 | info!(" {}", line); |
| 2509 | } |
| 2510 | } else { |
| 2511 | info!("Would remove repository file: {}", filepath.display()); |
| 2512 | } |
| 2513 | |
| 2514 | if let Some(ref ppa_info) = parsed.ppa_info { |
| 2515 | handle_ppa_keyring_removal(ppa_info, &args.keyring_dir, true); |
| 2516 | } |
| 2517 | |
| 2518 | if !args.no_update { |
| 2519 | info!("Would run: apt update"); |
| 2520 | } |
| 2521 | return Ok(()); |
| 2522 | } |
| 2523 | |
| 2524 | // Actual removal |
| 2525 | if is_main_file { |
| 2526 | let extension = filepath.extension().and_then(|s| s.to_str()).unwrap_or(""); |
| 2527 | match extension { |
| 2528 | "sources" => remove_from_deb822_file(filepath, &parsed.repository)?, |
| 2529 | _ => remove_from_legacy_file(filepath, &parsed.repository)?, |
| 2530 | } |
| 2531 | } else { |
| 2532 | fs::remove_file(filepath).map_err(|e| format!("Failed to remove file: {}", e))?; |
| 2533 | info!("Repository file removed: {}", filepath.display()); |
| 2534 | } |
| 2535 | |
| 2536 | if let Some(ref ppa_info) = parsed.ppa_info { |
| 2537 | handle_ppa_keyring_removal(ppa_info, &args.keyring_dir, false); |
| 2538 | } |
| 2539 | |
| 2540 | if !args.no_update { |
| 2541 | run_apt_update(); |
| 2542 | } |
| 2543 | |
| 2544 | Ok(()) |
| 2545 | } |
| 2546 | |
| 2547 | fn repositories_match(repo1: &Repository, repo2: &Repository) -> bool { |
| 2548 | // Compare repositories for equality |
| 2549 | repo1.types == repo2.types |
| 2550 | && repo1.uris == repo2.uris |
| 2551 | && repo1.suites == repo2.suites |
| 2552 | && repo1.components == repo2.components |
| 2553 | && repo1.architectures == repo2.architectures |
| 2554 | } |
| 2555 | |
| 2556 | fn main() { |
| 2557 | env_logger::init(); |
| 2558 | let args = Args::parse(); |
| 2559 | |
| 2560 | // Check if login is requested without launchpad feature |
| 2561 | #[cfg(not(feature = "launchpad"))] |
| 2562 | if args.login { |
| 2563 | error!("Private PPA support requires building with the 'launchpad' feature"); |
| 2564 | error!("Rebuild with: cargo build --features launchpad"); |
| 2565 | process::exit(1); |
| 2566 | } |
| 2567 | |
| 2568 | // Detect distribution and codename once at startup |
| 2569 | let distribution = Distribution::current().unwrap_or(Distribution::Debian); |
| 2570 | let (codename, _arch) = |
| 2571 | get_system_info().unwrap_or_else(|| ("stable".to_string(), String::new())); |
| 2572 | |
| 2573 | let result = if args.list { |
| 2574 | list_repositories(&args) |
| 2575 | } else if args.refresh_keys { |
| 2576 | refresh_ppa_keys(&args) |
| 2577 | } else if let Some(component) = &args.component { |
| 2578 | // Handle --component flag |
| 2579 | add_component_to_existing_repos(component, &args.directory, args.dry_run, &distribution) |
| 2580 | } else if args.enable_source > 0 && args.repository.is_none() { |
| 2581 | // Handle global source enablement when no repository is specified |
| 2582 | enable_sources_globally(&args) |
| 2583 | } else if args.remove { |
| 2584 | remove_repository(&args, &distribution, &codename) |
| 2585 | } else { |
| 2586 | add_repository(&args, &distribution, &codename) |
| 2587 | }; |
| 2588 | |
| 2589 | if let Err(e) = result { |
| 2590 | error!("{}", e); |
| 2591 | process::exit(1); |
| 2592 | } |
| 2593 | } |
| 2594 | |
| 2595 | #[cfg(test)] |
| 2596 | mod tests { |
| 2597 | use super::*; |
| 2598 | use sequoia_openpgp::cert::CertBuilder; |
| 2599 | use std::time::Duration; |
| 2600 | |
| 2601 | #[test] |
| 2602 | fn test_create_inline_signature() { |
| 2603 | // Use a minimal valid PGP key structure |
| 2604 | let key_data = "-----BEGIN PGP PUBLIC KEY BLOCK-----\n\nmQENBFXbjPUBCADRje\n=ABCD\n-----END PGP PUBLIC KEY BLOCK-----"; |
| 2605 | |
| 2606 | // The create_inline_signature now validates the key, so we expect it to fail |
| 2607 | // with this truncated test key |
| 2608 | let result = create_inline_signature(key_data); |
| 2609 | |
| 2610 | // For now, just check that the function exists and can be called |
| 2611 | // In real usage, it would have a valid key |
| 2612 | assert!(result.is_err() || result.is_ok()); |
| 2613 | } |
| 2614 | |
| 2615 | #[test] |
| 2616 | fn test_format_network_error() { |
| 2617 | // We can't easily create actual reqwest errors, but we can test the function exists |
| 2618 | // and returns reasonable strings for the error types we can simulate |
| 2619 | |
| 2620 | // In a real test environment, you would mock the reqwest errors |
| 2621 | // For now, we just verify the function compiles |
| 2622 | // Note: We can't call the function without a real reqwest::Error instance |
| 2623 | } |
| 2624 | |
| 2625 | #[test] |
| 2626 | fn test_is_main_distribution_file() { |
| 2627 | assert!(is_main_distribution_file(Path::new( |
| 2628 | "/etc/apt/sources.list" |
| 2629 | ))); |
| 2630 | assert!(is_main_distribution_file(Path::new( |
| 2631 | "/etc/apt/sources.list.d/ubuntu.sources" |
| 2632 | ))); |
| 2633 | assert!(is_main_distribution_file(Path::new( |
| 2634 | "/etc/apt/sources.list.d/debian.sources" |
| 2635 | ))); |
| 2636 | assert!(is_main_distribution_file(Path::new("/path/to/ubuntu.list"))); |
| 2637 | assert!(is_main_distribution_file(Path::new("/path/to/debian.list"))); |
| 2638 | |
| 2639 | assert!(!is_main_distribution_file(Path::new( |
| 2640 | "/etc/apt/sources.list.d/ppa.sources" |
| 2641 | ))); |
| 2642 | assert!(!is_main_distribution_file(Path::new( |
| 2643 | "/etc/apt/sources.list.d/custom.list" |
| 2644 | ))); |
| 2645 | } |
| 2646 | |
| 2647 | #[test] |
| 2648 | fn test_repositories_match() { |
| 2649 | let repo1 = Repository { |
| 2650 | types: HashSet::from([RepositoryType::Binary]), |
| 2651 | uris: vec![Url::parse("http://example.com/repo").unwrap()], |
| 2652 | suites: vec!["focal".to_string()], |
| 2653 | components: Some(vec!["main".to_string()]), |
| 2654 | architectures: Some(vec!["amd64".to_string()]), |
| 2655 | ..Default::default() |
| 2656 | }; |
| 2657 | |
| 2658 | let repo2 = repo1.clone(); |
| 2659 | assert!(repositories_match(&repo1, &repo2)); |
| 2660 | |
| 2661 | // Different URIs |
| 2662 | let mut repo3 = repo1.clone(); |
| 2663 | repo3.uris = vec![Url::parse("http://different.com/repo").unwrap()]; |
| 2664 | assert!(!repositories_match(&repo1, &repo3)); |
| 2665 | |
| 2666 | // Different components |
| 2667 | let mut repo4 = repo1.clone(); |
| 2668 | repo4.components = Some(vec!["universe".to_string()]); |
| 2669 | assert!(!repositories_match(&repo1, &repo4)); |
| 2670 | } |
| 2671 | |
| 2672 | #[test] |
| 2673 | fn test_get_distribution_info() { |
| 2674 | // This test will depend on the system it's run on |
| 2675 | // We just verify it returns a valid Distribution enum when available |
| 2676 | let dist = Distribution::current(); |
| 2677 | |
| 2678 | // On systems with /etc/os-release (Linux), we should get Some |
| 2679 | // On systems without it (macOS), we get None - both are acceptable |
| 2680 | if std::path::Path::new("/etc/os-release").exists() { |
| 2681 | assert!(dist.is_some()); |
| 2682 | match dist.unwrap() { |
| 2683 | Distribution::Ubuntu | Distribution::Debian | Distribution::Other(_) => { |
| 2684 | // All valid variants |
| 2685 | } |
| 2686 | } |
| 2687 | } else { |
| 2688 | // On macOS or other systems without /etc/os-release, None is expected |
| 2689 | assert!(dist.is_none()); |
| 2690 | } |
| 2691 | } |
| 2692 | |
| 2693 | #[test] |
| 2694 | fn test_check_key_expiration() { |
| 2695 | // Create a cert that's valid for 60 days |
| 2696 | let (cert, _) = CertBuilder::new() |
| 2697 | .set_validity_period(Duration::from_secs(60 * 24 * 60 * 60)) |
| 2698 | .generate() |
| 2699 | .unwrap(); |
| 2700 | |
| 2701 | let warning = apt_sources::key_management::check_key_expiration(&cert); |
| 2702 | assert!(warning.is_none()); |
| 2703 | |
| 2704 | // Note: Testing expired certs would require creating a cert with |
| 2705 | // a past expiration date, which CertBuilder doesn't easily support |
| 2706 | // The function only checks if a cert is currently expired, not if it's expiring soon |
| 2707 | } |
| 2708 | |
| 2709 | #[test] |
| 2710 | fn test_generate_filename() { |
| 2711 | let dist = Distribution::Ubuntu; |
| 2712 | |
| 2713 | // Test PPA URL |
| 2714 | let filename = generate_filename( |
| 2715 | "https://ppa.launchpad.net/user/ppa/ubuntu", |
| 2716 | OutputFormat::Deb822, |
| 2717 | &dist, |
| 2718 | ); |
| 2719 | assert!(filename.ends_with(".sources")); |
| 2720 | |
| 2721 | // Test main Ubuntu repository |
| 2722 | let filename = generate_filename( |
| 2723 | "http://archive.ubuntu.com/ubuntu", |
| 2724 | OutputFormat::Deb822, |
| 2725 | &dist, |
| 2726 | ); |
| 2727 | assert_eq!(filename, "ubuntu.sources"); |
| 2728 | |
| 2729 | // Test main Ubuntu repository with legacy format |
| 2730 | let filename = generate_filename( |
| 2731 | "http://archive.ubuntu.com/ubuntu", |
| 2732 | OutputFormat::Legacy, |
| 2733 | &dist, |
| 2734 | ); |
| 2735 | assert_eq!(filename, "ubuntu.list"); |
| 2736 | |
| 2737 | // Test third-party repository |
| 2738 | let filename = generate_filename("https://example.com/repo", OutputFormat::Deb822, &dist); |
| 2739 | assert!(filename.contains("example.com")); |
| 2740 | assert!(filename.ends_with(".sources")); |
| 2741 | } |
| 2742 | |
| 2743 | #[test] |
| 2744 | fn test_default_suite_components() { |
| 2745 | let (suite, components) = default_suite_components("focal"); |
| 2746 | assert_eq!(suite, "focal"); |
| 2747 | assert_eq!(components, vec!["main".to_string()]); |
| 2748 | } |
| 2749 | |
| 2750 | fn create_test_args() -> Args { |
| 2751 | Args { |
| 2752 | repository: None, |
| 2753 | no_update: false, |
| 2754 | enable_source: 0, |
| 2755 | assume_yes: false, |
| 2756 | remove: false, |
| 2757 | directory: DEFAULT_SOURCES_PATH.to_string(), |
| 2758 | keyring_dir: DEFAULT_KEYRING_PATH.to_string(), |
| 2759 | pocket: None, |
| 2760 | keyserver: None, |
| 2761 | component: None, |
| 2762 | list: false, |
| 2763 | login: false, |
| 2764 | dry_run: false, |
| 2765 | format: OutputFormat::Legacy, |
| 2766 | refresh_keys: false, |
| 2767 | inline_key: false, |
| 2768 | } |
| 2769 | } |
| 2770 | |
| 2771 | #[test] |
| 2772 | fn test_parse_repository_spec() { |
| 2773 | let args = create_test_args(); |
| 2774 | let distribution = Distribution::Ubuntu; |
| 2775 | let codename = "noble"; |
| 2776 | |
| 2777 | // Test PPA format |
| 2778 | let spec = |
| 2779 | parse_repository_spec("ppa:user/repo", 0, &args, &distribution, codename).unwrap(); |
| 2780 | match spec { |
| 2781 | RepositorySpec::Repository(parsed) => { |
| 2782 | assert!(parsed.ppa_info.is_some()); |
| 2783 | let ppa = parsed.ppa_info.unwrap(); |
| 2784 | assert_eq!(ppa.user, "user"); |
| 2785 | assert_eq!(ppa.name, "repo"); |
| 2786 | } |
| 2787 | _ => panic!("Expected Repository spec with PPA info"), |
| 2788 | } |
| 2789 | |
| 2790 | // NOTE: Component and pocket tests require real system info from get_system_info() |
| 2791 | // These tests are skipped as they depend on the runtime environment |
| 2792 | |
| 2793 | let distribution = Distribution::Debian; |
| 2794 | let codename = "stable"; |
| 2795 | |
| 2796 | // Test full deb line |
| 2797 | let spec = parse_repository_spec( |
| 2798 | "deb http://example.com focal main", |
| 2799 | 0, |
| 2800 | &args, |
| 2801 | &distribution, |
| 2802 | codename, |
| 2803 | ) |
| 2804 | .unwrap(); |
| 2805 | match spec { |
| 2806 | RepositorySpec::Repository(parsed) => { |
| 2807 | assert!(parsed.repository.uris[0] |
| 2808 | .as_str() |
| 2809 | .contains("http://example.com")); |
| 2810 | assert_eq!(parsed.repository.suites, vec!["focal"]); |
| 2811 | assert_eq!(parsed.repository.components, Some(vec!["main".to_string()])); |
| 2812 | } |
| 2813 | _ => panic!("Expected Repository spec"), |
| 2814 | } |
| 2815 | } |
| 2816 | |
| 2817 | #[test] |
| 2818 | fn test_parse_repository_line() { |
| 2819 | // Test basic deb line |
| 2820 | let (types, uri, suite, components, signed_by) = |
| 2821 | parse_repository_line("deb http://example.com focal main universe").unwrap(); |
| 2822 | assert!(types.contains(&RepositoryType::Binary)); |
| 2823 | assert_eq!(uri.as_str(), "http://example.com/"); |
| 2824 | assert_eq!(suite, "focal"); |
| 2825 | assert_eq!(components, vec!["main", "universe"]); |
| 2826 | assert!(signed_by.is_none()); |
| 2827 | |
| 2828 | // Test deb-src line |
| 2829 | let (types, uri, suite, components, signed_by) = |
| 2830 | parse_repository_line("deb-src http://example.com focal main").unwrap(); |
| 2831 | assert!(types.contains(&RepositoryType::Source)); |
| 2832 | assert_eq!(uri.as_str(), "http://example.com/"); |
| 2833 | assert_eq!(suite, "focal"); |
| 2834 | assert_eq!(components, vec!["main"]); |
| 2835 | assert!(signed_by.is_none()); |
| 2836 | |
| 2837 | // Test with trailing slash |
| 2838 | let (types, uri, suite, components, signed_by) = |
| 2839 | parse_repository_line("deb http://example.com/ focal main").unwrap(); |
| 2840 | assert!(types.contains(&RepositoryType::Binary)); |
| 2841 | assert_eq!(uri.as_str(), "http://example.com/"); |
| 2842 | assert_eq!(suite, "focal"); |
| 2843 | assert_eq!(components, vec!["main"]); |
| 2844 | assert!(signed_by.is_none()); |
| 2845 | |
| 2846 | // Test invalid line |
| 2847 | assert!(parse_repository_line("invalid line").is_err()); |
| 2848 | assert!(parse_repository_line("deb").is_err()); |
| 2849 | assert!(parse_repository_line("deb http://example.com").is_err()); |
| 2850 | } |
| 2851 | |
| 2852 | #[test] |
| 2853 | fn test_find_matching_binary_repo() { |
| 2854 | // Create a binary repository |
| 2855 | let binary_repo = Repository { |
| 2856 | types: HashSet::from([RepositoryType::Binary]), |
| 2857 | uris: vec![Url::parse("http://example.com/repo").unwrap()], |
| 2858 | suites: vec!["focal".to_string()], |
| 2859 | components: Some(vec!["main".to_string()]), |
| 2860 | ..Default::default() |
| 2861 | }; |
| 2862 | |
| 2863 | // Create a source repository |
| 2864 | let source_repo = Repository { |
| 2865 | types: HashSet::from([RepositoryType::Source]), |
| 2866 | uris: vec![Url::parse("http://example.com/repo").unwrap()], |
| 2867 | suites: vec!["focal".to_string()], |
| 2868 | components: Some(vec!["main".to_string()]), |
| 2869 | ..Default::default() |
| 2870 | }; |
| 2871 | |
| 2872 | let repos = Repositories::new(vec![binary_repo.clone(), source_repo.clone()]); |
| 2873 | |
| 2874 | // Test finding matching binary repo |
| 2875 | let match_found = find_matching_binary_repo(&repos, &source_repo); |
| 2876 | assert!(match_found.is_some()); |
| 2877 | assert_eq!( |
| 2878 | match_found.unwrap().types, |
| 2879 | HashSet::from([RepositoryType::Binary]) |
| 2880 | ); |
| 2881 | |
| 2882 | // Test with non-matching source repo |
| 2883 | let non_matching = Repository { |
| 2884 | types: HashSet::from([RepositoryType::Source]), |
| 2885 | uris: vec![Url::parse("http://different.com/repo").unwrap()], |
| 2886 | suites: vec!["focal".to_string()], |
| 2887 | components: Some(vec!["main".to_string()]), |
| 2888 | ..Default::default() |
| 2889 | }; |
| 2890 | let match_found = find_matching_binary_repo(&repos, &non_matching); |
| 2891 | assert!(match_found.is_none()); |
| 2892 | } |
| 2893 | |
| 2894 | #[test] |
| 2895 | fn test_is_duplicate_repository() { |
| 2896 | let repo1 = Repository { |
| 2897 | types: HashSet::from([RepositoryType::Binary]), |
| 2898 | uris: vec![Url::parse("http://example.com/repo").unwrap()], |
| 2899 | suites: vec!["focal".to_string()], |
| 2900 | components: Some(vec!["main".to_string()]), |
| 2901 | ..Default::default() |
| 2902 | }; |
| 2903 | |
| 2904 | // Test exact duplicate |
| 2905 | let uris: HashSet<String> = HashSet::from(["http://example.com/repo".to_string()]); |
| 2906 | let suites: HashSet<String> = HashSet::from(["focal".to_string()]); |
| 2907 | let components: HashSet<String> = HashSet::from(["main".to_string()]); |
| 2908 | let types = HashSet::from([RepositoryType::Binary]); |
| 2909 | |
| 2910 | assert!(is_duplicate_repository( |
| 2911 | &repo1, |
| 2912 | &uris, |
| 2913 | &suites, |
| 2914 | &components, |
| 2915 | &types |
| 2916 | )); |
| 2917 | |
| 2918 | // Different types |
| 2919 | let different_types = HashSet::from([RepositoryType::Source]); |
| 2920 | assert!(!is_duplicate_repository( |
| 2921 | &repo1, |
| 2922 | &uris, |
| 2923 | &suites, |
| 2924 | &components, |
| 2925 | &different_types |
| 2926 | )); |
| 2927 | |
| 2928 | // Different URIs |
| 2929 | let different_uris = HashSet::from(["http://different.com/repo".to_string()]); |
| 2930 | assert!(!is_duplicate_repository( |
| 2931 | &repo1, |
| 2932 | &different_uris, |
| 2933 | &suites, |
| 2934 | &components, |
| 2935 | &types |
| 2936 | )); |
| 2937 | |
| 2938 | // Different suites |
| 2939 | let different_suites = HashSet::from(["jammy".to_string()]); |
| 2940 | assert!(!is_duplicate_repository( |
| 2941 | &repo1, |
| 2942 | &uris, |
| 2943 | &different_suites, |
| 2944 | &components, |
| 2945 | &types |
| 2946 | )); |
| 2947 | } |
| 2948 | |
| 2949 | #[test] |
| 2950 | fn test_determine_repository_filepath() { |
| 2951 | let args = create_test_args(); |
| 2952 | let distribution = Distribution::Debian; |
| 2953 | |
| 2954 | // Test PPA repository |
| 2955 | let ppa_repo = ParsedRepository { |
| 2956 | repository: Repository { |
| 2957 | enabled: Some(true), |
| 2958 | types: HashSet::from([RepositoryType::Binary]), |
| 2959 | uris: vec![Url::parse("http://ppa.launchpad.net/user/ppa/ubuntu").unwrap()], |
| 2960 | suites: vec!["focal".to_string()], |
| 2961 | components: Some(vec!["main".to_string()]), |
| 2962 | ..Default::default() |
| 2963 | }, |
| 2964 | filename: "user-ubuntu-ppa-focal.list".to_string(), |
| 2965 | ppa_info: Some(PpaInfo { |
| 2966 | user: "user".to_string(), |
| 2967 | name: "ppa".to_string(), |
| 2968 | }), |
| 2969 | }; |
| 2970 | let path = determine_repository_filepath(&ppa_repo, &args, &distribution).unwrap(); |
| 2971 | assert!(path.to_str().unwrap().ends_with(".list")); // Legacy format is default in test args |
| 2972 | assert!(path.to_str().unwrap().contains("user")); |
| 2973 | |
| 2974 | // Test non-PPA repository |
| 2975 | let url_repo = ParsedRepository { |
| 2976 | repository: Repository { |
| 2977 | enabled: Some(true), |
| 2978 | types: HashSet::from([RepositoryType::Binary]), |
| 2979 | uris: vec![Url::parse("https://example.com/repo").unwrap()], |
| 2980 | suites: vec!["focal".to_string()], |
| 2981 | components: Some(vec!["main".to_string()]), |
| 2982 | ..Default::default() |
| 2983 | }, |
| 2984 | filename: "example.com.list".to_string(), |
| 2985 | ppa_info: None, |
| 2986 | }; |
| 2987 | let path = determine_repository_filepath(&url_repo, &args, &distribution).unwrap(); |
| 2988 | assert!(path.to_str().unwrap().ends_with(".list")); // Legacy format is default in test args |
| 2989 | assert!(path.to_str().unwrap().contains("example.com")); |
| 2990 | |
| 2991 | // Test with deb822 format |
| 2992 | let mut args_deb822 = create_test_args(); |
| 2993 | args_deb822.format = OutputFormat::Deb822; |
| 2994 | let mut url_repo_deb822 = url_repo.clone(); |
| 2995 | url_repo_deb822.filename = "example.com.sources".to_string(); |
| 2996 | let path = |
| 2997 | determine_repository_filepath(&url_repo_deb822, &args_deb822, &distribution).unwrap(); |
| 2998 | assert!(path.to_str().unwrap().ends_with(".sources")); |
| 2999 | } |
| 3000 | |
| 3001 | #[test] |
| 3002 | fn test_verify_key_fingerprint() { |
| 3003 | // This test needs a real PGP key to work properly |
| 3004 | // For unit testing, we'll verify the function handles invalid input correctly |
| 3005 | let invalid_key = "not a valid key"; |
| 3006 | let result = verify_key_fingerprint(invalid_key, "1234567890ABCDEF"); |
| 3007 | assert!(result.is_err()); |
| 3008 | |
| 3009 | // Test with empty fingerprint |
| 3010 | let result = verify_key_fingerprint(invalid_key, ""); |
| 3011 | assert!(result.is_err()); |
| 3012 | } |
| 3013 | |
| 3014 | #[test] |
| 3015 | fn test_get_distribution_specific_filename() { |
| 3016 | // Test Ubuntu |
| 3017 | let ubuntu_file = |
| 3018 | get_distribution_specific_filename("ubuntu", "sources", &Distribution::Ubuntu); |
| 3019 | assert_eq!(ubuntu_file, "ubuntu.sources"); |
| 3020 | |
| 3021 | let ubuntu_legacy = |
| 3022 | get_distribution_specific_filename("ubuntu", "list", &Distribution::Ubuntu); |
| 3023 | assert_eq!(ubuntu_legacy, "ubuntu.list"); |
| 3024 | |
| 3025 | // Test custom base name for Ubuntu |
| 3026 | let ubuntu_custom = |
| 3027 | get_distribution_specific_filename("custom", "sources", &Distribution::Ubuntu); |
| 3028 | assert_eq!(ubuntu_custom, "ubuntu.sources"); |
| 3029 | |
| 3030 | // Test Debian |
| 3031 | let debian_file = |
| 3032 | get_distribution_specific_filename("debian", "sources", &Distribution::Debian); |
| 3033 | assert_eq!(debian_file, "debian.sources"); |
| 3034 | |
| 3035 | let debian_legacy = |
| 3036 | get_distribution_specific_filename("debian", "list", &Distribution::Debian); |
| 3037 | assert_eq!(debian_legacy, "debian.list"); |
| 3038 | |
| 3039 | // Test custom base name for Debian |
| 3040 | let debian_custom = |
| 3041 | get_distribution_specific_filename("custom", "sources", &Distribution::Debian); |
| 3042 | assert_eq!(debian_custom, "debian.sources"); |
| 3043 | |
| 3044 | // Test Other |
| 3045 | let other_file = get_distribution_specific_filename( |
| 3046 | "myrepo", |
| 3047 | "sources", |
| 3048 | &Distribution::Other("custom".to_string()), |
| 3049 | ); |
| 3050 | assert_eq!(other_file, "myrepo.sources"); |
| 3051 | } |
| 3052 | |
| 3053 | #[test] |
| 3054 | fn test_output_format_from_str() { |
| 3055 | // Test valid formats |
| 3056 | assert_eq!( |
| 3057 | OutputFormat::from_str("deb822").unwrap(), |
| 3058 | OutputFormat::Deb822 |
| 3059 | ); |
| 3060 | assert_eq!( |
| 3061 | OutputFormat::from_str("sources").unwrap(), |
| 3062 | OutputFormat::Deb822 |
| 3063 | ); |
| 3064 | assert_eq!( |
| 3065 | OutputFormat::from_str("legacy").unwrap(), |
| 3066 | OutputFormat::Legacy |
| 3067 | ); |
| 3068 | assert_eq!( |
| 3069 | OutputFormat::from_str("list").unwrap(), |
| 3070 | OutputFormat::Legacy |
| 3071 | ); |
| 3072 | |
| 3073 | // Test case insensitive |
| 3074 | assert_eq!( |
| 3075 | OutputFormat::from_str("DEB822").unwrap(), |
| 3076 | OutputFormat::Deb822 |
| 3077 | ); |
| 3078 | assert_eq!( |
| 3079 | OutputFormat::from_str("LEGACY").unwrap(), |
| 3080 | OutputFormat::Legacy |
| 3081 | ); |
| 3082 | |
| 3083 | // Test invalid formats |
| 3084 | assert!(OutputFormat::from_str("invalid").is_err()); |
| 3085 | assert!(OutputFormat::from_str("").is_err()); |
| 3086 | } |
| 3087 | |
| 3088 | #[test] |
| 3089 | fn test_get_system_info() { |
| 3090 | // This test might fail on non-Linux systems |
| 3091 | if std::path::Path::new("/etc/os-release").exists() { |
| 3092 | if let Some((codename, arch)) = get_system_info() { |
| 3093 | assert!(!codename.is_empty()); |
| 3094 | // arch is now empty - APT will use system default |
| 3095 | assert!(arch.is_empty()); |
| 3096 | } |
| 3097 | // It's okay if this returns None on systems without VERSION_CODENAME |
| 3098 | } |
| 3099 | } |
| 3100 | |
| 3101 | #[test] |
| 3102 | fn test_has_matching_source_line() { |
| 3103 | let lines = vec![ |
| 3104 | "deb http://example.com focal main", |
| 3105 | "deb-src http://example.com focal main", |
| 3106 | "deb http://other.com focal universe", |
| 3107 | ]; |
| 3108 | |
| 3109 | // Test exact match |
| 3110 | assert!(has_matching_source_line( |
| 3111 | &lines, |
| 3112 | "deb-src http://example.com focal main" |
| 3113 | )); |
| 3114 | |
| 3115 | // Test no match |
| 3116 | assert!(!has_matching_source_line( |
| 3117 | &lines, |
| 3118 | "deb-src http://other.com focal main" |
| 3119 | )); |
| 3120 | assert!(!has_matching_source_line( |
| 3121 | &lines, |
| 3122 | "deb-src http://example.com focal universe" |
| 3123 | )); |
| 3124 | } |
| 3125 | |
| 3126 | #[test] |
| 3127 | fn test_has_matching_deb_line() { |
| 3128 | let lines = vec![ |
| 3129 | "deb http://example.com focal main", |
| 3130 | "deb-src http://example.com focal main", |
| 3131 | "deb http://other.com focal universe", |
| 3132 | ]; |
| 3133 | |
| 3134 | // Test conversion from deb-src to deb |
| 3135 | assert!(has_matching_deb_line( |
| 3136 | &lines, |
| 3137 | "deb-src http://example.com focal main" |
| 3138 | )); |
| 3139 | |
| 3140 | // Test no match |
| 3141 | assert!(!has_matching_deb_line( |
| 3142 | &lines, |
| 3143 | "deb-src http://other.com focal main" |
| 3144 | )); |
| 3145 | assert!(!has_matching_deb_line( |
| 3146 | &lines, |
| 3147 | "deb-src http://example.com focal universe" |
| 3148 | )); |
| 3149 | } |
| 3150 | |
| 3151 | #[test] |
| 3152 | fn test_has_matching_source_repo() { |
| 3153 | // Create binary repo |
| 3154 | let binary_repo = Repository { |
| 3155 | types: HashSet::from([RepositoryType::Binary]), |
| 3156 | uris: vec![Url::parse("http://example.com").unwrap()], |
| 3157 | suites: vec!["focal".to_string()], |
| 3158 | components: Some(vec!["main".to_string()]), |
| 3159 | ..Default::default() |
| 3160 | }; |
| 3161 | |
| 3162 | // Create matching source repo |
| 3163 | let source_repo = Repository { |
| 3164 | types: HashSet::from([RepositoryType::Source]), |
| 3165 | uris: vec![Url::parse("http://example.com").unwrap()], |
| 3166 | suites: vec!["focal".to_string()], |
| 3167 | components: Some(vec!["main".to_string()]), |
| 3168 | ..Default::default() |
| 3169 | }; |
| 3170 | |
| 3171 | // Create repos with both |
| 3172 | let repos = Repositories::new(vec![binary_repo.clone(), source_repo]); |
| 3173 | |
| 3174 | // Test match found |
| 3175 | assert!(has_matching_source_repo(&repos, &binary_repo)); |
| 3176 | |
| 3177 | // Test no match with different components |
| 3178 | let different_repo = Repository { |
| 3179 | types: HashSet::from([RepositoryType::Binary]), |
| 3180 | uris: vec![Url::parse("http://example.com").unwrap()], |
| 3181 | suites: vec!["focal".to_string()], |
| 3182 | components: Some(vec!["universe".to_string()]), |
| 3183 | ..Default::default() |
| 3184 | }; |
| 3185 | assert!(!has_matching_source_repo(&repos, &different_repo)); |
| 3186 | } |
| 3187 | |
| 3188 | #[test] |
| 3189 | fn test_ppa_info() { |
| 3190 | let ppa = PpaInfo { |
| 3191 | user: "test-user".to_string(), |
| 3192 | name: "test-ppa".to_string(), |
| 3193 | }; |
| 3194 | |
| 3195 | // Test Debug trait implementation |
| 3196 | let debug_str = format!("{:?}", ppa); |
| 3197 | assert!(debug_str.contains("test-user")); |
| 3198 | assert!(debug_str.contains("test-ppa")); |
| 3199 | } |
| 3200 | |
| 3201 | #[test] |
| 3202 | fn test_repository_spec_enum() { |
| 3203 | // Test Component variant |
| 3204 | let comp_spec = RepositorySpec::Component("main".to_string()); |
| 3205 | match comp_spec { |
| 3206 | RepositorySpec::Component(c) => assert_eq!(c, "main"), |
| 3207 | _ => panic!("Expected Component variant"), |
| 3208 | } |
| 3209 | |
| 3210 | // Test Pocket variant |
| 3211 | let pocket_spec = RepositorySpec::Pocket("security".to_string()); |
| 3212 | match pocket_spec { |
| 3213 | RepositorySpec::Pocket(p) => assert_eq!(p, "security"), |
| 3214 | _ => panic!("Expected Pocket variant"), |
| 3215 | } |
| 3216 | } |
| 3217 | |
| 3218 | #[test] |
| 3219 | fn test_create_http_client() { |
| 3220 | // Test without proxy env vars |
| 3221 | std::env::remove_var("HTTP_PROXY"); |
| 3222 | std::env::remove_var("http_proxy"); |
| 3223 | std::env::remove_var("HTTPS_PROXY"); |
| 3224 | std::env::remove_var("https_proxy"); |
| 3225 | |
| 3226 | let client_result = create_http_client(); |
| 3227 | assert!(client_result.is_ok()); |
| 3228 | |
| 3229 | // Test with invalid proxy |
| 3230 | std::env::set_var("HTTP_PROXY", "not-a-valid-url"); |
| 3231 | let client_result = create_http_client(); |
| 3232 | assert!(client_result.is_ok()); // Should still succeed, just warn about invalid proxy |
| 3233 | |
| 3234 | // Clean up |
| 3235 | std::env::remove_var("HTTP_PROXY"); |
| 3236 | } |
| 3237 | |
| 3238 | #[test] |
| 3239 | fn test_validate_fingerprint() { |
| 3240 | // Valid fingerprints (40 hex chars) |
| 3241 | let valid = "1234567890ABCDEF1234567890ABCDEF12345678"; |
| 3242 | assert!(valid.len() == 40); |
| 3243 | assert!(valid.chars().all(|c| c.is_ascii_hexdigit())); |
| 3244 | |
| 3245 | // Invalid fingerprints |
| 3246 | let invalid_short = "1234567890ABCDEF"; |
| 3247 | assert!(invalid_short.len() < 40); |
| 3248 | |
| 3249 | let invalid_chars = "1234567890ABCDEF1234567890ABCDEF12345XYZ"; |
| 3250 | assert!(!invalid_chars.chars().all(|c| c.is_ascii_hexdigit())); |
| 3251 | } |
| 3252 | |
| 3253 | #[test] |
| 3254 | fn test_parsed_repository_struct() { |
| 3255 | let repo = Repository::default(); |
| 3256 | let parsed = ParsedRepository { |
| 3257 | repository: repo, |
| 3258 | filename: "test.sources".to_string(), |
| 3259 | ppa_info: Some(PpaInfo { |
| 3260 | user: "test".to_string(), |
| 3261 | name: "ppa".to_string(), |
| 3262 | }), |
| 3263 | }; |
| 3264 | |
| 3265 | // Test Debug trait |
| 3266 | let debug_str = format!("{:?}", parsed); |
| 3267 | assert!(debug_str.contains("test.sources")); |
| 3268 | assert!(debug_str.contains("ppa_info")); |
| 3269 | } |
| 3270 | |
| 3271 | #[test] |
| 3272 | fn test_empty_component_handling() { |
| 3273 | // Test that empty components are handled properly |
| 3274 | let empty_vec: Vec<String> = vec![]; |
| 3275 | assert!(validate_ppa_components(&empty_vec).is_ok()); |
| 3276 | |
| 3277 | // Test with empty string in components |
| 3278 | let vec_with_empty = vec!["".to_string()]; |
| 3279 | assert!(validate_ppa_components(&vec_with_empty).is_err()); |
| 3280 | } |
| 3281 | } |