Fix most clippy warnings (#572)

The only remaining is at `NixInstallerSubcommand`

See https://rust-lang.github.io/rust-clippy/master/index.html#/large_enum_variant
This commit is contained in:
Hofer-Julian 2023-07-17 17:34:46 +02:00 committed by GitHub
parent 79ab8731fa
commit c3fa6e9623
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
39 changed files with 138 additions and 170 deletions

View file

@ -111,7 +111,6 @@ impl AddUserToGroup {
this.groupname this.groupname
); );
// The group will be created by the installer // The group will be created by the installer
()
}, },
_ => { _ => {
// Some other issue // Some other issue
@ -131,7 +130,7 @@ impl AddUserToGroup {
.await .await
.map_err(Self::error)?; .map_err(Self::error)?;
let output_str = String::from_utf8(output.stdout).map_err(Self::error)?; let output_str = String::from_utf8(output.stdout).map_err(Self::error)?;
let user_in_group = output_str.split(" ").any(|v| v == &this.groupname); let user_in_group = output_str.split(' ').any(|v| v == this.groupname);
if user_in_group { if user_in_group {
tracing::debug!( tracing::debug!(

View file

@ -35,9 +35,9 @@ pub enum CreateOrMergeNixConfigError {
UnmergeableConfig(Vec<String>, std::path::PathBuf), UnmergeableConfig(Vec<String>, std::path::PathBuf),
} }
impl Into<ActionErrorKind> for CreateOrMergeNixConfigError { impl From<CreateOrMergeNixConfigError> for ActionErrorKind {
fn into(self) -> ActionErrorKind { fn from(val: CreateOrMergeNixConfigError) -> Self {
ActionErrorKind::Custom(Box::new(self)) ActionErrorKind::Custom(Box::new(val))
} }
} }
@ -164,7 +164,7 @@ impl CreateOrMergeNixConfig {
.map_err(Self::error)?; .map_err(Self::error)?;
let (merged_nix_config, existing_nix_config) = Self::merge_pending_and_existing_nix_config( let (merged_nix_config, existing_nix_config) = Self::merge_pending_and_existing_nix_config(
&pending_nix_config, pending_nix_config,
&existing_nix_config, &existing_nix_config,
&path, &path,
) )
@ -273,7 +273,7 @@ impl Action for CreateOrMergeNixConfig {
let (mut merged_nix_config, mut existing_nix_config) = if path.exists() { let (mut merged_nix_config, mut existing_nix_config) = if path.exists() {
let (merged_nix_config, existing_nix_config) = let (merged_nix_config, existing_nix_config) =
Self::validate_existing_nix_config(&pending_nix_config, &path)?; Self::validate_existing_nix_config(pending_nix_config, path)?;
(merged_nix_config, Some(existing_nix_config)) (merged_nix_config, Some(existing_nix_config))
} else { } else {
(pending_nix_config.clone(), None) (pending_nix_config.clone(), None)
@ -342,7 +342,7 @@ impl Action for CreateOrMergeNixConfig {
// standalone comments to preserve, but no settings with inline comments. // standalone comments to preserve, but no settings with inline comments.
if setting_line.is_empty() { if setting_line.is_empty() {
for line in &line_group { for line in &line_group {
new_config.push_str(&line); new_config.push_str(line);
new_config.push('\n'); new_config.push('\n');
} }
@ -624,20 +624,19 @@ mod test {
.settings_mut() .settings_mut()
.insert("warn-dirty".into(), "false".into()); .insert("warn-dirty".into(), "false".into());
match CreateOrMergeNixConfig::plan(&test_file, nix_config).await { match CreateOrMergeNixConfig::plan(&test_file, nix_config).await {
Err(err) => match err.kind() { Err(err) => {
ActionErrorKind::Custom(e) => { if let ActionErrorKind::Custom(e) = err.kind() {
match e.downcast_ref::<CreateOrMergeNixConfigError>() { match e.downcast_ref::<CreateOrMergeNixConfigError>() {
Some(CreateOrMergeNixConfigError::UnmergeableConfig(_, path)) => { Some(CreateOrMergeNixConfigError::UnmergeableConfig(_, path)) => {
assert_eq!(path, test_file.as_path()) assert_eq!(path, test_file.as_path())
}, },
_ => { _ => {
return Err(eyre!( return Err(eyre!(
"Should have returned CreateOrMergeNixConfigError::UnmergeableConfig" "Should have returned CreateOrMergeNixConfigError::UnmergeableConfig"
)) ))
}, },
} }
}, }
_ => (),
}, },
_ => { _ => {
return Err(eyre!( return Err(eyre!(

View file

@ -211,7 +211,7 @@ impl Action for CreateUser {
"--home-dir", "--home-dir",
"/var/empty", "/var/empty",
"--comment", "--comment",
&comment, comment,
"--gid", "--gid",
&gid.to_string(), &gid.to_string(),
"--groups", "--groups",
@ -238,7 +238,7 @@ impl Action for CreateUser {
"--home", "--home",
"/var/empty", "/var/empty",
"--gecos", "--gecos",
&comment, comment,
"--ingroup", "--ingroup",
groupname, groupname,
"--system", "--system",

View file

@ -44,7 +44,7 @@ impl FetchAndUnpackNix {
} }
if let Some(ssl_cert_file) = &ssl_cert_file { if let Some(ssl_cert_file) = &ssl_cert_file {
parse_ssl_cert(&ssl_cert_file).await.map_err(Self::error)?; parse_ssl_cert(ssl_cert_file).await.map_err(Self::error)?;
} }
Ok(Self { Ok(Self {
@ -105,7 +105,7 @@ impl Action for FetchAndUnpackNix {
) )
} }
if let Some(ssl_cert_file) = &self.ssl_cert_file { if let Some(ssl_cert_file) = &self.ssl_cert_file {
let ssl_cert = parse_ssl_cert(&ssl_cert_file).await.map_err(Self::error)?; let ssl_cert = parse_ssl_cert(ssl_cert_file).await.map_err(Self::error)?;
buildable_client = buildable_client.add_root_certificate(ssl_cert); buildable_client = buildable_client.add_root_certificate(ssl_cert);
} }
let client = buildable_client let client = buildable_client
@ -181,8 +181,8 @@ pub enum FetchUrlError {
UnknownProxyScheme, UnknownProxyScheme,
} }
impl Into<ActionErrorKind> for FetchUrlError { impl From<FetchUrlError> for ActionErrorKind {
fn into(self) -> ActionErrorKind { fn from(val: FetchUrlError) -> Self {
ActionErrorKind::Custom(Box::new(self)) ActionErrorKind::Custom(Box::new(val))
} }
} }

View file

@ -50,7 +50,7 @@ impl Action for MoveUnpackedNix {
fn execute_description(&self) -> Vec<ActionDescription> { fn execute_description(&self) -> Vec<ActionDescription> {
vec![ActionDescription::new( vec![ActionDescription::new(
format!("Move the downloaded Nix into `/nix`"), "Move the downloaded Nix into `/nix`".to_string(),
vec![format!( vec![format!(
"Nix is being downloaded to `{}` and should be in `/nix`", "Nix is being downloaded to `{}` and should be in `/nix`",
self.unpacked_path.display(), self.unpacked_path.display(),
@ -107,9 +107,7 @@ impl Action for MoveUnpackedNix {
tracing::trace!(src = %entry.path().display(), dest = %entry_dest.display(), "Renaming"); tracing::trace!(src = %entry.path().display(), dest = %entry_dest.display(), "Renaming");
tokio::fs::rename(&entry.path(), &entry_dest) tokio::fs::rename(&entry.path(), &entry_dest)
.await .await
.map_err(|e| { .map_err(|e| ActionErrorKind::Rename(entry.path(), entry_dest.to_owned(), e))
ActionErrorKind::Rename(entry.path().clone(), entry_dest.to_owned(), e)
})
.map_err(Self::error)?; .map_err(Self::error)?;
let perms: Permissions = PermissionsExt::from_mode(0o555); let perms: Permissions = PermissionsExt::from_mode(0o555);
@ -134,9 +132,7 @@ impl Action for MoveUnpackedNix {
// eg, know which `nix` version we installed when curing a user with several versions installed // eg, know which `nix` version we installed when curing a user with several versions installed
tokio::fs::symlink(&entry_dest, entry.path()) tokio::fs::symlink(&entry_dest, entry.path())
.await .await
.map_err(|e| { .map_err(|e| ActionErrorKind::Symlink(entry_dest.to_owned(), entry.path(), e))
ActionErrorKind::Symlink(entry_dest.to_owned(), entry.path().clone(), e)
})
.map_err(Self::error)?; .map_err(Self::error)?;
} }
@ -171,8 +167,8 @@ pub enum MoveUnpackedNixError {
), ),
} }
impl Into<ActionErrorKind> for MoveUnpackedNixError { impl From<MoveUnpackedNixError> for ActionErrorKind {
fn into(self) -> ActionErrorKind { fn from(val: MoveUnpackedNixError) -> Self {
ActionErrorKind::Custom(Box::new(self)) ActionErrorKind::Custom(Box::new(val))
} }
} }

View file

@ -19,9 +19,7 @@ impl RemoveDirectory {
let path = path.as_ref().to_path_buf(); let path = path.as_ref().to_path_buf();
Ok(StatefulAction { Ok(StatefulAction {
action: Self { action: Self { path },
path: path.to_path_buf(),
},
state: ActionState::Uncompleted, state: ActionState::Uncompleted,
}) })
} }

View file

@ -54,7 +54,7 @@ impl Action for SetupDefaultProfile {
// Find an `nix` package // Find an `nix` package
let nix_pkg_glob = format!("{}/nix-*/store/*-nix-*.*.*", self.unpacked_path.display()); let nix_pkg_glob = format!("{}/nix-*/store/*-nix-*.*.*", self.unpacked_path.display());
let mut found_nix_pkg = None; let mut found_nix_pkg = None;
for entry in glob(&nix_pkg_glob).map_err(|e| Self::error(e))? { for entry in glob(&nix_pkg_glob).map_err(Self::error)? {
match entry { match entry {
Ok(path) => { Ok(path) => {
// If we are curing, the user may have multiple of these installed // If we are curing, the user may have multiple of these installed
@ -83,7 +83,7 @@ impl Action for SetupDefaultProfile {
self.unpacked_path.display() self.unpacked_path.display()
); );
let mut found_nss_ca_cert_pkg = None; let mut found_nss_ca_cert_pkg = None;
for entry in glob(&nss_ca_cert_pkg_glob).map_err(|e| Self::error(e))? { for entry in glob(&nss_ca_cert_pkg_glob).map_err(Self::error)? {
match entry { match entry {
Ok(path) => { Ok(path) => {
// If we are curing, the user may have multiple of these installed // If we are curing, the user may have multiple of these installed
@ -109,14 +109,14 @@ impl Action for SetupDefaultProfile {
}; };
let found_nix_paths = glob::glob(&format!("{}/nix-*", self.unpacked_path.display())) let found_nix_paths = glob::glob(&format!("{}/nix-*", self.unpacked_path.display()))
.map_err(|e| Self::error(e))? .map_err(Self::error)?
.collect::<Result<Vec<_>, _>>() .collect::<Result<Vec<_>, _>>()
.map_err(|e| Self::error(e))?; .map_err(Self::error)?;
if found_nix_paths.len() != 1 { if found_nix_paths.len() != 1 {
return Err(Self::error(ActionErrorKind::MalformedBinaryTarball)); return Err(Self::error(ActionErrorKind::MalformedBinaryTarball));
} }
let found_nix_path = found_nix_paths.into_iter().next().unwrap(); let found_nix_path = found_nix_paths.into_iter().next().unwrap();
let reginfo_path = PathBuf::from(found_nix_path).join(".reginfo"); let reginfo_path = found_nix_path.join(".reginfo");
let reginfo = tokio::fs::read(&reginfo_path) let reginfo = tokio::fs::read(&reginfo_path)
.await .await
.map_err(|e| ActionErrorKind::Read(reginfo_path.to_path_buf(), e)) .map_err(|e| ActionErrorKind::Read(reginfo_path.to_path_buf(), e))
@ -248,8 +248,8 @@ pub enum SetupDefaultProfileError {
MultipleNixPackages, MultipleNixPackages,
} }
impl Into<ActionErrorKind> for SetupDefaultProfileError { impl From<SetupDefaultProfileError> for ActionErrorKind {
fn into(self) -> ActionErrorKind { fn from(val: SetupDefaultProfileError) -> Self {
ActionErrorKind::Custom(Box::new(self)) ActionErrorKind::Custom(Box::new(val))
} }
} }

View file

@ -402,18 +402,14 @@ impl Action for ConfigureInitService {
// We separate stop and disable (instead of using `--now`) to avoid cases where the service isn't started, but is enabled. // We separate stop and disable (instead of using `--now`) to avoid cases where the service isn't started, but is enabled.
// These have to fail fast. // These have to fail fast.
let socket_is_active = is_active("nix-daemon.socket") let socket_is_active = is_active("nix-daemon.socket").await.map_err(Self::error)?;
.await let socket_is_enabled =
.map_err(|e| Self::error(e))?; is_enabled("nix-daemon.socket").await.map_err(Self::error)?;
let socket_is_enabled = is_enabled("nix-daemon.socket") let service_is_active =
.await is_active("nix-daemon.service").await.map_err(Self::error)?;
.map_err(|e| Self::error(e))?;
let service_is_active = is_active("nix-daemon.service")
.await
.map_err(|e| Self::error(e))?;
let service_is_enabled = is_enabled("nix-daemon.service") let service_is_enabled = is_enabled("nix-daemon.service")
.await .await
.map_err(|e| Self::error(e))?; .map_err(Self::error)?;
if socket_is_active { if socket_is_active {
if let Err(err) = execute_command( if let Err(err) = execute_command(

View file

@ -65,7 +65,7 @@ impl Action for CreateNixTree {
let mut create_directory_descriptions = Vec::new(); let mut create_directory_descriptions = Vec::new();
for create_directory in create_directories { for create_directory in create_directories {
if let Some(val) = create_directory.describe_execute().iter().next() { if let Some(val) = create_directory.describe_execute().first() {
create_directory_descriptions.push(val.description.clone()) create_directory_descriptions.push(val.description.clone())
} }
} }
@ -87,7 +87,7 @@ impl Action for CreateNixTree {
fn revert_description(&self) -> Vec<ActionDescription> { fn revert_description(&self) -> Vec<ActionDescription> {
vec![ActionDescription::new( vec![ActionDescription::new(
format!("Remove the directory tree in `/nix`"), "Remove the directory tree in `/nix`".to_string(),
vec![ vec![
format!( format!(
"Nix and the Nix daemon require a Nix Store, which will be stored at `/nix`" "Nix and the Nix daemon require a Nix Store, which will be stored at `/nix`"

View file

@ -110,14 +110,14 @@ impl Action for CreateUsersAndGroups {
let mut create_users_descriptions = Vec::new(); let mut create_users_descriptions = Vec::new();
for create_user in create_users { for create_user in create_users {
if let Some(val) = create_user.describe_execute().iter().next() { if let Some(val) = create_user.describe_execute().first() {
create_users_descriptions.push(val.description.clone()) create_users_descriptions.push(val.description.clone())
} }
} }
let mut add_user_to_group_descriptions = Vec::new(); let mut add_user_to_group_descriptions = Vec::new();
for add_user_to_group in add_users_to_groups { for add_user_to_group in add_users_to_groups {
if let Some(val) = add_user_to_group.describe_execute().iter().next() { if let Some(val) = add_user_to_group.describe_execute().first() {
add_user_to_group_descriptions.push(val.description.clone()) add_user_to_group_descriptions.push(val.description.clone())
} }
} }
@ -125,7 +125,7 @@ impl Action for CreateUsersAndGroups {
let mut explanation = vec![ let mut explanation = vec![
format!("The Nix daemon requires system users (and a group they share) which it can act as in order to build"), format!("The Nix daemon requires system users (and a group they share) which it can act as in order to build"),
]; ];
if let Some(val) = create_group.describe_execute().iter().next() { if let Some(val) = create_group.describe_execute().first() {
explanation.push(val.description.clone()) explanation.push(val.description.clone())
} }
explanation.append(&mut create_users_descriptions); explanation.append(&mut create_users_descriptions);
@ -222,14 +222,14 @@ impl Action for CreateUsersAndGroups {
} = &self; } = &self;
let mut create_users_descriptions = Vec::new(); let mut create_users_descriptions = Vec::new();
for create_user in create_users { for create_user in create_users {
if let Some(val) = create_user.describe_revert().iter().next() { if let Some(val) = create_user.describe_revert().first() {
create_users_descriptions.push(val.description.clone()) create_users_descriptions.push(val.description.clone())
} }
} }
let mut add_user_to_group_descriptions = Vec::new(); let mut add_user_to_group_descriptions = Vec::new();
for add_user_to_group in add_users_to_groups { for add_user_to_group in add_users_to_groups {
if let Some(val) = add_user_to_group.describe_revert().iter().next() { if let Some(val) = add_user_to_group.describe_revert().first() {
add_user_to_group_descriptions.push(val.description.clone()) add_user_to_group_descriptions.push(val.description.clone())
} }
} }
@ -237,7 +237,7 @@ impl Action for CreateUsersAndGroups {
let mut explanation = vec![ let mut explanation = vec![
format!("The Nix daemon requires system users (and a group they share) which it can act as in order to build"), format!("The Nix daemon requires system users (and a group they share) which it can act as in order to build"),
]; ];
if let Some(val) = create_group.describe_revert().iter().next() { if let Some(val) = create_group.describe_revert().first() {
explanation.push(val.description.clone()) explanation.push(val.description.clone())
} }
explanation.append(&mut create_users_descriptions); explanation.append(&mut create_users_descriptions);
@ -245,12 +245,12 @@ impl Action for CreateUsersAndGroups {
if create_users.is_empty() { if create_users.is_empty() {
vec![ActionDescription::new( vec![ActionDescription::new(
format!("Remove Nix group"), "Remove Nix group".to_string(),
explanation, explanation,
)] )]
} else { } else {
vec![ActionDescription::new( vec![ActionDescription::new(
format!("Remove Nix users and group"), "Remove Nix users and group".to_string(),
explanation, explanation,
)] )]
} }

View file

@ -58,7 +58,7 @@ impl Action for DeleteUsersInGroup {
fn execute_description(&self) -> Vec<ActionDescription> { fn execute_description(&self) -> Vec<ActionDescription> {
let mut delete_users_descriptions = Vec::new(); let mut delete_users_descriptions = Vec::new();
for delete_user in self.delete_users.iter() { for delete_user in self.delete_users.iter() {
if let Some(val) = delete_user.describe_execute().iter().next() { if let Some(val) = delete_user.describe_execute().first() {
delete_users_descriptions.push(val.description.clone()) delete_users_descriptions.push(val.description.clone())
} }
} }
@ -82,7 +82,7 @@ impl Action for DeleteUsersInGroup {
fn revert_description(&self) -> Vec<ActionDescription> { fn revert_description(&self) -> Vec<ActionDescription> {
let mut delete_users_descriptions = Vec::new(); let mut delete_users_descriptions = Vec::new();
for delete_user in self.delete_users.iter() { for delete_user in self.delete_users.iter() {
if let Some(val) = delete_user.describe_revert().iter().next() { if let Some(val) = delete_user.describe_revert().first() {
delete_users_descriptions.push(val.description.clone()) delete_users_descriptions.push(val.description.clone())
} }
} }

View file

@ -47,7 +47,7 @@ impl PlaceNixConfiguration {
} }
}, },
Entry::Vacant(slot) => { Entry::Vacant(slot) => {
let _ = slot.insert(experimental_features.join(" ").to_string()); let _ = slot.insert(experimental_features.join(" "));
}, },
}; };
@ -117,7 +117,7 @@ impl Action for PlaceNixConfiguration {
.to_string(), .to_string(),
]; ];
if let Some(val) = create_directory.describe_execute().iter().next() { if let Some(val) = create_directory.describe_execute().first() {
explanation.push(val.description.clone()) explanation.push(val.description.clone())
} }
for val in create_or_merge_nix_config.describe_execute().iter() { for val in create_or_merge_nix_config.describe_execute().iter() {

View file

@ -42,7 +42,7 @@ impl Action for EnsureSteamosNixDirectory {
ActionTag("ensure_steamos_nix_directory") ActionTag("ensure_steamos_nix_directory")
} }
fn tracing_synopsis(&self) -> String { fn tracing_synopsis(&self) -> String {
format!("Ensure SteamOS's `/nix` directory exists") "Ensure SteamOS's `/nix` directory exists".to_string()
} }
fn tracing_span(&self) -> Span { fn tracing_span(&self) -> Span {

View file

@ -37,7 +37,7 @@ impl Action for ProvisionSelinux {
ActionTag("provision_selinux") ActionTag("provision_selinux")
} }
fn tracing_synopsis(&self) -> String { fn tracing_synopsis(&self) -> String {
format!("Install an SELinux Policy for Nix") "Install an SELinux Policy for Nix".to_string()
} }
fn tracing_span(&self) -> Span { fn tracing_span(&self) -> Span {

View file

@ -6,7 +6,7 @@ use crate::action::{ActionError, ActionErrorKind, ActionTag};
use crate::action::{Action, ActionDescription, StatefulAction}; use crate::action::{Action, ActionDescription, StatefulAction};
const OFFLOAD_PATH: &'static str = "/home/.steamos/offload/nix"; const OFFLOAD_PATH: &str = "/home/.steamos/offload/nix";
/** /**
Clean out the `/home/.steamos/offload/nix` Clean out the `/home/.steamos/offload/nix`
@ -71,7 +71,7 @@ impl Action for RevertCleanSteamosNixOffload {
tracing::trace!(path = %path.display(), "Removing"); tracing::trace!(path = %path.display(), "Removing");
tokio::fs::remove_dir_all(&path) tokio::fs::remove_dir_all(&path)
.await .await
.map_err(|e| Self::error(ActionErrorKind::Remove(path.into(), e)))?; .map_err(|e| Self::error(ActionErrorKind::Remove(path, e)))?;
} }
Ok(()) Ok(())

View file

@ -81,7 +81,7 @@ impl Action for StartSystemdUnit {
.process_group(0) .process_group(0)
.arg("enable") .arg("enable")
.arg("--now") .arg("--now")
.arg(format!("{unit}")) .arg(&unit)
.stdin(std::process::Stdio::null()), .stdin(std::process::Stdio::null()),
) )
.await .await
@ -93,7 +93,7 @@ impl Action for StartSystemdUnit {
Command::new("systemctl") Command::new("systemctl")
.process_group(0) .process_group(0)
.arg("start") .arg("start")
.arg(format!("{unit}")) .arg(&unit)
.stdin(std::process::Stdio::null()), .stdin(std::process::Stdio::null()),
) )
.await .await
@ -120,7 +120,7 @@ impl Action for StartSystemdUnit {
Command::new("systemctl") Command::new("systemctl")
.process_group(0) .process_group(0)
.arg("disable") .arg("disable")
.arg(format!("{}", self.unit)) .arg(&self.unit)
.stdin(std::process::Stdio::null()), .stdin(std::process::Stdio::null()),
) )
.await .await
@ -135,7 +135,7 @@ impl Action for StartSystemdUnit {
Command::new("systemctl") Command::new("systemctl")
.process_group(0) .process_group(0)
.arg("stop") .arg("stop")
.arg(format!("{}", self.unit)) .arg(&self.unit)
.stdin(std::process::Stdio::null()), .stdin(std::process::Stdio::null()),
) )
.await .await

View file

@ -36,7 +36,7 @@ impl Action for SystemctlDaemonReload {
ActionTag("systemctl_daemon_reload") ActionTag("systemctl_daemon_reload")
} }
fn tracing_synopsis(&self) -> String { fn tracing_synopsis(&self) -> String {
format!("Run `systemctl daemon-reload`") "Run `systemctl daemon-reload`".to_string()
} }
fn tracing_span(&self) -> Span { fn tracing_span(&self) -> Span {

View file

@ -47,11 +47,7 @@ impl BootstrapLaunchctlService {
.await .await
.map_err(|e| Self::error(ActionErrorKind::command(&command, e)))?; .map_err(|e| Self::error(ActionErrorKind::command(&command, e)))?;
// We presume that success means it's found // We presume that success means it's found
if command_output.status.success() || command_output.status.code() == Some(37) { command_output.status.success() || command_output.status.code() == Some(37)
true
} else {
false
}
}; };
let is_disabled = service_is_disabled(&domain, &service) let is_disabled = service_is_disabled(&domain, &service)

View file

@ -122,7 +122,7 @@ impl Action for CreateFstabEntry {
existing_entry, existing_entry,
} = self; } = self;
let fstab_path = Path::new(FSTAB_PATH); let fstab_path = Path::new(FSTAB_PATH);
let uuid = match get_uuid_for_label(&apfs_volume_label) let uuid = match get_uuid_for_label(apfs_volume_label)
.await .await
.map_err(Self::error)? .map_err(Self::error)?
{ {
@ -158,7 +158,7 @@ impl Action for CreateFstabEntry {
.collect::<Vec<String>>(); .collect::<Vec<String>>();
let mut updated_line = false; let mut updated_line = false;
let mut saw_prelude = false; let mut saw_prelude = false;
let prelude = fstab_prelude_comment(&apfs_volume_label); let prelude = fstab_prelude_comment(apfs_volume_label);
for line in current_fstab_lines.iter_mut() { for line in current_fstab_lines.iter_mut() {
if line == &prelude { if line == &prelude {
saw_prelude = true; saw_prelude = true;
@ -306,8 +306,8 @@ pub enum CreateFstabEntryError {
CannotDetermineFstabLine, CannotDetermineFstabLine,
} }
impl Into<ActionErrorKind> for CreateFstabEntryError { impl From<CreateFstabEntryError> for ActionErrorKind {
fn into(self) -> ActionErrorKind { fn from(val: CreateFstabEntryError) -> Self {
ActionErrorKind::Custom(Box::new(self)) ActionErrorKind::Custom(Box::new(val))
} }
} }

View file

@ -117,7 +117,7 @@ impl CreateVolumeService {
.await .await
.map_err(|e| Self::error(ActionErrorKind::Read(fstab, e)))?; .map_err(|e| Self::error(ActionErrorKind::Read(fstab, e)))?;
for line in contents.lines() { for line in contents.lines() {
if line.starts_with("#") { if line.starts_with('#') {
continue; continue;
} }
let split = line.split_whitespace(); let split = line.split_whitespace();
@ -204,7 +204,7 @@ impl Action for CreateVolumeService {
} }
} }
let uuid = match get_uuid_for_label(&apfs_volume_label) let uuid = match get_uuid_for_label(apfs_volume_label)
.await .await
.map_err(Self::error)? .map_err(Self::error)?
{ {
@ -216,8 +216,8 @@ impl Action for CreateVolumeService {
}, },
}; };
let generated_plist = generate_mount_plist( let generated_plist = generate_mount_plist(
&mount_service_label, mount_service_label,
&apfs_volume_label, apfs_volume_label,
uuid, uuid,
mount_point, mount_point,
*encrypt, *encrypt,
@ -315,8 +315,8 @@ pub enum CreateVolumeServiceError {
VolumeDoesNotExistButVolumeServiceAndFstabEntryDoes(PathBuf, String), VolumeDoesNotExistButVolumeServiceAndFstabEntryDoes(PathBuf, String),
} }
impl Into<ActionErrorKind> for CreateVolumeServiceError { impl From<CreateVolumeServiceError> for ActionErrorKind {
fn into(self) -> ActionErrorKind { fn from(val: CreateVolumeServiceError) -> Self {
ActionErrorKind::Custom(Box::new(self)) ActionErrorKind::Custom(Box::new(val))
} }
} }

View file

@ -104,8 +104,8 @@ pub enum EnableOwnershipError {
Command(#[source] std::io::Error), Command(#[source] std::io::Error),
} }
impl Into<ActionErrorKind> for EnableOwnershipError { impl From<EnableOwnershipError> for ActionErrorKind {
fn into(self) -> ActionErrorKind { fn from(val: EnableOwnershipError) -> Self {
ActionErrorKind::Custom(Box::new(self)) ActionErrorKind::Custom(Box::new(val))
} }
} }

View file

@ -64,13 +64,11 @@ impl EncryptApfsVolume {
return Err(Self::error(EncryptApfsVolumeError::ExistingPasswordFound( return Err(Self::error(EncryptApfsVolumeError::ExistingPasswordFound(
name, disk, name, disk,
))); )));
} else { } else if planned_create_apfs_volume.state == ActionState::Completed {
if planned_create_apfs_volume.state == ActionState::Completed { // The user has a volume already created, but a password not set. This means we probably can't decrypt the volume.
// The user has a volume already created, but a password not set. This means we probably can't decrypt the volume. return Err(Self::error(
return Err(Self::error( EncryptApfsVolumeError::MissingPasswordForExistingVolume(name, disk),
EncryptApfsVolumeError::MissingPasswordForExistingVolume(name, disk), ));
));
}
} }
// Ensure if the disk already exists, that it's encrypted // Ensure if the disk already exists, that it's encrypted
@ -84,15 +82,12 @@ impl EncryptApfsVolume {
for container in parsed.containers { for container in parsed.containers {
for volume in container.volumes { for volume in container.volumes {
if volume.name.as_ref() == Some(&name) { if volume.name.as_ref() == Some(&name) {
match volume.encryption == false { if volume.encryption {
true => { return Err(Self::error(
return Ok(StatefulAction::completed(Self { disk, name })); EncryptApfsVolumeError::ExistingVolumeNotEncrypted(name, disk),
}, ));
false => { } else {
return Err(Self::error( return Ok(StatefulAction::completed(Self { disk, name }));
EncryptApfsVolumeError::ExistingVolumeNotEncrypted(name, disk),
));
},
} }
} }
} }
@ -265,8 +260,8 @@ pub enum EncryptApfsVolumeError {
ExistingVolumeNotEncrypted(String, PathBuf), ExistingVolumeNotEncrypted(String, PathBuf),
} }
impl Into<ActionErrorKind> for EncryptApfsVolumeError { impl From<EncryptApfsVolumeError> for ActionErrorKind {
fn into(self) -> ActionErrorKind { fn from(val: EncryptApfsVolumeError) -> Self {
ActionErrorKind::Custom(Box::new(self)) ActionErrorKind::Custom(Box::new(val))
} }
} }

View file

@ -43,7 +43,7 @@ impl KickstartLaunchctlService {
if output.status.success() { if output.status.success() {
service_exists = true; service_exists = true;
let output_string = String::from_utf8(output.stdout).map_err(|e| Self::error(e))?; let output_string = String::from_utf8(output.stdout).map_err(Self::error)?;
// We are looking for a line containing "state = " with some trailing content // We are looking for a line containing "state = " with some trailing content
// The output is not a JSON or a plist // The output is not a JSON or a plist
// MacOS's man pages explicitly tell us not to try to parse this output // MacOS's man pages explicitly tell us not to try to parse this output

View file

@ -55,12 +55,12 @@ async fn get_uuid_for_label(apfs_volume_label: &str) -> Result<Option<Uuid>, Act
if let Some(error_message) = parsed.error_message { if let Some(error_message) = parsed.error_message {
let expected_not_found = format!("Could not find disk: {apfs_volume_label}"); let expected_not_found = format!("Could not find disk: {apfs_volume_label}");
if error_message.contains(&expected_not_found) { if error_message.contains(&expected_not_found) {
return Ok(None); Ok(None)
} else { } else {
return Err(ActionErrorKind::DiskUtilInfoError { Err(ActionErrorKind::DiskUtilInfoError {
command: command_str, command: command_str,
message: error_message, message: error_message,
}); })
} }
} else if let Some(uuid) = parsed.volume_uuid { } else if let Some(uuid) = parsed.volume_uuid {
Ok(Some(uuid)) Ok(Some(uuid))
@ -86,7 +86,7 @@ pub(crate) async fn service_is_disabled(
let output = execute_command( let output = execute_command(
Command::new("launchctl") Command::new("launchctl")
.arg("print-disabled") .arg("print-disabled")
.arg(&domain) .arg(domain)
.stdin(std::process::Stdio::null()) .stdin(std::process::Stdio::null())
.stdout(std::process::Stdio::piped()) .stdout(std::process::Stdio::piped())
.stderr(std::process::Stdio::piped()), .stderr(std::process::Stdio::piped()),

View file

@ -78,7 +78,7 @@ impl Action for SetTmutilExclusions {
let mut set_tmutil_exclusion_descriptions = Vec::new(); let mut set_tmutil_exclusion_descriptions = Vec::new();
for set_tmutil_exclusion in set_tmutil_exclusions { for set_tmutil_exclusion in set_tmutil_exclusions {
if let Some(val) = set_tmutil_exclusion.describe_execute().iter().next() { if let Some(val) = set_tmutil_exclusion.describe_execute().first() {
set_tmutil_exclusion_descriptions.push(val.description.clone()) set_tmutil_exclusion_descriptions.push(val.description.clone())
} }
} }
@ -103,7 +103,7 @@ impl Action for SetTmutilExclusions {
fn revert_description(&self) -> Vec<ActionDescription> { fn revert_description(&self) -> Vec<ActionDescription> {
vec![ActionDescription::new( vec![ActionDescription::new(
format!("Remove time machine exclusions"), "Remove time machine exclusions".to_string(),
vec![], vec![],
)] )]
} }

View file

@ -69,7 +69,7 @@ impl Action for UnmountApfsVolume {
.map_err(Self::error)? .map_err(Self::error)?
.stdout; .stdout;
let the_plist: DiskUtilInfoOutput = let the_plist: DiskUtilInfoOutput =
plist::from_reader(Cursor::new(buf)).map_err(|e| Self::error(e))?; plist::from_reader(Cursor::new(buf)).map_err(Self::error)?;
the_plist.mount_point.is_some() the_plist.mount_point.is_some()
}; };
@ -111,7 +111,7 @@ impl Action for UnmountApfsVolume {
.map_err(Self::error)? .map_err(Self::error)?
.stdout; .stdout;
let the_plist: DiskUtilInfoOutput = let the_plist: DiskUtilInfoOutput =
plist::from_reader(Cursor::new(buf)).map_err(|e| Self::error(e))?; plist::from_reader(Cursor::new(buf)).map_err(Self::error)?;
the_plist.mount_point.is_some() the_plist.mount_point.is_some()
}; };

View file

@ -635,7 +635,7 @@ impl crate::diagnostics::ErrorDiagnostic for ActionErrorKind {
}, },
_ => vec![], _ => vec![],
}; };
return format!( format!(
"{}({})", "{}({})",
static_str, static_str,
context context
@ -643,6 +643,6 @@ impl crate::diagnostics::ErrorDiagnostic for ActionErrorKind {
.map(|v| format!("\"{v}\"")) .map(|v| format!("\"{v}\""))
.collect::<Vec<_>>() .collect::<Vec<_>>()
.join(", ") .join(", ")
); )
} }
} }

View file

@ -145,14 +145,14 @@ where
if self.state == ActionState::Completed { if self.state == ActionState::Completed {
return vec![]; return vec![];
} }
return self.action.execute_description(); self.action.execute_description()
} }
/// A description of what this action would do during revert /// A description of what this action would do during revert
pub fn describe_revert(&self) -> Vec<ActionDescription> { pub fn describe_revert(&self) -> Vec<ActionDescription> {
if self.state == ActionState::Uncompleted { if self.state == ActionState::Uncompleted {
return vec![]; return vec![];
} }
return self.action.revert_description(); self.action.revert_description()
} }
/// Perform any execution steps /// Perform any execution steps
/// ///

View file

@ -139,7 +139,7 @@ impl<'a> Instrumentation {
} }
EnvFilter::try_new(&format!( EnvFilter::try_new(&format!(
"{}={}", "{}={}",
env!("CARGO_PKG_NAME").replace("-", "_"), env!("CARGO_PKG_NAME").replace('-', "_"),
self.log_level() self.log_level()
))? ))?
}, },

View file

@ -123,7 +123,7 @@ pub fn ensure_root() -> eyre::Result<()> {
if is_ci::cached() { if is_ci::cached() {
// Normally `sudo` would erase those envs, so we detect and pass that along specifically to avoid having to pass around // Normally `sudo` would erase those envs, so we detect and pass that along specifically to avoid having to pass around
// a bunch of environment variables // a bunch of environment variables
env_list.push(format!("NIX_INSTALLER_CI=1")); env_list.push("NIX_INSTALLER_CI=1".to_string());
} }
if !env_list.is_empty() { if !env_list.is_empty() {

View file

@ -24,7 +24,7 @@ use color_eyre::{
}; };
use owo_colors::OwoColorize; use owo_colors::OwoColorize;
const EXISTING_INCOMPATIBLE_PLAN_GUIDANCE: &'static str = "\ const EXISTING_INCOMPATIBLE_PLAN_GUIDANCE: &str = "\
If you are trying to upgrade Nix, try running `sudo -i nix upgrade-nix` instead.\n\ If you are trying to upgrade Nix, try running `sudo -i nix upgrade-nix` instead.\n\
If you are trying to install Nix over an existing install (from an incompatible `nix-installer` install), try running `/nix/nix-installer uninstall` then try to install again.\n\ If you are trying to install Nix over an existing install (from an incompatible `nix-installer` install), try running `/nix/nix-installer uninstall` then try to install again.\n\
If you are using `nix-installer` in an automated curing process and seeing this message, consider pinning the version you use via https://github.com/DeterminateSystems/nix-installer#accessing-other-versions.\ If you are using `nix-installer` in an automated curing process and seeing this message, consider pinning the version you use via https://github.com/DeterminateSystems/nix-installer#accessing-other-versions.\

View file

@ -174,14 +174,12 @@ impl DiagnosticData {
tracing::debug!("Sending diagnostic to `{endpoint}`"); tracing::debug!("Sending diagnostic to `{endpoint}`");
let mut buildable_client = reqwest::Client::builder(); let mut buildable_client = reqwest::Client::builder();
if let Some(ssl_cert_file) = &self.ssl_cert_file { if let Some(ssl_cert_file) = &self.ssl_cert_file {
let ssl_cert = parse_ssl_cert(&ssl_cert_file).await.ok(); let ssl_cert = parse_ssl_cert(ssl_cert_file).await.ok();
if let Some(ssl_cert) = ssl_cert { if let Some(ssl_cert) = ssl_cert {
buildable_client = buildable_client.add_root_certificate(ssl_cert); buildable_client = buildable_client.add_root_certificate(ssl_cert);
} }
} }
let client = buildable_client let client = buildable_client.build().map_err(DiagnosticError::Reqwest)?;
.build()
.map_err(|e| DiagnosticError::Reqwest(e))?;
let res = client let res = client
.post(endpoint.clone()) .post(endpoint.clone())
@ -247,7 +245,7 @@ pub trait ErrorDiagnostic {
impl ErrorDiagnostic for DiagnosticError { impl ErrorDiagnostic for DiagnosticError {
fn diagnostic(&self) -> String { fn diagnostic(&self) -> String {
let static_str: &'static str = (self).into(); let static_str: &'static str = (self).into();
return static_str.to_string(); static_str.to_string()
} }
} }

View file

@ -128,16 +128,16 @@ impl crate::diagnostics::ErrorDiagnostic for NixInstallerError {
let context = match self { let context = match self {
Self::SelfTest(self_tests) => self_tests Self::SelfTest(self_tests) => self_tests
.iter() .iter()
.map(|self_test| self_test.diagnostic().to_string()) .map(|self_test| self_test.diagnostic())
.collect::<Vec<_>>(), .collect::<Vec<_>>(),
Self::Action(action_error) => vec![action_error.diagnostic().to_string()], Self::Action(action_error) => vec![action_error.diagnostic()],
Self::ActionRevert(action_errors) => action_errors Self::ActionRevert(action_errors) => action_errors
.iter() .iter()
.map(|action_error| action_error.diagnostic().to_string()) .map(|action_error| action_error.diagnostic())
.collect(), .collect(),
_ => vec![], _ => vec![],
}; };
return format!( format!(
"{}({})", "{}({})",
static_str, static_str,
context context
@ -145,6 +145,6 @@ impl crate::diagnostics::ErrorDiagnostic for NixInstallerError {
.map(|v| format!("\"{v}\"")) .map(|v| format!("\"{v}\""))
.collect::<Vec<_>>() .collect::<Vec<_>>()
.join(", ") .join(", ")
); )
} }
} }

View file

@ -128,8 +128,7 @@ impl InstallPlan {
}, },
actions = actions actions = actions
.iter() .iter()
.map(|v| v.describe_execute()) .flat_map(|v| v.describe_execute())
.flatten()
.map(|desc| { .map(|desc| {
let ActionDescription { let ActionDescription {
description, description,
@ -300,8 +299,7 @@ impl InstallPlan {
actions = actions actions = actions
.iter() .iter()
.rev() .rev()
.map(|v| v.describe_revert()) .flat_map(|v| v.describe_revert())
.flatten()
.map(|desc| { .map(|desc| {
let ActionDescription { let ActionDescription {
description, description,
@ -394,7 +392,7 @@ impl InstallPlan {
.await?; .await?;
} }
return Err(error); Err(error)
} }
} }

View file

@ -156,9 +156,9 @@ impl Planner for Linux {
} }
} }
impl Into<BuiltinPlanner> for Linux { impl From<Linux> for BuiltinPlanner {
fn into(self) -> BuiltinPlanner { fn from(val: Linux) -> Self {
BuiltinPlanner::Linux(self) BuiltinPlanner::Linux(val)
} }
} }
@ -196,11 +196,12 @@ pub(crate) async fn detect_selinux() -> Result<bool, PlannerError> {
pub(crate) async fn check_nix_not_already_installed() -> Result<(), PlannerError> { pub(crate) async fn check_nix_not_already_installed() -> Result<(), PlannerError> {
// For now, we don't try to repair the user's Nix install or anything special. // For now, we don't try to repair the user's Nix install or anything special.
if let Ok(_) = Command::new("nix-env") if Command::new("nix-env")
.arg("--version") .arg("--version")
.stdin(std::process::Stdio::null()) .stdin(std::process::Stdio::null())
.status() .status()
.await .await
.is_ok()
{ {
return Err(PlannerError::NixExists); return Err(PlannerError::NixExists);
} }

View file

@ -443,6 +443,6 @@ impl HasExpectedErrors for PlannerError {
impl crate::diagnostics::ErrorDiagnostic for PlannerError { impl crate::diagnostics::ErrorDiagnostic for PlannerError {
fn diagnostic(&self) -> String { fn diagnostic(&self) -> String {
let static_str: &'static str = (self).into(); let static_str: &'static str = (self).into();
return static_str.to_string(); static_str.to_string()
} }
} }

View file

@ -179,8 +179,7 @@ impl Planner for SteamDeck {
.boxed(), .boxed(),
); );
let nix_directory_buf = format!( let nix_directory_buf = "\
"\
[Unit]\n\ [Unit]\n\
Description=Create a `/nix` directory to be used for bind mounting\n\ Description=Create a `/nix` directory to be used for bind mounting\n\
PropagatesStopTo=nix-daemon.service\n\ PropagatesStopTo=nix-daemon.service\n\
@ -202,7 +201,7 @@ impl Planner for SteamDeck {
ExecStop=steamos-readonly enable\n\ ExecStop=steamos-readonly enable\n\
RemainAfterExit=true\n\ RemainAfterExit=true\n\
" "
); .to_string();
let nix_directory_unit = CreateFile::plan( let nix_directory_unit = CreateFile::plan(
"/etc/systemd/system/nix-directory.service", "/etc/systemd/system/nix-directory.service",
None, None,
@ -267,8 +266,7 @@ impl Planner for SteamDeck {
actions.push(start_nix_mount.boxed()); actions.push(start_nix_mount.boxed());
} }
let ensure_symlinked_units_resolve_buf = format!( let ensure_symlinked_units_resolve_buf = "\
"\
[Unit]\n\ [Unit]\n\
Description=Ensure Nix related units which are symlinked resolve\n\ Description=Ensure Nix related units which are symlinked resolve\n\
After=nix.mount\n\ After=nix.mount\n\
@ -284,7 +282,7 @@ impl Planner for SteamDeck {
[Install]\n\ [Install]\n\
WantedBy=sysinit.target\n\ WantedBy=sysinit.target\n\
" "
); .to_string();
let ensure_symlinked_units_resolve_unit = CreateFile::plan( let ensure_symlinked_units_resolve_unit = CreateFile::plan(
"/etc/systemd/system/ensure-symlinked-units-resolve.service", "/etc/systemd/system/ensure-symlinked-units-resolve.service",
None, None,
@ -422,9 +420,9 @@ impl Planner for SteamDeck {
} }
} }
impl Into<BuiltinPlanner> for SteamDeck { impl From<SteamDeck> for BuiltinPlanner {
fn into(self) -> BuiltinPlanner { fn from(val: SteamDeck) -> Self {
BuiltinPlanner::SteamDeck(self) BuiltinPlanner::SteamDeck(val)
} }
} }
@ -445,8 +443,7 @@ pub(crate) async fn detect_requires_bind_mount() -> Result<bool, PlannerError> {
let steamos_nix_mount_unit_path = "/usr/lib/systemd/system/nix.mount"; let steamos_nix_mount_unit_path = "/usr/lib/systemd/system/nix.mount";
let nix_mount_unit = tokio::fs::read_to_string(steamos_nix_mount_unit_path) let nix_mount_unit = tokio::fs::read_to_string(steamos_nix_mount_unit_path)
.await .await
.map(|v| Some(v)) .ok();
.unwrap_or_else(|_| None);
match nix_mount_unit { match nix_mount_unit {
Some(nix_mount_unit) if nix_mount_unit.contains("What=/home/.steamos/offload/nix") => { Some(nix_mount_unit) if nix_mount_unit.contains("What=/home/.steamos/offload/nix") => {

View file

@ -35,7 +35,7 @@ impl crate::diagnostics::ErrorDiagnostic for SelfTestError {
Self::Command { shell, .. } => vec![shell.to_string()], Self::Command { shell, .. } => vec![shell.to_string()],
Self::SystemTime(_) => vec![], Self::SystemTime(_) => vec![],
}; };
return format!( format!(
"{}({})", "{}({})",
static_str, static_str,
context context
@ -43,7 +43,7 @@ impl crate::diagnostics::ErrorDiagnostic for SelfTestError {
.map(|v| format!("\"{v}\"")) .map(|v| format!("\"{v}\""))
.collect::<Vec<_>>() .collect::<Vec<_>>()
.join(", ") .join(", ")
); )
} }
} }

View file

@ -372,7 +372,7 @@ async fn linux_detect_systemd_started() -> bool {
let mut started = false; let mut started = false;
if std::path::Path::new("/run/systemd/system").exists() { if std::path::Path::new("/run/systemd/system").exists() {
started = if tokio::process::Command::new("systemctl") started = tokio::process::Command::new("systemctl")
.arg("status") .arg("status")
.stdin(Stdio::null()) .stdin(Stdio::null())
.stdout(Stdio::null()) .stdout(Stdio::null())
@ -382,11 +382,6 @@ async fn linux_detect_systemd_started() -> bool {
.ok() .ok()
.map(|exit| exit.success()) .map(|exit| exit.success())
.unwrap_or(false) .unwrap_or(false)
{
true
} else {
false
}
} }
// TODO: Other inits // TODO: Other inits
@ -509,6 +504,6 @@ pub enum InstallSettingsError {
impl crate::diagnostics::ErrorDiagnostic for InstallSettingsError { impl crate::diagnostics::ErrorDiagnostic for InstallSettingsError {
fn diagnostic(&self) -> String { fn diagnostic(&self) -> String {
let static_str: &'static str = (self).into(); let static_str: &'static str = (self).into();
return static_str.to_string(); static_str.to_string()
} }
} }