ronantakizawa/codereview-bench huggingface dataset:
Repository: astral-sh/ruff
File: crates/ruff_linter/src/preview.rs (Rust)

Code before:
    settings: &LinterSettings,
) -> bool {
    settings.preview.is_enabled()
}

// https://github.com/astral-sh/ruff/pull/22830
pub(crate) const fn is_standalone_mock_non_existent_enabled(settings: &LinterSettings) -> bool {
    settings.preview.is_enabled()
}

// https://github.com/astral-sh/ruff/pull/23013
pub(crate) const fn is_up024_precise_highlighting_enabled(settings: &LinterSettings) -> bool {
    settings.preview.is_enabled()
}

// https://github.com/astral-sh/ruff/pull/21078
pub(crate) const fn is_plural_ngettext_check_enabled(settings: &LinterSettings) -> bool {
    settings.preview.is_enabled()
}

// https://github.com/astral-sh/ruff/pull/19023
pub(crate) const fn is_resolve_string_annotation_pyi041_enabled(settings: &LinterSettings) -> bool {
    settings.preview.is_enabled()
}

// https://github.com/astral-sh/ruff/issues/13604
pub(crate) const fn is_baseloader_safe_in_yaml_load_enabled(settings: &LinterSettings) -> bool {
    settings.preview.is_enabled()
}


Review comment (suggestion):
We usually put the PR link here:


```suggestion
// https://github.com/astral-sh/ruff/pull/23510
```

Code after:
    settings: &LinterSettings,
) -> bool {
    settings.preview.is_enabled()
}

// https://github.com/astral-sh/ruff/pull/22830
pub(crate) const fn is_standalone_mock_non_existent_enabled(settings: &LinterSettings) -> bool {
    settings.preview.is_enabled()
}

// https://github.com/astral-sh/ruff/pull/23013
pub(crate) const fn is_up024_precise_highlighting_enabled(settings: &LinterSettings) -> bool {
    settings.preview.is_enabled()
}

// https://github.com/astral-sh/ruff/pull/21078
pub(crate) const fn is_plural_ngettext_check_enabled(settings: &LinterSettings) -> bool {
    settings.preview.is_enabled()
}

// https://github.com/astral-sh/ruff/pull/19023
pub(crate) const fn is_resolve_string_annotation_pyi041_enabled(settings: &LinterSettings) -> bool {
    settings.preview.is_enabled()
}

// https://github.com/astral-sh/ruff/pull/23510
pub(crate) const fn is_baseloader_safe_in_yaml_load_enabled(settings: &LinterSettings) -> bool {
    settings.preview.is_enabled()
}
Repository: astral-sh/ruff
File: crates/ty_ide/src/folding_range.rs (Rust)

Code before:

    #[test]
    fn test_folding_range_decorated_function_multiple() {
        let test = CursorTest::builder()
            .source(
                "main.py",
                r#"
@first
@second
@third
def my_function():
    pass
<CURSOR>
"#,
            )
            .build();

        assert_snapshot!(test.folding_ranges(), @"
        info[folding-range]: Folding Range
         --> main.py:2:1
          |
        2 | / @first
        3 | | @second
        4 | | @third
          | |______^
        5 |   def my_function():
        6 |       pass
          |

        info[folding-range]: Folding Range
         --> main.py:5:1
          |
        3 |   @second
        4 |   @third
        5 | / def my_function():
        6 | |     pass
          | |________^
          |
        ");
    }

    #[test]
    fn test_folding_range_decorated_class_single() {
        let test = CursorTest::builder()
            .source(
                "main.py",
                r#"
@dataclass
class MyClass:
    value: int
    name: str

Review comment (suggestion):
I'm not sure if we should create a folding range for a group of decorators given that an individual decorator, if it spans multiple lines, will have a folding range.

Code after:
        ");
    }

    #[test]
    fn test_folding_range_decorated_function_multiple() {
        let test = CursorTest::builder()
            .source(
                "main.py",
                r#"
@first
@second
@third
def my_function():
    pass
<CURSOR>
"#,
            )
            .build();

        assert_snapshot!(test.folding_ranges(), @"
        info[folding-range]: Folding Range
         --> main.py:5:1
          |
        3 |   @second
        4 |   @third
        5 | / def my_function():
        6 | |     pass
          | |________^
          |
        ");
    }

    #[test]
    fn test_folding_range_decorated_class_single() {
        let test = CursorTest::builder()
            .source(
                "main.py",
                r#"
@dataclass
class MyClass:
    value: int
    name: str
<CURSOR>
"#,
            )
            .build();

        // Single decorator is one line, so no decorator folding range is emitted.
        assert_snapshot!(test.folding_ranges(), @"
        info[folding-range]: Folding Range
         --> main.py:3:1
Repository: astral-sh/ruff
File: crates/ruff_linter/src/rules/airflow/helpers.rs (Rust)

Code before:
        if semantic
            .resolve_qualified_name(expr)
            .is_some_and(|qn| matches!(qn.segments(), ["airflow", "decorators" | "sdk", "task"]))
        {
            return true;
        }

        // Match `@task.<variant>` (e.g., `@task.branch`, `@task.short_circuit`).
        if let Expr::Attribute(ExprAttribute { value, .. }) = expr {
            return semantic.resolve_qualified_name(value).is_some_and(|qn| {
                matches!(qn.segments(), ["airflow", "decorators" | "sdk", "task"])
            });
        }

        false
    })
}

/// Returns `true` if the current statement hierarchy has a function that's decorated with
/// `@airflow.decorators.task` or `@airflow.sdk.task`.
pub(crate) fn in_airflow_task_function(semantic: &SemanticModel) -> bool {
    semantic
        .current_statements()
        .find_map(|stmt| stmt.as_function_def_stmt())
        .is_some_and(|function_def| is_airflow_task(function_def, semantic))
}


Review comment (suggestion):
Prefer to have this above `is_airflow_task` since it depends on it.

Code after:

/// Returns `true` if the given function is decorated with `@airflow.decorators.task`
/// (or `@airflow.sdk.task`), including variant forms like `@task.branch` and
/// `@task.short_circuit`.
pub(crate) fn is_airflow_task(function_def: &StmtFunctionDef, semantic: &SemanticModel) -> bool {
    function_def.decorator_list.iter().any(|decorator| {
        let expr = map_callable(&decorator.expression);

        // Match `@task` and `@task()` directly.
        if semantic
            .resolve_qualified_name(expr)
            .is_some_and(|qn| matches!(qn.segments(), ["airflow", "decorators" | "sdk", "task"]))
        {
            return true;
        }

        // Match `@task.<variant>` (e.g., `@task.branch`, `@task.short_circuit`).
        if let Expr::Attribute(ExprAttribute { value, .. }) = expr {
            return semantic.resolve_qualified_name(value).is_some_and(|qn| {
                matches!(qn.segments(), ["airflow", "decorators" | "sdk", "task"])
            });
        }

        false
    })
}
Repository: astral-sh/uv
File: crates/uv-cache-info/src/glob.rs (Rust)

Code before:
use std::{
    collections::BTreeMap,
    path::{Component, Components, Path, PathBuf},
};

fn is_glob_like(part: Component) -> bool {
    matches!(part, Component::Normal(_))
        && part
            .as_os_str()
            .to_str()
            .is_some_and(|part| ["*", "{", "}", "?"].into_iter().any(|c| part.contains(c)))
}

#[derive(Debug, Default, Clone, PartialEq, Eq)]
struct GlobParts {
    base: PathBuf,
    pattern: PathBuf,
}

/// Split a glob into longest possible base + shortest possible glob pattern.
fn split_glob(pattern: impl AsRef<str>) -> GlobParts {
    let pattern: &Path = pattern.as_ref().as_ref();

    let mut glob = GlobParts::default();
    let mut current = PathBuf::new();
    let mut globbing = false;
    let mut last = None;

    for part in pattern.components() {
        if let Some(last) = last {
            if last != Component::CurDir {
                current.push(last);
                if globbing {
                    glob.pattern.push(last);
                } else {
                    glob.base.push(last);

Review comment (suggestion):
I think this needs to check for `[` and `]` too. I think [that's it](https://docs.rs/globset/latest/src/globset/lib.rs.html#944-961).

Code after:
use std::{
    collections::BTreeMap,
    path::{Component, Components, Path, PathBuf},
};

/// Check if a component of the path looks like it may be a glob pattern.
///
/// Note: this function is being used when splitting a glob pattern into a long possible
/// base and the glob remainder (scanning through components until we hit the first component
/// for which this function returns true). It is acceptable for this function to return
/// false positives (e.g. patterns like 'foo[bar' or 'foo{bar') in which case correctness
/// will not be affected but efficiency might be (because we'll traverse more than we should),
/// however it should not return false negatives.
fn is_glob_like(part: Component) -> bool {
    matches!(part, Component::Normal(_))
        && part.as_os_str().to_str().is_some_and(|part| {
            ["*", "{", "}", "?", "[", "]"]
                .into_iter()
                .any(|c| part.contains(c))
        })
}

#[derive(Debug, Default, Clone, PartialEq, Eq)]
struct GlobParts {
    base: PathBuf,
    pattern: PathBuf,
}

/// Split a glob into longest possible base + shortest possible glob pattern.
fn split_glob(pattern: impl AsRef<str>) -> GlobParts {
    let pattern: &Path = pattern.as_ref().as_ref();

    let mut glob = GlobParts::default();
    let mut globbing = false;
    let mut last = None;
Repository: astral-sh/uv
File: crates/uv-resolver/src/preferences.rs (Rust)

Code before:
        }
    }
}

impl From<Option<IndexUrl>> for PreferenceIndex {
    fn from(index: Option<IndexUrl>) -> Self {
        match index {
            Some(index) => Self::Explicit(index),
            None => Self::Implicit,
        }
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum PreferenceSource {
    /// The preference is from an installed package in the environment.
    Environment,
    /// The preference is from a `uv.ock` file.
    Lock,
    /// The preference is from a `requirements.txt` file.
    RequirementsTxt,
    /// The preference is from the current solve, without a fork.
    Resolve,
    /// The preference is from a fork in the current solve.
    Fork,
}

#[derive(Debug, Clone)]
pub(crate) struct Entry {
    marker: UniversalMarker,
    index: PreferenceIndex,
    pin: Pin,
    source: PreferenceSource,
}

impl Entry {
    /// Return the [`UniversalMarker`] associated with the entry.
    pub(crate) fn marker(&self) -> &UniversalMarker {
        &self.marker
    }

    /// Return the [`IndexUrl`] associated with the entry, if any.
    pub(crate) fn index(&self) -> &PreferenceIndex {
        &self.index
    }

    /// Return the pinned data associated with the entry.
    pub(crate) fn pin(&self) -> &Pin {
        &self.pin
    }


Review comment (suggestion):
A little annoyed by the number of source variants, but propagating them from the original location seemed better than assuming one variant during `Preferences::from_iter` and another during `Preferences::insert` (which was my first implementation)

Code after:
        }
    }
}

impl From<Option<IndexUrl>> for PreferenceIndex {
    fn from(index: Option<IndexUrl>) -> Self {
        match index {
            Some(index) => Self::Explicit(index),
            None => Self::Implicit,
        }
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum PreferenceSource {
    /// The preference is from an installed package in the environment.
    Environment,
    /// The preference is from a `uv.ock` file.
    Lock,
    /// The preference is from a `requirements.txt` file.
    RequirementsTxt,
    /// The preference is from the current solve.
    Resolver,
}

#[derive(Debug, Clone)]
pub(crate) struct Entry {
    marker: UniversalMarker,
    index: PreferenceIndex,
    pin: Pin,
    source: PreferenceSource,
}

impl Entry {
    /// Return the [`UniversalMarker`] associated with the entry.
    pub(crate) fn marker(&self) -> &UniversalMarker {
        &self.marker
    }

    /// Return the [`IndexUrl`] associated with the entry, if any.
    pub(crate) fn index(&self) -> &PreferenceIndex {
        &self.index
    }

    /// Return the pinned data associated with the entry.
    pub(crate) fn pin(&self) -> &Pin {
        &self.pin
    }

    /// Return the source of the entry.
    pub(crate) fn source(&self) -> PreferenceSource {
Repository: astral-sh/uv
File: crates/uv/tests/it/edit.rs (Rust)

Code before:
    Ok(())
}

#[test]
fn add_preserves_first_line_bracket_comment() -> Result<()> {
    let context = TestContext::new("3.12");

    let pyproject_toml = context.temp_dir.child("pyproject.toml");
    pyproject_toml.write_str(indoc! {r#"
        [project]
        name = "project"
        version = "0.1.0"
        requires-python = ">=3.12"
        dependencies = [ # comment
            "sniffio==1.3.1",
        ]
    "#})?;

    uv_snapshot!(context.filters(), context.add().arg("charset-normalizer"), @r###"
    success: true
    exit_code: 0
    ----- stdout -----

    ----- stderr -----
    Resolved 3 packages in [TIME]
    Prepared 2 packages in [TIME]
    Installed 2 packages in [TIME]
     + charset-normalizer==3.3.2
     + sniffio==1.3.1
    "###);

    let pyproject_toml = context.read("pyproject.toml");

    insta::with_settings!({
        filters => context.filters(),
    }, {
        assert_snapshot!(
            pyproject_toml, @r###"
        [project]
        name = "project"
        version = "0.1.0"
        requires-python = ">=3.12"
        dependencies = [ # comment
            "charset-normalizer>=3.3.2",
            "sniffio==1.3.1",
        ]
        "###
        );
    });
    Ok(())
}

Review comment (bug):
Fairly sure this is a bug in `toml_edit`, because the actual parsed `DocumentMut` drops the comments. Opened https://github.com/toml-rs/toml/issues/1007.

Code after:
    exit_code: 0
    ----- stdout -----

    ----- stderr -----
    Resolved 4 packages in [TIME]
    Prepared 3 packages in [TIME]
    Installed 3 packages in [TIME]
     + anyio==3.7.0
     + idna==3.6
     + sniffio==1.3.1
    ");

    let pyproject_toml = context.read("pyproject.toml");

    insta::with_settings!({
        filters => context.filters(),
    }, {
        assert_snapshot!(
            pyproject_toml, @r#"
        [project]
        name = "project"
        version = "0.1.0"
        requires-python = ">=3.12"
        dependencies = [
            # First line.
            # Second line.
            "anyio==3.7.0",
        ]
        "#
        );
    });

    Ok(())
}

#[test]
fn add_preserves_trailing_comment() -> Result<()> {
    let context = TestContext::new("3.12");

    let pyproject_toml = context.temp_dir.child("pyproject.toml");
    pyproject_toml.write_str(indoc! {r#"
        [project]
        name = "project"
        version = "0.1.0"
        requires-python = ">=3.12"
        dependencies = [
            "idna",
            "iniconfig",  # Use iniconfig.
            # First line.
            # Second line.
        ]
Repository: astral-sh/uv
File: crates/uv/src/windows_exception.rs (Rust)

Code before:
//! Helper for setting up Windows exception handling.
//!
//! Recent versions of Windows seem to no longer show dialog boxes on access violations
//! (segfaults) or similar errors. The user experience is that the command exits with
//! the exception code as its exit status and no visible output. In order to see these
//! errors both in the field and in CI, we need to install our own exception handler.
//!
//! This is a relatively simple exception handler that leans on Rust's own backtrace
//! implementation and also displays some minimal information from the exception itself.

#![allow(unsafe_code)]

use windows::Win32::{
    Foundation,
    System::Diagnostics::Debug::{
        CONTEXT, EXCEPTION_CONTINUE_SEARCH, EXCEPTION_POINTERS, SetUnhandledExceptionFilter,
    },
};

fn display_exception_info(name: &str, info: &[usize; 15]) {
    match info[0] {
        0 => eprintln!("{name} reading {:#16x}", info[1]),
        1 => eprintln!("{name} writing {:#16x}", info[1]),
        8 => eprintln!("{name} executing {:#16x}", info[1]),
        _ => eprintln!("{name} from operation {} at {:#16x}", info[0], info[1]),
    }
}

#[cfg(target_arch = "x86")]
fn dump_regs(c: &CONTEXT) {
    eprintln!(
        "eax={:08x} ebx={:08x} ecx={:08x} edx={:08x} esi={:08x} edi={:08x}",
        c.Eax, c.Ebx, c.Ecx, c.Edx, c.Esi, c.Edi
    );
    eprintln!(
        "eip={:08x} ebp={:08x} esp={:08x} eflags={:08x}",

Review comment (bug):
```suggestion
#![allow(unsafe_code)]
#![allow(clippy::print_stderr)]
```

Will help pass clippy failing CI job for windows

Code after:
//! Helper for setting up Windows exception handling.
//!
//! Recent versions of Windows seem to no longer show dialog boxes on access violations
//! (segfaults) or similar errors. The user experience is that the command exits with
//! the exception code as its exit status and no visible output. In order to see these
//! errors both in the field and in CI, we need to install our own exception handler.
//!
//! This is a relatively simple exception handler that leans on Rust's own backtrace
//! implementation and also displays some minimal information from the exception itself.

#![allow(unsafe_code)]
#![allow(clippy::print_stderr)]

use windows::Win32::{
    Foundation,
    System::Diagnostics::Debug::{
        CONTEXT, EXCEPTION_CONTINUE_SEARCH, EXCEPTION_POINTERS, SetUnhandledExceptionFilter,
    },
};

fn display_exception_info(name: &str, info: &[usize; 15]) {
    match info[0] {
        0 => eprintln!("{name} reading {:#x}", info[1]),
        1 => eprintln!("{name} writing {:#x}", info[1]),
        8 => eprintln!("{name} executing {:#x}", info[1]),
        _ => eprintln!("{name} from operation {} at {:#x}", info[0], info[1]),
    }
}

#[cfg(target_arch = "x86")]
fn dump_regs(c: &CONTEXT) {
    eprintln!(
        "eax={:08x} ebx={:08x} ecx={:08x} edx={:08x} esi={:08x} edi={:08x}",
        c.Eax, c.Ebx, c.Ecx, c.Edx, c.Esi, c.Edi
    );
    eprintln!(
Repository: astral-sh/uv
File: crates/uv-auth/src/providers.rs (Rust)

Code before:
/// The authentication token for the Hugging Face platform, if set.
static HUGGING_FACE_TOKEN: LazyLock<Option<Vec<u8>>> = LazyLock::new(|| {
    if std::env::var_os(EnvVars::UV_NO_HF_TOKEN).is_some() {
        return None;
    }
    std::env::var(EnvVars::HF_TOKEN)
        .map(String::into_bytes)
        .ok()
});

/// A provider for authentication credentials for the Hugging Face platform.
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) struct HuggingFaceProvider;

impl HuggingFaceProvider {
    /// Returns the credentials for the Hugging Face platform, if available.
    pub(crate) fn credentials_for(url: &Url) -> Option<Credentials> {
        if Realm::from(url) == *HUGGING_FACE_REALM {
            if let Some(token) = HUGGING_FACE_TOKEN.as_ref() {
                return Some(Credentials::Bearer {
                    token: token.clone(),
                });
            }
        }
        None
    }
}


Review comment (bug):
Should we have a debug or trace log that we loaded this from `HF_TOKEN`?

Code after:
/// The authentication token for the Hugging Face platform, if set.
static HUGGING_FACE_TOKEN: LazyLock<Option<Vec<u8>>> = LazyLock::new(|| {
    // Extract the Hugging Face token from the environment variable, if it exists.
    let hf_token = std::env::var(EnvVars::HF_TOKEN)
        .ok()
        .map(String::into_bytes)
        .filter(|token| !token.is_empty())?;

    if std::env::var_os(EnvVars::UV_NO_HF_TOKEN).is_some() {
        debug!("Ignoring Hugging Face token from environment due to `UV_NO_HF_TOKEN`");
        return None;
    }

    debug!("Found Hugging Face token in environment");
    Some(hf_token)
});

/// A provider for authentication credentials for the Hugging Face platform.
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) struct HuggingFaceProvider;

impl HuggingFaceProvider {
    /// Returns the credentials for the Hugging Face platform, if available.
    pub(crate) fn credentials_for(url: &Url) -> Option<Credentials> {
        if Realm::from(url) == *HUGGING_FACE_REALM {
            if let Some(token) = HUGGING_FACE_TOKEN.as_ref() {
                return Some(Credentials::Bearer {
                    token: token.clone(),
                });
            }
        }
        None
    }
}
Repository: astral-sh/uv
File: crates/uv-auth/src/providers.rs (Rust)

Code before:

use url::Url;

use uv_static::EnvVars;

use crate::Credentials;
use crate::realm::Realm;

/// The [`Realm`] for the Hugging Face platform.
static HUGGING_FACE_REALM: LazyLock<Realm> = LazyLock::new(|| {
    let url = Url::parse("https://huggingface.co").expect("Failed to parse Hugging Face URL");
    Realm::from(&url)
});

/// The authentication token for the Hugging Face platform, if set.
static HUGGING_FACE_TOKEN: LazyLock<Option<Vec<u8>>> = LazyLock::new(|| {
    if std::env::var_os(EnvVars::UV_NO_HF_TOKEN).is_some() {
        return None;
    }
    std::env::var(EnvVars::HF_TOKEN)
        .map(String::into_bytes)
        .ok()
});

/// A provider for authentication credentials for the Hugging Face platform.
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) struct HuggingFaceProvider;

impl HuggingFaceProvider {
    /// Returns the credentials for the Hugging Face platform, if available.
    pub(crate) fn credentials_for(url: &Url) -> Option<Credentials> {
        if Realm::from(url) == *HUGGING_FACE_REALM {
            if let Some(token) = HUGGING_FACE_TOKEN.as_ref() {
                return Some(Credentials::Bearer {
                    token: token.clone(),
                });
            }
        }
        None
    }
}


Review comment (bug):
We might want to do this after we've determined `HF_TOKEN` is populated (i.e., via `filter`) so we can include a debug log indicating we ignored `HF_TOKEN` because of `UV_NO_HF_TOKEN`.

Code after:
use tracing::debug;
use url::Url;

use uv_static::EnvVars;

use crate::Credentials;
use crate::realm::Realm;

/// The [`Realm`] for the Hugging Face platform.
static HUGGING_FACE_REALM: LazyLock<Realm> = LazyLock::new(|| {
    let url = Url::parse("https://huggingface.co").expect("Failed to parse Hugging Face URL");
    Realm::from(&url)
});

/// The authentication token for the Hugging Face platform, if set.
static HUGGING_FACE_TOKEN: LazyLock<Option<Vec<u8>>> = LazyLock::new(|| {
    // Extract the Hugging Face token from the environment variable, if it exists.
    let hf_token = std::env::var(EnvVars::HF_TOKEN)
        .ok()
        .map(String::into_bytes)
        .filter(|token| !token.is_empty())?;

    if std::env::var_os(EnvVars::UV_NO_HF_TOKEN).is_some() {
        debug!("Ignoring Hugging Face token from environment due to `UV_NO_HF_TOKEN`");
        return None;
    }

    debug!("Found Hugging Face token in environment");
    Some(hf_token)
});

/// A provider for authentication credentials for the Hugging Face platform.
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) struct HuggingFaceProvider;

impl HuggingFaceProvider {
    /// Returns the credentials for the Hugging Face platform, if available.
    pub(crate) fn credentials_for(url: &Url) -> Option<Credentials> {
        if Realm::from(url) == *HUGGING_FACE_REALM {
            if let Some(token) = HUGGING_FACE_TOKEN.as_ref() {
                return Some(Credentials::Bearer {
                    token: token.clone(),
                });
            }
        }
        None
    }
}