ronantakizawa/codereview-bench huggingface dataset:
Repository: tauri-apps/tauri
File: crates/tauri-cli/src/helpers/mod.rs (Rust)

Code before:
  let mut map = HashMap::new();

  map.insert(
    "TAURI_ENV_PLATFORM_VERSION",
    os_info::get().version().to_string(),
  );

  if debug {
    map.insert("TAURI_ENV_DEBUG", "true".into());
  }

  map
}

pub fn resolve_tauri_path<P: AsRef<Path>>(path: P, crate_name: &str) -> PathBuf {
  let path = path.as_ref();
  if path.is_absolute() {
    path.join(crate_name)
  } else {
    PathBuf::from("..").join(path).join(crate_name)
  }
}

pub fn cross_command(bin: &str) -> Command {
  #[cfg(target_os = "windows")]
  let cmd = Command::new(format!("{bin}.cmd"));
  #[cfg(not(target_os = "windows"))]
  let cmd = Command::new(bin);
  cmd
}

pub fn run_hook(
  name: &str,
  hook: HookCommand,
  interface: &AppInterface,
  debug: bool,
) -> crate::Result<()> {
  let (script, script_cwd) = match hook {
    HookCommand::Script(s) if s.is_empty() => (None, None),
    HookCommand::Script(s) => (Some(s), None),
    HookCommand::ScriptWithOptions { script, cwd } => (Some(script), cwd.map(Into::into)),
  };
  let cwd = script_cwd.unwrap_or_else(|| frontend_dir().clone());
  if let Some(script) = script {
    log::info!(action = "Running"; "{} `{}`", name, script);

    let mut env = command_env(debug);
    env.extend(interface.env());

    log::debug!("Setting environment for hook {:?}", env);


Review comment (security):
I can't seem to make the `yarn` command work without changing this, `cmd /c` seems to have some escape problems with `|` that `yarn` pattern uses

Would love some help

Code after:
  let mut map = HashMap::new();

  map.insert(
    "TAURI_ENV_PLATFORM_VERSION",
    os_info::get().version().to_string(),
  );

  if debug {
    map.insert("TAURI_ENV_DEBUG", "true".into());
  }

  map
}

pub fn resolve_tauri_path<P: AsRef<Path>>(path: P, crate_name: &str) -> PathBuf {
  let path = path.as_ref();
  if path.is_absolute() {
    path.join(crate_name)
  } else {
    PathBuf::from("..").join(path).join(crate_name)
  }
}

pub fn cross_command(bin: &str) -> Command {
  #[cfg(target_os = "windows")]
  let cmd = {
    let mut cmd = Command::new("cmd");
    cmd.arg("/c").arg(bin);
    cmd
  };
  #[cfg(not(target_os = "windows"))]
  let cmd = Command::new(bin);
  cmd
}

pub fn run_hook(
  name: &str,
  hook: HookCommand,
  interface: &AppInterface,
  debug: bool,
) -> crate::Result<()> {
  let (script, script_cwd) = match hook {
    HookCommand::Script(s) if s.is_empty() => (None, None),
    HookCommand::Script(s) => (Some(s), None),
    HookCommand::ScriptWithOptions { script, cwd } => (Some(script), cwd.map(Into::into)),
  };
  let cwd = script_cwd.unwrap_or_else(|| frontend_dir().clone());
  if let Some(script) = script {
    log::info!(action = "Running"; "{} `{}`", name, script);

    let mut env = command_env(debug);
Repository: tauri-apps/tauri
File: crates/tauri-cli/src/build.rs (Rust)

Code before:
      verbosity,
      ci,
      &interface,
      &app_settings,
      config_,
      &out_dir,
    )?;
  }

  Ok(())
}

pub fn setup(
  interface: &AppInterface,
  options: &mut Options,
  config: ConfigHandle,
  mobile: bool,
) -> Result<()> {
  let tauri_path = tauri_dir();

  let ignore_version_mismatches = options.ignore_version_mismatches;
  std::thread::spawn(move || {
    if let Err(error) = check_mismatched_packages(frontend_dir(), tauri_path) {
      log::error!("{error}");
      if !ignore_version_mismatches {
        std::process::exit(1);
      }
    }
  });

  set_current_dir(tauri_path).with_context(|| "failed to change current working directory")?;

  let config_guard = config.lock().unwrap();
  let config_ = config_guard.as_ref().unwrap();

  let bundle_identifier_source = config_
    .find_bundle_identifier_overwriter()
    .unwrap_or_else(|| "tauri.conf.json".into());

  if config_.identifier == "com.tauri.dev" {
    log::error!(
      "You must change the bundle identifier in `{} identifier`. The default value `com.tauri.dev` is not allowed as it must be unique across applications.",
      bundle_identifier_source
    );
    std::process::exit(1);
  }

  if config_
    .identifier
    .chars()
    .any(|ch| !(ch.is_alphanumeric() || ch == '-' || ch == '.'))

Review comment (suggestion):
This doesn't seem to stop the spawned processes (e.g. `vite`, `cargo`) though, feels like a pain to deal with 😂

Code after:
      verbosity,
      ci,
      &interface,
      &app_settings,
      config_,
      &out_dir,
    )?;
  }

  Ok(())
}

pub fn setup(
  interface: &AppInterface,
  options: &mut Options,
  config: ConfigHandle,
  mobile: bool,
) -> Result<()> {
  let tauri_path = tauri_dir();

  // TODO: Maybe optimize this to run in parallel in the future
  // see https://github.com/tauri-apps/tauri/pull/13993#discussion_r2280697117
  log::info!("Looking up installed tauri packages to check mismatched versions...");
  if let Err(error) = check_mismatched_packages(frontend_dir(), tauri_path) {
    if options.ignore_version_mismatches {
      log::error!("{error}");
    } else {
      return Err(error);
    }
  }

  set_current_dir(tauri_path).with_context(|| "failed to change current working directory")?;

  let config_guard = config.lock().unwrap();
  let config_ = config_guard.as_ref().unwrap();

  let bundle_identifier_source = config_
    .find_bundle_identifier_overwriter()
    .unwrap_or_else(|| "tauri.conf.json".into());

  if config_.identifier == "com.tauri.dev" {
    anyhow::bail!(
      "You must change the bundle identifier in `{bundle_identifier_source} identifier`. The default value `com.tauri.dev` is not allowed as it must be unique across applications.",
    );
  }

  if config_
    .identifier
    .chars()
    .any(|ch| !(ch.is_alphanumeric() || ch == '-' || ch == '.'))
  {
Repository: tauri-apps/tauri
File: crates/tauri-utils/src/build.rs (Rust)

Code before:
    .arg("-sdk")
    .arg(sdk)
    .arg("-arch")
    .arg(arch)
    .arg("-derivedDataPath")
    .arg(&derived_data_path)
    .arg("BUILD_LIBRARY_FOR_DISTRIBUTION=YES")
    .arg("OTHER_SWIFT_FLAGS=-no-verify-emitted-module-interface")
    .current_dir(source)
    .env_clear()
    .env("PATH", std::env::var_os("PATH").unwrap_or_default())
    .status()
    .unwrap();

  assert!(status.success());

  let lib_out_dir = derived_data_path
    .join("Build")
    .join("Products")
    .join(format!("{configuration}-{sdk}"));

  println!(
    "cargo::rustc-link-search=framework={}",
    lib_out_dir.display()
  );
  println!("cargo:include={}", lib_out_dir.display());
  println!("cargo:rerun-if-changed={}", source.display());
  println!("cargo:rustc-link-search=native={}", lib_out_dir.display());
  println!("cargo:rustc-link-lib=static={name}");
}


Review comment (suggestion):
```suggestion
```

doesn't seem like cargo:include actually exists as a cargo instruction

Code after:
    .arg("-sdk")
    .arg(sdk)
    .arg("-arch")
    .arg(arch)
    .arg("-derivedDataPath")
    .arg(&derived_data_path)
    .arg("BUILD_LIBRARY_FOR_DISTRIBUTION=YES")
    .arg("OTHER_SWIFT_FLAGS=-no-verify-emitted-module-interface")
    .current_dir(source)
    .env_clear()
    .env("PATH", std::env::var_os("PATH").unwrap_or_default())
    .status()
    .unwrap();

  assert!(status.success());

  let lib_out_dir = derived_data_path
    .join("Build")
    .join("Products")
    .join(format!("{configuration}-{sdk}"));

  println!(
    "cargo::rustc-link-search=framework={}",
    lib_out_dir.display()
  );
  println!("cargo:rerun-if-changed={}", source.display());
  println!("cargo:rustc-link-search=native={}", lib_out_dir.display());
  println!("cargo:rustc-link-lib=static={name}");
}
Repository: tauri-apps/tauri
File: crates/tauri-utils/src/build.rs (Rust)

Code before:
    .arg(name)
    .arg("-configuration")
    .arg(configuration)
    .arg("-sdk")
    .arg(sdk)
    .arg("-arch")
    .arg(arch)
    .arg("-derivedDataPath")
    .arg(&derived_data_path)
    .arg("BUILD_LIBRARY_FOR_DISTRIBUTION=YES")
    .arg("OTHER_SWIFT_FLAGS=-no-verify-emitted-module-interface")
    .current_dir(source)
    .env_clear()
    .env("PATH", std::env::var_os("PATH").unwrap_or_default())
    .status()
    .unwrap();

  assert!(status.success());

  let lib_out_dir = derived_data_path
    .join("Build")
    .join("Products")
    .join(format!("{configuration}-{sdk}"));

  println!(
    "cargo::rustc-link-search=framework={}",
    lib_out_dir.display()
  );
  println!("cargo:include={}", lib_out_dir.display());
  println!("cargo:rerun-if-changed={}", source.display());
  println!("cargo:rustc-link-search=native={}", lib_out_dir.display());
  println!("cargo:rustc-link-lib=static={name}");
}


Review comment (suggestion):
```suggestion
    "cargo:rustc-link-search=framework={}",
```

Code after:
    .arg(name)
    .arg("-configuration")
    .arg(configuration)
    .arg("-sdk")
    .arg(sdk)
    .arg("-arch")
    .arg(arch)
    .arg("-derivedDataPath")
    .arg(&derived_data_path)
    .arg("BUILD_LIBRARY_FOR_DISTRIBUTION=YES")
    .arg("OTHER_SWIFT_FLAGS=-no-verify-emitted-module-interface")
    .current_dir(source)
    .env_clear()
    .env("PATH", std::env::var_os("PATH").unwrap_or_default())
    .status()
    .unwrap();

  assert!(status.success());

  let lib_out_dir = derived_data_path
    .join("Build")
    .join("Products")
    .join(format!("{configuration}-{sdk}"));

  println!(
    "cargo::rustc-link-search=framework={}",
    lib_out_dir.display()
  );
  println!("cargo:rerun-if-changed={}", source.display());
  println!("cargo:rustc-link-search=native={}", lib_out_dir.display());
  println!("cargo:rustc-link-lib=static={name}");
}
Repository: tauri-apps/tauri
File: crates/tauri-cli/src/interface/rust.rs (Rust)

Code before:
      };
      path.set_extension(extension);
    };
    Ok(path)
  }

  fn get_binaries(&self) -> crate::Result<Vec<BundleBinary>> {
    let mut binaries: Vec<BundleBinary> = vec![];

    if let Some(bins) = &self.cargo_settings.bin {
      let default_run = self
        .package_settings
        .default_run
        .clone()
        .unwrap_or_default();
      for bin in bins {
        let file_name = bin.file_name();
        let is_main = file_name == self.cargo_package_settings.name || file_name == default_run;
        binaries.push(BundleBinary::with_path(
          file_name.to_owned(),
          is_main,
          bin.path.clone(),
        ))
      }
    }

    let tauri_dir = tauri_dir();

    let mut binaries_paths = std::fs::read_dir(tauri_dir.join("src/bin"))
      .map(|dir| {
        dir
          .into_iter()
          .flatten()
          .map(|entry| {
            (
              entry
                .path()
                .file_stem()
                .unwrap_or_default()
                .to_string_lossy()
                .into_owned(),
              entry.path(),
            )
          })
          .collect::<Vec<_>>()
      })
      .unwrap_or_default();

    if !binaries_paths
      .iter()
      .any(|(_name, path)| path == Path::new("src/main.rs"))

Review comment (suggestion):
Shouldn't this have the same code path if `options.features == None` vs `options.features == Some(["a", "b"])` when `req_features == Some(["c"])`? The `continue` will be hit in the latter case, but not in the former.

Looking into this due to #14607 

Code after:
      } else {
        "exe".into()
      };
      path.set_extension(extension);
    };
    Ok(path)
  }

  fn get_binaries(&self, options: &Options) -> crate::Result<Vec<BundleBinary>> {
    let mut binaries = Vec::new();

    if let Some(bins) = &self.cargo_settings.bin {
      let default_run = self
        .package_settings
        .default_run
        .clone()
        .unwrap_or_default();
      for bin in bins {
        if let (Some(req_features), Some(opt_features)) =
          (&bin.required_features, &options.features)
        {
          // Check if all required features are enabled.
          if !req_features.iter().all(|feat| opt_features.contains(feat)) {
            continue;
          }
        }
        let file_name = bin.file_name();
        let is_main = file_name == self.cargo_package_settings.name || file_name == default_run;
        binaries.push(BundleBinary::with_path(
          file_name.to_owned(),
          is_main,
          bin.path.clone(),
        ))
      }
    }

    let tauri_dir = tauri_dir();

    let mut binaries_paths = std::fs::read_dir(tauri_dir.join("src/bin"))
      .map(|dir| {
        dir
          .into_iter()
          .flatten()
          .map(|entry| {
            (
              entry
                .path()
                .file_stem()
                .unwrap_or_default()
                .to_string_lossy()
                .into_owned(),
Repository: tauri-apps/tauri
File: crates/tauri-bundler/src/utils/http_utils.rs (Rust)

Code before:

fn generate_github_alternative_url(url: &str) -> Option<(ureq::Agent, String)> {
  if !url.starts_with("https://github.com/") {
    return None;
  }

  generate_github_mirror_url_from_template(url)
    .or_else(|| generate_github_mirror_url_from_base(url))
    .map(|alt_url| {
      (
        ureq::Agent::config_builder()
          .user_agent(BUNDLER_USER_AGENT)
          .build()
          .into(),
        alt_url,
      )
    })
}

fn create_agent_and_url(url: &str) -> (ureq::Agent, String) {
  generate_github_alternative_url(url).unwrap_or((base_ureq_agent(), url.to_owned()))
}

pub(crate) fn base_ureq_agent() -> ureq::Agent {
  let mut config_builder = ureq::Agent::config_builder()
    .user_agent(BUNDLER_USER_AGENT)
    .proxy(ureq::Proxy::try_from_env());

  #[cfg(feature = "platform-certs")]
  {
    config_builder = config_builder.tls_config(
      ureq::tls::TlsConfig::builder()
        .root_certs(ureq::tls::RootCerts::PlatformVerifier)
        .build(),
    );
  }

  config_builder.build().into()
}

#[allow(dead_code)]
pub fn download(url: &str) -> crate::Result<Vec<u8>> {
  let (agent, final_url) = create_agent_and_url(url);

  log::info!(action = "Downloading"; "{}", final_url);

  let response = agent.get(&final_url).call().map_err(Box::new)?;
  let mut bytes = Vec::new();
  response.into_body().into_reader().read_to_end(&mut bytes)?;
  Ok(bytes)
}

Review comment (suggestion):
```suggestion
  #[allow(unused_mut)]
  let mut config_builder = ureq::Agent::config_builder()
```

Probably doesn't really matter though

Code after:

fn generate_github_alternative_url(url: &str) -> Option<(ureq::Agent, String)> {
  if !url.starts_with("https://github.com/") {
    return None;
  }

  generate_github_mirror_url_from_template(url)
    .or_else(|| generate_github_mirror_url_from_base(url))
    .map(|alt_url| {
      (
        ureq::Agent::config_builder()
          .user_agent(BUNDLER_USER_AGENT)
          .build()
          .into(),
        alt_url,
      )
    })
}

fn create_agent_and_url(url: &str) -> (ureq::Agent, String) {
  generate_github_alternative_url(url).unwrap_or((base_ureq_agent(), url.to_owned()))
}

pub(crate) fn base_ureq_agent() -> ureq::Agent {
  #[allow(unused_mut)]
  let mut config_builder = ureq::Agent::config_builder()
    .user_agent(BUNDLER_USER_AGENT)
    .proxy(ureq::Proxy::try_from_env());

  #[cfg(feature = "platform-certs")]
  {
    config_builder = config_builder.tls_config(
      ureq::tls::TlsConfig::builder()
        .root_certs(ureq::tls::RootCerts::PlatformVerifier)
        .build(),
    );
  }

  config_builder.build().into()
}

#[allow(dead_code)]
pub fn download(url: &str) -> crate::Result<Vec<u8>> {
  let (agent, final_url) = create_agent_and_url(url);

  log::info!(action = "Downloading"; "{}", final_url);

  let response = agent.get(&final_url).call().map_err(Box::new)?;
  let mut bytes = Vec::new();
  response.into_body().into_reader().read_to_end(&mut bytes)?;
  Ok(bytes)
Repository: tauri-apps/tauri
File: crates/tauri-cli/src/mobile/mod.rs (Rust)

Code before:
    }
  }
}

impl Default for DevHost {
  fn default() -> Self {
    // on Windows we want to force using the public network address for the development server
    // because the adb port forwarding does not work well
    if cfg!(windows) {
      Self(Some(None))
    } else {
      Self(None)
    }
  }
}

fn is_empty(v: &[String]) -> bool {
  v.is_empty()
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CliOptions {
  pub dev: bool,
  #[serde(default)]
  #[serde(skip_serializing_if = "is_empty")]
  pub features: Vec<String>,
  pub args: Vec<String>,
  pub noise_level: NoiseLevel,
  pub vars: HashMap<String, OsString>,
  pub config: Vec<ConfigValue>,
  pub target_device: Option<TargetDevice>,
}

impl Default for CliOptions {
  fn default() -> Self {
    Self {
      dev: false,
      features: Vec::new(),
      args: vec!["--lib".into()],
      noise_level: Default::default(),
      vars: Default::default(),
      config: Vec::new(),
      target_device: None,
    }
  }
}

fn local_ip_address(force: bool) -> &'static IpAddr {
  static LOCAL_IP: OnceLock<IpAddr> = OnceLock::new();
  LOCAL_IP.get_or_init(|| {
    let prompt_for_ip = || {

Review comment (suggestion):
This `Serialize` and `Deserialize` impl is the only publically visible way the change of internal fields might be observable. This uses `serde` configuration so serialization strings remain identical.

Code after:
    }
  }
}

impl Default for DevHost {
  fn default() -> Self {
    // on Windows we want to force using the public network address for the development server
    // because the adb port forwarding does not work well
    if cfg!(windows) {
      Self(Some(None))
    } else {
      Self(None)
    }
  }
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CliOptions {
  pub dev: bool,
  pub features: Vec<String>,
  pub args: Vec<String>,
  pub noise_level: NoiseLevel,
  pub vars: HashMap<String, OsString>,
  pub config: Vec<ConfigValue>,
  pub target_device: Option<TargetDevice>,
}

impl Default for CliOptions {
  fn default() -> Self {
    Self {
      dev: false,
      features: Vec::new(),
      args: vec!["--lib".into()],
      noise_level: Default::default(),
      vars: Default::default(),
      config: Vec::new(),
      target_device: None,
    }
  }
}

fn local_ip_address(force: bool) -> &'static IpAddr {
  static LOCAL_IP: OnceLock<IpAddr> = OnceLock::new();
  LOCAL_IP.get_or_init(|| {
    let prompt_for_ip = || {
      let addresses: Vec<IpAddr> = local_ip_address::list_afinet_netifas()
        .expect("failed to list networks")
        .into_iter()
        .map(|(_, ipaddr)| ipaddr)
        .filter(|ipaddr| match ipaddr {
          IpAddr::V4(i) => i != &Ipv4Addr::LOCALHOST,
Repository: tauri-apps/tauri
File: crates/tauri-cli/src/mobile/android/build.rs (Rust)

Code before:
    noise_level,
  )?;

  if open {
    open_and_wait(&config, &env);
  }

  Ok(BuiltApplication {
    config,
    interface,
    options_handle,
  })
}

#[allow(clippy::too_many_arguments)]
fn run_build(
  interface: &AppInterface,
  mut options: Options,
  build_options: BuildOptions,
  tauri_config: ConfigHandle,
  profile: Profile,
  config: &AndroidConfig,
  env: &mut Env,
  noise_level: NoiseLevel,
) -> Result<OptionsHandle> {
  if !options.skip_bundle && !(options.apk || options.aab) {
    // if the user didn't specify the format to build, we'll do both
    options.apk = true;
    options.aab = true;
  }

  let interface_options = InterfaceOptions {
    debug: build_options.debug,
    target: build_options.target.clone(),
    args: build_options.args.clone(),
    ..Default::default()
  };

  let app_settings = interface.app_settings();
  let out_dir = app_settings.out_dir(&interface_options)?;
  let _lock = flock::open_rw(out_dir.join("lock").with_extension("android"), "Android")?;

  let cli_options = CliOptions {
    dev: false,
    features: build_options.features.clone(),
    args: build_options.args.clone(),
    noise_level,
    vars: Default::default(),
    config: build_options.config,
    target_device: options.target_device.clone(),
  };

Review comment (suggestion):
```suggestion
  if !(options.skip_bundle || options.apk || options.aab) {
```
clippy

Code after:
    &config,
    &mut env,
    noise_level,
    dirs.tauri,
  )?;

  if open {
    open_and_wait(&config, &env);
  }

  Ok(BuiltApplication {
    config,
    interface,
    options_handle,
  })
}

#[allow(clippy::too_many_arguments)]
fn run_build(
  interface: &AppInterface,
  mut options: Options,
  build_options: BuildOptions,
  tauri_config: &ConfigMetadata,
  profile: Profile,
  config: &AndroidConfig,
  env: &mut Env,
  noise_level: NoiseLevel,
  tauri_dir: &Path,
) -> Result<OptionsHandle> {
  if !(options.skip_bundle || options.apk || options.aab) {
    // if the user didn't specify the format to build, we'll do both
    options.apk = true;
    options.aab = true;
  }

  let interface_options = InterfaceOptions {
    debug: build_options.debug,
    target: build_options.target.clone(),
    args: build_options.args.clone(),
    ..Default::default()
  };

  let app_settings = interface.app_settings();
  let out_dir = app_settings.out_dir(&interface_options, tauri_dir)?;
  let _lock = flock::open_rw(out_dir.join("lock").with_extension("android"), "Android")?;

  let cli_options = CliOptions {
    dev: false,
    features: build_options.features.clone(),
    args: build_options.args.clone(),
    noise_level,