Repository: astral-sh/uv
File: crates/uv/src/commands/project/run.rs (Rust)

Code before:

    use fs_err::os::unix::fs::OpenOptionsExt;

    let mut file = fs_err::File::open(source)?;
    let mut buffer = [0u8; 2];
    if file.read_exact(&mut buffer).is_err() {
        // File is too small to have a shebang
        trace!(
            "Skipping copy of entrypoint `{}`: file is too small to contain a shebang",
            source.user_display()
        );
        return Ok(());
    }

    // Check if it starts with `#!` to avoid reading binary files and such into memory
    if &buffer != b"#!" {
        trace!(
            "Skipping copy of entrypoint `{}`: does not start with #!",
            source.user_display()
        );
        return Ok(());
    }

    let mut contents = String::new();
    file.seek(std::io::SeekFrom::Start(0))?;
    file.read_to_string(&mut contents)?;

    let Some(contents) = contents
        // Check for a relative path or relocatable shebang
        .strip_prefix(
            r#"#!/bin/sh
'''exec' "$(dirname -- "$(realpath -- "$0")")"/'python' "$0" "$@"
' '''
"#,
        )
        // Or an absolute path shebang
        .or_else(|| contents.strip_prefix(&format!("#!{}\n", previous_executable.display())))
    else {
        // If it's not a Python shebang, we'll skip it
        trace!(
            "Skipping copy of entrypoint `{}`: does not start with expected shebang",
            source.user_display()
        );
        return Ok(());
    };

    let contents = format!("#!{}\n{}", python_executable.display(), contents);
    let mode = fs_err::metadata(source)?.permissions().mode();
    let mut file = fs_err::OpenOptions::new()
        .create_new(true)
        .write(true)

Review comment (suggestion):
We could use a bigger buffer here to scan for our expected shebang. It gets a little more complicated though, because then we need to make assumptions about the length of the file path? I guess we could cast `previous_executable` to a byte length and use a constant for the reloctable header?

In some world, it'd be ideal to stream reading from the source to the other file too, instead of reading it all to memory.

Code after:

    use fs_err::os::unix::fs::OpenOptionsExt;

    let mut file = fs_err::File::open(source)?;
    let mut buffer = [0u8; 2];
    if file.read_exact(&mut buffer).is_err() {
        // File is too small to have a shebang
        trace!(
            "Skipping copy of entrypoint `{}`: file is too small to contain a shebang",
            source.user_display()
        );
        return Ok(());
    }

    // Check if it starts with `#!` to avoid reading binary files and such into memory
    if &buffer != b"#!" {
        trace!(
            "Skipping copy of entrypoint `{}`: does not start with #!",
            source.user_display()
        );
        return Ok(());
    }

    let mut contents = String::new();
    file.seek(std::io::SeekFrom::Start(0))?;
    match file.read_to_string(&mut contents) {
        Ok(_) => {}
        Err(err) if err.kind() == std::io::ErrorKind::InvalidData => {
            // If the file is not valid UTF-8, we skip it in case it was a binary file with `#!` at
            // the start (which seems pretty niche, but being defensive here seems safe)
            trace!(
                "Skipping copy of entrypoint `{}`: is not valid UTF-8",
                source.user_display()
            );
            return Ok(());
        }
        Err(err) => return Err(err.into()),
    }

    let Some(contents) = contents
        // Check for a relative path or relocatable shebang
        .strip_prefix(
            r#"#!/bin/sh
'''exec' "$(dirname -- "$(realpath -- "$0")")"/'python' "$0" "$@"
' '''
"#,
        )
        // Or an absolute path shebang
        .or_else(|| contents.strip_prefix(&format!("#!{}\n", previous_executable.display())))
    else {
        // If it's not a Python shebang, we'll skip it