ronantakizawa/codereview-bench huggingface dataset:
Repository: starship/starship
File: src/modules/direnv.rs (Rust)

Code before:
use std::borrow::Cow;
use std::path::PathBuf;
use std::str::FromStr;

use super::{Context, Module, ModuleConfig};

use crate::configs::direnv::DirenvConfig;
use crate::formatter::StringFormatter;

use serde::Deserialize;

/// Creates a module with the current direnv rc
pub fn module<'a>(context: &'a Context) -> Option<Module<'a>> {
    let mut module = context.new_module("direnv");
    let config = DirenvConfig::try_load(module.config);
    let has_detected_env_var = context.detect_env_vars(&config.detect_env_vars);

    let direnv_applies = !config.disabled && has_detected_env_var
        || context
            .try_begin_scan()?
            .set_extensions(&config.detect_extensions)
            .set_files(&config.detect_files)
            .set_folders(&config.detect_folders)
            .is_match();

    if !direnv_applies {
        return None;
    }

    // the `--json` flag is silently ignored for direnv versions <2.33.0
    let direnv_status = &context.exec_cmd("direnv", &["status", "--json"])?.stdout;
    let state = match DirenvState::from_str(direnv_status) {
        Ok(s) => s,
        Err(e) => {
            log::warn!("{e}");

            return None;
        }
    };

    let parsed = StringFormatter::new(config.format).and_then(|formatter| {
        formatter
            .map_style(|variable| match variable {
                "style" => Some(Ok(config.style)),

Review comment (suggestion):
I think the `||` expression should be wrapped in braces.

Code after:
use std::borrow::Cow;
use std::path::PathBuf;
use std::str::FromStr;

use super::{Context, Module, ModuleConfig};

use crate::configs::direnv::DirenvConfig;
use crate::formatter::StringFormatter;

use serde::Deserialize;

/// Creates a module with the current direnv rc
pub fn module<'a>(context: &'a Context) -> Option<Module<'a>> {
    let mut module = context.new_module("direnv");
    let config = DirenvConfig::try_load(module.config);
    let has_detected_env_var = context.detect_env_vars(&config.detect_env_vars);

    let direnv_applies = !config.disabled
        && (has_detected_env_var
            || context
                .try_begin_scan()?
                .set_extensions(&config.detect_extensions)
                .set_files(&config.detect_files)
                .set_folders(&config.detect_folders)
                .is_match());

    if !direnv_applies {
        return None;
    }

    // the `--json` flag is silently ignored for direnv versions <2.33.0
    let direnv_status = &context.exec_cmd("direnv", &["status", "--json"])?.stdout;
    let state = match DirenvState::from_str(direnv_status) {
        Ok(s) => s,
        Err(e) => {
            log::warn!("{e}");

            return None;
        }
    };

    let parsed = StringFormatter::new(config.format).and_then(|formatter| {
        formatter
            .map_style(|variable| match variable {
Repository: starship/starship
File: src/main.rs (Rust)

Code before:
use rand::Rng;
use starship::context::{Context, Properties, Target};
use starship::module::ALL_MODULES;
use starship::*;

#[derive(Parser, Debug)]
#[clap(
    author=crate_authors!(),
    version=shadow::PKG_VERSION,
    long_version=shadow::CLAP_LONG_VERSION,
    about="The cross-shell prompt for astronauts. ☄🌌️",
    subcommand_required=true,
    arg_required_else_help=true,
)]
struct Cli {
    #[clap(subcommand)]
    command: Commands,
}

#[derive(Subcommand, Debug)]
enum Commands {
    /// Create a pre-populated GitHub issue with information about your configuration
    BugReport,
    /// Generate starship shell completions for your shell to stdout
    Completions {
        #[clap(value_enum)]
        shell: CompletionShell,
    },
    /// Edit the starship configuration
    Config {
        /// Configuration key to edit
        #[clap(requires = "value")]
        name: Option<String>,
        /// Value to place into that key
        value: Option<String>,
    },
    /// Explains the currently showing modules
    Explain(Properties),
    ///  Prints the shell function used to execute starship
    Init {
        shell: String,
        #[clap(long)]
        print_full_init: bool,
    },
    ///  Prints a specific prompt module
    Module {
        /// The name of the module to be printed
        #[clap(required_unless_present("list"))]
        name: Option<String>,
        /// List out all supported modules
        #[clap(short, long)]

Review comment (suggestion):
The variant should be named `Powershell` to prevent `-` from being added to the `<SHELL>` arg value.

Code after:
use rand::Rng;
use starship::context::{Context, Properties, Target};
use starship::module::ALL_MODULES;
use starship::*;

#[derive(Parser, Debug)]
#[clap(
    author=crate_authors!(),
    version=shadow::PKG_VERSION,
    long_version=shadow::CLAP_LONG_VERSION,
    about="The cross-shell prompt for astronauts. ☄🌌️",
    subcommand_required=true,
    arg_required_else_help=true,
)]
struct Cli {
    #[clap(subcommand)]
    command: Commands,
}

#[derive(clap::Parser, ValueEnum, Debug, Clone, PartialEq, Eq)]
enum CompletionShell {
    Bash,
    Elvish,
    Fish,
    Nushell,
    PowerShell,
    Zsh,
}

fn generate_shell(shell: impl clap_complete::Generator) {
    generate(
        shell,
        &mut Cli::command(),
        "starship",
        &mut io::stdout().lock(),
    )
}

fn generate_completions(shell: CompletionShell) {
    match shell {
        CompletionShell::Bash => generate_shell(clap_complete::Shell::Bash),
        CompletionShell::Elvish => generate_shell(clap_complete::Shell::Elvish),
        CompletionShell::Fish => generate_shell(clap_complete::Shell::Fish),
        CompletionShell::PowerShell => generate_shell(clap_complete::Shell::PowerShell),
        CompletionShell::Zsh => generate_shell(clap_complete::Shell::Zsh),
        CompletionShell::Nushell => generate_shell(clap_complete_nushell::Nushell),
    }
}

#[derive(Subcommand, Debug)]
enum Commands {
Repository: starship/starship
File: src/configs/netns.rs (Rust)

Code before:
use serde::{Deserialize, Serialize};

#[derive(Clone, Deserialize, Serialize)]
#[cfg_attr(
    feature = "config-schema",
    derive(schemars::JsonSchema),
    schemars(deny_unknown_fields)
)]
#[serde(default)]
pub struct NetnsConfig<'a> {
    pub format: &'a str,
    pub symbol: &'a str,
    pub style: &'a str,
    pub disabled: bool,
}

impl<'a> Default for NetnsConfig<'a> {
    fn default() -> Self {
        NetnsConfig {
            format: "[$symbol \\[$name\\]]($style) ",
            symbol: "🛜",
            style: "blue bold dimmed",
            disabled: false,
        }
    }
}


Review comment (suggestion):
```suggestion
impl Default for NetnsConfig<'_> {
```

Code after:
use serde::{Deserialize, Serialize};

#[derive(Clone, Deserialize, Serialize)]
#[cfg_attr(
    feature = "config-schema",
    derive(schemars::JsonSchema),
    schemars(deny_unknown_fields)
)]
#[serde(default)]
pub struct NetnsConfig<'a> {
    pub format: &'a str,
    pub symbol: &'a str,
    pub style: &'a str,
    pub disabled: bool,
}

impl Default for NetnsConfig<'_> {
    fn default() -> Self {
        NetnsConfig {
            format: "[$symbol \\[$name\\]]($style) ",
            symbol: "🛜",
            style: "blue bold dimmed",
            disabled: false,
        }
    }
}
Repository: starship/starship
File: src/modules/python.rs (Rust)

Code before:
    Some(module)
}

fn get_pyenv_version(context: &Context) -> Option<String> {
    let mut version_name = context.get_env("PYENV_VERSION");

    if version_name.is_none() {
        version_name = Some(
            context
                .exec_cmd("pyenv", &["version-name"])?
                .stdout
                .trim()
                .to_string(),
        )
    }

    version_name
}

fn get_python_version(context: &Context, config: &PythonConfig) -> Option<String> {
    config
        .python_binary
        .0
        .iter()
        .find_map(|binary| {
            let command = binary.0[0];
            let args: Vec<_> = binary
                .0
                .iter()
                .skip(1)
                .copied()
                .chain(std::iter::once("--version"))
                .collect();

            context.exec_cmd(command, &args)
        })
        .map(get_command_string_output)
        .map(|output| parse_python_version(&output))?
}

fn parse_python_version(python_version_string: &str) -> Option<String> {
    let version = python_version_string
        // split into ["Python", "3.8.6", ...]
        .split_whitespace()
        // get down to "3.8.6"
        .nth(1)?;

    Some(version.to_string())
}

fn get_python_virtual_env(context: &Context) -> Option<String> {

Review comment (suggestion):
```suggestion
            let command = binary.0.get(0)?;
```

Code after:
    Some(module)
}

fn get_pyenv_version(context: &Context) -> Option<String> {
    let mut version_name = context.get_env("PYENV_VERSION");

    if version_name.is_none() {
        version_name = Some(
            context
                .exec_cmd("pyenv", &["version-name"])?
                .stdout
                .trim()
                .to_string(),
        )
    }

    version_name
}

fn get_python_version(context: &Context, config: &PythonConfig) -> Option<String> {
    config
        .python_binary
        .0
        .iter()
        .find_map(|binary| {
            let command = binary.0.first()?;
            let args: Vec<_> = binary
                .0
                .iter()
                .skip(1)
                .copied()
                .chain(std::iter::once("--version"))
                .collect();

            context.exec_cmd(command, &args)
        })
        .map(get_command_string_output)
        .map(|output| parse_python_version(&output))?
}

fn parse_python_version(python_version_string: &str) -> Option<String> {
    let version = python_version_string
        // split into ["Python", "3.8.6", ...]
        .split_whitespace()
        // get down to "3.8.6"
        .nth(1)?;

    Some(version.to_string())
}

fn get_python_virtual_env(context: &Context) -> Option<String> {
Repository: starship/starship
File: install/install.sh (Shell)

Code before:

confirm() {
  if [ -z "${FORCE-}" ]; then
    trap 'echo; error "Interrupted (please re-run with the '--yes' option)"; exit 130' INT
    printf "%s " "${MAGENTA}?${NO_COLOR} $* ${BOLD}[y/N]${NO_COLOR}"
    set +e
    read -r yn </dev/tty
    trap - INT
    yn=$(echo "$yn" | tr '[:upper:]' '[:lower:]')
    rc=$?
    set -e
    if [ $rc -ne 0 ]; then
      error "Error reading from prompt (please re-run with the '--yes' option)"
      exit 1
    fi
    if [ "$yn" != "y" ] && [ "$yn" != "yes" ]; then
      if [ "$yn" = "n" ] || [ "$yn" = "no" ]; then
        trap 'echo; error "Interrupted (please re-run with the '--yes' option)"; exit 130' INT
        set +e
        read -p "${MAGENTA}?${NO_COLOR} Install Starship ${GREEN}${VERSION}${NO_COLOR} to: " path
        trap - INT
        rc=$?
        set -e
        BIN_DIR=$path
        if [ $rc != 0 ] || [ -z "$path"]; then
          if [ -z "$path"]; then
            echo
          fi
          error "Error reading from prompt (please re-run with '--yes' or provide path)"
          exit 1
        fi
      else
        if [ -z "$yn" ]; then
          echo
        fi
        error 'Aborting (please answer "yes" to continue)'
        exit 1
      fi
    fi
  fi
}

check_bin_dir() {
  bin_dir="${1%/}"

  if [ ! -d "$BIN_DIR" ]; then
    error "Installation location $BIN_DIR does not appear to be a directory"
    info "Make sure the location exists and is a directory, then try again."
    usage
    exit 1
  fi

Review comment (suggestion):
Missing space before `]` - should be `[ -z "$path" ];`

Code after:

set_interrupt_handler() {
  trap 'echo; error "Interrupted (please re-run with the '--yes' option)"; exit 130' INT
}

confirm() {
  if [ -z "${FORCE-}" ]; then
    set_interrupt_handler
    printf "%s " "${MAGENTA}?${NO_COLOR} $* ${BOLD}[y/N]${NO_COLOR}"
    set +e
    read -r yn </dev/tty
    trap - INT
    yn=$(echo "$yn" | tr '[:upper:]' '[:lower:]')
    rc=$?
    set -e
    if [ $rc -ne 0 ]; then
      error "Error reading from prompt (please re-run with the '--yes' option)"
      exit 1
    fi
    if [ "$yn" != "y" ] && [ "$yn" != "yes" ]; then
      if [ "$yn" = "n" ] || [ "$yn" = "no" ]; then
        set_interrupt_handler
        set +e
        printf "Where would you like to install Starship? ${GREY}(e.g., /usr/local/bin)${NO_COLOR}\n"
        read -p "> Install Starship ${GREEN}${VERSION}${NO_COLOR} to: " path
        trap - INT
        rc=$?
        set -e
        BIN_DIR=$path
        if [ $rc != 0 ] || [ -z "$path" ]; then
          if [ -z "$path" ]; then
            echo
          fi
          error "Error reading from prompt (please re-run with '--yes' or provide path)"
          exit 1
        fi
      else
        if [ -z "$yn" ]; then
          echo
        fi
        error 'Aborting (please answer "yes" to continue)'
        exit 1
      fi
    fi
  fi
}

check_bin_dir() {
  bin_dir="${1%/}"

  if [ ! -d "$BIN_DIR" ]; then
Repository: starship/starship
File: src/configs/directory.rs (Rust)

Code before:
use crate::config::Either;
use indexmap::IndexMap;
use serde::{Deserialize, Serialize};

#[derive(Clone, Deserialize, Serialize)]
#[cfg_attr(
    feature = "config-schema",
    derive(schemars::JsonSchema),
    schemars(deny_unknown_fields)
)]
pub struct SubstitutionConfig<'a> {
    pub from: String,
    pub to: &'a str,
    pub regex: Option<bool>,
}

impl<'a> SubstitutionConfig<'a> {
    pub fn new(from: String, to: &'a str) -> Self {
        Self {
            from,
            to,
            regex: Some(false),
        }
    }
}

#[derive(Clone, Deserialize, Serialize)]
#[cfg_attr(
    feature = "config-schema",
    derive(schemars::JsonSchema),
    schemars(deny_unknown_fields)
)]
#[serde(default)]
pub struct DirectoryConfig<'a> {
    pub truncation_length: i64,
    pub truncate_to_repo: bool,
    pub substitutions: Either<Vec<SubstitutionConfig<'a>>, IndexMap<String, &'a str>>,
    pub fish_style_pwd_dir_length: i64,
    pub use_logical_path: bool,

Review comment (suggestion):
```suggestion
    #[serde(default)]
    pub regex: bool,
```

Code after:
use crate::config::Either;
use indexmap::IndexMap;
use serde::{Deserialize, Serialize};

#[derive(Clone, Deserialize, Serialize)]
#[cfg_attr(
    feature = "config-schema",
    derive(schemars::JsonSchema),
    schemars(deny_unknown_fields)
)]
pub struct SubstitutionConfig<'a> {
    pub from: String,
    pub to: &'a str,
    #[serde(default)]
    pub regex: bool,
}

#[derive(Clone, Deserialize, Serialize)]
#[cfg_attr(
    feature = "config-schema",
    derive(schemars::JsonSchema),
    schemars(deny_unknown_fields)
)]
#[serde(default)]
pub struct DirectoryConfig<'a> {
    pub truncation_length: i64,
    pub truncate_to_repo: bool,
    pub substitutions: Either<Vec<SubstitutionConfig<'a>>, IndexMap<String, &'a str>>,
    pub fish_style_pwd_dir_length: i64,
    pub use_logical_path: bool,
    pub format: &'a str,
    pub repo_root_format: &'a str,
    pub style: &'a str,
    pub repo_root_style: Option<&'a str>,
    pub before_repo_root_style: Option<&'a str>,
    pub disabled: bool,
    pub read_only: &'a str,
    pub read_only_style: &'a str,
    pub truncation_symbol: &'a str,
Repository: starship/starship
File: src/modules/maven.rs (Rust)

Code before:
        .strip_prefix("apache-maven-")?
        .rsplit_once('-')?
        .0;
    Some(version.to_string())
}

/// Tries to find the maven-wrapper.properties file.
fn get_wrapper_properties_file(context: &Context, recursive: bool) -> Option<String> {
    let read_wrapper_properties = |base_dir: &Path| {
        utils::read_file(base_dir.join(".mvn/wrapper/maven-wrapper.properties")).ok()
    };

    // Try current directory first
    if context.try_begin_scan()?.set_folders(&[".mvn"]).is_match()
        && let Some(properties) = read_wrapper_properties(&context.current_dir)
    {
        return Some(properties);
    }

    // Try parent directories if recursive
    if recursive {
        for dir in context.current_dir.ancestors().skip(1) {
            if let Some(properties) = read_wrapper_properties(dir) {
                return Some(properties);
            }
        }
    }

    None
}

#[cfg(test)]
mod tests {
    use nu_ansi_term::Color;

    use super::*;
    use crate::test::ModuleRenderer;
    use std::fs::{self, File};
    use std::io::{self, Write};

    #[test]
    fn folder_without_maven_files() -> io::Result<()> {
        let dir = tempfile::tempdir()?;

        let actual = ModuleRenderer::new("maven").path(dir.path()).collect();

        let expected = None;
        assert_eq!(expected, actual);
        dir.close()
    }


Review comment (suggestion):
Please make use of `context.begin_ancestor_scan()`

Code after:
        .strip_prefix("apache-maven-")?
        .rsplit_once('-')?
        .0;
    Some(version.to_string())
}

/// Tries to find the maven-wrapper.properties file.
fn get_wrapper_properties_file(context: &Context, recursive: bool) -> Option<String> {
    let read_wrapper_properties = |base_dir: &Path| {
        utils::read_file(base_dir.join(".mvn/wrapper/maven-wrapper.properties")).ok()
    };

    // Try current directory first
    if context.try_begin_scan()?.set_folders(&[".mvn"]).is_match()
        && let Some(properties) = read_wrapper_properties(&context.current_dir)
    {
        return Some(properties);
    }

    // Try parent directories if recursive
    if recursive
        && let Some(base_dir) = context.begin_ancestor_scan().set_folders(&[".mvn"]).scan()
        && let Some(properties) = read_wrapper_properties(&base_dir)
    {
        return Some(properties);
    }

    None
}

#[cfg(test)]
mod tests {
    use nu_ansi_term::Color;

    use super::*;
    use crate::test::ModuleRenderer;
    use std::fs::{self, File};
    use std::io::{self, Write};

    #[test]
    fn folder_without_maven_files() -> io::Result<()> {
        let dir = tempfile::tempdir()?;

        let actual = ModuleRenderer::new("maven").path(dir.path()).collect();

        let expected = None;
        assert_eq!(expected, actual);
        dir.close()
    }

    #[test]
Repository: storybookjs/storybook
File: addons/a11y/preset.js (JavaScript)

Code before:
function managerEntries(entry = []) {
  return [...entry, require.resolve('./dist/esm/register')];
}

function config(entry = []) {
  return [
    ...entry,
    require.resolve('./dist/esm/a11yRunner'),
    require.resolve('./dist/esm/a11yHighlight'),
  ];
}

async function webpack(webpackConfig, options) {
  const core = await options.presets.apply('core');
  if (core && core.builder !== 'webpack5') {
    return webpackConfig;
  }
  if (!webpackConfig.resolve.fallback) {
    webpackConfig.resolve.fallback = {};
  }
  webpackConfig.resolve.fallback.crypto = false;

  return webpackConfig;
}

module.exports = { managerEntries, config };


Review comment (suggestion):
```suggestion
module.exports = { managerEntries, config, webpack };
```

Code after:
function managerEntries(entry = []) {
  return [...entry, require.resolve('./dist/esm/register')];
}

function config(entry = []) {
  return [
    ...entry,
    require.resolve('./dist/esm/a11yRunner'),
    require.resolve('./dist/esm/a11yHighlight'),
  ];
}

async function webpack(webpackConfig, options) {
  const core = await options.presets.apply('core');
  if ((core && core.builder) !== 'webpack5') {
    return webpackConfig;
  }
  if (!webpackConfig.resolve.fallback) {
    webpackConfig.resolve.fallback = {};
  }
  webpackConfig.resolve.fallback.crypto = false;

  return webpackConfig;
}

module.exports = { managerEntries, config, webpack };
Repository: storybookjs/storybook
File: app/angular/src/builders/utils/run-compodoc.ts (TypeScript)

Code before:
import { BuilderContext } from '@angular-devkit/architect';
import { spawn } from 'child_process';
import { Observable } from 'rxjs';
import * as path from 'path';

const hasTsConfigArg = (args: string[]) => args.indexOf('-p') !== -1;

// path.relative is necessary to workaround a compodoc issue with
// absolute paths on windows machines
const toRelativePath = (pathToTsConfig: string) => {
  return path.isAbsolute(pathToTsConfig) ? path.relative('.', pathToTsConfig) : pathToTsConfig;
};

export const runCompodoc = (
  { compodocArgs, tsconfig }: { compodocArgs: string[]; tsconfig: string },
  context: BuilderContext
): Observable<void> => {
  return new Observable<void>((observer) => {
    const tsConfigPath = toRelativePath('./tsconfig.json');
    const finalCompodocArgs = [
      'compodoc',
      // Default options
      ...(hasTsConfigArg(compodocArgs) ? [] : ['-p', tsConfigPath]),
      '-d',
      `${context.workspaceRoot}`,
      ...compodocArgs,
    ];

    try {
      context.logger.info(finalCompodocArgs.join(' '));
      const child = spawn('npx', finalCompodocArgs, {
        cwd: context.workspaceRoot,
        env: process.env,
        shell: true,
      });

      child.stdout.on('data', (data) => {
        context.logger.info(data.toString());
      });
      child.stderr.on('data', (data) => {
        context.logger.error(data.toString());
      });

      child.on('close', (code) => {

Review comment (refactor):
@shilman  🤦‍♂️ When you look at code for too long, right?

```suggestion
    const tsConfigPath = toRelativePath(tsconfig);
```

Code after:
import { BuilderContext } from '@angular-devkit/architect';
import { spawn } from 'child_process';
import { Observable } from 'rxjs';
import * as path from 'path';

const hasTsConfigArg = (args: string[]) => args.indexOf('-p') !== -1;

// path.relative is necessary to workaround a compodoc issue with
// absolute paths on windows machines
const toRelativePath = (pathToTsConfig: string) => {
  return path.isAbsolute(pathToTsConfig) ? path.relative('.', pathToTsConfig) : pathToTsConfig;
};

export const runCompodoc = (
  { compodocArgs, tsconfig }: { compodocArgs: string[]; tsconfig: string },
  context: BuilderContext
): Observable<void> => {
  return new Observable<void>((observer) => {
    const tsConfigPath = toRelativePath(tsconfig);
    const finalCompodocArgs = [
      'compodoc',
      // Default options
      ...(hasTsConfigArg(compodocArgs) ? [] : ['-p', tsConfigPath]),
      '-d',
      `${context.workspaceRoot}`,
      ...compodocArgs,
    ];

    try {
      context.logger.info(finalCompodocArgs.join(' '));
      const child = spawn('npx', finalCompodocArgs, {
        cwd: context.workspaceRoot,
        env: process.env,
        shell: true,
      });

      child.stdout.on('data', (data) => {
        context.logger.info(data.toString());
      });
      child.stderr.on('data', (data) => {
        context.logger.error(data.toString());
      });

      child.on('close', (code) => {