Merge pull request #285 from tmuehlbacher/fix-pedantic-clippy-lints

Fix pedantic clippy lints
This commit is contained in:
koverstreet 2024-05-31 11:34:06 -04:00 committed by GitHub
commit af05a54922
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
8 changed files with 82 additions and 66 deletions

View File

@ -57,21 +57,29 @@
... ...
}: }:
let let
inherit (builtins) readFile split;
inherit (lib.lists) findFirst;
inherit (lib.strings) hasPrefix removePrefix substring;
cargoToml = builtins.fromTOML (builtins.readFile ./Cargo.toml); cargoToml = builtins.fromTOML (builtins.readFile ./Cargo.toml);
rustfmtToml = builtins.fromTOML (builtins.readFile ./rustfmt.toml); rustfmtToml = builtins.fromTOML (builtins.readFile ./rustfmt.toml);
craneLib = crane.mkLib pkgs; craneLib = crane.mkLib pkgs;
commit = lib.strings.substring 0 7 (builtins.readFile ./.bcachefs_revision); libbcachefsCommit = substring 0 7 (builtins.readFile ./.bcachefs_revision);
makefileVersion = removePrefix "VERSION=" (
findFirst (line: hasPrefix "VERSION=" line) "VERSION=0.0.0" (split "\n" (readFile ./Makefile))
);
version = "${makefileVersion}+git-${libbcachefsCommit}";
commonArgs = { commonArgs = {
version = "git-${commit}"; inherit version;
src = self; src = self;
makeFlags = [ makeFlags = [
"DESTDIR=${placeholder "out"}" "DESTDIR=${placeholder "out"}"
"PREFIX=" "PREFIX="
"VERSION=${commit}" "VERSION=${version}"
]; ];
dontStrip = true; dontStrip = true;
@ -116,7 +124,7 @@
installCheckPhase = '' installCheckPhase = ''
runHook preInstallCheck runHook preInstallCheck
test "$($out/bin/bcachefs version)" = "${commit}" test "$($out/bin/bcachefs version)" = "${version}"
runHook postInstallCheck runHook postInstallCheck
''; '';

View File

@ -28,7 +28,7 @@ fn handle_c_command(mut argv: Vec<String>, symlink_cmd: Option<&str>) -> i32 {
let argv: Vec<_> = argv.into_iter().map(|s| CString::new(s).unwrap()).collect(); let argv: Vec<_> = argv.into_iter().map(|s| CString::new(s).unwrap()).collect();
let mut argv = argv let mut argv = argv
.into_iter() .into_iter()
.map(|s| Box::into_raw(s.into_boxed_c_str()) as *mut c_char) .map(|s| Box::into_raw(s.into_boxed_c_str()).cast::<c_char>())
.collect::<Box<[*mut c_char]>>(); .collect::<Box<[*mut c_char]>>();
let argv = argv.as_mut_ptr(); let argv = argv.as_mut_ptr();
@ -63,7 +63,7 @@ fn handle_c_command(mut argv: Vec<String>, symlink_cmd: Option<&str>) -> i32 {
"fusemount" => c::cmd_fusemount(argc, argv), "fusemount" => c::cmd_fusemount(argc, argv),
_ => { _ => {
println!("Unknown command {}", cmd); println!("Unknown command {cmd}");
c::bcachefs_usage(); c::bcachefs_usage();
1 1
} }

View File

@ -10,7 +10,7 @@ use clap::Parser;
use log::error; use log::error;
use std::io::{stdout, IsTerminal}; use std::io::{stdout, IsTerminal};
fn list_keys(fs: &Fs, opt: Cli) -> anyhow::Result<()> { fn list_keys(fs: &Fs, opt: &Cli) -> anyhow::Result<()> {
let trans = BtreeTrans::new(fs); let trans = BtreeTrans::new(fs);
let mut iter = BtreeIter::new( let mut iter = BtreeIter::new(
&trans, &trans,
@ -38,7 +38,7 @@ fn list_keys(fs: &Fs, opt: Cli) -> anyhow::Result<()> {
Ok(()) Ok(())
} }
fn list_btree_formats(fs: &Fs, opt: Cli) -> anyhow::Result<()> { fn list_btree_formats(fs: &Fs, opt: &Cli) -> anyhow::Result<()> {
let trans = BtreeTrans::new(fs); let trans = BtreeTrans::new(fs);
let mut iter = BtreeNodeIter::new( let mut iter = BtreeNodeIter::new(
&trans, &trans,
@ -61,7 +61,7 @@ fn list_btree_formats(fs: &Fs, opt: Cli) -> anyhow::Result<()> {
Ok(()) Ok(())
} }
fn list_btree_nodes(fs: &Fs, opt: Cli) -> anyhow::Result<()> { fn list_btree_nodes(fs: &Fs, opt: &Cli) -> anyhow::Result<()> {
let trans = BtreeTrans::new(fs); let trans = BtreeTrans::new(fs);
let mut iter = BtreeNodeIter::new( let mut iter = BtreeNodeIter::new(
&trans, &trans,
@ -84,7 +84,7 @@ fn list_btree_nodes(fs: &Fs, opt: Cli) -> anyhow::Result<()> {
Ok(()) Ok(())
} }
fn list_nodes_ondisk(fs: &Fs, opt: Cli) -> anyhow::Result<()> { fn list_nodes_ondisk(fs: &Fs, opt: &Cli) -> anyhow::Result<()> {
let trans = BtreeTrans::new(fs); let trans = BtreeTrans::new(fs);
let mut iter = BtreeNodeIter::new( let mut iter = BtreeNodeIter::new(
&trans, &trans,
@ -157,8 +157,8 @@ pub struct Cli {
devices: Vec<std::path::PathBuf>, devices: Vec<std::path::PathBuf>,
} }
fn cmd_list_inner(opt: Cli) -> anyhow::Result<()> { fn cmd_list_inner(opt: &Cli) -> anyhow::Result<()> {
let mut fs_opts: bcachefs::bch_opts = Default::default(); let mut fs_opts = bcachefs::bch_opts::default();
opt_set!(fs_opts, nochanges, 1); opt_set!(fs_opts, nochanges, 1);
opt_set!(fs_opts, read_only, 1); opt_set!(fs_opts, read_only, 1);
@ -197,7 +197,7 @@ fn cmd_list_inner(opt: Cli) -> anyhow::Result<()> {
pub fn list(argv: Vec<String>) -> i32 { pub fn list(argv: Vec<String>) -> i32 {
let opt = Cli::parse_from(argv); let opt = Cli::parse_from(argv);
colored::control::set_override(opt.colorize); colored::control::set_override(opt.colorize);
if let Err(e) = cmd_list_inner(opt) { if let Err(e) = cmd_list_inner(&opt) {
error!("Fatal error: {}", e); error!("Fatal error: {}", e);
1 1
} else { } else {

View File

@ -27,13 +27,27 @@ enum Subcommands {
Subvolume(subvolume::Cli), Subvolume(subvolume::Cli),
} }
// FIXME: Can be removed after bumping MSRV >= 1.77 in favor of `c""` literals
#[macro_export] #[macro_export]
macro_rules! c_str { macro_rules! c_str {
($lit:expr) => { ($lit:expr) => {
unsafe { ::std::ffi::CStr::from_bytes_with_nul(concat!($lit, "\0").as_bytes())
std::ffi::CStr::from_ptr(concat!($lit, "\0").as_ptr() as *const std::os::raw::c_char) .unwrap()
.to_bytes_with_nul() .as_ptr()
.as_ptr() as *const std::os::raw::c_char
}
}; };
} }
#[cfg(test)]
mod tests {
use std::ffi::CStr;
#[test]
fn check_cstr_macro() {
let literal = c_str!("hello");
assert_eq!(
literal,
CStr::from_bytes_with_nul(b"hello\0").unwrap().as_ptr()
);
}
}

View File

@ -1,9 +1,11 @@
use std::{ use std::{
collections::HashMap, collections::HashMap,
ffi::{c_char, c_void, CString}, env,
ffi::CString,
fs,
io::{stdout, IsTerminal}, io::{stdout, IsTerminal},
path::{Path, PathBuf}, path::{Path, PathBuf},
{env, fs, str}, ptr, str,
}; };
use anyhow::{ensure, Result}; use anyhow::{ensure, Result};
@ -28,12 +30,10 @@ fn mount_inner(
let fstype = CString::new(fstype)?; let fstype = CString::new(fstype)?;
// convert to pointers for ffi // convert to pointers for ffi
let src = src.as_c_str().to_bytes_with_nul().as_ptr() as *const c_char; let src = src.as_ptr();
let target = target.as_c_str().to_bytes_with_nul().as_ptr() as *const c_char; let target = target.as_ptr();
let data = data.as_ref().map_or(std::ptr::null(), |data| { let data = data.map_or(ptr::null(), |data| data.as_ptr().cast());
data.as_c_str().to_bytes_with_nul().as_ptr() as *const c_void let fstype = fstype.as_ptr();
});
let fstype = fstype.as_c_str().to_bytes_with_nul().as_ptr() as *const c_char;
let ret = { let ret = {
info!("mounting filesystem"); info!("mounting filesystem");
@ -49,7 +49,8 @@ fn mount_inner(
/// Parse a comma-separated mount options and split out mountflags and filesystem /// Parse a comma-separated mount options and split out mountflags and filesystem
/// specific options. /// specific options.
fn parse_mount_options(options: impl AsRef<str>) -> (Option<String>, libc::c_ulong) { fn parse_mount_options(options: impl AsRef<str>) -> (Option<String>, libc::c_ulong) {
use either::Either::*; use either::Either::{Left, Right};
debug!("parsing mount options: {}", options.as_ref()); debug!("parsing mount options: {}", options.as_ref());
let (opts, flags) = options let (opts, flags) = options
.as_ref() .as_ref()
@ -66,10 +67,9 @@ fn parse_mount_options(options: impl AsRef<str>) -> (Option<String>, libc::c_ulo
"relatime" => Left(libc::MS_RELATIME), "relatime" => Left(libc::MS_RELATIME),
"remount" => Left(libc::MS_REMOUNT), "remount" => Left(libc::MS_REMOUNT),
"ro" => Left(libc::MS_RDONLY), "ro" => Left(libc::MS_RDONLY),
"rw" => Left(0), "rw" | "" => Left(0),
"strictatime" => Left(libc::MS_STRICTATIME), "strictatime" => Left(libc::MS_STRICTATIME),
"sync" => Left(libc::MS_SYNCHRONOUS), "sync" => Left(libc::MS_SYNCHRONOUS),
"" => Left(0),
o => Right(o), o => Right(o),
}) })
.fold((Vec::new(), 0), |(mut opts, flags), next| match next { .fold((Vec::new(), 0), |(mut opts, flags), next| match next {
@ -127,7 +127,7 @@ fn udev_bcachefs_info() -> anyhow::Result<HashMap<String, Vec<String>>> {
for m in udev for m in udev
.scan_devices()? .scan_devices()?
.filter(|dev| dev.is_initialized()) .filter(udev::Device::is_initialized)
.map(|dev| device_property_map(&dev)) .map(|dev| device_property_map(&dev))
.filter(|m| m.contains_key("ID_FS_UUID") && m.contains_key("DEVNAME")) .filter(|m| m.contains_key("ID_FS_UUID") && m.contains_key("DEVNAME"))
{ {
@ -140,11 +140,8 @@ fn udev_bcachefs_info() -> anyhow::Result<HashMap<String, Vec<String>>> {
Ok(info) Ok(info)
} }
fn get_super_blocks( fn get_super_blocks(uuid: Uuid, devices: &[String]) -> Vec<(PathBuf, bch_sb_handle)> {
uuid: Uuid, devices
devices: &[String],
) -> anyhow::Result<Vec<(PathBuf, bch_sb_handle)>> {
Ok(devices
.iter() .iter()
.filter_map(|dev| { .filter_map(|dev| {
read_super_silent(PathBuf::from(dev)) read_super_silent(PathBuf::from(dev))
@ -152,7 +149,7 @@ fn get_super_blocks(
.map(|sb| (PathBuf::from(dev), sb)) .map(|sb| (PathBuf::from(dev), sb))
}) })
.filter(|(_, sb)| sb.sb().uuid() == uuid) .filter(|(_, sb)| sb.sb().uuid() == uuid)
.collect::<Vec<_>>()) .collect::<Vec<_>>()
} }
fn get_all_block_devnodes() -> anyhow::Result<Vec<String>> { fn get_all_block_devnodes() -> anyhow::Result<Vec<String>> {
@ -189,14 +186,14 @@ fn get_devices_by_uuid(
} }
}; };
get_super_blocks(uuid, &devices) Ok(get_super_blocks(uuid, &devices))
} }
#[allow(clippy::type_complexity)] #[allow(clippy::type_complexity)]
fn get_uuid_for_dev_node( fn get_uuid_for_dev_node(
udev_bcachefs: &HashMap<String, Vec<String>>, udev_bcachefs: &HashMap<String, Vec<String>>,
device: &std::path::PathBuf, device: impl AsRef<Path>,
) -> anyhow::Result<(Option<Uuid>, Option<(PathBuf, bch_sb_handle)>)> { ) -> Result<(Option<Uuid>, Option<(PathBuf, bch_sb_handle)>)> {
let canonical = fs::canonicalize(device)?; let canonical = fs::canonicalize(device)?;
if !udev_bcachefs.is_empty() { if !udev_bcachefs.is_empty() {
@ -264,11 +261,11 @@ pub struct Cli {
fn devs_str_sbs_from_uuid( fn devs_str_sbs_from_uuid(
udev_info: &HashMap<String, Vec<String>>, udev_info: &HashMap<String, Vec<String>>,
uuid: String, uuid: &str,
) -> anyhow::Result<(String, Vec<bch_sb_handle>)> { ) -> anyhow::Result<(String, Vec<bch_sb_handle>)> {
debug!("enumerating devices with UUID {}", uuid); debug!("enumerating devices with UUID {}", uuid);
let devs_sbs = Uuid::parse_str(&uuid).map(|uuid| get_devices_by_uuid(udev_info, uuid))??; let devs_sbs = Uuid::parse_str(uuid).map(|uuid| get_devices_by_uuid(udev_info, uuid))??;
let devs_str = devs_sbs let devs_str = devs_sbs
.iter() .iter()
@ -283,7 +280,7 @@ fn devs_str_sbs_from_uuid(
fn devs_str_sbs_from_device( fn devs_str_sbs_from_device(
udev_info: &HashMap<String, Vec<String>>, udev_info: &HashMap<String, Vec<String>>,
device: &std::path::PathBuf, device: impl AsRef<Path>,
) -> anyhow::Result<(String, Vec<bch_sb_handle>)> { ) -> anyhow::Result<(String, Vec<bch_sb_handle>)> {
let (uuid, sb_info) = get_uuid_for_dev_node(udev_info, device)?; let (uuid, sb_info) = get_uuid_for_dev_node(udev_info, device)?;
@ -300,10 +297,10 @@ fn devs_str_sbs_from_device(
let dev = path.into_os_string().into_string().unwrap(); let dev = path.into_os_string().into_string().unwrap();
Ok((dev, vec![sb])) Ok((dev, vec![sb]))
} else { } else {
devs_str_sbs_from_uuid(udev_info, uuid.to_string()) devs_str_sbs_from_uuid(udev_info, &uuid.to_string())
} }
} }
(Some(uuid), None) => devs_str_sbs_from_uuid(udev_info, uuid.to_string()), (Some(uuid), None) => devs_str_sbs_from_uuid(udev_info, &uuid.to_string()),
_ => Ok((String::new(), Vec::new())), _ => Ok((String::new(), Vec::new())),
} }
} }
@ -312,11 +309,9 @@ fn cmd_mount_inner(opt: Cli) -> Result<()> {
// Grab the udev information once // Grab the udev information once
let udev_info = udev_bcachefs_info()?; let udev_info = udev_bcachefs_info()?;
let (devices, sbs) = if opt.dev.starts_with("UUID=") { let (devices, sbs) = if let Some(uuid) = opt.dev.strip_prefix("UUID=") {
let uuid = opt.dev.replacen("UUID=", "", 1);
devs_str_sbs_from_uuid(&udev_info, uuid)? devs_str_sbs_from_uuid(&udev_info, uuid)?
} else if opt.dev.starts_with("OLD_BLKID_UUID=") { } else if let Some(uuid) = opt.dev.strip_prefix("OLD_BLKID_UUID=") {
let uuid = opt.dev.replacen("OLD_BLKID_UUID=", "", 1);
devs_str_sbs_from_uuid(&udev_info, uuid)? devs_str_sbs_from_uuid(&udev_info, uuid)?
} else { } else {
// If the device string contains ":" we will assume the user knows the entire list. // If the device string contains ":" we will assume the user knows the entire list.
@ -324,16 +319,15 @@ fn cmd_mount_inner(opt: Cli) -> Result<()> {
// only 1 of a number of devices which are part of the FS. This appears to be the case // only 1 of a number of devices which are part of the FS. This appears to be the case
// when we get called during fstab mount processing and the fstab specifies a UUID. // when we get called during fstab mount processing and the fstab specifies a UUID.
if opt.dev.contains(':') { if opt.dev.contains(':') {
let mut block_devices_to_mount = Vec::new(); let sbs = opt
.dev
.split(':')
.map(read_super_silent)
.collect::<Result<Vec<_>>>()?;
for dev in opt.dev.split(':') { (opt.dev, sbs)
let dev = PathBuf::from(dev);
block_devices_to_mount.push(read_super_silent(&dev)?);
}
(opt.dev, block_devices_to_mount)
} else { } else {
devs_str_sbs_from_device(&udev_info, &PathBuf::from(opt.dev))? devs_str_sbs_from_device(&udev_info, Path::new(&opt.dev))?
} }
}; };

View File

@ -37,9 +37,9 @@ enum Subcommands {
} }
pub fn subvolume(argv: Vec<String>) -> i32 { pub fn subvolume(argv: Vec<String>) -> i32 {
let args = Cli::parse_from(argv); let cli = Cli::parse_from(argv);
match args.subcommands { match cli.subcommands {
Subcommands::Create { targets } => { Subcommands::Create { targets } => {
for target in targets { for target in targets {
if let Some(dirname) = target.parent() { if let Some(dirname) = target.parent() {

View File

@ -4,7 +4,7 @@ use std::{
io::{stdin, IsTerminal}, io::{stdin, IsTerminal},
mem, mem,
path::Path, path::Path,
thread, ptr, thread,
time::Duration, time::Duration,
}; };
@ -66,7 +66,7 @@ impl KeyHandle {
let bch_key_magic = BCH_KEY_MAGIC.as_bytes().read_u64::<LittleEndian>().unwrap(); let bch_key_magic = BCH_KEY_MAGIC.as_bytes().read_u64::<LittleEndian>().unwrap();
let crypt = sb.sb().crypt().unwrap(); let crypt = sb.sb().crypt().unwrap();
let crypt_ptr = crypt as *const _ as *mut _; let crypt_ptr = ptr::addr_of!(*crypt).cast_mut();
let mut output: bch_key = let mut output: bch_key =
unsafe { bcachefs::derive_passphrase(crypt_ptr, passphrase.get().as_ptr()) }; unsafe { bcachefs::derive_passphrase(crypt_ptr, passphrase.get().as_ptr()) };
@ -75,9 +75,9 @@ impl KeyHandle {
let ret = unsafe { let ret = unsafe {
bch2_chacha_encrypt_key( bch2_chacha_encrypt_key(
&mut output as *mut _, ptr::addr_of_mut!(output),
sb.sb().nonce(), sb.sb().nonce(),
&mut key as *mut _ as *mut _, ptr::addr_of_mut!(key).cast(),
mem::size_of_val(&key), mem::size_of_val(&key),
) )
}; };
@ -93,7 +93,7 @@ impl KeyHandle {
keyutils::add_key( keyutils::add_key(
key_type, key_type,
key_name, key_name,
&output as *const _ as *const _, ptr::addr_of!(output).cast(),
mem::size_of_val(&output), mem::size_of_val(&output),
keyutils::KEY_SPEC_USER_KEYRING, keyutils::KEY_SPEC_USER_KEYRING,
) )
@ -103,7 +103,7 @@ impl KeyHandle {
info!("Found key in keyring"); info!("Found key in keyring");
Ok(KeyHandle { Ok(KeyHandle {
_uuid: sb.sb().uuid(), _uuid: sb.sb().uuid(),
_id: key_id as c_long, _id: c_long::from(key_id),
}) })
} else { } else {
Err(anyhow!("failed to add key to keyring: {}", errno::errno())) Err(anyhow!("failed to add key to keyring: {}", errno::errno()))

View File

@ -1,4 +1,4 @@
use std::path::Path; use std::{path::Path, ptr};
use bch_bindgen::c::{ use bch_bindgen::c::{
bcache_fs_close, bcache_fs_open, bch_ioctl_subvolume, bchfs_handle, BCH_IOCTL_SUBVOLUME_CREATE, bcache_fs_close, bcache_fs_open, bch_ioctl_subvolume, bchfs_handle, BCH_IOCTL_SUBVOLUME_CREATE,
@ -42,7 +42,7 @@ pub enum BcachefsIoctlPayload {
impl From<&BcachefsIoctlPayload> for *const libc::c_void { impl From<&BcachefsIoctlPayload> for *const libc::c_void {
fn from(value: &BcachefsIoctlPayload) -> Self { fn from(value: &BcachefsIoctlPayload) -> Self {
match value { match value {
BcachefsIoctlPayload::Subvolume(p) => p as *const _ as *const libc::c_void, BcachefsIoctlPayload::Subvolume(p) => ptr::addr_of!(p).cast(),
} }
} }
} }