Skip to main content

uv_shell/
configuration.rs

1use std::path::Path;
2
3use tokio::io::AsyncWriteExt;
4use tracing::debug;
5
6use uv_fs::Simplified;
7
8/// The change made while ensuring a command is present in a shell configuration file.
9#[derive(Debug, Clone, Copy, PartialEq, Eq)]
10pub enum ConfigurationUpdate {
11    /// The configuration file was created.
12    Created,
13    /// The command was appended to an existing configuration file.
14    Updated,
15    /// The command was already present in an uncommented line.
16    Unchanged,
17}
18
19/// Append a command to a shell configuration file if no uncommented line contains it.
20pub async fn update_configuration_file(
21    path: &Path,
22    command: &str,
23) -> std::io::Result<ConfigurationUpdate> {
24    let (contents, update) = match fs_err::tokio::read_to_string(path).await {
25        Ok(contents) => {
26            if contents
27                .lines()
28                .map(str::trim)
29                .filter(|line| !line.starts_with('#'))
30                .any(|line| line.contains(command))
31            {
32                debug!(
33                    "Skipping already-updated configuration file: {}",
34                    path.simplified_display()
35                );
36                return Ok(ConfigurationUpdate::Unchanged);
37            }
38            (
39                format!("{contents}\n# uv\n{command}\n"),
40                ConfigurationUpdate::Updated,
41            )
42        }
43        Err(error) if error.kind() == std::io::ErrorKind::NotFound => {
44            if let Some(parent) = path.parent() {
45                fs_err::tokio::create_dir_all(parent).await?;
46            }
47            (format!("# uv\n{command}\n"), ConfigurationUpdate::Created)
48        }
49        Err(error) => return Err(error),
50    };
51
52    let mut configuration_file = fs_err::tokio::OpenOptions::new()
53        .create(true)
54        .truncate(true)
55        .write(true)
56        .open(path)
57        .await?;
58    configuration_file.write_all(contents.as_bytes()).await?;
59    configuration_file.flush().await?;
60    Ok(update)
61}